@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.
Files changed (180) hide show
  1. package/README.md +18 -4
  2. package/access/findings.d.ts +93 -0
  3. package/access/findings.js +434 -0
  4. package/access/index.d.ts +5 -0
  5. package/access/index.js +27 -0
  6. package/access/policies.d.ts +142 -0
  7. package/access/policies.js +338 -0
  8. package/access/provisioning.d.ts +121 -0
  9. package/access/provisioning.js +381 -0
  10. package/access/rule-check.d.ts +52 -0
  11. package/access/rule-check.js +307 -0
  12. package/access/words.d.ts +38 -0
  13. package/access/words.js +530 -0
  14. package/app-workspace.d.ts +1 -0
  15. package/app-workspace.js +7 -9
  16. package/blueprint/blueprint-defaults.d.ts +9 -0
  17. package/blueprint/blueprint-defaults.js +77 -0
  18. package/blueprint/blueprint-schema.d.ts +68 -0
  19. package/blueprint/blueprint-schema.js +139 -0
  20. package/blueprint/field-type.d.ts +4 -0
  21. package/blueprint/field-type.js +100 -0
  22. package/blueprint/internal-policies.d.ts +1 -0
  23. package/blueprint/internal-policies.js +10 -0
  24. package/blueprint-construction.d.ts +10 -6
  25. package/blueprint-construction.js +34 -25
  26. package/context.d.ts +15 -0
  27. package/context.js +132 -69
  28. package/db-probe.d.ts +1 -1
  29. package/db-probe.js +19 -4
  30. package/esm/access/findings.d.ts +93 -0
  31. package/esm/access/findings.js +428 -0
  32. package/esm/access/index.d.ts +5 -0
  33. package/esm/access/index.js +5 -0
  34. package/esm/access/policies.d.ts +142 -0
  35. package/esm/access/policies.js +315 -0
  36. package/esm/access/provisioning.d.ts +121 -0
  37. package/esm/access/provisioning.js +375 -0
  38. package/esm/access/rule-check.d.ts +52 -0
  39. package/esm/access/rule-check.js +297 -0
  40. package/esm/access/words.d.ts +38 -0
  41. package/esm/access/words.js +524 -0
  42. package/esm/app-workspace.d.ts +1 -0
  43. package/esm/app-workspace.js +7 -10
  44. package/esm/blueprint/blueprint-defaults.d.ts +9 -0
  45. package/esm/blueprint/blueprint-defaults.js +74 -0
  46. package/esm/blueprint/blueprint-schema.d.ts +68 -0
  47. package/esm/blueprint/blueprint-schema.js +134 -0
  48. package/esm/blueprint/field-type.d.ts +4 -0
  49. package/esm/blueprint/field-type.js +95 -0
  50. package/esm/blueprint/internal-policies.d.ts +1 -0
  51. package/esm/blueprint/internal-policies.js +7 -0
  52. package/esm/blueprint-construction.d.ts +10 -6
  53. package/esm/blueprint-construction.js +32 -24
  54. package/esm/context.d.ts +15 -0
  55. package/esm/context.js +133 -70
  56. package/esm/db-probe.d.ts +1 -1
  57. package/esm/db-probe.js +21 -6
  58. package/esm/failure.d.ts +89 -0
  59. package/esm/failure.js +362 -0
  60. package/esm/gate.d.ts +6 -4
  61. package/esm/gate.js +42 -14
  62. package/esm/graphql-http.d.ts +27 -6
  63. package/esm/graphql-http.js +96 -24
  64. package/esm/host.d.ts +33 -8
  65. package/esm/host.js +42 -2
  66. package/esm/index.d.ts +22 -12
  67. package/esm/index.js +21 -39
  68. package/esm/provision-database/env-file.d.ts +7 -0
  69. package/esm/provision-database/env-file.js +30 -0
  70. package/esm/provision-database/preset-match.js +1 -2
  71. package/esm/provision-database/provision.d.ts +21 -4
  72. package/esm/provision-database/provision.js +330 -85
  73. package/esm/provision-database/request-database.d.ts +22 -3
  74. package/esm/provision-database/request-database.js +46 -13
  75. package/esm/ready.d.ts +20 -0
  76. package/esm/ready.js +45 -0
  77. package/esm/run-codegen/barrels.js +1 -1
  78. package/esm/run-codegen/endpoints.js +5 -6
  79. package/esm/schema-model/normalize.js +1 -1
  80. package/esm/schema-model.js +4 -5
  81. package/esm/schema-resolve.d.ts +50 -0
  82. package/esm/schema-resolve.js +200 -14
  83. package/esm/table-access.d.ts +116 -0
  84. package/esm/table-access.js +418 -0
  85. package/esm/tools/access.d.ts +218 -0
  86. package/esm/tools/access.js +651 -0
  87. package/esm/tools/add-policies.d.ts +44 -12
  88. package/esm/tools/add-policies.js +84 -84
  89. package/esm/tools/add-records.d.ts +23 -2
  90. package/esm/tools/add-records.js +113 -75
  91. package/esm/tools/add-relation-schema.d.ts +5 -5
  92. package/esm/tools/add-relation-schema.js +13 -14
  93. package/esm/tools/add-relation.d.ts +11 -2
  94. package/esm/tools/add-relation.js +68 -31
  95. package/esm/tools/create-api-key.d.ts +18 -4
  96. package/esm/tools/create-api-key.js +105 -54
  97. package/esm/tools/describe-schema.d.ts +5 -7
  98. package/esm/tools/describe-schema.js +41 -118
  99. package/esm/tools/entity-types.d.ts +54 -0
  100. package/esm/tools/entity-types.js +233 -0
  101. package/esm/tools/index.d.ts +26 -0
  102. package/esm/tools/index.js +151 -0
  103. package/esm/tools/mutations.d.ts +36 -7
  104. package/esm/tools/mutations.js +245 -99
  105. package/esm/tools/provision-blueprint.d.ts +25 -1
  106. package/esm/tools/provision-blueprint.js +184 -42
  107. package/esm/tools/provision-database.d.ts +7 -5
  108. package/esm/tools/provision-database.js +31 -17
  109. package/esm/tools/run-codegen.d.ts +27 -4
  110. package/esm/tools/run-codegen.js +143 -76
  111. package/esm/tools/templates.d.ts +30 -7
  112. package/esm/tools/templates.js +166 -95
  113. package/failure.d.ts +89 -0
  114. package/failure.js +375 -0
  115. package/gate.d.ts +6 -4
  116. package/gate.js +41 -13
  117. package/graphql-http.d.ts +27 -6
  118. package/graphql-http.js +105 -25
  119. package/host.d.ts +33 -8
  120. package/host.js +45 -2
  121. package/index.d.ts +22 -12
  122. package/index.js +86 -43
  123. package/package.json +6 -5
  124. package/provision-database/env-file.d.ts +7 -0
  125. package/provision-database/env-file.js +32 -1
  126. package/provision-database/preset-match.js +1 -2
  127. package/provision-database/provision.d.ts +21 -4
  128. package/provision-database/provision.js +327 -81
  129. package/provision-database/request-database.d.ts +22 -3
  130. package/provision-database/request-database.js +49 -14
  131. package/ready.d.ts +20 -0
  132. package/ready.js +52 -0
  133. package/run-codegen/barrels.js +1 -1
  134. package/run-codegen/endpoints.js +5 -6
  135. package/schema-model/normalize.js +4 -4
  136. package/schema-model.js +4 -5
  137. package/schema-resolve.d.ts +50 -0
  138. package/schema-resolve.js +209 -14
  139. package/table-access.d.ts +116 -0
  140. package/table-access.js +437 -0
  141. package/tools/access.d.ts +218 -0
  142. package/tools/access.js +669 -0
  143. package/tools/add-policies.d.ts +44 -12
  144. package/tools/add-policies.js +86 -84
  145. package/tools/add-records.d.ts +23 -2
  146. package/tools/add-records.js +113 -74
  147. package/tools/add-relation-schema.d.ts +5 -5
  148. package/tools/add-relation-schema.js +13 -14
  149. package/tools/add-relation.d.ts +11 -2
  150. package/tools/add-relation.js +69 -31
  151. package/tools/create-api-key.d.ts +18 -4
  152. package/tools/create-api-key.js +104 -53
  153. package/tools/describe-schema.d.ts +5 -7
  154. package/tools/describe-schema.js +40 -117
  155. package/tools/entity-types.d.ts +54 -0
  156. package/tools/entity-types.js +240 -0
  157. package/tools/index.d.ts +26 -0
  158. package/tools/index.js +154 -0
  159. package/tools/mutations.d.ts +36 -7
  160. package/tools/mutations.js +252 -101
  161. package/tools/provision-blueprint.d.ts +25 -1
  162. package/tools/provision-blueprint.js +186 -43
  163. package/tools/provision-database.d.ts +7 -5
  164. package/tools/provision-database.js +33 -18
  165. package/tools/run-codegen.d.ts +27 -4
  166. package/tools/run-codegen.js +141 -73
  167. package/tools/templates.d.ts +30 -7
  168. package/tools/templates.js +167 -94
  169. package/esm/policy/add-policies-to-table.d.ts +0 -26
  170. package/esm/policy/add-policies-to-table.js +0 -66
  171. package/esm/policy/provision-helpers.d.ts +0 -38
  172. package/esm/policy/provision-helpers.js +0 -50
  173. package/esm/tools/manage-entity-types.d.ts +0 -40
  174. package/esm/tools/manage-entity-types.js +0 -201
  175. package/policy/add-policies-to-table.d.ts +0 -26
  176. package/policy/add-policies-to-table.js +0 -71
  177. package/policy/provision-helpers.d.ts +0 -38
  178. package/policy/provision-helpers.js +0 -58
  179. package/tools/manage-entity-types.d.ts +0 -40
  180. package/tools/manage-entity-types.js +0 -206
@@ -1,42 +1,79 @@
1
- import { expandBlueprintDefaults } from '@agentic-kit/harness';
1
+ import { expandBlueprintDefaults } from '../blueprint/blueprint-defaults';
2
2
  import { buildBlueprint } from '../blueprint-construction';
3
- import { resolveProjectContext } from '../context';
4
- import { resolveSchema, resolveTable } from '../schema-resolve';
3
+ import { DESCRIBE_SCHEMA, failedResult, failureFromError, failureText, noRowCreated, suggest } from '../failure';
4
+ import { ownedProjectReady } from '../ready';
5
+ import { resolveSchema, resolveTable, storedName, tablesTaken } from '../schema-resolve';
5
6
  import { AddRelationZod, buildRelation } from './add-relation-schema';
6
- function fail(message) {
7
- return { content: [{ type: 'text', text: message }], details: { success: false, message } };
7
+ /**
8
+ * What add_relation checks before it changes anything: its input, an owned
9
+ * project with both tables, and no field or junction table of the new name.
10
+ */
11
+ export async function addRelationReady(params, cwd) {
12
+ const type = params.relation_type ?? 'belongs_to';
13
+ if (type === 'belongs_to' && !params.field_name) {
14
+ return {
15
+ kind: 'failed',
16
+ failure: {
17
+ code: 'invalid-input',
18
+ message: 'A belongs_to relation needs the name of its foreign-key column on the source table.',
19
+ },
20
+ };
21
+ }
22
+ if (type === 'many_to_many' && !params.junction_table_name) {
23
+ return {
24
+ kind: 'failed',
25
+ failure: { code: 'invalid-input', message: 'A many_to_many relation needs the name of its junction table.' },
26
+ };
27
+ }
28
+ const ready = await ownedProjectReady(cwd);
29
+ if (ready.kind === 'failed')
30
+ return ready;
31
+ // Both tables must exist: a clearer error than the backend's, and no no-op blueprint.
32
+ let source;
33
+ try {
34
+ const schema = await resolveSchema(ready.value);
35
+ source = resolveTable(schema, params.source_table);
36
+ resolveTable(schema, params.target_table);
37
+ }
38
+ catch (err) {
39
+ return { kind: 'failed', failure: failureFromError(err, 'Failed to resolve schema') };
40
+ }
41
+ if (type === 'many_to_many') {
42
+ const taken = await tablesTaken(ready.value, [{ name: params.junction_table_name }]);
43
+ return taken ? { kind: 'failed', failure: taken } : ready;
44
+ }
45
+ if (source.fields.some((field) => field.name === (storedName(params.field_name) ?? params.field_name))) {
46
+ const again = Object.fromEntries(Object.entries(params).filter(([key]) => key !== 'field_name'));
47
+ return {
48
+ kind: 'failed',
49
+ failure: {
50
+ code: 'name-taken',
51
+ message: `Table "${params.source_table}" already has a field named "${params.field_name}".`,
52
+ hint: 'Call again with another field name.',
53
+ calls: [
54
+ suggest('add_relation', again, 'Add the relation under a field name the table does not have yet', ['field_name']),
55
+ ],
56
+ },
57
+ };
58
+ }
59
+ return ready;
60
+ }
61
+ function fail(failure) {
62
+ return failedResult(failure, { success: false, message: failureText(failure) });
8
63
  }
9
64
  export const addRelationTool = {
10
65
  name: 'add_relation',
11
66
  label: 'Add relation',
12
- 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 a single provision_blueprint call.',
67
+ 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.',
13
68
  promptSnippet: 'add_relation: link two existing tables (belongs_to FK column, or many_to_many junction). Gated.',
14
69
  parameters: AddRelationZod,
70
+ effect: 'write',
15
71
  async execute(params, ctx) {
72
+ const ready = await addRelationReady(params, ctx.cwd);
73
+ if (ready.kind === 'failed')
74
+ return fail(ready.failure);
16
75
  const type = params.relation_type ?? 'belongs_to';
17
- if (type === 'belongs_to' && !params.field_name) {
18
- return fail('field_name is required for a belongs_to relation (the FK column name on the source table).');
19
- }
20
- if (type === 'many_to_many' && !params.junction_table_name) {
21
- return fail('junction_table_name is required for a many_to_many relation.');
22
- }
23
- const resolved = await resolveProjectContext(ctx.cwd);
24
- if (!resolved.context)
25
- return fail(resolved.reason);
26
- const { modules, databaseId, schemaId, ownerId } = resolved.context;
27
- if (!ownerId)
28
- return fail('Not authenticated (missing OWNER_ID in .env).');
29
- // Validate both tables exist before constructing — a clearer error than the
30
- // backend's, and avoids a no-op blueprint.
31
- let schema;
32
- try {
33
- schema = await resolveSchema(resolved.context);
34
- resolveTable(schema, params.source_table);
35
- resolveTable(schema, params.target_table);
36
- }
37
- catch (err) {
38
- return fail(err instanceof Error ? err.message : 'Failed to resolve schema.');
39
- }
76
+ const { modules, databaseId, schemaId, ownerId } = ready.value;
40
77
  const definition = expandBlueprintDefaults({ tables: [], relations: buildRelation(params) });
41
78
  const uniqueName = `add_relation_${Date.now()}`;
42
79
  try {
@@ -55,11 +92,11 @@ export const addRelationTool = {
55
92
  .unwrap();
56
93
  const blueprintId = created.createBlueprint?.blueprint?.id;
57
94
  if (!blueprintId)
58
- throw new Error('Failed to create relation blueprint');
95
+ return fail(noRowCreated('Failed to add relation', DESCRIBE_SCHEMA));
59
96
  await buildBlueprint(modules, { blueprintId, schemaId }, { signal: ctx.signal });
60
97
  }
61
98
  catch (err) {
62
- return fail(`Failed to add relation: ${err instanceof Error ? err.message : String(err)}`);
99
+ return fail(failureFromError(err, 'Failed to add relation'));
63
100
  }
64
101
  const message = type === 'many_to_many'
65
102
  ? `Created junction table "${params.junction_table_name}" linking ${params.source_table} ↔ ${params.target_table}.`
@@ -1,12 +1,14 @@
1
- import type { HarnessTool } from '@agentic-kit/harness';
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.ZodString>>;
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.$strip>;
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 {};
@@ -1,18 +1,19 @@
1
+ import { idParam, strictObject, textParam } from '@agentic-kit/harness';
1
2
  import { auth } from '@constructive-io/sdk';
2
3
  import { z } from 'zod';
3
- import { deriveSubdomainEndpoint, resolveDataToken, resolveProjectContext } from '../context';
4
- import { classifyBackendErrors, errorsText, postGraphQL, statusAdapter, } from '../graphql-http';
4
+ import { deriveSubdomainEndpoint } from '../context';
5
+ import { failedResult, failureFromError, failureFromErrors, failureText, noRowCreated, suggest } from '../failure';
6
+ import { classifyBackendErrors, postGraphQL, statusAdapter } from '../graphql-http';
5
7
  import { getHost } from '../host';
6
- const CreateApiKeyZod = z.object({
7
- key_name: z
8
- .string()
8
+ import { appSessionReady, projectReady } from '../ready';
9
+ const CreateApiKeyZod = strictObject('the input', {
10
+ key_name: textParam()
9
11
  .describe('Name for the API key (e.g. "deploy bot"). The .env variable name derives from it (UPPER_SNAKE + _API_KEY).'),
10
- principal_name: z
11
- .string()
12
+ principal_name: textParam()
12
13
  .describe('Machine identity (principal) that owns the key. Defaults to key_name. An existing principal with this name is reused for unscoped keys.')
13
14
  .optional(),
14
15
  entity_ids: z
15
- .array(z.string())
16
+ .array(idParam())
16
17
  .describe('Entity row UUIDs to scope the principal to. Omit for a personal (unscoped) key that acts as the signed-in app user.')
17
18
  .optional(),
18
19
  read_only: z
@@ -26,11 +27,8 @@ const CreateApiKeyZod = z.object({
26
27
  .describe('Key lifetime in days. Default 90.')
27
28
  .optional(),
28
29
  });
29
- function fail(message, extra) {
30
- return {
31
- content: [{ type: 'text', text: message }],
32
- details: { success: false, message, ...extra },
33
- };
30
+ function fail(failure, extra) {
31
+ return failedResult(failure, { success: false, message: failureText(failure), ...extra });
34
32
  }
35
33
  export function toEnvVar(keyName) {
36
34
  const base = keyName
@@ -40,9 +38,7 @@ export function toEnvVar(keyName) {
40
38
  .replace(/^_+|_+$/g, '');
41
39
  return base.endsWith('_API_KEY') ? base : `${base}_API_KEY`;
42
40
  }
43
- export function isStepUpError(messages) {
44
- return messages.some((m) => /step[\s_-]?up/i.test(m));
45
- }
41
+ const needsStepUp = (errors) => errors.some((error) => error?.extensions?.code === 'STEP_UP_REQUIRED');
46
42
  export function describeScope(entityIds, readOnly) {
47
43
  const parts = [];
48
44
  parts.push(entityIds?.length
@@ -66,7 +62,7 @@ async function rawGraphql(endpoint, token, query, variables) {
66
62
  }
67
63
  const UNAVAILABLE_MESSAGE = 'The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. No key was minted.';
68
64
  const isSuspended = (errors) => Boolean(errors?.length) && classifyBackendErrors(errors) === 'suspended';
69
- const unavailable = () => fail(UNAVAILABLE_MESSAGE, { code: 'database-unavailable' });
65
+ const unavailable = () => fail({ code: 'database-unavailable', message: UNAVAILABLE_MESSAGE }, { code: 'database-unavailable' });
70
66
  async function createPrincipalInputFields(endpoint) {
71
67
  const probe = await rawGraphql(endpoint, undefined, '{ __type(name: "CreatePrincipalInput") { inputFields { name } } }');
72
68
  if (isSuspended(probe.errors))
@@ -74,37 +70,69 @@ async function createPrincipalInputFields(endpoint) {
74
70
  const type = probe.data?.__type;
75
71
  return new Set((type?.inputFields ?? []).map((f) => f.name));
76
72
  }
73
+ /**
74
+ * What create_api_key checks before it changes anything: a key name, the
75
+ * project on the data plane, a host that can deliver the secret, and an app
76
+ * sign-in.
77
+ */
78
+ export async function createApiKeyReady(params, cwd) {
79
+ const keyName = params.key_name?.trim();
80
+ if (!keyName) {
81
+ return { kind: 'failed', failure: { code: 'invalid-input', message: 'The key needs a name that is not blank.' } };
82
+ }
83
+ const ready = await projectReady(cwd, 'data');
84
+ if (ready.kind === 'failed')
85
+ return ready;
86
+ const { databaseName, apiEndpoint } = ready.value;
87
+ if (!databaseName) {
88
+ return {
89
+ kind: 'failed',
90
+ failure: {
91
+ code: 'missing-credentials',
92
+ message: 'Cannot resolve the app auth endpoint (DATABASE_NAME missing from .env).',
93
+ hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
94
+ },
95
+ };
96
+ }
97
+ if (!getHost().deliverSecret) {
98
+ return {
99
+ kind: 'failed',
100
+ failure: {
101
+ code: 'unsupported',
102
+ message: 'This host cannot deliver secrets (no .env write + reveal flow), so no key was minted.',
103
+ hint: 'Create the key from a host that supports secret delivery.',
104
+ },
105
+ };
106
+ }
107
+ const session = await appSessionReady(ready.value);
108
+ if (session.kind === 'failed')
109
+ return session;
110
+ const authEndpoint = deriveSubdomainEndpoint(apiEndpoint, `auth-${databaseName}`);
111
+ if (!authEndpoint) {
112
+ return { kind: 'failed', failure: { code: 'failed', message: `Cannot derive the app auth endpoint from ${apiEndpoint}.` } };
113
+ }
114
+ return { kind: 'ok', value: { context: ready.value, keyName, token: session.value.token, authEndpoint } };
115
+ }
77
116
  export const createApiKeyTool = {
78
117
  name: 'create_api_key',
79
118
  label: 'Create API key',
80
119
  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.',
81
120
  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.',
82
121
  parameters: CreateApiKeyZod,
122
+ effect: 'write',
83
123
  async execute(params, ctx) {
84
- const keyName = params.key_name?.trim();
85
- if (!keyName)
86
- return fail('create_api_key requires "key_name".');
87
- const resolved = await resolveProjectContext(ctx.cwd, { plane: 'data' });
88
- if (!resolved.context)
89
- return fail(resolved.reason);
90
- const { databaseId, databaseName, apiEndpoint } = resolved.context;
91
- if (!databaseName) {
92
- return fail('Cannot resolve the app auth endpoint (DATABASE_NAME missing from .env). Re-provision the database, then retry.');
124
+ const ready = await createApiKeyReady(params, ctx.cwd);
125
+ if (ready.kind === 'failed') {
126
+ return fail(ready.failure, ready.failure.code === 'app-signed-out' ? { needsAuth: true } : {});
93
127
  }
128
+ const { context, keyName, token, authEndpoint } = ready.value;
129
+ const { databaseId, databaseName, apiEndpoint } = context;
94
130
  const host = getHost();
95
- if (!host.deliverSecret) {
96
- 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.');
97
- }
98
- const token = await resolveDataToken(resolved.context);
99
- if (!token.token) {
100
- return fail(token.reason ?? 'Sign in to the app database to create an API key.', {
101
- needsAuth: true,
102
- });
103
- }
104
- const authEndpoint = deriveSubdomainEndpoint(apiEndpoint, `auth-${databaseName}`);
105
- if (!authEndpoint)
106
- return fail('Cannot derive the app auth endpoint.');
107
131
  const scoped = Boolean(params.entity_ids?.length) || params.read_only === true;
132
+ // The calls the refusals below suggest: the same key without its scope, or under a principal name still free.
133
+ const without = (keys) => Object.fromEntries(Object.entries(params).filter(([key]) => !keys.includes(key)));
134
+ const unscoped = suggest('create_api_key', without(['entity_ids', 'read_only']), 'Mint an unscoped key that acts as the signed-in app user');
135
+ const newPrincipal = suggest('create_api_key', without(['principal_name']), 'Mint the key under a principal name that is free', ['principal_name']);
108
136
  try {
109
137
  if (scoped) {
110
138
  const fields = await createPrincipalInputFields(authEndpoint);
@@ -115,11 +143,16 @@ export const createApiKeyTool = {
115
143
  ...(params.read_only === true && !fields.has('isReadOnly') ? ['isReadOnly'] : []),
116
144
  ];
117
145
  if (missing.length) {
118
- return fail(`This deployment does not support scoping a principal at create time (no ${missing.join(', ')} on createPrincipal). No key was minted. If an unscoped key that acts as the signed-in user is acceptable, ask for one explicitly.`);
146
+ return fail({
147
+ code: 'unsupported',
148
+ message: `This deployment does not support scoping a principal at create time (no ${missing.join(', ')} on createPrincipal). No key was minted.`,
149
+ hint: 'If an unscoped key that acts as the signed-in user is acceptable, call again without the scope and without read-only.',
150
+ calls: [unscoped],
151
+ });
119
152
  }
120
153
  }
121
154
  const dbAuth = auth.createClient({
122
- adapter: statusAdapter(authEndpoint, { Authorization: `Bearer ${token.token}` }),
155
+ adapter: statusAdapter(authEndpoint, { Authorization: `Bearer ${token}` }),
123
156
  });
124
157
  const principalName = params.principal_name?.trim() || keyName;
125
158
  const existing = await dbAuth.principal
@@ -132,7 +165,12 @@ export const createApiKeyTool = {
132
165
  // identity userId; principal_entity.principalId references the row id.
133
166
  let principalId = existing.principal?.userId;
134
167
  if (existing.principal && scoped) {
135
- return fail(`Principal "${principalName}" already exists, and its scope cannot be verified against the requested one. No key was minted. Use a new principal_name for a scoped key, or mint an unscoped key on the existing principal explicitly.`);
168
+ return fail({
169
+ code: 'name-taken',
170
+ message: `Principal "${principalName}" already exists, and its scope cannot be verified against the requested one. No key was minted.`,
171
+ 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.',
172
+ calls: [newPrincipal, unscoped],
173
+ });
136
174
  }
137
175
  if (existing.principal) {
138
176
  const scopeRow = await dbAuth.principalEntity
@@ -142,14 +180,19 @@ export const createApiKeyTool = {
142
180
  })
143
181
  .unwrap();
144
182
  if (scopeRow.principalEntity || existing.principal?.isReadOnly) {
145
- return fail(`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. Use a new principal_name for an unscoped key.`);
183
+ return fail({
184
+ code: 'name-taken',
185
+ 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.`,
186
+ hint: 'Call again with a new principal name.',
187
+ calls: [newPrincipal],
188
+ });
146
189
  }
147
190
  }
148
191
  if (!principalId) {
149
192
  // The SDK's PrincipalModel.create sends a nested {principal} input, but
150
193
  // the live CreatePrincipalInput is flat and its payload only exposes
151
194
  // `result: UUID` — raw GraphQL is the only working surface.
152
- const created = await rawGraphql(authEndpoint, token.token, 'mutation ($input: CreatePrincipalInput!) { createPrincipal(input: $input) { result } }', {
195
+ const created = await rawGraphql(authEndpoint, token, 'mutation ($input: CreatePrincipalInput!) { createPrincipal(input: $input) { result } }', {
153
196
  input: {
154
197
  name: principalName,
155
198
  ...(params.entity_ids?.length && { entityIds: params.entity_ids }),
@@ -158,13 +201,12 @@ export const createApiKeyTool = {
158
201
  });
159
202
  if (isSuspended(created.errors))
160
203
  return unavailable();
161
- if (created.errors?.length) {
162
- return fail(`createPrincipal failed: ${errorsText(created.errors)}`);
163
- }
204
+ if (created.errors?.length)
205
+ return fail(failureFromErrors(created.errors, 'createPrincipal failed'));
164
206
  const payload = created.data?.createPrincipal;
165
207
  principalId = payload?.result;
166
208
  if (!principalId)
167
- return fail('createPrincipal returned no principal id.');
209
+ return fail(noRowCreated(`Failed to create the principal "${principalName}"`));
168
210
  }
169
211
  const mint = () => dbAuth.mutation
170
212
  .createApiKey({
@@ -177,23 +219,32 @@ export const createApiKeyTool = {
177
219
  }, { select: { result: { select: { apiKey: true, keyId: true, expiresAt: true } } } })
178
220
  .execute();
179
221
  let minted = await mint();
180
- if (!minted.ok && isStepUpError(minted.errors.map((e) => e.message))) {
222
+ if (!minted.ok && needsStepUp(minted.errors)) {
181
223
  if (!host.requestStepUp) {
182
- return fail('Creating this key requires MFA step-up, and this host has no step-up flow. Complete step-up in the app (verify your password), then retry.');
224
+ return fail({
225
+ code: 'step-up-required',
226
+ message: 'Creating this key needs a recent sign-in of the app user, and this host cannot ask for one.',
227
+ hint: 'Sign in again in the app (verify your password), then retry.',
228
+ });
183
229
  }
184
230
  const verified = await host.requestStepUp({ databaseId, databaseName, apiEndpoint });
185
- if (!verified)
186
- return fail('Step-up verification was not completed. No key was minted.');
231
+ if (!verified) {
232
+ return fail({
233
+ code: 'failed',
234
+ message: 'Step-up verification was not completed. No key was minted.',
235
+ hint: 'Retry and complete the password check.',
236
+ });
237
+ }
187
238
  minted = await mint();
188
239
  }
189
240
  if (!minted.ok) {
190
241
  if (isSuspended(minted.errors))
191
242
  return unavailable();
192
- return fail(`createApiKey failed: ${errorsText(minted.errors)}`);
243
+ return fail(failureFromErrors(minted.errors, 'createApiKey failed'));
193
244
  }
194
245
  const record = minted.data?.createApiKey?.result;
195
246
  if (!record?.apiKey || !record.keyId)
196
- return fail('createApiKey returned no key.');
247
+ return fail(noRowCreated(`Failed to create API key "${keyName}"`));
197
248
  const envVar = toEnvVar(keyName);
198
249
  await host.deliverSecret({
199
250
  databaseId,
@@ -223,7 +274,7 @@ export const createApiKeyTool = {
223
274
  // The SDK's unwrap() throws its errors as `errors`.
224
275
  if (isSuspended(err?.errors))
225
276
  return unavailable();
226
- return fail(err instanceof Error ? err.message : 'Failed to create the API key.');
277
+ return fail(failureFromError(err, `Failed to create API key "${keyName}"`));
227
278
  }
228
279
  },
229
280
  };
@@ -1,16 +1,14 @@
1
1
  import { type HarnessTool } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
- declare const ParamZod: z.ZodObject<{}, z.core.$strip>;
4
- type SchemaField = {
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[];
@@ -1,130 +1,53 @@
1
- import { fieldTypeToTypeName, isInternalPolicy } from '@agentic-kit/harness';
2
- import { z } from 'zod';
3
- import { resolveProjectContext } from '../context';
4
- const ParamZod = z.object({});
5
- function toDefaultValueString(value) {
6
- if (value == null)
7
- return null;
8
- if (typeof value === 'string')
9
- return value;
10
- return JSON.stringify(value);
11
- }
1
+ import { alignColumns, strictObject } from '@agentic-kit/harness';
2
+ import { failedResult, failureFromError } from '../failure';
3
+ import { projectReady } from '../ready';
4
+ import { accessInputOf, asWritten, defaultText, readTables } from '../table-access';
5
+ const ParamZod = strictObject('the input', {});
6
+ const ruleCells = (rule) => [
7
+ rule.permissive ? 'rule' : 'limit',
8
+ rule.$type,
9
+ rule.privileges.join(' '),
10
+ rule.policy_role === 'authenticated' ? '' : `role ${rule.policy_role}`
11
+ ];
12
12
  function formatText(details) {
13
- const lines = [];
14
- if (details.tables.length === 0) {
15
- lines.push('No application tables yet.');
16
- }
17
- else {
18
- lines.push(`Tables (${details.tables.length}):`);
19
- for (const table of details.tables) {
20
- lines.push(` ${table.name}`);
21
- for (const field of table.fields) {
22
- const req = field.isRequired ? ' required' : '';
23
- const def = field.defaultValue != null ? ` default=${field.defaultValue}` : '';
24
- lines.push(` - ${field.name}: ${field.type}${req}${def}`);
25
- }
26
- if (table.policies.length > 0) {
27
- lines.push(` policies: ${table.policies.join(', ')}`);
28
- }
29
- }
30
- }
31
- return lines.join('\n');
13
+ if (details.tables.length === 0)
14
+ return 'No tables yet.';
15
+ const indent = (lines) => lines.map((line) => ` ${line}`);
16
+ return details.tables
17
+ .map((table) => [
18
+ table.name,
19
+ ...indent(alignColumns(table.fields.map((field) => [field.name, field.type, field.isRequired ? 'required' : '', defaultText(field.defaultValue)]))),
20
+ ...indent(alignColumns(table.policyRules.map(ruleCells)))
21
+ ].join('\n'))
22
+ .join('\n\n');
32
23
  }
33
24
  export const describeSchemaTool = {
34
25
  name: 'describe_schema',
35
26
  label: 'Describe schema',
36
- description: 'Inspect the current Constructive database schema for this project: application tables with their fields (name, type, required, default). Read-only.',
27
+ 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.',
37
28
  promptSnippet: 'describe_schema: list the project database tables and their fields. Read-only — call before modifying schema.',
38
29
  parameters: ParamZod,
30
+ effect: 'read',
39
31
  async execute(_params, ctx) {
40
- const resolved = await resolveProjectContext(ctx.cwd);
41
- if (!resolved.context) {
42
- return {
43
- content: [{ type: 'text', text: resolved.reason }],
44
- details: { tables: [] },
45
- };
32
+ const ready = await projectReady(ctx.cwd);
33
+ if (ready.kind === 'failed')
34
+ return failedResult(ready.failure, { tables: [] });
35
+ try {
36
+ return await describeTables(ready.value);
46
37
  }
47
- const { api, databaseId } = resolved.context;
48
- const tablesResult = await api.table
49
- .findMany({
50
- select: { id: true, name: true, category: true },
51
- where: {
52
- databaseId: { equalTo: databaseId },
53
- or: [{ category: { equalTo: 'APP' } }, { name: { equalTo: 'users' } }],
54
- },
55
- orderBy: ['NAME_ASC'],
56
- })
57
- .execute();
58
- if (!tablesResult.ok) {
59
- const message = tablesResult.errors.map((e) => e.message).join('; ');
60
- return {
61
- content: [{ type: 'text', text: `Failed to read schema: ${message}` }],
62
- details: { tables: [] },
63
- };
38
+ catch (err) {
39
+ return failedResult(failureFromError(err, 'Failed to read schema'), { tables: [] });
64
40
  }
65
- const tableNodes = tablesResult.data.tables?.nodes ?? [];
66
- const tableIds = tableNodes.map((t) => t.id);
67
- const fieldsByTable = new Map();
68
- const policiesByTable = new Map();
69
- if (tableIds.length > 0) {
70
- const [fieldsResult, policiesResult] = await Promise.all([
71
- api.field
72
- .findMany({
73
- select: {
74
- name: true,
75
- type: true,
76
- isRequired: true,
77
- defaultValue: true,
78
- tableId: true,
79
- },
80
- where: { tableId: { in: tableIds } },
81
- })
82
- .execute(),
83
- api.policy
84
- .findMany({
85
- select: { tableId: true, policyType: true },
86
- where: { tableId: { in: tableIds } },
87
- })
88
- .execute(),
89
- ]);
90
- if (!fieldsResult.ok) {
91
- const message = fieldsResult.errors.map((e) => e.message).join('; ');
92
- return {
93
- content: [{ type: 'text', text: `Failed to read fields: ${message}` }],
94
- details: { tables: [] },
95
- };
96
- }
97
- for (const field of fieldsResult.data.fields?.nodes ?? []) {
98
- const list = fieldsByTable.get(field.tableId) ?? [];
99
- list.push({
100
- name: field.name,
101
- type: fieldTypeToTypeName(field.type),
102
- isRequired: Boolean(field.isRequired),
103
- defaultValue: toDefaultValueString(field.defaultValue),
104
- });
105
- fieldsByTable.set(field.tableId, list);
106
- }
107
- // One policy spans CRUD as several rows; collapse to distinct types per table.
108
- if (policiesResult.ok) {
109
- for (const policy of policiesResult.data.policies?.nodes ?? []) {
110
- if (isInternalPolicy(policy.policyType))
111
- continue;
112
- const list = policiesByTable.get(policy.tableId) ?? [];
113
- if (!list.includes(policy.policyType))
114
- list.push(policy.policyType);
115
- policiesByTable.set(policy.tableId, list);
116
- }
117
- }
118
- }
119
- const tables = tableNodes.map((table) => ({
120
- name: table.name,
121
- fields: fieldsByTable.get(table.id) ?? [],
122
- policies: policiesByTable.get(table.id) ?? [],
123
- }));
124
- const details = { tables };
125
- return {
126
- content: [{ type: 'text', text: formatText(details) }],
127
- details,
128
- };
129
41
  },
130
42
  };
43
+ async function describeTables(context) {
44
+ const read = await readTables(context);
45
+ if (read.kind === 'failed')
46
+ return failedResult(read.failure, { tables: [] });
47
+ const tables = read.value.map((table) => {
48
+ const policyRules = accessInputOf(table).policies.map(asWritten);
49
+ return { name: table.name, fields: table.fields, policies: [...new Set(policyRules.map((rule) => rule.$type))], policyRules };
50
+ });
51
+ const details = { tables };
52
+ return { content: [{ type: 'text', text: formatText(details) }], details };
53
+ }