@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
package/esm/context.js CHANGED
@@ -3,7 +3,14 @@ import path from 'node:path';
3
3
  import { api, auth, modules } from '@constructive-io/sdk';
4
4
  import { parseDotenv } from '12factor-env/dotenv';
5
5
  import { probeDatabase } from './db-probe';
6
- import { DEFAULT_DATA_TOKEN_SKEW_MS, getHost, noBackendReason, reprovisionAdvice } from './host';
6
+ import { failureFromError, failureFromErrors, failureText, invalidBinding, NEW_DATABASE, noBackendFailure } from './failure';
7
+ import { DEFAULT_DATA_TOKEN_SKEW_MS, getHost, readAccount, readBackendConfig, replaceCall, reprovisionAdvice, } from './host';
8
+ import { invalidBindingKeys } from './provision-database/env-file';
9
+ // The failure's code is `code` unless `why.code` names a more precise one.
10
+ function unresolved(code, why, cause) {
11
+ const failure = { ...why, code: why.code ?? code };
12
+ return { context: null, reason: failureText(failure), code, ...(cause ? { cause } : {}), failure };
13
+ }
7
14
  // The project values pi needs, and where they come from. A scaffolded project
8
15
  // folder carries binding metadata in `.env`; a headless host — a container,
9
16
  // a Job, CI — injects values without writing credentials into a git clone.
@@ -52,29 +59,37 @@ export async function resolveProjectContext(input, options = {}) {
52
59
  const fileBacked = typeof input === 'string';
53
60
  const source = fileBacked ? await fromEnvFile(input) : input;
54
61
  if (!source) {
55
- return {
56
- context: null,
57
- reason: 'No .env found in the project. Provision a Constructive database first (scaffold the project), then retry.',
58
- code: 'no-env',
59
- };
62
+ return unresolved('no-env', {
63
+ message: 'No .env found in the project.',
64
+ hint: 'Create a database for this directory (the person approves it), then retry.',
65
+ calls: [NEW_DATABASE],
66
+ });
60
67
  }
61
68
  const env = Object.fromEntries(CONTEXT_ENV_KEYS.map((key) => [key, fileBacked && key === 'ACCESS_TOKEN' ? undefined : readContextValue(source, key)]));
69
+ const invalid = invalidBindingKeys(env);
70
+ if (invalid.length)
71
+ return unresolved('missing-credentials', invalidBinding(invalid, fileBacked ? '.env' : 'the injected project context'));
62
72
  const accessToken = env.ACCESS_TOKEN;
63
73
  const databaseId = env.DATABASE_ID;
64
74
  if (!databaseId || (!fileBacked && !accessToken)) {
65
- return {
66
- context: null,
67
- reason: fileBacked
68
- ? 'Project is not connected to a Constructive database yet (missing DATABASE_ID in .env). Provision the database first, then retry.'
69
- : `Missing ${CONTEXT_ENV_PREFIX}ACCESS_TOKEN or ${CONTEXT_ENV_PREFIX}DATABASE_ID from the injected project context.`,
70
- code: 'missing-credentials',
71
- };
75
+ return unresolved('missing-credentials', fileBacked
76
+ ? {
77
+ message: 'Project is not connected to a Constructive database yet (missing DATABASE_ID in .env).',
78
+ hint: 'Bind this directory to a database (the person approves it), then retry.',
79
+ calls: [NEW_DATABASE],
80
+ }
81
+ : {
82
+ message: `Missing ${CONTEXT_ENV_PREFIX}ACCESS_TOKEN or ${CONTEXT_ENV_PREFIX}DATABASE_ID from the injected project context.`,
83
+ });
72
84
  }
73
85
  // A source-supplied pin wins for the DATA plane (the access key belongs to
74
86
  // whatever backend wrote it); otherwise fall back to the app's backend-config
75
87
  // store (environment-aware) so app + harness share one endpoint source.
76
88
  const host = getHost();
77
- const backend = host.backendConfig();
89
+ const backendRead = readBackendConfig(host);
90
+ if (backendRead.kind === 'failed')
91
+ return unresolved('no-backend', backendRead.failure);
92
+ const backend = backendRead.value;
78
93
  const controlApiEndpoint = backend?.apiEndpoint;
79
94
  const controlModulesEndpoint = backend?.modulesEndpoint;
80
95
  // The whole control plane (binding probe, schema resolution, blueprint/schema
@@ -83,17 +98,20 @@ export async function resolveProjectContext(input, options = {}) {
83
98
  // surfaces. An explicitly injected key stays in the context for the data plane only.
84
99
  // The bearer is only ever sent to the app-configured backend — never a
85
100
  // source-pinned endpoint, which an untrusted cloned project controls.
86
- const account = host.account();
101
+ const accountRead = await readAccount(host);
102
+ if (accountRead.kind === 'failed')
103
+ return unresolved('missing-credentials', accountRead.failure);
104
+ const account = accountRead.value;
87
105
  const accountBearer = account?.apiKey ?? account?.accessToken;
88
106
  if (!accountBearer) {
89
- return {
90
- context: null,
91
- reason: `No usable account credential to reach the Constructive control plane. ${host.signInHint ?? 'Sign in to the app, then retry.'}`,
92
- code: 'missing-credentials',
93
- };
107
+ return unresolved('missing-credentials', {
108
+ code: 'signed-out',
109
+ message: 'No usable account credential to reach the Constructive control plane.',
110
+ hint: host.signInHint ?? 'Sign in to the app, then retry.',
111
+ });
94
112
  }
95
113
  if (!controlApiEndpoint || !controlModulesEndpoint) {
96
- return { context: null, reason: noBackendReason(host.signInHint), code: 'no-backend' };
114
+ return unresolved('no-backend', noBackendFailure(host.signInHint));
97
115
  }
98
116
  const apiEndpoint = env.API_ENDPOINT || controlApiEndpoint;
99
117
  const modulesEndpoint = env.MODULES_ENDPOINT || controlModulesEndpoint;
@@ -109,19 +127,14 @@ export async function resolveProjectContext(input, options = {}) {
109
127
  signInHint: host.signInHint,
110
128
  });
111
129
  if (probe.status === 'unreachable') {
112
- return {
113
- context: null,
114
- reason: unreachableReason(controlApiEndpoint, probe.cause, probe.detail),
115
- code: 'backend-unreachable',
116
- cause: probe.cause,
117
- };
130
+ return unresolved('backend-unreachable', unreachableFailure(controlApiEndpoint, probe.cause, probe.detail), probe.cause);
118
131
  }
119
132
  if (probe.status === 'missing') {
120
- return {
121
- context: null,
122
- reason: `The bound database (DATABASE_ID=${databaseId}) no longer exists on this backend, or this account lost access to it. ${reprovisionAdvice(host)}`,
123
- code: 'db-missing',
124
- };
133
+ return unresolved('db-missing', {
134
+ message: `The bound database (DATABASE_ID=${databaseId}) no longer exists on this backend, or this account lost access to it.`,
135
+ hint: reprovisionAdvice(host),
136
+ ...replaceCall(host),
137
+ });
125
138
  }
126
139
  // Schemas are account-scoped: a live binding under a different account is
127
140
  // never shown in the Schemas tab or written to by the agent. The project's
@@ -134,21 +147,19 @@ export async function resolveProjectContext(input, options = {}) {
134
147
  probe.ownerId &&
135
148
  sessionUserId &&
136
149
  probe.ownerId !== sessionUserId) {
137
- return {
138
- context: null,
139
- reason: `The bound database (DATABASE_ID=${databaseId}) was provisioned under a different account than the one signed in. ${reprovisionAdvice(host)}`,
140
- code: 'account-mismatch',
141
- };
150
+ return unresolved('account-mismatch', {
151
+ message: `The bound database (DATABASE_ID=${databaseId}) was provisioned under a different account than the one signed in.`,
152
+ hint: reprovisionAdvice(host),
153
+ ...replaceCall(host),
154
+ });
142
155
  }
143
156
  // A suspended database still holds its data, so it is never a reason to
144
157
  // reprovision: nothing can read or change it until the hold is lifted.
145
158
  if (probe.status === 'suspended') {
146
159
  const why = probe.suspendedReason ? ` (${probe.suspendedReason})` : '';
147
- return {
148
- context: null,
149
- reason: `The bound database (DATABASE_ID=${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, but nothing can read or change it until the suspension is lifted.`,
150
- code: 'db-suspended',
151
- };
160
+ return unresolved('db-suspended', {
161
+ message: `The bound database (DATABASE_ID=${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, but nothing can read or change it until the suspension is lifted.`,
162
+ });
152
163
  }
153
164
  const databaseName = env.DATABASE_NAME || probe.name || '';
154
165
  const ownerId = probe.ownerId || env.OWNER_ID || undefined;
@@ -156,9 +167,8 @@ export async function resolveProjectContext(input, options = {}) {
156
167
  ? deriveSubdomainEndpoint(apiEndpoint, `api-${databaseName}`)
157
168
  : '';
158
169
  const schema = await resolveSchemaId(apiClient, databaseId);
159
- if ('reason' in schema) {
160
- return { context: null, reason: schema.reason, code: 'schema-unresolved' };
161
- }
170
+ if ('failure' in schema)
171
+ return unresolved('schema-unresolved', schema.failure);
162
172
  const schemaId = schema.id;
163
173
  return {
164
174
  context: {
@@ -167,6 +177,10 @@ export async function resolveProjectContext(input, options = {}) {
167
177
  databaseId,
168
178
  schemaId,
169
179
  ownerId,
180
+ accountUserId: account.userId,
181
+ ...(account.email ? { accountEmail: account.email } : {}),
182
+ ...(account.agent ? { accountAgent: account.agent } : {}),
183
+ controlApiEndpoint,
170
184
  apiEndpoint,
171
185
  modulesEndpoint,
172
186
  databaseName,
@@ -177,21 +191,53 @@ export async function resolveProjectContext(input, options = {}) {
177
191
  reason: '',
178
192
  };
179
193
  }
180
- function unreachableReason(endpoint, cause, detail) {
194
+ function unreachableFailure(endpoint, cause, detail) {
181
195
  switch (cause) {
182
196
  case 'auth':
183
197
  // The probe's detail says the credential was rejected and how to sign in.
184
- return `Could not check the bound database on the Constructive backend at ${endpoint}: ${detail}`;
198
+ return {
199
+ code: 'signed-out',
200
+ message: `Could not check the bound database on the Constructive backend at ${endpoint}: ${detail}`,
201
+ };
185
202
  case 'error':
186
- return `The Constructive backend at ${endpoint} answered with an error while checking the bound database (${detail}). Retry; if it keeps failing, check the backend's logs.`;
203
+ return {
204
+ code: 'backend-unreachable',
205
+ message: `The Constructive backend at ${endpoint} answered with an error while checking the bound database (${detail}).`,
206
+ hint: "Retry; if it keeps failing, check the backend's logs.",
207
+ retryable: true,
208
+ };
187
209
  case 'server':
188
- return `The Constructive backend at ${endpoint} is failing (${detail}). Check it is running, then retry.`;
210
+ return {
211
+ code: 'backend-unreachable',
212
+ message: `The Constructive backend at ${endpoint} is failing (${detail}).`,
213
+ hint: 'Check it is running, then retry.',
214
+ retryable: true,
215
+ };
216
+ case 'rate-limited':
217
+ return {
218
+ code: 'rate-limited',
219
+ message: `The Constructive backend at ${endpoint} is limiting how many requests it takes (${detail}).`,
220
+ hint: 'Wait, as long as the message says when the backend gave a time, then call again.',
221
+ retryable: true,
222
+ };
189
223
  default:
190
- return `Could not reach the Constructive backend at ${endpoint} (${detail}). Check it is running, then retry.`;
224
+ return {
225
+ code: 'backend-unreachable',
226
+ message: `Could not reach the Constructive backend at ${endpoint} (${detail}).`,
227
+ hint: 'Check it is running, then retry.',
228
+ retryable: true,
229
+ };
191
230
  }
192
231
  }
193
- const needsAuthReason = () => `Not signed in to the app database yet. ${getHost().signInHint ??
194
- 'Sign in from the Sheets tab, or open the Preview and sign in to your app, then try again.'}`;
232
+ function appSignedOut(why = 'Not signed in to the app database yet.') {
233
+ const failure = {
234
+ code: 'app-signed-out',
235
+ message: why,
236
+ hint: getHost().signInHint ??
237
+ 'Sign in from the Sheets tab, or open the Preview and sign in to your app, then try again.',
238
+ };
239
+ return { reason: failureText(failure), failure };
240
+ }
195
241
  // Resolve a data-plane token for record operations: serve the broker's active
196
242
  // account while valid, otherwise harvest the token the user created by signing
197
243
  // into their app in the Preview and adopt it into the broker. Also returns the
@@ -204,17 +250,22 @@ export async function resolveDataToken(context) {
204
250
  const active = broker?.getActiveToken(context.databaseId);
205
251
  if (active)
206
252
  return { token: active.token, userId: active.userId };
207
- const preview = host.previewToken ? await host.previewToken() : null;
208
- if (!preview)
209
- return { reason: needsAuthReason() };
210
- if (broker?.isInvalidToken(context.databaseId, preview.accessToken)) {
211
- return { reason: needsAuthReason() };
253
+ let preview = null;
254
+ try {
255
+ preview = host.previewToken ? await host.previewToken() : null;
212
256
  }
257
+ catch (err) {
258
+ return appSignedOut(`Could not read the app sign-in: ${err instanceof Error ? err.message : String(err)}`);
259
+ }
260
+ if (!preview)
261
+ return appSignedOut();
262
+ if (broker?.isInvalidToken(context.databaseId, preview.accessToken))
263
+ return appSignedOut();
213
264
  const parsed = preview.accessTokenExpiresAt ? Date.parse(preview.accessTokenExpiresAt) : NaN;
214
265
  const expiresAt = Number.isNaN(parsed) ? Date.now() + 60 * 60 * 1000 : parsed;
215
266
  const skewMs = host.dataTokenSkewMs ?? DEFAULT_DATA_TOKEN_SKEW_MS;
216
267
  if (expiresAt <= Date.now() + skewMs)
217
- return { reason: needsAuthReason() };
268
+ return appSignedOut();
218
269
  broker?.adoptToken(context.databaseId, {
219
270
  userId: preview.userId,
220
271
  token: preview.accessToken,
@@ -225,7 +276,7 @@ export async function resolveDataToken(context) {
225
276
  }
226
277
  // Per-DB endpoints are deterministic on the provisioning subdomain (= DATABASE_NAME):
227
278
  // each plane swaps the first host label of its control-plane endpoint
228
- // (e.g. api.localhost -> api-myapp.localhost, auth.localhost -> auth-myapp.localhost).
279
+ // (e.g. api.example.com -> api-myapp.example.com, auth.example.com -> auth-myapp.example.com).
229
280
  export function deriveSubdomainEndpoint(baseEndpoint, firstLabel) {
230
281
  try {
231
282
  const url = new URL(baseEndpoint);
@@ -246,7 +297,7 @@ export function deriveSubdomainEndpoint(baseEndpoint, firstLabel) {
246
297
  export async function resolveOrgName(ownerId) {
247
298
  try {
248
299
  const host = getHost();
249
- const account = host.account();
300
+ const account = await host.account();
250
301
  const bearer = account?.apiKey ?? account?.accessToken;
251
302
  if (!bearer)
252
303
  return undefined;
@@ -278,20 +329,32 @@ export async function resolveOrgName(ownerId) {
278
329
  // `name` is the logical schema name, identical on every backend; the physical
279
330
  // (possibly hashed) name is `schemaName`.
280
331
  async function resolveSchemaId(apiClient, databaseId) {
281
- const result = await apiClient.schema
282
- .findMany({
283
- select: { id: true, name: true },
284
- where: { databaseId: { equalTo: databaseId }, name: { equalTo: 'app_public' } },
285
- })
286
- .execute();
287
- if (!result.ok) {
288
- const detail = result.errors?.[0]?.message ?? 'unknown error';
289
- return { reason: `Could not query the app_public schema for database ${databaseId}: ${detail}` };
332
+ // The answer's code decides (a sign-in that ended is signed-out); an answer no code explains is this step's.
333
+ const action = `Could not query the app_public schema for database ${databaseId}`;
334
+ const queryFailed = (failure) => ({
335
+ failure: failure.code === 'failed' ? { ...failure, code: 'schema-unresolved' } : failure,
336
+ });
337
+ let result;
338
+ try {
339
+ result = await apiClient.schema
340
+ .findMany({
341
+ select: { id: true, name: true },
342
+ where: { databaseId: { equalTo: databaseId }, name: { equalTo: 'app_public' } },
343
+ })
344
+ .execute();
345
+ }
346
+ catch (err) {
347
+ return queryFailed(failureFromError(err, action));
290
348
  }
349
+ if (!result.ok)
350
+ return queryFailed(failureFromErrors(result.errors ?? [], action));
291
351
  const appPublic = (result.data.schemas?.nodes ?? []).find((s) => s?.name === 'app_public');
292
352
  if (!appPublic?.id) {
293
353
  return {
294
- reason: `Database ${databaseId} has no app_public schema. The database may not be fully provisioned yet.`,
354
+ failure: {
355
+ code: 'schema-unresolved',
356
+ message: `Database ${databaseId} has no app_public schema. The database may not be fully provisioned yet.`,
357
+ },
295
358
  };
296
359
  }
297
360
  return { id: appPublic.id };
package/esm/db-probe.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { postGraphQL } from './graphql-http';
2
- export type UnreachableCause = 'network' | 'server' | 'auth' | 'error';
2
+ export type UnreachableCause = 'network' | 'server' | 'rate-limited' | 'auth' | 'error';
3
3
  export type DatabaseProbe = {
4
4
  status: 'found';
5
5
  databaseId: string;
package/esm/db-probe.js CHANGED
@@ -1,5 +1,6 @@
1
- import { classifyBackendErrors, errorsText, postGraphQL } from './graphql-http';
2
- import { getHost, noBackendReason } from './host';
1
+ import { failureText } from './failure';
2
+ import { answerText, classifyBackendErrors, postGraphQL, retryAfterOf } from './graphql-http';
3
+ import { getHost, noBackendReason, readAccount, readBackendConfig } from './host';
3
4
  const FIELDS = 'id name ownerId hash suspendedAt suspendedReason';
4
5
  // A backend from before `hash` and the suspension columns.
5
6
  const BASIC_FIELDS = 'id name ownerId';
@@ -60,12 +61,16 @@ export async function probeDatabase(args) {
60
61
  return { status: 'found', ...found };
61
62
  }
62
63
  function unreachable(databaseId, errors, signInHint) {
63
- const detail = errorsText(errors);
64
+ const detail = answerText(errors);
64
65
  switch (classifyBackendErrors(errors)) {
65
66
  case 'network':
66
67
  return { status: 'unreachable', databaseId, cause: 'network', detail };
67
68
  case 'server':
68
69
  return { status: 'unreachable', databaseId, cause: 'server', detail };
70
+ case 'rate-limited': {
71
+ const seconds = retryAfterOf(errors);
72
+ return { status: 'unreachable', databaseId, cause: 'rate-limited', detail: seconds === undefined ? detail : `${detail}; it asks to wait ${seconds} seconds` };
73
+ }
69
74
  case 'auth':
70
75
  case 'forbidden':
71
76
  // A rejected ACCOUNT credential is never evidence the binding is dead.
@@ -73,7 +78,7 @@ function unreachable(databaseId, errors, signInHint) {
73
78
  status: 'unreachable',
74
79
  databaseId,
75
80
  cause: 'auth',
76
- detail: `${detail}: the account credential was rejected. ${signInHint ?? 'Sign in again, then retry.'}`,
81
+ detail: `the account credential was rejected (${detail}). ${signInHint ?? 'Sign in again, then retry.'}`,
77
82
  };
78
83
  default:
79
84
  return { status: 'unreachable', databaseId, cause: 'error', detail };
@@ -86,7 +91,17 @@ function unreachable(databaseId, errors, signInHint) {
86
91
  */
87
92
  export async function probeBoundDatabase(databaseId) {
88
93
  const host = getHost();
89
- const account = host.account();
94
+ // A host that cannot give its backend (a wrong override, an incomplete
95
+ // context) fails both reads; its own reason must win over "sign in".
96
+ const backendRead = readBackendConfig(host);
97
+ if (backendRead.kind === 'failed') {
98
+ return { status: 'unreachable', databaseId, cause: 'error', detail: failureText(backendRead.failure) };
99
+ }
100
+ const accountRead = await readAccount(host);
101
+ if (accountRead.kind === 'failed') {
102
+ return { status: 'unreachable', databaseId, cause: 'auth', detail: failureText(accountRead.failure) };
103
+ }
104
+ const account = accountRead.value;
90
105
  const bearer = account?.apiKey ?? account?.accessToken;
91
106
  if (!bearer) {
92
107
  return {
@@ -96,7 +111,7 @@ export async function probeBoundDatabase(databaseId) {
96
111
  detail: `No usable account credential. ${host.signInHint ?? 'Sign in to the app, then retry.'}`,
97
112
  };
98
113
  }
99
- const endpoint = host.backendConfig()?.apiEndpoint;
114
+ const endpoint = backendRead.value?.apiEndpoint;
100
115
  if (!endpoint) {
101
116
  return { status: 'unreachable', databaseId, cause: 'error', detail: noBackendReason(host.signInHint) };
102
117
  }
@@ -0,0 +1,89 @@
1
+ import { failureText, type HarnessToolResult, type ToolCallSuggestion, type ToolFailure } from '@agentic-kit/harness';
2
+ import { type GraphQLError } from './graphql-http';
3
+ export { failureText };
4
+ /** A value, or the failure that says why there is none. */
5
+ export type Result<T> = {
6
+ kind: 'ok';
7
+ value: T;
8
+ } | {
9
+ kind: 'failed';
10
+ failure: ToolFailure;
11
+ };
12
+ /** A failure a helper raises for the tool that called it to report as is. */
13
+ export declare class ToolFailureError extends Error {
14
+ readonly failure: ToolFailure;
15
+ constructor(failure: ToolFailure);
16
+ }
17
+ /** A failed call, with the tool's own `details`. */
18
+ export declare function failedResult<TDetails>(failure: ToolFailure, details: TDetails): HarnessToolResult<TDetails>;
19
+ export declare function noBackendFailure(hint?: string): ToolFailure;
20
+ /** A call to suggest; `choose` names the inputs the caller must still choose, which `why` explains. */
21
+ export declare const suggest: (tool: string, input: Record<string, unknown>, why: string, choose?: string[]) => ToolCallSuggestion;
22
+ export declare const DESCRIBE_SCHEMA: ToolCallSuggestion;
23
+ /** No database is bound yet: the call that makes one, with its name left to choose. */
24
+ export declare const NEW_DATABASE: ToolCallSuggestion;
25
+ /**
26
+ * An update or delete the backend answered without an error but with no row in
27
+ * its payload: on the latest server that is how row-level security answers for
28
+ * a row this account cannot see, and how any server answers for a row that is
29
+ * gone. `check` is the call that lists what exists.
30
+ */
31
+ export declare function noRowsChanged(action: string, check: ToolCallSuggestion): ToolFailure;
32
+ /** What a row the backend answered without is, in a row's own record (add_records' failedRows). */
33
+ export declare const NO_NEW_ROW = "The backend answered without the new row, so it may not exist, or this account may not read it.";
34
+ /**
35
+ * A create the backend answered without an error but without the new row:
36
+ * the row may not exist, or a policy lets this account create it but not
37
+ * read it back. `check` is the call that shows whether it exists, when a tool
38
+ * has one.
39
+ */
40
+ export declare function noRowCreated(action: string, check?: ToolCallSuggestion): ToolFailure;
41
+ /**
42
+ * A project binding with values that are not of their form (`keys`, in `where`): none of them is used, sent or shown,
43
+ * so the project acts as bound to no database until the person fixes them.
44
+ */
45
+ export declare function invalidBinding(keys: readonly string[], where?: string): ToolFailure;
46
+ export declare const MISSING_OWNER: ToolFailure;
47
+ /**
48
+ * What the call means, when it knows. `taken` names a unique value that is
49
+ * already taken ('a field named "slug" already exists on "posts"'), and
50
+ * `check` the read that shows what exists; without `taken`, a duplicate is a
51
+ * `conflict` with other rows. `rows` names the app table a call on rows acts
52
+ * on, so a refusal suggests the read of its rules; a refusal on the control
53
+ * plane is about the account's rights on the database, which those rules do
54
+ * not decide. `notNull` is what a refused NOT NULL means for a call that adds
55
+ * required columns to a table that may have rows. `policyTypes` are the policy
56
+ * types a call that builds access rules sends, for the calls that show their
57
+ * parameters when a rule is refused.
58
+ */
59
+ export type FailureMeaning = {
60
+ taken?: string;
61
+ check?: ToolCallSuggestion;
62
+ rows?: {
63
+ table: string;
64
+ };
65
+ notNull?: {
66
+ message: string;
67
+ hint: string;
68
+ calls: ToolCallSuggestion[];
69
+ };
70
+ policyTypes?: readonly string[];
71
+ };
72
+ /** The read of a table's rules, for a refusal on its rows. */
73
+ export declare const explainAccessCall: (table: string) => ToolCallSuggestion;
74
+ /** The next step of a refusal on the rows of an app table, in words. */
75
+ export declare const ROWS_REFUSED_HINT = "The table's rules or grants refuse this person: read the rules of the table to see who they let in.";
76
+ /**
77
+ * A failed backend answer as a failure. `action` says what was attempted
78
+ * ("Failed to delete table \"posts\""); the meaning of the code follows it, or,
79
+ * for a code with no sentence here, the code itself. The public code decides
80
+ * first (packages/errors/src/registry.ts), then the HTTP status (the one the
81
+ * server put inside the error first), then a masked internal error with its
82
+ * id. A message's text never decides and is never shown.
83
+ */
84
+ export declare function failureFromErrors(errors: readonly GraphQLError[], action: string, meaning?: FailureMeaning): ToolFailure;
85
+ /**
86
+ * A thrown error as a failure: a `ToolFailureError` keeps its own, an SDK
87
+ * error is classified by its GraphQL errors, anything else is `failed`.
88
+ */
89
+ export declare function failureFromError(err: unknown, action: string, meaning?: FailureMeaning): ToolFailure;