@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.
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,46 +1,84 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.addRelationTool = void 0;
4
- const harness_1 = require("@agentic-kit/harness");
4
+ exports.addRelationReady = addRelationReady;
5
+ const blueprint_defaults_1 = require("../blueprint/blueprint-defaults");
5
6
  const blueprint_construction_1 = require("../blueprint-construction");
6
- const context_1 = require("../context");
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
- function fail(message) {
10
- return { content: [{ type: 'text', text: message }], details: { success: false, message } };
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 a single provision_blueprint call.',
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
- if (type === 'belongs_to' && !params.field_name) {
21
- return fail('field_name is required for a belongs_to relation (the FK column name on the source table).');
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
- throw new Error('Failed to create relation blueprint');
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(`Failed to add relation: ${err instanceof Error ? err.message : String(err)}`);
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 { 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 {};
@@ -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 CreateApiKeyZod = zod_1.z.object({
13
- key_name: zod_1.z
14
- .string()
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: zod_1.z
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(zod_1.z.string())
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(message, extra) {
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
- function isStepUpError(messages) {
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 keyName = params.key_name?.trim();
91
- if (!keyName)
92
- return fail('create_api_key requires "key_name".');
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(`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.`);
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.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(`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.`);
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(`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.`);
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.token, 'mutation ($input: CreatePrincipalInput!) { createPrincipal(input: $input) { result } }', {
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(`createPrincipal failed: ${(0, graphql_http_1.errorsText)(created.errors)}`);
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('createPrincipal returned no principal id.');
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 && isStepUpError(minted.errors.map((e) => e.message))) {
228
+ if (!minted.ok && needsStepUp(minted.errors)) {
187
229
  if (!host.requestStepUp) {
188
- 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.');
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('Step-up verification was not completed. No key was minted.');
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(`createApiKey failed: ${(0, graphql_http_1.errorsText)(minted.errors)}`);
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('createApiKey returned no key.');
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(err instanceof Error ? err.message : 'Failed to create the API key.');
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
- 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[];
@@ -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 zod_1 = require("zod");
6
- const context_1 = require("../context");
7
- const ParamZod = zod_1.z.object({});
8
- function toDefaultValueString(value) {
9
- if (value == null)
10
- return null;
11
- if (typeof value === 'string')
12
- return value;
13
- return JSON.stringify(value);
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
- const lines = [];
17
- if (details.tables.length === 0) {
18
- lines.push('No application tables yet.');
19
- }
20
- else {
21
- lines.push(`Tables (${details.tables.length}):`);
22
- for (const table of details.tables) {
23
- lines.push(` ${table.name}`);
24
- for (const field of table.fields) {
25
- const req = field.isRequired ? ' required' : '';
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 resolved = await (0, context_1.resolveProjectContext)(ctx.cwd);
44
- if (!resolved.context) {
45
- return {
46
- content: [{ type: 'text', text: resolved.reason }],
47
- details: { tables: [] },
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
- const { api, databaseId } = resolved.context;
51
- const tablesResult = await api.table
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
+ }