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