@agentic-kit/db-tools 0.12.46 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-relation.js
CHANGED
|
@@ -1,46 +1,84 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.addRelationTool = void 0;
|
|
4
|
-
|
|
4
|
+
exports.addRelationReady = addRelationReady;
|
|
5
|
+
const blueprint_defaults_1 = require("../blueprint/blueprint-defaults");
|
|
5
6
|
const blueprint_construction_1 = require("../blueprint-construction");
|
|
6
|
-
const
|
|
7
|
+
const failure_1 = require("../failure");
|
|
8
|
+
const ready_1 = require("../ready");
|
|
7
9
|
const schema_resolve_1 = require("../schema-resolve");
|
|
8
10
|
const add_relation_schema_1 = require("./add-relation-schema");
|
|
9
|
-
|
|
10
|
-
|
|
11
|
+
/**
|
|
12
|
+
* What add_relation checks before it changes anything: its input, an owned
|
|
13
|
+
* project with both tables, and no field or junction table of the new name.
|
|
14
|
+
*/
|
|
15
|
+
async function addRelationReady(params, cwd) {
|
|
16
|
+
const type = params.relation_type ?? 'belongs_to';
|
|
17
|
+
if (type === 'belongs_to' && !params.field_name) {
|
|
18
|
+
return {
|
|
19
|
+
kind: 'failed',
|
|
20
|
+
failure: {
|
|
21
|
+
code: 'invalid-input',
|
|
22
|
+
message: 'A belongs_to relation needs the name of its foreign-key column on the source table.',
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
if (type === 'many_to_many' && !params.junction_table_name) {
|
|
27
|
+
return {
|
|
28
|
+
kind: 'failed',
|
|
29
|
+
failure: { code: 'invalid-input', message: 'A many_to_many relation needs the name of its junction table.' },
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const ready = await (0, ready_1.ownedProjectReady)(cwd);
|
|
33
|
+
if (ready.kind === 'failed')
|
|
34
|
+
return ready;
|
|
35
|
+
// Both tables must exist: a clearer error than the backend's, and no no-op blueprint.
|
|
36
|
+
let source;
|
|
37
|
+
try {
|
|
38
|
+
const schema = await (0, schema_resolve_1.resolveSchema)(ready.value);
|
|
39
|
+
source = (0, schema_resolve_1.resolveTable)(schema, params.source_table);
|
|
40
|
+
(0, schema_resolve_1.resolveTable)(schema, params.target_table);
|
|
41
|
+
}
|
|
42
|
+
catch (err) {
|
|
43
|
+
return { kind: 'failed', failure: (0, failure_1.failureFromError)(err, 'Failed to resolve schema') };
|
|
44
|
+
}
|
|
45
|
+
if (type === 'many_to_many') {
|
|
46
|
+
const taken = await (0, schema_resolve_1.tablesTaken)(ready.value, [{ name: params.junction_table_name }]);
|
|
47
|
+
return taken ? { kind: 'failed', failure: taken } : ready;
|
|
48
|
+
}
|
|
49
|
+
if (source.fields.some((field) => field.name === ((0, schema_resolve_1.storedName)(params.field_name) ?? params.field_name))) {
|
|
50
|
+
const again = Object.fromEntries(Object.entries(params).filter(([key]) => key !== 'field_name'));
|
|
51
|
+
return {
|
|
52
|
+
kind: 'failed',
|
|
53
|
+
failure: {
|
|
54
|
+
code: 'name-taken',
|
|
55
|
+
message: `Table "${params.source_table}" already has a field named "${params.field_name}".`,
|
|
56
|
+
hint: 'Call again with another field name.',
|
|
57
|
+
calls: [
|
|
58
|
+
(0, failure_1.suggest)('add_relation', again, 'Add the relation under a field name the table does not have yet', ['field_name']),
|
|
59
|
+
],
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return ready;
|
|
64
|
+
}
|
|
65
|
+
function fail(failure) {
|
|
66
|
+
return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure) });
|
|
11
67
|
}
|
|
12
68
|
exports.addRelationTool = {
|
|
13
69
|
name: 'add_relation',
|
|
14
70
|
label: 'Add relation',
|
|
15
|
-
description: 'Add a relation between two EXISTING tables without recreating them: belongs_to adds a foreign-key column on the source table; many_to_many creates a junction table. Use this for relations discovered after the tables were provisioned. For brand-new related tables, prefer
|
|
71
|
+
description: 'Add a relation between two EXISTING tables without recreating them: belongs_to adds a foreign-key column on the source table; many_to_many creates a junction table. Use this for relations discovered after the tables were provisioned. For brand-new related tables, prefer one blueprint that creates them together.',
|
|
16
72
|
promptSnippet: 'add_relation: link two existing tables (belongs_to FK column, or many_to_many junction). Gated.',
|
|
17
73
|
parameters: add_relation_schema_1.AddRelationZod,
|
|
74
|
+
effect: 'write',
|
|
18
75
|
async execute(params, ctx) {
|
|
76
|
+
const ready = await addRelationReady(params, ctx.cwd);
|
|
77
|
+
if (ready.kind === 'failed')
|
|
78
|
+
return fail(ready.failure);
|
|
19
79
|
const type = params.relation_type ?? 'belongs_to';
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
23
|
-
if (type === 'many_to_many' && !params.junction_table_name) {
|
|
24
|
-
return fail('junction_table_name is required for a many_to_many relation.');
|
|
25
|
-
}
|
|
26
|
-
const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
|
|
27
|
-
if (!resolved.context)
|
|
28
|
-
return fail(resolved.reason);
|
|
29
|
-
const { modules, databaseId, schemaId, ownerId } = resolved.context;
|
|
30
|
-
if (!ownerId)
|
|
31
|
-
return fail('Not authenticated (missing OWNER_ID in .env).');
|
|
32
|
-
// Validate both tables exist before constructing — a clearer error than the
|
|
33
|
-
// backend's, and avoids a no-op blueprint.
|
|
34
|
-
let schema;
|
|
35
|
-
try {
|
|
36
|
-
schema = await (0, schema_resolve_1.resolveSchema)(resolved.context);
|
|
37
|
-
(0, schema_resolve_1.resolveTable)(schema, params.source_table);
|
|
38
|
-
(0, schema_resolve_1.resolveTable)(schema, params.target_table);
|
|
39
|
-
}
|
|
40
|
-
catch (err) {
|
|
41
|
-
return fail(err instanceof Error ? err.message : 'Failed to resolve schema.');
|
|
42
|
-
}
|
|
43
|
-
const definition = (0, harness_1.expandBlueprintDefaults)({ tables: [], relations: (0, add_relation_schema_1.buildRelation)(params) });
|
|
80
|
+
const { modules, databaseId, schemaId, ownerId } = ready.value;
|
|
81
|
+
const definition = (0, blueprint_defaults_1.expandBlueprintDefaults)({ tables: [], relations: (0, add_relation_schema_1.buildRelation)(params) });
|
|
44
82
|
const uniqueName = `add_relation_${Date.now()}`;
|
|
45
83
|
try {
|
|
46
84
|
const created = await modules.blueprint
|
|
@@ -58,11 +96,11 @@ exports.addRelationTool = {
|
|
|
58
96
|
.unwrap();
|
|
59
97
|
const blueprintId = created.createBlueprint?.blueprint?.id;
|
|
60
98
|
if (!blueprintId)
|
|
61
|
-
|
|
99
|
+
return fail((0, failure_1.noRowCreated)('Failed to add relation', failure_1.DESCRIBE_SCHEMA));
|
|
62
100
|
await (0, blueprint_construction_1.buildBlueprint)(modules, { blueprintId, schemaId }, { signal: ctx.signal });
|
|
63
101
|
}
|
|
64
102
|
catch (err) {
|
|
65
|
-
return fail(
|
|
103
|
+
return fail((0, failure_1.failureFromError)(err, 'Failed to add relation'));
|
|
66
104
|
}
|
|
67
105
|
const message = type === 'many_to_many'
|
|
68
106
|
? `Created junction table "${params.junction_table_name}" linking ${params.source_table} ↔ ${params.target_table}.`
|
|
@@ -1,12 +1,14 @@
|
|
|
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';
|
|
3
5
|
declare const CreateApiKeyZod: z.ZodObject<{
|
|
4
6
|
key_name: z.ZodString;
|
|
5
7
|
principal_name: z.ZodOptional<z.ZodString>;
|
|
6
|
-
entity_ids: z.ZodOptional<z.ZodArray<z.
|
|
8
|
+
entity_ids: z.ZodOptional<z.ZodArray<z.ZodGUID>>;
|
|
7
9
|
read_only: z.ZodOptional<z.ZodBoolean>;
|
|
8
10
|
expires_in_days: z.ZodOptional<z.ZodNumber>;
|
|
9
|
-
}, z.core.$
|
|
11
|
+
}, z.core.$strict>;
|
|
10
12
|
export type CreateApiKeyDetails = {
|
|
11
13
|
success: boolean;
|
|
12
14
|
message: string;
|
|
@@ -21,7 +23,19 @@ export type CreateApiKeyDetails = {
|
|
|
21
23
|
code?: 'database-unavailable';
|
|
22
24
|
};
|
|
23
25
|
export declare function toEnvVar(keyName: string): string;
|
|
24
|
-
export declare function isStepUpError(messages: string[]): boolean;
|
|
25
26
|
export declare function describeScope(entityIds: string[] | undefined, readOnly: boolean): string;
|
|
27
|
+
type Params = z.infer<typeof CreateApiKeyZod>;
|
|
28
|
+
type ApiKeyReady = {
|
|
29
|
+
context: ProjectContext;
|
|
30
|
+
keyName: string;
|
|
31
|
+
token: string;
|
|
32
|
+
authEndpoint: string;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* What create_api_key checks before it changes anything: a key name, the
|
|
36
|
+
* project on the data plane, a host that can deliver the secret, and an app
|
|
37
|
+
* sign-in.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createApiKeyReady(params: Params, cwd: string): Promise<Result<ApiKeyReady>>;
|
|
26
40
|
export declare const createApiKeyTool: HarnessTool<typeof CreateApiKeyZod, CreateApiKeyDetails>;
|
|
27
41
|
export {};
|
package/tools/create-api-key.js
CHANGED
|
@@ -2,23 +2,24 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createApiKeyTool = void 0;
|
|
4
4
|
exports.toEnvVar = toEnvVar;
|
|
5
|
-
exports.isStepUpError = isStepUpError;
|
|
6
5
|
exports.describeScope = describeScope;
|
|
6
|
+
exports.createApiKeyReady = createApiKeyReady;
|
|
7
|
+
const harness_1 = require("@agentic-kit/harness");
|
|
7
8
|
const sdk_1 = require("@constructive-io/sdk");
|
|
8
9
|
const zod_1 = require("zod");
|
|
9
10
|
const context_1 = require("../context");
|
|
11
|
+
const failure_1 = require("../failure");
|
|
10
12
|
const graphql_http_1 = require("../graphql-http");
|
|
11
13
|
const host_1 = require("../host");
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
const ready_1 = require("../ready");
|
|
15
|
+
const CreateApiKeyZod = (0, harness_1.strictObject)('the input', {
|
|
16
|
+
key_name: (0, harness_1.textParam)()
|
|
15
17
|
.describe('Name for the API key (e.g. "deploy bot"). The .env variable name derives from it (UPPER_SNAKE + _API_KEY).'),
|
|
16
|
-
principal_name:
|
|
17
|
-
.string()
|
|
18
|
+
principal_name: (0, harness_1.textParam)()
|
|
18
19
|
.describe('Machine identity (principal) that owns the key. Defaults to key_name. An existing principal with this name is reused for unscoped keys.')
|
|
19
20
|
.optional(),
|
|
20
21
|
entity_ids: zod_1.z
|
|
21
|
-
.array(
|
|
22
|
+
.array((0, harness_1.idParam)())
|
|
22
23
|
.describe('Entity row UUIDs to scope the principal to. Omit for a personal (unscoped) key that acts as the signed-in app user.')
|
|
23
24
|
.optional(),
|
|
24
25
|
read_only: zod_1.z
|
|
@@ -32,11 +33,8 @@ const CreateApiKeyZod = zod_1.z.object({
|
|
|
32
33
|
.describe('Key lifetime in days. Default 90.')
|
|
33
34
|
.optional(),
|
|
34
35
|
});
|
|
35
|
-
function fail(
|
|
36
|
-
return {
|
|
37
|
-
content: [{ type: 'text', text: message }],
|
|
38
|
-
details: { success: false, message, ...extra },
|
|
39
|
-
};
|
|
36
|
+
function fail(failure, extra) {
|
|
37
|
+
return (0, failure_1.failedResult)(failure, { success: false, message: (0, failure_1.failureText)(failure), ...extra });
|
|
40
38
|
}
|
|
41
39
|
function toEnvVar(keyName) {
|
|
42
40
|
const base = keyName
|
|
@@ -46,9 +44,7 @@ function toEnvVar(keyName) {
|
|
|
46
44
|
.replace(/^_+|_+$/g, '');
|
|
47
45
|
return base.endsWith('_API_KEY') ? base : `${base}_API_KEY`;
|
|
48
46
|
}
|
|
49
|
-
|
|
50
|
-
return messages.some((m) => /step[\s_-]?up/i.test(m));
|
|
51
|
-
}
|
|
47
|
+
const needsStepUp = (errors) => errors.some((error) => error?.extensions?.code === 'STEP_UP_REQUIRED');
|
|
52
48
|
function describeScope(entityIds, readOnly) {
|
|
53
49
|
const parts = [];
|
|
54
50
|
parts.push(entityIds?.length
|
|
@@ -72,7 +68,7 @@ async function rawGraphql(endpoint, token, query, variables) {
|
|
|
72
68
|
}
|
|
73
69
|
const UNAVAILABLE_MESSAGE = 'The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. No key was minted.';
|
|
74
70
|
const isSuspended = (errors) => Boolean(errors?.length) && (0, graphql_http_1.classifyBackendErrors)(errors) === 'suspended';
|
|
75
|
-
const unavailable = () => fail(UNAVAILABLE_MESSAGE, { code: 'database-unavailable' });
|
|
71
|
+
const unavailable = () => fail({ code: 'database-unavailable', message: UNAVAILABLE_MESSAGE }, { code: 'database-unavailable' });
|
|
76
72
|
async function createPrincipalInputFields(endpoint) {
|
|
77
73
|
const probe = await rawGraphql(endpoint, undefined, '{ __type(name: "CreatePrincipalInput") { inputFields { name } } }');
|
|
78
74
|
if (isSuspended(probe.errors))
|
|
@@ -80,37 +76,69 @@ async function createPrincipalInputFields(endpoint) {
|
|
|
80
76
|
const type = probe.data?.__type;
|
|
81
77
|
return new Set((type?.inputFields ?? []).map((f) => f.name));
|
|
82
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* What create_api_key checks before it changes anything: a key name, the
|
|
81
|
+
* project on the data plane, a host that can deliver the secret, and an app
|
|
82
|
+
* sign-in.
|
|
83
|
+
*/
|
|
84
|
+
async function createApiKeyReady(params, cwd) {
|
|
85
|
+
const keyName = params.key_name?.trim();
|
|
86
|
+
if (!keyName) {
|
|
87
|
+
return { kind: 'failed', failure: { code: 'invalid-input', message: 'The key needs a name that is not blank.' } };
|
|
88
|
+
}
|
|
89
|
+
const ready = await (0, ready_1.projectReady)(cwd, 'data');
|
|
90
|
+
if (ready.kind === 'failed')
|
|
91
|
+
return ready;
|
|
92
|
+
const { databaseName, apiEndpoint } = ready.value;
|
|
93
|
+
if (!databaseName) {
|
|
94
|
+
return {
|
|
95
|
+
kind: 'failed',
|
|
96
|
+
failure: {
|
|
97
|
+
code: 'missing-credentials',
|
|
98
|
+
message: 'Cannot resolve the app auth endpoint (DATABASE_NAME missing from .env).',
|
|
99
|
+
hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (!(0, host_1.getHost)().deliverSecret) {
|
|
104
|
+
return {
|
|
105
|
+
kind: 'failed',
|
|
106
|
+
failure: {
|
|
107
|
+
code: 'unsupported',
|
|
108
|
+
message: 'This host cannot deliver secrets (no .env write + reveal flow), so no key was minted.',
|
|
109
|
+
hint: 'Create the key from a host that supports secret delivery.',
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const session = await (0, ready_1.appSessionReady)(ready.value);
|
|
114
|
+
if (session.kind === 'failed')
|
|
115
|
+
return session;
|
|
116
|
+
const authEndpoint = (0, context_1.deriveSubdomainEndpoint)(apiEndpoint, `auth-${databaseName}`);
|
|
117
|
+
if (!authEndpoint) {
|
|
118
|
+
return { kind: 'failed', failure: { code: 'failed', message: `Cannot derive the app auth endpoint from ${apiEndpoint}.` } };
|
|
119
|
+
}
|
|
120
|
+
return { kind: 'ok', value: { context: ready.value, keyName, token: session.value.token, authEndpoint } };
|
|
121
|
+
}
|
|
83
122
|
exports.createApiKeyTool = {
|
|
84
123
|
name: 'create_api_key',
|
|
85
124
|
label: 'Create API key',
|
|
86
125
|
description: 'Mint an API key for the project database, owned by a machine principal. Optionally scope it to specific entity rows and/or read-only. The human confirms the mint, completes MFA step-up in the app when required, and receives the key via .env + a one-time reveal — the plaintext key never appears in this conversation. Requires the user to be signed in to their app in the Preview.',
|
|
87
126
|
promptSnippet: 'create_api_key: mint an entity-scoped API key for the project database. Gated; the plaintext goes to .env + a one-time reveal, never into the chat — reference it as its env var.',
|
|
88
127
|
parameters: CreateApiKeyZod,
|
|
128
|
+
effect: 'write',
|
|
89
129
|
async execute(params, ctx) {
|
|
90
|
-
const
|
|
91
|
-
if (
|
|
92
|
-
return fail('
|
|
93
|
-
const resolved = await (0, context_1.resolveProjectContext)(ctx.cwd, { plane: 'data' });
|
|
94
|
-
if (!resolved.context)
|
|
95
|
-
return fail(resolved.reason);
|
|
96
|
-
const { databaseId, databaseName, apiEndpoint } = resolved.context;
|
|
97
|
-
if (!databaseName) {
|
|
98
|
-
return fail('Cannot resolve the app auth endpoint (DATABASE_NAME missing from .env). Re-provision the database, then retry.');
|
|
130
|
+
const ready = await createApiKeyReady(params, ctx.cwd);
|
|
131
|
+
if (ready.kind === 'failed') {
|
|
132
|
+
return fail(ready.failure, ready.failure.code === 'app-signed-out' ? { needsAuth: true } : {});
|
|
99
133
|
}
|
|
134
|
+
const { context, keyName, token, authEndpoint } = ready.value;
|
|
135
|
+
const { databaseId, databaseName, apiEndpoint } = context;
|
|
100
136
|
const host = (0, host_1.getHost)();
|
|
101
|
-
if (!host.deliverSecret) {
|
|
102
|
-
return fail('This host cannot deliver secrets (no .env write + reveal flow), so no key was minted. Create the key from a host that supports secret delivery.');
|
|
103
|
-
}
|
|
104
|
-
const token = await (0, context_1.resolveDataToken)(resolved.context);
|
|
105
|
-
if (!token.token) {
|
|
106
|
-
return fail(token.reason ?? 'Sign in to the app database to create an API key.', {
|
|
107
|
-
needsAuth: true,
|
|
108
|
-
});
|
|
109
|
-
}
|
|
110
|
-
const authEndpoint = (0, context_1.deriveSubdomainEndpoint)(apiEndpoint, `auth-${databaseName}`);
|
|
111
|
-
if (!authEndpoint)
|
|
112
|
-
return fail('Cannot derive the app auth endpoint.');
|
|
113
137
|
const scoped = Boolean(params.entity_ids?.length) || params.read_only === true;
|
|
138
|
+
// The calls the refusals below suggest: the same key without its scope, or under a principal name still free.
|
|
139
|
+
const without = (keys) => Object.fromEntries(Object.entries(params).filter(([key]) => !keys.includes(key)));
|
|
140
|
+
const unscoped = (0, failure_1.suggest)('create_api_key', without(['entity_ids', 'read_only']), 'Mint an unscoped key that acts as the signed-in app user');
|
|
141
|
+
const newPrincipal = (0, failure_1.suggest)('create_api_key', without(['principal_name']), 'Mint the key under a principal name that is free', ['principal_name']);
|
|
114
142
|
try {
|
|
115
143
|
if (scoped) {
|
|
116
144
|
const fields = await createPrincipalInputFields(authEndpoint);
|
|
@@ -121,11 +149,16 @@ exports.createApiKeyTool = {
|
|
|
121
149
|
...(params.read_only === true && !fields.has('isReadOnly') ? ['isReadOnly'] : []),
|
|
122
150
|
];
|
|
123
151
|
if (missing.length) {
|
|
124
|
-
return fail(
|
|
152
|
+
return fail({
|
|
153
|
+
code: 'unsupported',
|
|
154
|
+
message: `This deployment does not support scoping a principal at create time (no ${missing.join(', ')} on createPrincipal). No key was minted.`,
|
|
155
|
+
hint: 'If an unscoped key that acts as the signed-in user is acceptable, call again without the scope and without read-only.',
|
|
156
|
+
calls: [unscoped],
|
|
157
|
+
});
|
|
125
158
|
}
|
|
126
159
|
}
|
|
127
160
|
const dbAuth = sdk_1.auth.createClient({
|
|
128
|
-
adapter: (0, graphql_http_1.statusAdapter)(authEndpoint, { Authorization: `Bearer ${token
|
|
161
|
+
adapter: (0, graphql_http_1.statusAdapter)(authEndpoint, { Authorization: `Bearer ${token}` }),
|
|
129
162
|
});
|
|
130
163
|
const principalName = params.principal_name?.trim() || keyName;
|
|
131
164
|
const existing = await dbAuth.principal
|
|
@@ -138,7 +171,12 @@ exports.createApiKeyTool = {
|
|
|
138
171
|
// identity userId; principal_entity.principalId references the row id.
|
|
139
172
|
let principalId = existing.principal?.userId;
|
|
140
173
|
if (existing.principal && scoped) {
|
|
141
|
-
return fail(
|
|
174
|
+
return fail({
|
|
175
|
+
code: 'name-taken',
|
|
176
|
+
message: `Principal "${principalName}" already exists, and its scope cannot be verified against the requested one. No key was minted.`,
|
|
177
|
+
hint: 'Call again with a new principal name for a scoped key, or without the scope and without read-only for an unscoped key on the existing principal.',
|
|
178
|
+
calls: [newPrincipal, unscoped],
|
|
179
|
+
});
|
|
142
180
|
}
|
|
143
181
|
if (existing.principal) {
|
|
144
182
|
const scopeRow = await dbAuth.principalEntity
|
|
@@ -148,14 +186,19 @@ exports.createApiKeyTool = {
|
|
|
148
186
|
})
|
|
149
187
|
.unwrap();
|
|
150
188
|
if (scopeRow.principalEntity || existing.principal?.isReadOnly) {
|
|
151
|
-
return fail(
|
|
189
|
+
return fail({
|
|
190
|
+
code: 'name-taken',
|
|
191
|
+
message: `Principal "${principalName}" already exists with a narrower scope (entity-scoped or read-only), so a key minted under it would not act as the signed-in user. No key was minted.`,
|
|
192
|
+
hint: 'Call again with a new principal name.',
|
|
193
|
+
calls: [newPrincipal],
|
|
194
|
+
});
|
|
152
195
|
}
|
|
153
196
|
}
|
|
154
197
|
if (!principalId) {
|
|
155
198
|
// The SDK's PrincipalModel.create sends a nested {principal} input, but
|
|
156
199
|
// the live CreatePrincipalInput is flat and its payload only exposes
|
|
157
200
|
// `result: UUID` — raw GraphQL is the only working surface.
|
|
158
|
-
const created = await rawGraphql(authEndpoint, token
|
|
201
|
+
const created = await rawGraphql(authEndpoint, token, 'mutation ($input: CreatePrincipalInput!) { createPrincipal(input: $input) { result } }', {
|
|
159
202
|
input: {
|
|
160
203
|
name: principalName,
|
|
161
204
|
...(params.entity_ids?.length && { entityIds: params.entity_ids }),
|
|
@@ -164,13 +207,12 @@ exports.createApiKeyTool = {
|
|
|
164
207
|
});
|
|
165
208
|
if (isSuspended(created.errors))
|
|
166
209
|
return unavailable();
|
|
167
|
-
if (created.errors?.length)
|
|
168
|
-
return fail(
|
|
169
|
-
}
|
|
210
|
+
if (created.errors?.length)
|
|
211
|
+
return fail((0, failure_1.failureFromErrors)(created.errors, 'createPrincipal failed'));
|
|
170
212
|
const payload = created.data?.createPrincipal;
|
|
171
213
|
principalId = payload?.result;
|
|
172
214
|
if (!principalId)
|
|
173
|
-
return fail(
|
|
215
|
+
return fail((0, failure_1.noRowCreated)(`Failed to create the principal "${principalName}"`));
|
|
174
216
|
}
|
|
175
217
|
const mint = () => dbAuth.mutation
|
|
176
218
|
.createApiKey({
|
|
@@ -183,23 +225,32 @@ exports.createApiKeyTool = {
|
|
|
183
225
|
}, { select: { result: { select: { apiKey: true, keyId: true, expiresAt: true } } } })
|
|
184
226
|
.execute();
|
|
185
227
|
let minted = await mint();
|
|
186
|
-
if (!minted.ok &&
|
|
228
|
+
if (!minted.ok && needsStepUp(minted.errors)) {
|
|
187
229
|
if (!host.requestStepUp) {
|
|
188
|
-
return fail(
|
|
230
|
+
return fail({
|
|
231
|
+
code: 'step-up-required',
|
|
232
|
+
message: 'Creating this key needs a recent sign-in of the app user, and this host cannot ask for one.',
|
|
233
|
+
hint: 'Sign in again in the app (verify your password), then retry.',
|
|
234
|
+
});
|
|
189
235
|
}
|
|
190
236
|
const verified = await host.requestStepUp({ databaseId, databaseName, apiEndpoint });
|
|
191
|
-
if (!verified)
|
|
192
|
-
return fail(
|
|
237
|
+
if (!verified) {
|
|
238
|
+
return fail({
|
|
239
|
+
code: 'failed',
|
|
240
|
+
message: 'Step-up verification was not completed. No key was minted.',
|
|
241
|
+
hint: 'Retry and complete the password check.',
|
|
242
|
+
});
|
|
243
|
+
}
|
|
193
244
|
minted = await mint();
|
|
194
245
|
}
|
|
195
246
|
if (!minted.ok) {
|
|
196
247
|
if (isSuspended(minted.errors))
|
|
197
248
|
return unavailable();
|
|
198
|
-
return fail(
|
|
249
|
+
return fail((0, failure_1.failureFromErrors)(minted.errors, 'createApiKey failed'));
|
|
199
250
|
}
|
|
200
251
|
const record = minted.data?.createApiKey?.result;
|
|
201
252
|
if (!record?.apiKey || !record.keyId)
|
|
202
|
-
return fail(
|
|
253
|
+
return fail((0, failure_1.noRowCreated)(`Failed to create API key "${keyName}"`));
|
|
203
254
|
const envVar = toEnvVar(keyName);
|
|
204
255
|
await host.deliverSecret({
|
|
205
256
|
databaseId,
|
|
@@ -229,7 +280,7 @@ exports.createApiKeyTool = {
|
|
|
229
280
|
// The SDK's unwrap() throws its errors as `errors`.
|
|
230
281
|
if (isSuspended(err?.errors))
|
|
231
282
|
return unavailable();
|
|
232
|
-
return fail(
|
|
283
|
+
return fail((0, failure_1.failureFromError)(err, `Failed to create API key "${keyName}"`));
|
|
233
284
|
}
|
|
234
285
|
},
|
|
235
286
|
};
|
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
import { type HarnessTool } from '@agentic-kit/harness';
|
|
2
2
|
import { z } from 'zod';
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
name: string;
|
|
6
|
-
type: string;
|
|
7
|
-
isRequired: boolean;
|
|
8
|
-
defaultValue: string | null;
|
|
9
|
-
};
|
|
3
|
+
import { type SchemaField, type WrittenRule } from '../table-access';
|
|
4
|
+
declare const ParamZod: z.ZodObject<{}, z.core.$strict>;
|
|
10
5
|
type SchemaTable = {
|
|
11
6
|
name: string;
|
|
12
7
|
fields: SchemaField[];
|
|
8
|
+
/** Every policy type of the table, each once. */
|
|
13
9
|
policies: string[];
|
|
10
|
+
/** Each rule that applies, in the shape a caller writes one. */
|
|
11
|
+
policyRules: WrittenRule[];
|
|
14
12
|
};
|
|
15
13
|
export type DescribeSchemaDetails = {
|
|
16
14
|
tables: SchemaTable[];
|
package/tools/describe-schema.js
CHANGED
|
@@ -2,132 +2,55 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.describeSchemaTool = void 0;
|
|
4
4
|
const harness_1 = require("@agentic-kit/harness");
|
|
5
|
-
const
|
|
6
|
-
const
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
5
|
+
const failure_1 = require("../failure");
|
|
6
|
+
const ready_1 = require("../ready");
|
|
7
|
+
const table_access_1 = require("../table-access");
|
|
8
|
+
const ParamZod = (0, harness_1.strictObject)('the input', {});
|
|
9
|
+
const ruleCells = (rule) => [
|
|
10
|
+
rule.permissive ? 'rule' : 'limit',
|
|
11
|
+
rule.$type,
|
|
12
|
+
rule.privileges.join(' '),
|
|
13
|
+
rule.policy_role === 'authenticated' ? '' : `role ${rule.policy_role}`
|
|
14
|
+
];
|
|
15
15
|
function formatText(details) {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const def = field.defaultValue != null ? ` default=${field.defaultValue}` : '';
|
|
27
|
-
lines.push(` - ${field.name}: ${field.type}${req}${def}`);
|
|
28
|
-
}
|
|
29
|
-
if (table.policies.length > 0) {
|
|
30
|
-
lines.push(` policies: ${table.policies.join(', ')}`);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
return lines.join('\n');
|
|
16
|
+
if (details.tables.length === 0)
|
|
17
|
+
return 'No tables yet.';
|
|
18
|
+
const indent = (lines) => lines.map((line) => ` ${line}`);
|
|
19
|
+
return details.tables
|
|
20
|
+
.map((table) => [
|
|
21
|
+
table.name,
|
|
22
|
+
...indent((0, harness_1.alignColumns)(table.fields.map((field) => [field.name, field.type, field.isRequired ? 'required' : '', (0, table_access_1.defaultText)(field.defaultValue)]))),
|
|
23
|
+
...indent((0, harness_1.alignColumns)(table.policyRules.map(ruleCells)))
|
|
24
|
+
].join('\n'))
|
|
25
|
+
.join('\n\n');
|
|
35
26
|
}
|
|
36
27
|
exports.describeSchemaTool = {
|
|
37
28
|
name: 'describe_schema',
|
|
38
29
|
label: 'Describe schema',
|
|
39
|
-
description: 'Inspect the current Constructive database schema for this project: application tables with their fields (name, type, required, default). Read-only.',
|
|
30
|
+
description: 'Inspect the current Constructive database schema for this project: application tables with their fields (name, type, required, default) and every access rule that applies to each table, in the shape a rule is written, without the parts the backend sets. Read-only.',
|
|
40
31
|
promptSnippet: 'describe_schema: list the project database tables and their fields. Read-only — call before modifying schema.',
|
|
41
32
|
parameters: ParamZod,
|
|
33
|
+
effect: 'read',
|
|
42
34
|
async execute(_params, ctx) {
|
|
43
|
-
const
|
|
44
|
-
if (
|
|
45
|
-
return {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
};
|
|
35
|
+
const ready = await (0, ready_1.projectReady)(ctx.cwd);
|
|
36
|
+
if (ready.kind === 'failed')
|
|
37
|
+
return (0, failure_1.failedResult)(ready.failure, { tables: [] });
|
|
38
|
+
try {
|
|
39
|
+
return await describeTables(ready.value);
|
|
49
40
|
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
.findMany({
|
|
53
|
-
select: { id: true, name: true, category: true },
|
|
54
|
-
where: {
|
|
55
|
-
databaseId: { equalTo: databaseId },
|
|
56
|
-
or: [{ category: { equalTo: 'APP' } }, { name: { equalTo: 'users' } }],
|
|
57
|
-
},
|
|
58
|
-
orderBy: ['NAME_ASC'],
|
|
59
|
-
})
|
|
60
|
-
.execute();
|
|
61
|
-
if (!tablesResult.ok) {
|
|
62
|
-
const message = tablesResult.errors.map((e) => e.message).join('; ');
|
|
63
|
-
return {
|
|
64
|
-
content: [{ type: 'text', text: `Failed to read schema: ${message}` }],
|
|
65
|
-
details: { tables: [] },
|
|
66
|
-
};
|
|
41
|
+
catch (err) {
|
|
42
|
+
return (0, failure_1.failedResult)((0, failure_1.failureFromError)(err, 'Failed to read schema'), { tables: [] });
|
|
67
43
|
}
|
|
68
|
-
const tableNodes = tablesResult.data.tables?.nodes ?? [];
|
|
69
|
-
const tableIds = tableNodes.map((t) => t.id);
|
|
70
|
-
const fieldsByTable = new Map();
|
|
71
|
-
const policiesByTable = new Map();
|
|
72
|
-
if (tableIds.length > 0) {
|
|
73
|
-
const [fieldsResult, policiesResult] = await Promise.all([
|
|
74
|
-
api.field
|
|
75
|
-
.findMany({
|
|
76
|
-
select: {
|
|
77
|
-
name: true,
|
|
78
|
-
type: true,
|
|
79
|
-
isRequired: true,
|
|
80
|
-
defaultValue: true,
|
|
81
|
-
tableId: true,
|
|
82
|
-
},
|
|
83
|
-
where: { tableId: { in: tableIds } },
|
|
84
|
-
})
|
|
85
|
-
.execute(),
|
|
86
|
-
api.policy
|
|
87
|
-
.findMany({
|
|
88
|
-
select: { tableId: true, policyType: true },
|
|
89
|
-
where: { tableId: { in: tableIds } },
|
|
90
|
-
})
|
|
91
|
-
.execute(),
|
|
92
|
-
]);
|
|
93
|
-
if (!fieldsResult.ok) {
|
|
94
|
-
const message = fieldsResult.errors.map((e) => e.message).join('; ');
|
|
95
|
-
return {
|
|
96
|
-
content: [{ type: 'text', text: `Failed to read fields: ${message}` }],
|
|
97
|
-
details: { tables: [] },
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
for (const field of fieldsResult.data.fields?.nodes ?? []) {
|
|
101
|
-
const list = fieldsByTable.get(field.tableId) ?? [];
|
|
102
|
-
list.push({
|
|
103
|
-
name: field.name,
|
|
104
|
-
type: (0, harness_1.fieldTypeToTypeName)(field.type),
|
|
105
|
-
isRequired: Boolean(field.isRequired),
|
|
106
|
-
defaultValue: toDefaultValueString(field.defaultValue),
|
|
107
|
-
});
|
|
108
|
-
fieldsByTable.set(field.tableId, list);
|
|
109
|
-
}
|
|
110
|
-
// One policy spans CRUD as several rows; collapse to distinct types per table.
|
|
111
|
-
if (policiesResult.ok) {
|
|
112
|
-
for (const policy of policiesResult.data.policies?.nodes ?? []) {
|
|
113
|
-
if ((0, harness_1.isInternalPolicy)(policy.policyType))
|
|
114
|
-
continue;
|
|
115
|
-
const list = policiesByTable.get(policy.tableId) ?? [];
|
|
116
|
-
if (!list.includes(policy.policyType))
|
|
117
|
-
list.push(policy.policyType);
|
|
118
|
-
policiesByTable.set(policy.tableId, list);
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
const tables = tableNodes.map((table) => ({
|
|
123
|
-
name: table.name,
|
|
124
|
-
fields: fieldsByTable.get(table.id) ?? [],
|
|
125
|
-
policies: policiesByTable.get(table.id) ?? [],
|
|
126
|
-
}));
|
|
127
|
-
const details = { tables };
|
|
128
|
-
return {
|
|
129
|
-
content: [{ type: 'text', text: formatText(details) }],
|
|
130
|
-
details,
|
|
131
|
-
};
|
|
132
44
|
},
|
|
133
45
|
};
|
|
46
|
+
async function describeTables(context) {
|
|
47
|
+
const read = await (0, table_access_1.readTables)(context);
|
|
48
|
+
if (read.kind === 'failed')
|
|
49
|
+
return (0, failure_1.failedResult)(read.failure, { tables: [] });
|
|
50
|
+
const tables = read.value.map((table) => {
|
|
51
|
+
const policyRules = (0, table_access_1.accessInputOf)(table).policies.map(table_access_1.asWritten);
|
|
52
|
+
return { name: table.name, fields: table.fields, policies: [...new Set(policyRules.map((rule) => rule.$type))], policyRules };
|
|
53
|
+
});
|
|
54
|
+
const details = { tables };
|
|
55
|
+
return { content: [{ type: 'text', text: formatText(details) }], details };
|
|
56
|
+
}
|