@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
@@ -4,6 +4,7 @@
4
4
  // deleted or suspended database) reads the same as any other refusal. Here
5
5
  // the body's errors keep their `extensions.code`, and every error carries the
6
6
  // HTTP status it arrived with.
7
+ import { listed } from '@agentic-kit/harness';
7
8
  import { createFetch, } from '@constructive-io/graphql-query/runtime';
8
9
  const errorText = (err) => (err instanceof Error ? err.message : String(err));
9
10
  export async function postGraphQL(args) {
@@ -17,7 +18,11 @@ export async function postGraphQL(args) {
17
18
  Accept: 'application/json',
18
19
  ...args.headers,
19
20
  },
20
- body: JSON.stringify({ query: args.query, variables: args.variables ?? {} }),
21
+ body: JSON.stringify({
22
+ query: args.query,
23
+ variables: args.variables ?? {},
24
+ ...(args.operationName === undefined ? {} : { operationName: args.operationName }),
25
+ }),
21
26
  });
22
27
  }
23
28
  catch (err) {
@@ -34,6 +39,8 @@ export async function postGraphQL(args) {
34
39
  };
35
40
  }
36
41
  const httpStatus = response.status;
42
+ const retryAfter = retryAfterSeconds(response.headers?.get?.('Retry-After') ?? null);
43
+ const waited = retryAfter === undefined ? {} : { retryAfterSeconds: retryAfter };
37
44
  let body = null;
38
45
  try {
39
46
  body = (await response.json());
@@ -49,7 +56,7 @@ export async function postGraphQL(args) {
49
56
  errors: bodyErrors.map((error) => ({
50
57
  ...error,
51
58
  message: error?.message ?? '',
52
- extensions: { ...error?.extensions, httpStatus },
59
+ extensions: { ...error?.extensions, httpStatus, ...waited },
53
60
  })),
54
61
  };
55
62
  }
@@ -61,7 +68,7 @@ export async function postGraphQL(args) {
61
68
  errors: [
62
69
  {
63
70
  message: response.ok ? `HTTP ${httpStatus}${text} (the body was not JSON)` : `HTTP ${httpStatus}${text}`,
64
- extensions: { code: 'HTTP_ERROR', httpStatus },
71
+ extensions: { code: 'HTTP_ERROR', httpStatus, ...waited },
65
72
  },
66
73
  ],
67
74
  };
@@ -87,26 +94,61 @@ export function statusAdapter(endpoint, headers, fetchFn) {
87
94
  getEndpoint: () => endpoint,
88
95
  };
89
96
  }
97
+ // The backend's own codes for a request it limits (admission-control.ts), which it answers with 429.
98
+ const LIMITED = new Set(['RATE_LIMITED', 'CONCURRENCY_LIMIT_REACHED']);
99
+ /** Whether the backend limited the request (a 429, or its code): the step is to wait. */
100
+ export const isRateLimited = (error) => LIMITED.has(codeOf(error) ?? '') || statusOf(error) === 429;
101
+ /** The seconds the backend asked to wait (its Retry-After), when it said. */
102
+ export function retryAfterOf(errors) {
103
+ const seconds = (errors ?? []).map((error) => error?.extensions?.retryAfterSeconds).find((value) => typeof value === 'number');
104
+ return seconds;
105
+ }
106
+ // Retry-After is seconds, or an HTTP date.
107
+ function retryAfterSeconds(value) {
108
+ if (!value)
109
+ return undefined;
110
+ if (/^\d+$/.test(value.trim()))
111
+ return Number(value.trim());
112
+ const at = Date.parse(value);
113
+ return Number.isNaN(at) ? undefined : Math.max(0, Math.ceil((at - Date.now()) / 1000));
114
+ }
115
+ // The code of a public error. An internal error may keep a public-looking
116
+ // code (FORBIDDEN) over a masked message, so its code means nothing.
90
117
  const codeOf = (error) => {
91
118
  const code = error?.extensions?.code;
92
- return typeof code === 'string' ? code : undefined;
119
+ return typeof code === 'string' && error?.extensions?.class !== 'internal' ? code : undefined;
93
120
  };
94
- // The status an error arrived with: ours from extensions, or the SDK
95
- // adapter's `HTTP 503: …` message.
96
- const statusOf = (error) => {
97
- const status = error?.extensions?.httpStatus;
98
- if (typeof status === 'number')
99
- return status;
121
+ /**
122
+ * The HTTP status of one error: the one the server put inside it
123
+ * (`extensions.http`, since it answers every GraphQL request with HTTP 200),
124
+ * else the response's own (`extensions.httpStatus`, added by `postGraphQL`),
125
+ * else the one in the SDK FetchAdapter's "HTTP 503: …" message, which drops
126
+ * the body.
127
+ */
128
+ export function statusOf(error) {
129
+ for (const status of [error?.extensions?.http, error?.extensions?.httpStatus]) {
130
+ if (typeof status === 'number')
131
+ return status;
132
+ }
100
133
  const match = /^HTTP (\d{3})\b/.exec(error?.message ?? '');
101
134
  return match ? Number(match[1]) : undefined;
102
- };
103
- const AUTH_MESSAGE_RE = /jwt|unauthenticated|invalid token/i;
104
- const FORBIDDEN_MESSAGE_RE = /permission denied/i;
135
+ }
105
136
  /**
106
- * What a failed backend answer says, first match wins: the database is
107
- * suspended or gone (`ACCESS_SUSPENDED`), no response, the backend failing
108
- * (5xx, 429), a rejected credential (401), a refusal (403), or anything else.
137
+ * What a failed backend answer says, by its code and status, first match
138
+ * wins: the database is suspended or gone (`ACCESS_SUSPENDED`), no response,
139
+ * the backend limiting requests (429), the backend failing (5xx), a rejected credential (401,
140
+ * `UNAUTHENTICATED`), a refusal (403, `FORBIDDEN`), or anything else.
109
141
  */
142
+ const SIGNED_OUT_CODES = new Set(['UNAUTHENTICATED', 'NOT_AUTHENTICATED', 'USER_NOT_AUTHENTICATED']);
143
+ /** Whether a public code says the request's sign-in has ended or is missing (packages/errors registry). */
144
+ export const isSignedOutCode = (code) => SIGNED_OUT_CODES.has(code ?? '');
145
+ /** Whether an error says the backend did not accept the request's credential: one of those codes, or a 401. */
146
+ export const isSignedOut = (error) => statusOf(error) === 401 || isSignedOutCode(codeOf(error));
147
+ /** Whether a thrown SDK error carries an answer that says so. */
148
+ export const answersSignedOut = (err) => {
149
+ const errors = err?.errors;
150
+ return Array.isArray(errors) && errors.some(isSignedOut);
151
+ };
110
152
  export function classifyBackendErrors(errors) {
111
153
  const list = errors ?? [];
112
154
  const some = (test) => list.some((error) => test(error));
@@ -114,21 +156,51 @@ export function classifyBackendErrors(errors) {
114
156
  return 'suspended';
115
157
  if (some((e) => codeOf(e) === 'NETWORK'))
116
158
  return 'network';
159
+ if (some(isRateLimited))
160
+ return 'rate-limited';
117
161
  if (some((e) => {
118
162
  const status = statusOf(e);
119
- return status !== undefined && (status >= 500 || status === 429);
163
+ return status !== undefined && status >= 500;
120
164
  })) {
121
165
  return 'server';
122
166
  }
123
- if (some((e) => statusOf(e) === 401 || codeOf(e) === 'UNAUTHENTICATED' || AUTH_MESSAGE_RE.test(e?.message ?? ''))) {
167
+ if (some(isSignedOut))
124
168
  return 'auth';
125
- }
126
- if (some((e) => statusOf(e) === 403 || codeOf(e) === 'FORBIDDEN' || FORBIDDEN_MESSAGE_RE.test(e?.message ?? ''))) {
169
+ if (some((e) => statusOf(e) === 403 || codeOf(e) === 'FORBIDDEN'))
127
170
  return 'forbidden';
128
- }
129
171
  return 'graphql';
130
172
  }
131
- /** The messages of a failed answer, joined for a reason string. */
132
- export function errorsText(errors) {
133
- return (errors ?? []).map((error) => error?.message || codeOf(error) || 'unknown error').join('; ');
173
+ // A code a server means for its caller is a word in capitals (FORBIDDEN, UNIQUE_VIOLATION). A database error's own
174
+ // code has a digit in its first word, so it is never named.
175
+ const PUBLIC_CODE = /^[A-Z]+(?:_[A-Z0-9]+)*$/;
176
+ // One error in fixed words: a logged error by its id, else its public code, else its HTTP status.
177
+ function errorWords(error) {
178
+ const id = error?.extensions?.errorId;
179
+ if (typeof id === 'string')
180
+ return `an internal error (error id ${id})`;
181
+ const code = codeOf(error);
182
+ if (code && PUBLIC_CODE.test(code))
183
+ return `the code ${code}`;
184
+ const status = statusOf(error);
185
+ return status === undefined || status === 200 ? 'an error without a public code' : `HTTP ${status}`;
186
+ }
187
+ /**
188
+ * What a failed answer was, in fixed words: each error's public code, HTTP status or error id. The text a server writes
189
+ * is never in them, since a server can pass the database's own text through, with internal table names and error
190
+ * codes. Only a request that got no answer keeps its text, which postGraphQL made from the local fetch failure.
191
+ */
192
+ export function answerText(errors) {
193
+ const list = errors ?? [];
194
+ const unanswered = list.find((error) => codeOf(error) === 'NETWORK' && error?.extensions?.httpStatus === undefined);
195
+ if (unanswered)
196
+ return `the backend did not answer (${unanswered.message || 'no response'})`;
197
+ const words = [...new Set(list.map(errorWords))];
198
+ return `the backend answered with ${words.length ? listed(words) : 'an error without a public code'}`;
199
+ }
200
+ /** A thrown error in words that hold no server text: an SDK error by its GraphQL errors, any other by its own message. */
201
+ export function thrownText(err) {
202
+ const errors = err?.errors;
203
+ if (Array.isArray(errors) && errors.length > 0)
204
+ return answerText(errors);
205
+ return err instanceof Error ? err.message : String(err);
134
206
  }
package/esm/host.d.ts CHANGED
@@ -10,8 +10,14 @@
10
10
  * Nothing here is harness-specific: the host is the *application* a tool acts
11
11
  * on behalf of, so the same contract serves whichever adapter runs the tools.
12
12
  */
13
+ import type { PlanAgent, ToolCallSuggestion } from '@agentic-kit/harness';
14
+ import { type Result } from './failure';
13
15
  export type HostAccount = {
14
16
  userId: string;
17
+ /** Shown beside the user id in a plan, when the host knows it. */
18
+ email?: string;
19
+ /** The agent of the person the session acts as, when it acts as one; a plan names it beside the account. */
20
+ agent?: PlanAgent;
15
21
  accessToken: string;
16
22
  apiKey?: string;
17
23
  };
@@ -99,8 +105,11 @@ export type ProjectBinding = {
99
105
  skipped?: boolean;
100
106
  };
101
107
  export interface ToolsHost {
102
- /** Signed-in platform account, or null/undefined when signed out. */
103
- account(): HostAccount | null | undefined;
108
+ /**
109
+ * Signed-in platform account, or null/undefined when signed out. It may be a promise: a host that mints a
110
+ * short-lived token answers once it has one. A rejection reads as signed out, like a throw.
111
+ */
112
+ account(): HostAccount | null | undefined | Promise<HostAccount | null | undefined>;
104
113
  /** Host-configured backend endpoints (env-aware). */
105
114
  backendConfig(): HostBackendConfig | null | undefined;
106
115
  /** Optional data-plane token broker (see DataAuthBroker). */
@@ -142,17 +151,25 @@ export interface ToolsHost {
142
151
  deliverSecret?(delivery: SecretDelivery): Promise<void>;
143
152
  /**
144
153
  * What to tell the agent to do about a database that is gone or belongs to
145
- * another account, in place of the default advice to call
146
- * provision_database with `reprovision: true`.
154
+ * another account, in place of the default advice to bind the directory to
155
+ * a new database.
147
156
  */
148
157
  reprovisionHint?: string;
149
158
  /**
150
- * Whether the agent may replace a binding through provision_database's
151
- * `reprovision: true`. Default true. A host that replaces databases only
152
- * after the user approves (calling `provisionDatabase` in replace mode
153
- * itself) sets false, and the tool then refuses.
159
+ * Whether the agent may replace a binding through replace_database. Default
160
+ * true. A host that replaces databases only after the user approves (calling
161
+ * `provisionDatabase` in replace mode itself) sets false, and the tool then
162
+ * refuses.
154
163
  */
155
164
  toolReprovision?: boolean;
165
+ /**
166
+ * Whether the tools prepare packages/app: provision_database clones the app
167
+ * template and installs it while the backend provisions, and run_codegen
168
+ * creates or installs the app it generates into. Default true. A host that
169
+ * prepares the app itself, or not at all, sets false: then nothing is cloned
170
+ * or installed, and run_codegen only generates into an app that is there.
171
+ */
172
+ prewarmApp?: boolean;
156
173
  /**
157
174
  * Save a binding in the host's own store. Provisioning calls it before
158
175
  * writing `.env`, on a new binding and on a kept one (`skipped`). If it
@@ -164,5 +181,13 @@ export interface ToolsHost {
164
181
  export declare const DEFAULT_DATA_TOKEN_SKEW_MS = 30000;
165
182
  /** The advice for a database that is gone or under another account. */
166
183
  export declare function reprovisionAdvice(host: ToolsHost): string;
184
+ /** The call that binds the directory to a new database in place of its own, when the agent may make it. */
185
+ export declare function replaceCall(host: ToolsHost): {
186
+ calls?: ToolCallSuggestion[];
187
+ };
167
188
  export declare function configureHost(host: ToolsHost): void;
189
+ /** The host's backend config, or `no-backend` when the host could not give it. */
190
+ export declare function readBackendConfig(host: ToolsHost): Result<HostBackendConfig | null | undefined>;
191
+ /** The signed-in account, or `signed-out` when the host could not give it (it threw, or its promise rejected). */
192
+ export declare function readAccount(host: ToolsHost): Promise<Result<HostAccount | null | undefined>>;
168
193
  export declare function getHost(): ToolsHost;
package/esm/host.js CHANGED
@@ -10,15 +10,17 @@
10
10
  * Nothing here is harness-specific: the host is the *application* a tool acts
11
11
  * on behalf of, so the same contract serves whichever adapter runs the tools.
12
12
  */
13
+ import { failureText, noBackendFailure, suggest } from './failure';
14
+ import { thrownText } from './graphql-http';
13
15
  /**
14
16
  * The tools never default to a backend: with no configured endpoint they fail
15
17
  * and say so, rather than sending the account credential to a guessed host.
16
18
  */
17
19
  export function noBackendReason(hint) {
18
- return `No Constructive backend is configured. ${hint ?? 'Choose a backend in the app, then retry.'}`;
20
+ return failureText(noBackendFailure(hint));
19
21
  }
20
22
  export const DEFAULT_DATA_TOKEN_SKEW_MS = 30_000;
21
- const DEFAULT_REPROVISION_ADVICE = 'Re-provision with provision_database (reprovision: true): the schema is rebuilt from the project, and records do not carry over.';
23
+ const DEFAULT_REPROVISION_ADVICE = 'Bind the directory to a new database in place of this one: the schema is rebuilt from the project, and records do not carry over.';
22
24
  /** The advice for a database that is gone or under another account. */
23
25
  export function reprovisionAdvice(host) {
24
26
  if (host.reprovisionHint)
@@ -27,10 +29,48 @@ export function reprovisionAdvice(host) {
27
29
  return 'Ask the user to re-provision it from the app.';
28
30
  return DEFAULT_REPROVISION_ADVICE;
29
31
  }
32
+ /** The call that binds the directory to a new database in place of its own, when the agent may make it. */
33
+ export function replaceCall(host) {
34
+ return host.toolReprovision === false ? {} : { calls: [suggest('replace_database', {}, 'Bind the directory to a new, empty database in place of this one', ['database_name'])] };
35
+ }
30
36
  let currentHost = null;
31
37
  export function configureHost(host) {
32
38
  currentHost = host;
33
39
  }
40
+ // A host callback may throw (a backend override that is not a URL, a locked
41
+ // keychain); a tool returns a failure instead.
42
+ /** The host's backend config, or `no-backend` when the host could not give it. */
43
+ export function readBackendConfig(host) {
44
+ try {
45
+ return { kind: 'ok', value: host.backendConfig() };
46
+ }
47
+ catch (err) {
48
+ return {
49
+ kind: 'failed',
50
+ failure: {
51
+ code: 'no-backend',
52
+ message: `Could not read the backend settings: ${thrownText(err)}`,
53
+ hint: 'Fix the backend settings, then retry.',
54
+ },
55
+ };
56
+ }
57
+ }
58
+ /** The signed-in account, or `signed-out` when the host could not give it (it threw, or its promise rejected). */
59
+ export async function readAccount(host) {
60
+ try {
61
+ return { kind: 'ok', value: await host.account() };
62
+ }
63
+ catch (err) {
64
+ return {
65
+ kind: 'failed',
66
+ failure: {
67
+ code: 'signed-out',
68
+ message: `Could not read the signed-in account: ${thrownText(err)}`,
69
+ hint: host.signInHint ?? 'Sign in again, then retry.',
70
+ },
71
+ };
72
+ }
73
+ }
34
74
  export function getHost() {
35
75
  if (!currentHost) {
36
76
  throw new Error('@agentic-kit/db-tools host not configured. Call configureHost() (or createDbTools(host)) before using the db tools.');
package/esm/index.d.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  import type { AnyHarnessTool } from '@agentic-kit/harness';
2
2
  import { type ToolsHost } from './host';
3
- /**
4
- * The Constructive database tools, in registration order.
5
- *
6
- * Plain `HarnessTool`s: a harness gets them by mapping them into its own tool
7
- * shape, which is the adapter's job, so this package stays free of any harness
8
- * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding).
9
- */
10
- export declare const constructiveDbTools: readonly AnyHarnessTool[];
3
+ import { constructiveDbTools } from './tools';
4
+ export { constructiveDbTools };
11
5
  /** Configure the host and get the tools in one call. */
12
6
  export declare function createConstructiveDbTools(host: ToolsHost): readonly AnyHarnessTool[];
7
+ export { ACCESS_CHECKS, type AccessCheck, type AccessFinding, accessFindings, type AccessOperation, ADDED_FIELDS, type AddedColumn, type AddedDefault, type AddedField, BUILT_IN_SCOPES, checkRule, type ColumnGap, columnGaps, type ColumnRead, columnsReadByPolicies, type DataNodeNeed, dataNodesForPolicies, defaultFills, DERIVED_KEYS, explainPolicy, fieldsAddedByNodes, type MembershipScope, type NeededDataNode, POLICY_ROLES, POLICY_WORDS, policyDifference, type PolicyWordsTemplate, type ResolvedPolicy, resolveEntityTypes, ROW_ID, type RuleProblem, TABLE_NEEDS, type TableAccessInput, type TableField, type TableKind, type TablePolicy, tablePolicyFromBlueprint, type TablePrivilege, } from './access';
8
+ export { expandBlueprintDefaults } from './blueprint/blueprint-defaults';
9
+ export { type AccessPolicy, AccessPolicyZod, AuthzTypeZod, type Blueprint, blueprintProblems, BlueprintZod, type FieldBlueprint, type TableBlueprint, } from './blueprint/blueprint-schema';
10
+ export { fieldTypeToTypeName, toFieldDefault, toFieldType } from './blueprint/field-type';
11
+ export { isInternalPolicy } from './blueprint/internal-policies';
13
12
  export { BlueprintBuildError, buildBlueprint, CONSTRUCTION_DEADLINE_MS, type ConstructionTableMap, readConstructionFailure, waitForConstruction, type WaitForConstructionOptions, } from './blueprint-construction';
14
13
  export { CONTEXT_ENV_KEYS, CONTEXT_ENV_PREFIX, type ContextEnvKey, type ContextSource, deriveSubdomainEndpoint, fromEnvFile, fromEnvironment, type ModulesClient, type ProjectContext, type ProjectContextFailureCode, resolveDataToken, resolveProjectContext, type ResolveResult, } from './context';
15
14
  export { type DatabaseProbe, probeBoundDatabase, probeDatabase, type UnreachableCause, } from './db-probe';
15
+ export { failureFromErrors, type FailureMeaning } from './failure';
16
16
  export { constructiveGateDeps, type ConstructiveGateResolvers } from './gate';
17
17
  export { type BackendErrorKind, classifyBackendErrors, type HttpGraphQLResponse, postGraphQL, statusAdapter, } from './graphql-http';
18
+ export { type PostGraphQLArgs } from './graphql-http';
18
19
  export { type ActiveDataToken, configureHost, type DataAuthBroker, DEFAULT_DATA_TOKEN_SKEW_MS, getHost, type HostAccount, type HostBackendConfig, type HostProvisionOverlay, noBackendReason, type PreviewToken, type ProjectBinding, type SecretDelivery, type StepUpRequest, type ToolsHost, } from './host';
19
20
  export { archiveBindingKeys, ARCHIVED_BINDING_KEYS, type EnvVars, mergeEnv, provisionEnvVars, readEnv, } from './provision-database/env-file';
20
21
  export { loadProvisionManifest, parseProvisionManifest, PROVISION_MANIFEST_FILE, type ProvisionManifest, } from './provision-database/manifest';
@@ -22,9 +23,18 @@ export { allModulePresets, DEFAULT_PROVISION_PRESET, getModulePreset, type Modul
22
23
  export { provisionDatabase, type ProvisionDatabaseDetails, type ProvisionFailureCode, type ProvisionInput, } from './provision-database/provision';
23
24
  export { moduleKey, type ProvisionOverlay, resolveProvisionModules, } from './provision-database/resolve';
24
25
  export { accessOf, type ColumnDefault, type FkAction, type ModelColumn, type ModelForeignKey, type ModelPolicy, type ModelTable, type ObjectCategory, readSchemaModel, type SchemaModel, SchemaReadError, type TableAccess, } from './schema-model';
26
+ export { accessState, asWritten, grantWords, planRule, ruleWords, type WrittenRule } from './table-access';
25
27
  export { toolSchema } from './tool-schema';
26
- export { type AddRecordsDetails } from './tools/add-records';
27
- export { type CreateApiKeyDetails } from './tools/create-api-key';
28
- export { type RunCodegenDetails, type RunCodegenTimings } from './tools/run-codegen';
29
- export { createTemplatePreviewTables } from './tools/templates';
28
+ export { describePolicyTypeTool, explainAccessTool, type ExplainedRule, type ExplainedTable, setAccessTool } from './tools/access';
29
+ export { type AddPoliciesDetails, addPoliciesTool } from './tools/add-policies';
30
+ export { type AddRecordsDetails, addRecordsTool } from './tools/add-records';
31
+ export { type AddRelationDetails, addRelationTool } from './tools/add-relation';
32
+ export { type CreateApiKeyDetails, createApiKeyTool } from './tools/create-api-key';
33
+ export { type DescribeSchemaDetails, describeSchemaTool } from './tools/describe-schema';
34
+ export { createEntityTypeTool, deleteEntityTypeTool, type EntityTypesDetails, type EntityTypeSummary, listEntityTypesTool } from './tools/entity-types';
35
+ export { createFieldTool, deleteFieldTool, deleteTableTool, type MutationDetails, retypeFieldTool, updateFieldTool, } from './tools/mutations';
36
+ export { type ProvisionBlueprintDetails, provisionBlueprintTool } from './tools/provision-blueprint';
37
+ export { provisionDatabaseTool, replaceDatabaseTool } from './tools/provision-database';
38
+ export { type RunCodegenDetails, type RunCodegenTimings, runCodegenTool } from './tools/run-codegen';
39
+ export { applyTemplateTool, type CreateTemplateDetails, createTemplatePreviewTables, createTemplateTool, deleteTemplateTool, type ListTemplatesDetails, listTemplatesTool, type TemplateDetails, updateTemplateTool, } from './tools/templates';
30
40
  export default constructiveDbTools;
package/esm/index.js CHANGED
@@ -1,50 +1,20 @@
1
1
  import { configureHost } from './host';
2
- import { addPoliciesTool } from './tools/add-policies';
3
- import { addRecordsTool } from './tools/add-records';
4
- import { addRelationTool } from './tools/add-relation';
5
- import { createApiKeyTool } from './tools/create-api-key';
6
- import { describeSchemaTool } from './tools/describe-schema';
7
- import { manageEntityTypesTool } from './tools/manage-entity-types';
8
- import { createFieldTool, deleteFieldTool, deleteTableTool, updateFieldTool } from './tools/mutations';
9
- import { provisionBlueprintTool } from './tools/provision-blueprint';
10
- import { provisionDatabaseTool } from './tools/provision-database';
11
- import { runCodegenTool } from './tools/run-codegen';
12
- import { applyTemplateTool, createTemplateTool, deleteTemplateTool, listTemplatesTool, updateTemplateTool, } from './tools/templates';
13
- /**
14
- * The Constructive database tools, in registration order.
15
- *
16
- * Plain `HarnessTool`s: a harness gets them by mapping them into its own tool
17
- * shape, which is the adapter's job, so this package stays free of any harness
18
- * dependency (see `toPiTool` in `@agentic-kit/pi` for that binding).
19
- */
20
- export const constructiveDbTools = [
21
- provisionDatabaseTool,
22
- describeSchemaTool,
23
- listTemplatesTool,
24
- provisionBlueprintTool,
25
- addRelationTool,
26
- deleteTableTool,
27
- createFieldTool,
28
- updateFieldTool,
29
- deleteFieldTool,
30
- addPoliciesTool,
31
- applyTemplateTool,
32
- createTemplateTool,
33
- updateTemplateTool,
34
- deleteTemplateTool,
35
- addRecordsTool,
36
- manageEntityTypesTool,
37
- createApiKeyTool,
38
- runCodegenTool,
39
- ];
2
+ import { constructiveDbTools } from './tools';
3
+ export { constructiveDbTools };
40
4
  /** Configure the host and get the tools in one call. */
41
5
  export function createConstructiveDbTools(host) {
42
6
  configureHost(host);
43
7
  return constructiveDbTools;
44
8
  }
9
+ export { ACCESS_CHECKS, accessFindings, ADDED_FIELDS, BUILT_IN_SCOPES, checkRule, columnGaps, columnsReadByPolicies, dataNodesForPolicies, defaultFills, DERIVED_KEYS, explainPolicy, fieldsAddedByNodes, POLICY_ROLES, POLICY_WORDS, policyDifference, resolveEntityTypes, ROW_ID, TABLE_NEEDS, tablePolicyFromBlueprint, } from './access';
10
+ export { expandBlueprintDefaults } from './blueprint/blueprint-defaults';
11
+ export { AccessPolicyZod, AuthzTypeZod, blueprintProblems, BlueprintZod, } from './blueprint/blueprint-schema';
12
+ export { fieldTypeToTypeName, toFieldDefault, toFieldType } from './blueprint/field-type';
13
+ export { isInternalPolicy } from './blueprint/internal-policies';
45
14
  export { BlueprintBuildError, buildBlueprint, CONSTRUCTION_DEADLINE_MS, readConstructionFailure, waitForConstruction, } from './blueprint-construction';
46
15
  export { CONTEXT_ENV_KEYS, CONTEXT_ENV_PREFIX, deriveSubdomainEndpoint, fromEnvFile, fromEnvironment, resolveDataToken, resolveProjectContext, } from './context';
47
16
  export { probeBoundDatabase, probeDatabase, } from './db-probe';
17
+ export { failureFromErrors } from './failure';
48
18
  export { constructiveGateDeps } from './gate';
49
19
  export { classifyBackendErrors, postGraphQL, statusAdapter, } from './graphql-http';
50
20
  export { configureHost, DEFAULT_DATA_TOKEN_SKEW_MS, getHost, noBackendReason, } from './host';
@@ -54,6 +24,18 @@ export { allModulePresets, DEFAULT_PROVISION_PRESET, getModulePreset, } from './
54
24
  export { provisionDatabase, } from './provision-database/provision';
55
25
  export { moduleKey, resolveProvisionModules, } from './provision-database/resolve';
56
26
  export { accessOf, readSchemaModel, SchemaReadError, } from './schema-model';
27
+ export { accessState, asWritten, grantWords, planRule, ruleWords } from './table-access';
57
28
  export { toolSchema } from './tool-schema';
58
- export { createTemplatePreviewTables } from './tools/templates';
29
+ export { describePolicyTypeTool, explainAccessTool, setAccessTool } from './tools/access';
30
+ export { addPoliciesTool } from './tools/add-policies';
31
+ export { addRecordsTool } from './tools/add-records';
32
+ export { addRelationTool } from './tools/add-relation';
33
+ export { createApiKeyTool } from './tools/create-api-key';
34
+ export { describeSchemaTool } from './tools/describe-schema';
35
+ export { createEntityTypeTool, deleteEntityTypeTool, listEntityTypesTool } from './tools/entity-types';
36
+ export { createFieldTool, deleteFieldTool, deleteTableTool, retypeFieldTool, updateFieldTool, } from './tools/mutations';
37
+ export { provisionBlueprintTool } from './tools/provision-blueprint';
38
+ export { provisionDatabaseTool, replaceDatabaseTool } from './tools/provision-database';
39
+ export { runCodegenTool } from './tools/run-codegen';
40
+ export { applyTemplateTool, createTemplatePreviewTables, createTemplateTool, deleteTemplateTool, listTemplatesTool, updateTemplateTool, } from './tools/templates';
59
41
  export default constructiveDbTools;
@@ -26,6 +26,13 @@ export declare const PENDING_PROVISION_KEYS: {
26
26
  readonly userId: "PROVISION_TICKET_USER_ID";
27
27
  readonly attempts: "PROVISION_TICKET_ATTEMPTS";
28
28
  };
29
+ /** The backend's own check on a database name, which is 3 to 63 characters long. */
30
+ export declare const DATABASE_NAME_PATTERN: RegExp;
31
+ /**
32
+ * The binding keys whose value in `env` is not of its form. The .env of a cloned project is not the person's text, so
33
+ * such a value is never used, sent or shown: the caller refuses with the keys alone.
34
+ */
35
+ export declare const invalidBindingKeys: (env: Record<string, string | undefined>) => string[];
29
36
  /** The binding keys provision_database owns in a project's .env. */
30
37
  export declare const PROVISION_ENV_KEYS: readonly ["DATABASE_ID", "DATABASE_NAME", "OWNER_ID", "PGDATABASE", "API_ENDPOINT", "MODULES_ENDPOINT"];
31
38
  /**
@@ -87,6 +87,36 @@ export const PENDING_PROVISION_KEYS = {
87
87
  userId: 'PROVISION_TICKET_USER_ID',
88
88
  attempts: 'PROVISION_TICKET_ATTEMPTS',
89
89
  };
90
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
91
+ /** The backend's own check on a database name, which is 3 to 63 characters long. */
92
+ export const DATABASE_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
93
+ const isDatabaseName = (value) => value.length >= 3 && value.length <= 63 && DATABASE_NAME_PATTERN.test(value);
94
+ function isEndpoint(value) {
95
+ try {
96
+ return ['http:', 'https:'].includes(new URL(value).protocol);
97
+ }
98
+ catch {
99
+ return false;
100
+ }
101
+ }
102
+ /**
103
+ * The form of each binding value the tools read from a project's .env. The ticket's endpoint and account need none:
104
+ * they are used only when they equal the host's own, and its attempt count is read as a number.
105
+ */
106
+ const BINDING_FORMS = {
107
+ DATABASE_ID: (value) => UUID.test(value),
108
+ OWNER_ID: (value) => UUID.test(value),
109
+ DATABASE_NAME: isDatabaseName,
110
+ API_ENDPOINT: isEndpoint,
111
+ MODULES_ENDPOINT: isEndpoint,
112
+ [PENDING_PROVISION_KEYS.ticketId]: (value) => UUID.test(value),
113
+ [PENDING_PROVISION_KEYS.databaseName]: isDatabaseName,
114
+ };
115
+ /**
116
+ * The binding keys whose value in `env` is not of its form. The .env of a cloned project is not the person's text, so
117
+ * such a value is never used, sent or shown: the caller refuses with the keys alone.
118
+ */
119
+ export const invalidBindingKeys = (env) => Object.entries(BINDING_FORMS).flatMap(([key, valid]) => (env[key] && !valid(env[key]) ? [key] : []));
90
120
  /** The binding keys provision_database owns in a project's .env. */
91
121
  export const PROVISION_ENV_KEYS = [
92
122
  'DATABASE_ID',
@@ -1,5 +1,4 @@
1
- // Client-side mirror of the backend's modules_hash normalization
2
- // (constructive-db: metaschema_private.modules_hash), used to decide whether a
1
+ // Client-side mirror of the backend's normalization of a module set, used to decide whether a
3
2
  // resolved module set can be requested by preset slug — the warm-pool-eligible
4
3
  // path — or must be sent as an explicit modules array:
5
4
  // 1. A bare module name normalizes to [name, {}]; a missing/null options
@@ -1,4 +1,6 @@
1
+ import type { PlanTarget, ToolFailure } from '@agentic-kit/harness';
1
2
  import { type RunCommand } from '../app-workspace';
3
+ import { type Result } from '../failure';
2
4
  export type ProvisionInput = {
3
5
  databaseName: string;
4
6
  /** `ensure` keeps a live binding; `replace` swaps the binding for a new database. */
@@ -16,7 +18,7 @@ export type ProvisionInput = {
16
18
  */
17
19
  adopt?: string;
18
20
  };
19
- export type ProvisionFailureCode = 'signed-out' | 'backend-unreachable' | 'db-missing' | 'db-suspended' | 'account-mismatch' | 'binding-live' | 'binding-changed' | 'pending-other' | 'ticket-lost' | 'provision-stuck' | 'name-taken' | 'binding-not-saved' | 'env-write-failed' | 'reprovision-not-allowed' | 'failed';
21
+ export type ProvisionFailureCode = 'signed-out' | 'backend-unreachable' | 'db-missing' | 'db-suspended' | 'account-mismatch' | 'binding-live' | 'binding-changed' | 'pending-other' | 'ticket-lost' | 'provision-stuck' | 'name-taken' | 'binding-not-saved' | 'env-write-failed' | 'reprovision-not-allowed' | 'no-backend' | 'invalid-input' | 'missing-credentials' | 'plan-required' | 'limit-reached' | 'failed';
20
22
  export type ProvisionDatabaseDetails = {
21
23
  success: boolean;
22
24
  message: string;
@@ -46,10 +48,22 @@ export type ProvisionDatabaseDetails = {
46
48
  yours: boolean;
47
49
  createdAt?: string;
48
50
  };
51
+ /**
52
+ * On a failed call: true when the prewarm, which starts with the request,
53
+ * prepared packages/app (scaffold and install) before the call ended.
54
+ */
55
+ appWorkspacePrepared?: boolean;
49
56
  };
50
57
  type Details = ProvisionDatabaseDetails;
51
- /** The DATABASE_ID in a project's `.env`, if any. */
58
+ /** The DATABASE_ID in a project's `.env`, if it has one of the form a database id takes. */
52
59
  export declare function boundDatabaseId(cwd: string): Promise<string | undefined>;
60
+ /**
61
+ * What provision_database and replace_database check before they change
62
+ * anything: a backend and an account to provision under, and a binding whose
63
+ * values are of their form. They act on no bound database; a replace names
64
+ * the one the directory leaves.
65
+ */
66
+ export declare function provisionDatabaseReady(replace: boolean, cwd: string): Promise<Result<PlanTarget>>;
53
67
  /**
54
68
  * Provision the project's database, or keep the one it is bound to. The host
55
69
  * entry point: replace mode refuses a live binding here, and `abandonPending`
@@ -60,12 +74,15 @@ export declare function provisionDatabase(input: ProvisionInput, ctx: {
60
74
  signal?: AbortSignal;
61
75
  }, exec?: RunCommand): Promise<Details>;
62
76
  /**
63
- * The provision_database tool's entry point: its `reprovision: true` may
77
+ * The entry point of provision_database and replace_database: a replace may
64
78
  * replace a live binding (a clean rebuild), unless the host turned tool
65
79
  * reprovisioning off.
66
80
  */
67
81
  export declare function provisionFromTool(input: Pick<ProvisionInput, 'databaseName' | 'mode' | 'replaces'>, ctx: {
68
82
  cwd: string;
69
83
  signal?: AbortSignal;
70
- }, exec?: RunCommand): Promise<Details>;
84
+ }, exec?: RunCommand): Promise<{
85
+ details: Details;
86
+ failure?: ToolFailure;
87
+ }>;
71
88
  export {};