@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
|
@@ -1,21 +1,53 @@
|
|
|
1
1
|
import { type HarnessTool } from '@agentic-kit/harness';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
import type { ProjectContext } from '../context';
|
|
4
|
+
import { type FailureMeaning, type Result } from '../failure';
|
|
5
|
+
import { type ColumnChange, type TableRecord } from '../table-access';
|
|
6
|
+
import { type PlannedAccess, type Provision } from './access';
|
|
3
7
|
declare const AddPoliciesZod: z.ZodObject<{
|
|
4
8
|
table_name: z.ZodString;
|
|
5
9
|
policies: z.ZodArray<z.ZodObject<{
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
update: "update";
|
|
12
|
-
}>>;
|
|
13
|
-
role_name: z.ZodOptional<z.ZodString>;
|
|
14
|
-
is_permissive: z.ZodOptional<z.ZodBoolean>;
|
|
10
|
+
$type: z.ZodString;
|
|
11
|
+
privileges: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
12
|
+
permissive: z.ZodOptional<z.ZodBoolean>;
|
|
13
|
+
policy_role: z.ZodOptional<z.ZodString>;
|
|
14
|
+
policy_name: z.ZodOptional<z.ZodString>;
|
|
15
15
|
data: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
}, z.core.$loose>>;
|
|
17
|
+
}, z.core.$strict>;
|
|
18
|
+
type AddPoliciesParams = z.infer<typeof AddPoliciesZod>;
|
|
19
|
+
export type AddPoliciesReady = {
|
|
20
|
+
context: ProjectContext;
|
|
21
|
+
table: TableRecord;
|
|
22
|
+
/** What the call sends: the Data nodes, the rules as the backend will store them, and the grants. */
|
|
23
|
+
provision: Provision;
|
|
24
|
+
/** What the plan says beside the rules. */
|
|
25
|
+
notes: string[];
|
|
26
|
+
after: PlannedAccess;
|
|
27
|
+
/** The columns the change adds. */
|
|
28
|
+
columns: ColumnChange;
|
|
29
|
+
/** What a refusal of the change means. */
|
|
30
|
+
meaning: FailureMeaning;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* What add_policies checks before it changes anything: a list of rules, the
|
|
34
|
+
* table, and the columns the rules need. It resolves the access the table
|
|
35
|
+
* will have, which keeps its own rules and grants.
|
|
36
|
+
*/
|
|
37
|
+
export declare function addPoliciesReady(params: AddPoliciesParams, cwd: string): Promise<Result<AddPoliciesReady>>;
|
|
38
|
+
/** The plan's access for add_policies: the live table now, and with the added rules and the columns they add. */
|
|
39
|
+
export declare const addPoliciesPlan: ({ table, after, notes, columns }: AddPoliciesReady) => {
|
|
40
|
+
notes?: string[];
|
|
41
|
+
columnsAdded?: import("@agentic-kit/harness").PlanColumn[];
|
|
42
|
+
columnsReused?: import("@agentic-kit/harness").PlanColumn[];
|
|
43
|
+
failsIfRows?: string[];
|
|
44
|
+
table: string;
|
|
45
|
+
schema?: string;
|
|
46
|
+
before?: import("@agentic-kit/harness").PlanAccessState;
|
|
47
|
+
after: import("@agentic-kit/harness").PlanAccessState;
|
|
48
|
+
findingsAdded: import("@agentic-kit/harness").PlanFinding[];
|
|
49
|
+
findingsRemoved: import("@agentic-kit/harness").PlanFinding[];
|
|
50
|
+
}[];
|
|
19
51
|
export type AddPoliciesDetails = {
|
|
20
52
|
success: boolean;
|
|
21
53
|
message: string;
|
|
@@ -1,94 +1,94 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { identifierParam, strictObject } from '@agentic-kit/harness';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
.array(CrudOperationSchema)
|
|
14
|
-
.min(1)
|
|
15
|
-
.describe('CRUD operations the policy applies to: any subset of ["create","read","update","delete"].'),
|
|
16
|
-
role_name: z
|
|
17
|
-
.string()
|
|
18
|
-
.describe('PostgreSQL role the policy applies to. Defaults to "authenticated".')
|
|
19
|
-
.optional(),
|
|
20
|
-
is_permissive: z
|
|
21
|
-
.boolean()
|
|
22
|
-
.describe('PERMISSIVE (default true) vs RESTRICTIVE — most policies should be permissive.')
|
|
23
|
-
.optional(),
|
|
24
|
-
data: z
|
|
25
|
-
.record(z.string(), z.unknown())
|
|
26
|
-
.describe('Type-specific shared data. AuthzDirectOwner: { entity_field: "owner_id" }. AuthzAppMembership: { permission?, is_admin?, is_owner? }. Empty object {} for AuthzAllowAll / AuthzDenyAll.')
|
|
27
|
-
.optional(),
|
|
28
|
-
node_data: z
|
|
29
|
-
.record(z.string(), z.unknown())
|
|
30
|
-
.describe('Optional data for the underlying Data* node (has-module policies only).')
|
|
31
|
-
.optional(),
|
|
3
|
+
import { AccessPolicyZod } from '../blueprint/blueprint-schema';
|
|
4
|
+
import { failedResult, failureText } from '../failure';
|
|
5
|
+
import { projectReady } from '../ready';
|
|
6
|
+
import { accessInputOf, changeMeaning, columnPlan, planTableAccess, readTable } from '../table-access';
|
|
7
|
+
import { applyProvision, existingTableChange, neededNodes, plannedPolicies, readBack, readOnlyNotes, storedRules } from './access';
|
|
8
|
+
// The grants a rule list sends beside its rules: every privilege on every column, to the signed-in.
|
|
9
|
+
const LIST_GRANTS = [{ roles: ['authenticated'], privileges: [['select', '*'], ['insert', '*'], ['update', '*'], ['delete', '*']] }];
|
|
10
|
+
const AddPoliciesZod = strictObject('the input', {
|
|
11
|
+
table_name: identifierParam().describe('Name of the existing table to attach the rules to'),
|
|
12
|
+
policies: z.array(AccessPolicyZod).describe("One or more rules to add, in one change; the table's own rules stay"),
|
|
32
13
|
});
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
14
|
+
/**
|
|
15
|
+
* What add_policies checks before it changes anything: a list of rules, the
|
|
16
|
+
* table, and the columns the rules need. It resolves the access the table
|
|
17
|
+
* will have, which keeps its own rules and grants.
|
|
18
|
+
*/
|
|
19
|
+
export async function addPoliciesReady(params, cwd) {
|
|
20
|
+
if (params.policies.length === 0) {
|
|
21
|
+
return { kind: 'failed', failure: { code: 'invalid-input', message: 'The rule list is empty: give at least one rule to add.' } };
|
|
22
|
+
}
|
|
23
|
+
const ready = await projectReady(cwd);
|
|
24
|
+
if (ready.kind === 'failed')
|
|
25
|
+
return ready;
|
|
26
|
+
const context = ready.value;
|
|
27
|
+
const read = await readTable(context, params.table_name);
|
|
28
|
+
if (read.kind === 'failed')
|
|
29
|
+
return read;
|
|
30
|
+
const table = read.value;
|
|
31
|
+
const now = accessInputOf(table);
|
|
32
|
+
const prepared = await storedRules(context, params.policies, { table, grants: LIST_GRANTS });
|
|
33
|
+
if (prepared.kind === 'failed')
|
|
34
|
+
return prepared;
|
|
35
|
+
const { policies, scopes, related } = prepared.value;
|
|
36
|
+
const nodes = neededNodes(policies, table);
|
|
37
|
+
if (nodes.kind === 'failed')
|
|
38
|
+
return nodes;
|
|
39
|
+
const provision = { nodes: nodes.value, policies, grants: LIST_GRANTS };
|
|
40
|
+
const rules = policies.map((policy) => ({ type: policy.$type, data: policy.data ?? {} }));
|
|
41
|
+
const columns = await existingTableChange(context, table, provision.nodes, rules);
|
|
42
|
+
if (columns.kind === 'failed')
|
|
43
|
+
return columns;
|
|
44
|
+
return {
|
|
45
|
+
kind: 'ok',
|
|
46
|
+
value: {
|
|
47
|
+
context,
|
|
48
|
+
table,
|
|
49
|
+
provision,
|
|
50
|
+
notes: [...readOnlyNotes(policies, LIST_GRANTS), ...columns.value.notes],
|
|
51
|
+
after: {
|
|
52
|
+
...now,
|
|
53
|
+
policies: plannedPolicies(now.policies, policies, LIST_GRANTS, scopes),
|
|
54
|
+
grants: [...(now.grants ?? []), ...LIST_GRANTS],
|
|
55
|
+
rls_enabled: true,
|
|
56
|
+
fields: [...(now.fields ?? []), ...columns.value.fields],
|
|
57
|
+
...(related ? { related } : {}),
|
|
58
|
+
},
|
|
59
|
+
columns: columns.value,
|
|
60
|
+
meaning: changeMeaning(table.name, columns.value, rules),
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** The plan's access for add_policies: the live table now, and with the added rules and the columns they add. */
|
|
65
|
+
export const addPoliciesPlan = ({ table, after, notes, columns }) => [
|
|
66
|
+
{ ...planTableAccess(table.name, { ...accessInputOf(table), ...(after.related ? { related: after.related } : {}) }, after), ...columnPlan(columns, true), ...(notes.length ? { notes } : {}) },
|
|
67
|
+
];
|
|
68
|
+
function fail(failure) {
|
|
69
|
+
return failedResult(failure, { success: false, message: failureText(failure) });
|
|
45
70
|
}
|
|
46
71
|
export const addPoliciesTool = {
|
|
47
72
|
name: 'add_policies',
|
|
48
73
|
label: 'Add policies',
|
|
49
|
-
description: 'Add one or more
|
|
50
|
-
promptSnippet: 'add_policies:
|
|
74
|
+
description: 'Add one or more access rules to an existing table; the rules it has stay. A rule whose Authz node reads columns a Data node adds (AuthzDirectOwner, AuthzEntityMembership, AuthzPublishable, ...) gets those columns when the table lacks them, so do not add them first. Gated.',
|
|
75
|
+
promptSnippet: 'add_policies: add access rules to an existing table (one call can add many). Gated.',
|
|
51
76
|
parameters: AddPoliciesZod,
|
|
77
|
+
effect: 'write',
|
|
52
78
|
async execute(params, ctx) {
|
|
53
|
-
const
|
|
54
|
-
if (
|
|
55
|
-
return
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
const mergedData = { ...defaults, ...(entry.data ?? {}) };
|
|
68
|
-
const nodeData = entry.node_data ?? buildNodeData(entry.policy_type, mergedData);
|
|
69
|
-
return {
|
|
70
|
-
policyType: entry.policy_type,
|
|
71
|
-
dataNodeType: config?.dataNodeType,
|
|
72
|
-
nodeData,
|
|
73
|
-
sharedPolicyData: mergedData,
|
|
74
|
-
operations: buildOperations(entry.role_name ?? DEFAULT_ROLE, entry.is_permissive ?? true),
|
|
75
|
-
enabledOperations: entry.operations,
|
|
76
|
-
};
|
|
77
|
-
});
|
|
78
|
-
await addPoliciesToExistingTable({
|
|
79
|
-
client: modules,
|
|
80
|
-
databaseId,
|
|
81
|
-
schemaId,
|
|
82
|
-
tableId: table.id,
|
|
83
|
-
policies,
|
|
84
|
-
});
|
|
85
|
-
const count = params.policies.length;
|
|
86
|
-
const message = `Added ${count} ${count === 1 ? 'policy' : 'policies'} to ${params.table_name}`;
|
|
87
|
-
return { content: [{ type: 'text', text: message }], details: { success: true, message } };
|
|
88
|
-
}
|
|
89
|
-
catch (err) {
|
|
90
|
-
const message = err instanceof Error ? err.message : 'Failed to add policies';
|
|
91
|
-
return { content: [{ type: 'text', text: message }], details: { success: false, message } };
|
|
92
|
-
}
|
|
79
|
+
const ready = await addPoliciesReady(params, ctx.cwd);
|
|
80
|
+
if (ready.kind === 'failed')
|
|
81
|
+
return fail(ready.failure);
|
|
82
|
+
const { context, table, provision, meaning } = ready.value;
|
|
83
|
+
const failure = await applyProvision(context, table, provision, `Failed to add policies to "${params.table_name}"`, meaning);
|
|
84
|
+
if (failure)
|
|
85
|
+
return fail(failure);
|
|
86
|
+
// An add has no call that makes the table as planned again: adding the rules twice adds them twice.
|
|
87
|
+
const checked = await readBack(context, table.name, ready.value.after, ready.value.columns.added.map((column) => column.name));
|
|
88
|
+
if (checked.kind !== 'same')
|
|
89
|
+
return fail(checked.failure);
|
|
90
|
+
const count = provision.policies.length;
|
|
91
|
+
const message = `Added ${count} ${count === 1 ? 'rule' : 'rules'} to ${params.table_name}`;
|
|
92
|
+
return { content: [{ type: 'text', text: message }], details: { success: true, message } };
|
|
93
93
|
},
|
|
94
94
|
};
|
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type HarnessTool } from '@agentic-kit/harness';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
+
import type { ProjectContext } from '../context';
|
|
4
|
+
import { type Result } from '../failure';
|
|
5
|
+
import { statusAdapter } from '../graphql-http';
|
|
6
|
+
import { type RawMetaTable } from '../records/meta';
|
|
3
7
|
export type AddRecordsDetails = {
|
|
4
8
|
success: boolean;
|
|
5
9
|
message: string;
|
|
@@ -10,10 +14,27 @@ export type AddRecordsDetails = {
|
|
|
10
14
|
asOf?: string;
|
|
11
15
|
needsAuth?: boolean;
|
|
12
16
|
code?: 'database-unavailable';
|
|
17
|
+
/** The rows that were not inserted: their place in `records` and what the backend said. */
|
|
18
|
+
failedRows?: {
|
|
19
|
+
index: number;
|
|
20
|
+
message: string;
|
|
21
|
+
}[];
|
|
13
22
|
};
|
|
14
23
|
declare const AddRecordsZod: z.ZodObject<{
|
|
15
24
|
table_name: z.ZodString;
|
|
16
25
|
records: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
17
|
-
}, z.core.$
|
|
26
|
+
}, z.core.$strict>;
|
|
27
|
+
type AddRecordsParams = z.infer<typeof AddRecordsZod>;
|
|
28
|
+
type AddRecordsReady = {
|
|
29
|
+
context: ProjectContext;
|
|
30
|
+
token: string;
|
|
31
|
+
userId?: string;
|
|
32
|
+
/** The app's own API, as the person signed in to the app. */
|
|
33
|
+
adapter: ReturnType<typeof statusAdapter>;
|
|
34
|
+
tables: RawMetaTable[];
|
|
35
|
+
table: RawMetaTable;
|
|
36
|
+
};
|
|
37
|
+
/** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, and the table on the app's API. */
|
|
38
|
+
export declare function addRecordsReady(params: AddRecordsParams, cwd: string): Promise<Result<AddRecordsReady>>;
|
|
18
39
|
export declare const addRecordsTool: HarnessTool<typeof AddRecordsZod, AddRecordsDetails>;
|
|
19
40
|
export {};
|
package/esm/tools/add-records.js
CHANGED
|
@@ -1,26 +1,19 @@
|
|
|
1
|
+
import { identifierParam, strictObject } from '@agentic-kit/harness';
|
|
1
2
|
import { buildPostGraphileCreate, toCamelCaseSingular, toCreateMutationName, } from '@constructive-io/graphql-query/generators';
|
|
2
3
|
import { z } from 'zod';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
4
|
+
import { DESCRIBE_SCHEMA, explainAccessCall, failedResult, failureFromError, failureFromErrors, failureText, NO_NEW_ROW, noRowCreated } from '../failure';
|
|
5
|
+
import { answerText, classifyBackendErrors, statusAdapter, thrownText } from '../graphql-http';
|
|
6
|
+
import { appSessionReady, projectReady } from '../ready';
|
|
5
7
|
import { cleanTable, findMetaTable, META_QUERY } from '../records/meta';
|
|
6
|
-
function fail(
|
|
7
|
-
return
|
|
8
|
+
function fail(failure, extra = {}) {
|
|
9
|
+
return failedResult(failure, { success: false, message: failureText(failure), ...extra });
|
|
8
10
|
}
|
|
9
11
|
const UNAVAILABLE = "The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. Retrying won't help until it is restored.";
|
|
10
12
|
function unavailable(inserted = 0) {
|
|
11
13
|
const message = inserted > 0 ? `${UNAVAILABLE} ${inserted} row(s) were inserted before it stopped.` : `${UNAVAILABLE} No rows were inserted.`;
|
|
12
|
-
return {
|
|
13
|
-
content: [{ type: 'text', text: message }],
|
|
14
|
-
details: { success: false, message, code: 'database-unavailable', ...(inserted > 0 ? { createdCount: inserted } : {}) },
|
|
15
|
-
};
|
|
14
|
+
return fail({ code: 'database-unavailable', message }, { code: 'database-unavailable', ...(inserted > 0 ? { createdCount: inserted } : {}) });
|
|
16
15
|
}
|
|
17
16
|
const isSuspended = (errors) => classifyBackendErrors(errors) === 'suspended';
|
|
18
|
-
function needsAuth(message) {
|
|
19
|
-
return {
|
|
20
|
-
content: [{ type: 'text', text: message }],
|
|
21
|
-
details: { success: false, message, needsAuth: true },
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
17
|
// Mirror @constructive-io/data's prepareCreateInput (create semantics): drop
|
|
25
18
|
// undefined/null/empty-string so server defaults apply; keep false/0/[]/objects.
|
|
26
19
|
function stripForCreate(record) {
|
|
@@ -32,52 +25,77 @@ function stripForCreate(record) {
|
|
|
32
25
|
}
|
|
33
26
|
return out;
|
|
34
27
|
}
|
|
35
|
-
const AddRecordsZod =
|
|
36
|
-
table_name:
|
|
37
|
-
.string()
|
|
28
|
+
const AddRecordsZod = strictObject('the input', {
|
|
29
|
+
table_name: identifierParam()
|
|
38
30
|
.describe('Name of the table to insert rows into (snake_case, singular or plural).'),
|
|
39
31
|
records: z
|
|
40
32
|
.array(z.record(z.string(), z.unknown()))
|
|
41
33
|
.describe('Rows to insert. Each is an object of column → value (camelCase or snake_case column names).'),
|
|
42
34
|
});
|
|
35
|
+
/** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, and the table on the app's API. */
|
|
36
|
+
export async function addRecordsReady(params, cwd) {
|
|
37
|
+
if (params.records.length === 0)
|
|
38
|
+
return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
|
|
39
|
+
const ready = await projectReady(cwd);
|
|
40
|
+
if (ready.kind === 'failed')
|
|
41
|
+
return ready;
|
|
42
|
+
if (!ready.value.dataEndpoint) {
|
|
43
|
+
return {
|
|
44
|
+
kind: 'failed',
|
|
45
|
+
failure: {
|
|
46
|
+
code: 'missing-credentials',
|
|
47
|
+
message: 'Cannot resolve the app data endpoint (DATABASE_NAME missing from .env).',
|
|
48
|
+
hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const session = await appSessionReady(ready.value);
|
|
53
|
+
if (session.kind === 'failed')
|
|
54
|
+
return session;
|
|
55
|
+
// Keeps the status and extensions.code that the SDK adapter drops.
|
|
56
|
+
const adapter = statusAdapter(ready.value.dataEndpoint, { Authorization: `Bearer ${session.value.token}` });
|
|
57
|
+
let tables;
|
|
58
|
+
try {
|
|
59
|
+
const meta = await adapter.execute(META_QUERY);
|
|
60
|
+
if (!meta.ok) {
|
|
61
|
+
const failure = isSuspended(meta.errors)
|
|
62
|
+
? { code: 'database-unavailable', message: `${UNAVAILABLE} No rows were inserted.` }
|
|
63
|
+
: failureFromErrors(meta.errors, 'Failed to read schema from the app database');
|
|
64
|
+
return { kind: 'failed', failure };
|
|
65
|
+
}
|
|
66
|
+
tables = (meta.data._meta?.tables ?? []).filter((t) => Boolean(t));
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
return { kind: 'failed', failure: failureFromError(err, 'Failed to query the app database schema') };
|
|
70
|
+
}
|
|
71
|
+
const table = findMetaTable(tables, params.table_name);
|
|
72
|
+
if (!table) {
|
|
73
|
+
return {
|
|
74
|
+
kind: 'failed',
|
|
75
|
+
failure: {
|
|
76
|
+
code: 'not-found',
|
|
77
|
+
message: `Table "${params.table_name}" was not found in the app database.`,
|
|
78
|
+
hint: 'Check the table names that exist, then retry.',
|
|
79
|
+
calls: [DESCRIBE_SCHEMA],
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables, table } };
|
|
84
|
+
}
|
|
43
85
|
export const addRecordsTool = {
|
|
44
86
|
name: 'add_records',
|
|
45
87
|
label: 'Add records',
|
|
46
88
|
description: "Insert one or more rows into a table in the project's app database.",
|
|
47
89
|
promptSnippet: 'add_records: insert rows into an existing table. Gated.',
|
|
48
90
|
parameters: AddRecordsZod,
|
|
91
|
+
effect: 'write',
|
|
49
92
|
async execute(params, ctx) {
|
|
50
|
-
const
|
|
51
|
-
if (
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (!dataEndpoint) {
|
|
55
|
-
return fail('Cannot resolve the app data endpoint (DATABASE_NAME missing from .env). Re-provision the database, then retry.');
|
|
56
|
-
}
|
|
57
|
-
if (params.records.length === 0)
|
|
58
|
-
return fail('No records provided.');
|
|
59
|
-
const token = await resolveDataToken(resolved.context);
|
|
60
|
-
if (!token.token)
|
|
61
|
-
return needsAuth(token.reason ?? 'Sign in to the database to insert records.');
|
|
62
|
-
// Keeps the status and extensions.code that the SDK adapter drops.
|
|
63
|
-
const adapter = statusAdapter(dataEndpoint, { Authorization: `Bearer ${token.token}` });
|
|
64
|
-
let tables;
|
|
65
|
-
try {
|
|
66
|
-
const meta = await adapter.execute(META_QUERY);
|
|
67
|
-
if (!meta.ok) {
|
|
68
|
-
if (isSuspended(meta.errors))
|
|
69
|
-
return unavailable();
|
|
70
|
-
return fail(`Failed to read schema from the app database: ${errorsText(meta.errors)}`);
|
|
71
|
-
}
|
|
72
|
-
tables = (meta.data._meta?.tables ?? []).filter((t) => Boolean(t));
|
|
73
|
-
}
|
|
74
|
-
catch (err) {
|
|
75
|
-
return fail(err instanceof Error ? err.message : 'Failed to query the app database schema.');
|
|
76
|
-
}
|
|
77
|
-
const rawTable = findMetaTable(tables, params.table_name);
|
|
78
|
-
if (!rawTable) {
|
|
79
|
-
return fail(`Table "${params.table_name}" was not found in the app database.`);
|
|
93
|
+
const ready = await addRecordsReady(params, ctx.cwd);
|
|
94
|
+
if (ready.kind === 'failed') {
|
|
95
|
+
const { code } = ready.failure;
|
|
96
|
+
return fail(ready.failure, code === 'app-signed-out' ? { needsAuth: true } : code === 'database-unavailable' ? { code } : {});
|
|
80
97
|
}
|
|
98
|
+
const { userId, adapter, tables, table: rawTable } = ready.value;
|
|
81
99
|
const table = cleanTable(rawTable);
|
|
82
100
|
const allTables = tables.map(cleanTable);
|
|
83
101
|
const mutation = buildPostGraphileCreate(table, allTables).toString();
|
|
@@ -90,45 +108,65 @@ export const addRecordsTool = {
|
|
|
90
108
|
const hasEntityId = table.fields.some((f) => f.name === 'entityId');
|
|
91
109
|
const created = [];
|
|
92
110
|
const errors = [];
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
111
|
+
const failedRows = [];
|
|
112
|
+
for (const [index, record] of params.records.entries()) {
|
|
113
|
+
const prepared = hasEntityId && userId && record.entityId == null && record.entity_id == null
|
|
114
|
+
? { ...record, entityId: userId }
|
|
96
115
|
: record;
|
|
97
116
|
const variables = { input: { [singularName]: stripForCreate(prepared) } };
|
|
117
|
+
let rowErrors;
|
|
98
118
|
try {
|
|
99
119
|
const result = await adapter.execute(mutation, variables);
|
|
100
|
-
if (
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
120
|
+
if (result.ok) {
|
|
121
|
+
const payload = result.data?.[mutationName];
|
|
122
|
+
const row = payload?.[singularName];
|
|
123
|
+
if (row) {
|
|
124
|
+
created.push(row);
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
failedRows.push({ index, message: NO_NEW_ROW });
|
|
128
|
+
}
|
|
104
129
|
continue;
|
|
105
130
|
}
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
131
|
+
if (isSuspended(result.errors))
|
|
132
|
+
return unavailable(created.length);
|
|
133
|
+
rowErrors = result.errors;
|
|
109
134
|
}
|
|
110
135
|
catch (err) {
|
|
111
|
-
|
|
136
|
+
// The request threw before any answer came back, so the error is the local one.
|
|
137
|
+
rowErrors = [{ message: thrownText(err), extensions: { code: 'NETWORK' } }];
|
|
112
138
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
return fail(`Failed to insert into "${params.table_name}": ${errors.join('; ') || 'unknown error'}`);
|
|
139
|
+
errors.push(...rowErrors);
|
|
140
|
+
failedRows.push({ index, message: answerText(rowErrors) });
|
|
116
141
|
}
|
|
117
142
|
const columns = table.fields.map((f) => f.name);
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
success: true,
|
|
125
|
-
message,
|
|
126
|
-
tableName: rawTable.name,
|
|
127
|
-
columns,
|
|
128
|
-
rows: created,
|
|
129
|
-
createdCount: created.length,
|
|
130
|
-
asOf: new Date().toISOString(),
|
|
131
|
-
},
|
|
143
|
+
const rowDetails = {
|
|
144
|
+
tableName: rawTable.name,
|
|
145
|
+
columns,
|
|
146
|
+
rows: created,
|
|
147
|
+
createdCount: created.length,
|
|
148
|
+
asOf: new Date().toISOString(),
|
|
132
149
|
};
|
|
150
|
+
if (created.length === 0) {
|
|
151
|
+
const action = `Failed to insert into "${params.table_name}"`;
|
|
152
|
+
const rows = { table: params.table_name };
|
|
153
|
+
// A row the backend answers without was refused by, or is hidden by, the read rule.
|
|
154
|
+
const hidden = {
|
|
155
|
+
...noRowCreated(action),
|
|
156
|
+
hint: "The table's read rules may hide the new row from this person: read the rules of the table to see who they let read.",
|
|
157
|
+
calls: [explainAccessCall(params.table_name)],
|
|
158
|
+
};
|
|
159
|
+
return fail(errors.length ? failureFromErrors(errors, action, { rows }) : hidden, { failedRows });
|
|
160
|
+
}
|
|
161
|
+
if (failedRows.length > 0) {
|
|
162
|
+
const first = failedRows[0];
|
|
163
|
+
return fail({
|
|
164
|
+
code: 'partial',
|
|
165
|
+
message: `Inserted ${created.length} of ${params.records.length} rows into ${params.table_name}; ${failedRows.length} were not inserted (row ${first.index}: ${first.message}).`,
|
|
166
|
+
hint: 'Fix the rows listed in details.failedRows, then call again with only those rows: the inserted rows stay.',
|
|
167
|
+
}, { ...rowDetails, failedRows });
|
|
168
|
+
}
|
|
169
|
+
const message = `Inserted ${created.length} row(s) into ${params.table_name}.`;
|
|
170
|
+
return { content: [{ type: 'text', text: message }], details: { success: true, message, ...rowDetails } };
|
|
133
171
|
},
|
|
134
172
|
};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { BlueprintRelation } from 'node-type-registry';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
export declare const DeleteAction: z.ZodEnum<{
|
|
4
|
+
a: "a";
|
|
4
5
|
c: "c";
|
|
5
6
|
r: "r";
|
|
6
7
|
n: "n";
|
|
7
|
-
a: "a";
|
|
8
8
|
d: "d";
|
|
9
9
|
}>;
|
|
10
10
|
export declare const AddRelationZod: z.ZodObject<{
|
|
@@ -17,13 +17,13 @@ export declare const AddRelationZod: z.ZodObject<{
|
|
|
17
17
|
field_name: z.ZodOptional<z.ZodString>;
|
|
18
18
|
junction_table_name: z.ZodOptional<z.ZodString>;
|
|
19
19
|
delete_action: z.ZodOptional<z.ZodEnum<{
|
|
20
|
+
a: "a";
|
|
20
21
|
c: "c";
|
|
21
22
|
r: "r";
|
|
22
23
|
n: "n";
|
|
23
|
-
a: "a";
|
|
24
24
|
d: "d";
|
|
25
25
|
}>>;
|
|
26
26
|
is_required: z.ZodOptional<z.ZodBoolean>;
|
|
27
|
-
}, z.core.$
|
|
27
|
+
}, z.core.$strict>;
|
|
28
28
|
export type AddRelationParams = z.infer<typeof AddRelationZod>;
|
|
29
|
-
export declare function buildRelation(params: AddRelationParams):
|
|
29
|
+
export declare function buildRelation(params: AddRelationParams): BlueprintRelation[];
|
|
@@ -1,24 +1,22 @@
|
|
|
1
|
+
import { identifierParam, strictObject } from '@agentic-kit/harness';
|
|
1
2
|
import { z } from 'zod';
|
|
2
|
-
// delete_action is
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// never has to supply it.
|
|
3
|
+
// delete_action is always sent: the backend refuses a RelationBelongsTo
|
|
4
|
+
// without one. It defaults to 'a' (NO ACTION) so the model never has to
|
|
5
|
+
// supply it.
|
|
6
6
|
export const DeleteAction = z
|
|
7
7
|
.enum(['c', 'r', 'n', 'a', 'd'])
|
|
8
8
|
.describe('FK delete action: c=CASCADE, r=RESTRICT, n=SET NULL, a=NO ACTION (default), d=SET DEFAULT');
|
|
9
|
-
export const AddRelationZod =
|
|
9
|
+
export const AddRelationZod = strictObject('the input', {
|
|
10
10
|
relation_type: z
|
|
11
11
|
.enum(['belongs_to', 'many_to_many'])
|
|
12
12
|
.describe('belongs_to adds an FK column on the source table; many_to_many adds a junction table. Defaults to belongs_to.')
|
|
13
13
|
.optional(),
|
|
14
|
-
source_table:
|
|
15
|
-
target_table:
|
|
16
|
-
field_name:
|
|
17
|
-
.string()
|
|
14
|
+
source_table: identifierParam().describe('Existing source table name (snake_case).'),
|
|
15
|
+
target_table: identifierParam().describe('Existing target table name (snake_case).'),
|
|
16
|
+
field_name: identifierParam()
|
|
18
17
|
.describe('belongs_to only: FK column name to add on the source table, e.g. "author_id".')
|
|
19
18
|
.optional(),
|
|
20
|
-
junction_table_name:
|
|
21
|
-
.string()
|
|
19
|
+
junction_table_name: identifierParam()
|
|
22
20
|
.describe('many_to_many only: name of the junction table to create, e.g. "post_tags".')
|
|
23
21
|
.optional(),
|
|
24
22
|
delete_action: DeleteAction.optional(),
|
|
@@ -27,12 +25,13 @@ export const AddRelationZod = z.object({
|
|
|
27
25
|
.describe('belongs_to only: make the FK NOT NULL. Defaults to false — a NOT NULL FK fails if the source table already has rows.')
|
|
28
26
|
.optional(),
|
|
29
27
|
});
|
|
30
|
-
// Build a relation-only blueprint definition (no tables):
|
|
31
|
-
//
|
|
32
|
-
//
|
|
28
|
+
// Build a relation-only blueprint definition (no tables): constructBlueprint
|
|
29
|
+
// applies relations to existing tables without recreating them, as long as
|
|
30
|
+
// delete_action is supplied.
|
|
33
31
|
export function buildRelation(params) {
|
|
34
32
|
const deleteAction = params.delete_action ?? 'a';
|
|
35
33
|
if ((params.relation_type ?? 'belongs_to') === 'many_to_many') {
|
|
34
|
+
// The backend reads delete_action for every relation; the registry's type of this one does not name it.
|
|
36
35
|
return [
|
|
37
36
|
{
|
|
38
37
|
$type: 'RelationManyToMany',
|
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import type { HarnessTool } from '@agentic-kit/harness';
|
|
2
|
+
import type { ProjectContext } from '../context';
|
|
3
|
+
import { type Result } from '../failure';
|
|
4
|
+
import { type AddRelationParams as Params, AddRelationZod } from './add-relation-schema';
|
|
3
5
|
export type AddRelationDetails = {
|
|
4
6
|
success: boolean;
|
|
5
7
|
message: string;
|
|
@@ -7,4 +9,11 @@ export type AddRelationDetails = {
|
|
|
7
9
|
targetTable?: string;
|
|
8
10
|
fieldName?: string;
|
|
9
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* What add_relation checks before it changes anything: its input, an owned
|
|
14
|
+
* project with both tables, and no field or junction table of the new name.
|
|
15
|
+
*/
|
|
16
|
+
export declare function addRelationReady(params: Params, cwd: string): Promise<Result<ProjectContext & {
|
|
17
|
+
ownerId: string;
|
|
18
|
+
}>>;
|
|
10
19
|
export declare const addRelationTool: HarnessTool<typeof AddRelationZod, AddRelationDetails>;
|