@agentic-kit/db-tools 0.15.1 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/blueprint/blueprint-schema.js +3 -1
- package/context.d.ts +9 -9
- package/context.js +92 -54
- package/db-probe.js +2 -2
- package/esm/blueprint/blueprint-schema.js +3 -1
- package/esm/context.d.ts +9 -9
- package/esm/context.js +91 -54
- package/esm/db-probe.js +2 -2
- package/esm/failure.d.ts +1 -1
- package/esm/failure.js +2 -2
- package/esm/gate.js +1 -1
- package/esm/graphql-http.d.ts +3 -2
- package/esm/graphql-http.js +26 -7
- package/esm/host.d.ts +20 -7
- package/esm/host.js +7 -2
- package/esm/index.d.ts +175 -14
- package/esm/index.js +5 -15
- package/esm/project-file.d.ts +72 -0
- package/esm/project-file.js +161 -0
- package/esm/provision-database/provision.d.ts +8 -3
- package/esm/provision-database/provision.js +63 -94
- package/esm/ready.d.ts +7 -3
- package/esm/ready.js +3 -3
- package/esm/records/rows.d.ts +1 -0
- package/esm/records/rows.js +9 -6
- package/esm/tools/access.js +1 -1
- package/esm/tools/create-api-key.js +2 -2
- package/esm/tools/delete-records.d.ts +1 -1
- package/esm/tools/delete-records.js +7 -7
- package/esm/tools/index.d.ts +195 -2
- package/esm/tools/index.js +25 -15
- package/esm/tools/mutations.js +7 -6
- package/esm/tools/provision-database.js +4 -4
- package/esm/tools/run-codegen.d.ts +2 -2
- package/esm/tools/run-codegen.js +10 -11
- package/esm/tools/update-records.js +1 -1
- package/failure.d.ts +1 -1
- package/failure.js +2 -2
- package/gate.js +1 -1
- package/graphql-http.d.ts +3 -2
- package/graphql-http.js +26 -7
- package/host.d.ts +20 -7
- package/host.js +7 -2
- package/index.d.ts +175 -14
- package/index.js +9 -45
- package/package.json +19 -16
- package/project-file.d.ts +72 -0
- package/project-file.js +178 -0
- package/provision-database/provision.d.ts +8 -3
- package/provision-database/provision.js +66 -96
- package/ready.d.ts +7 -3
- package/ready.js +3 -3
- package/records/rows.d.ts +1 -0
- package/records/rows.js +8 -5
- package/tools/access.js +1 -1
- package/tools/create-api-key.js +2 -2
- package/tools/delete-records.d.ts +1 -1
- package/tools/delete-records.js +8 -8
- package/tools/index.d.ts +195 -2
- package/tools/index.js +53 -43
- package/tools/mutations.js +6 -5
- package/tools/provision-database.js +5 -5
- package/tools/run-codegen.d.ts +2 -2
- package/tools/run-codegen.js +8 -9
- package/tools/update-records.js +1 -1
- package/esm/provision-database/env-file.d.ts +0 -62
- package/esm/provision-database/env-file.js +0 -170
- package/esm/provision-database/pending-ticket.d.ts +0 -33
- package/esm/provision-database/pending-ticket.js +0 -63
- package/provision-database/env-file.d.ts +0 -62
- package/provision-database/env-file.js +0 -179
- package/provision-database/pending-ticket.d.ts +0 -33
- package/provision-database/pending-ticket.js +0 -72
|
@@ -7,19 +7,17 @@
|
|
|
7
7
|
// - a recorded ticket that reads back empty, or a call that lost its ticket,
|
|
8
8
|
// finds an in-flight provision of the same name before anything new is
|
|
9
9
|
// requested, and a completed one is only reported (binding it is `adopt`);
|
|
10
|
-
// - the host saves the binding before
|
|
10
|
+
// - the host saves the binding before the project file is written.
|
|
11
11
|
import { realpathSync } from 'node:fs';
|
|
12
|
-
import { readFile, writeFile } from 'node:fs/promises';
|
|
13
12
|
import path from 'node:path';
|
|
14
13
|
import { prewarmAppWorkspace, run } from '../app-workspace';
|
|
15
14
|
import { probeDatabase } from '../db-probe';
|
|
16
|
-
import { failureText,
|
|
15
|
+
import { failureText, noBackendFailure, suggest } from '../failure';
|
|
17
16
|
import { answersSignedOut, thrownText } from '../graphql-http';
|
|
18
17
|
import { getHost, readAccount, readBackendConfig, replaceCall, reprovisionAdvice } from '../host';
|
|
18
|
+
import { abandonedTickets, archivePendingTicket, bindProject, clearPendingTicket, PROJECT_FILE, readProjectFile, recordAbandoned, recordPendingTicket, updateProjectFile, } from '../project-file';
|
|
19
19
|
import { selectProvisionCredential } from './credential';
|
|
20
|
-
import { archiveBindingKeys, ARCHIVED_BINDING_KEYS, invalidBindingKeys, mergeEnv, provisionEnvVars, readEnv } from './env-file';
|
|
21
20
|
import { loadProvisionManifest } from './manifest';
|
|
22
|
-
import { abandonedTickets, archivePendingTicket, clearPendingTicket, MAX_PENDING_ATTEMPTS, recordAbandoned, recordedTicket, recordPendingTicket, } from './pending-ticket';
|
|
23
21
|
import { selectProvisionRequest } from './preset-match';
|
|
24
22
|
import { createProvisionExecutor, isTicketInFlight, isTransientProvisionError, ProvisionJobError, ProvisionPendingError, ProvisionSignedOutError, ProvisionTicketLostError, requestDatabaseProvision, } from './request-database';
|
|
25
23
|
import { resolveProvisionModules } from './resolve';
|
|
@@ -39,38 +37,28 @@ function unanswered(probe, message, hint, extra = {}) {
|
|
|
39
37
|
}
|
|
40
38
|
const today = () => new Date().toISOString().slice(0, 10);
|
|
41
39
|
const noop = () => undefined;
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
// made while this call waited on the backend (by another tool or the user)
|
|
52
|
-
// aren't overwritten with what the file held when the call started.
|
|
53
|
-
async function updateEnvFile(envPath, edit) {
|
|
54
|
-
await writeFile(envPath, edit(await readText(envPath)));
|
|
55
|
-
}
|
|
56
|
-
/** A project's `.env`, with each binding value checked: one that is not of its form is never used, sent or shown. */
|
|
57
|
-
async function readBinding(envPath) {
|
|
58
|
-
const env = readEnv(await readText(envPath));
|
|
59
|
-
const invalid = invalidBindingKeys(env);
|
|
60
|
-
return invalid.length ? { kind: 'failed', failure: invalidBinding(invalid) } : { kind: 'ok', value: env };
|
|
40
|
+
/**
|
|
41
|
+
* Pending results recorded for one ticket before provision_database stops
|
|
42
|
+
* following it. At the default 240 s deadline that is about 20 minutes.
|
|
43
|
+
*/
|
|
44
|
+
export const MAX_PENDING_ATTEMPTS = 5;
|
|
45
|
+
/** The binding of `cwd`, empty when it has none; a file with a value not of its form is a failure. */
|
|
46
|
+
async function readBinding(cwd) {
|
|
47
|
+
const file = await readProjectFile(cwd);
|
|
48
|
+
return file.kind === 'failed' ? file : { kind: 'ok', value: file.value ?? {} };
|
|
61
49
|
}
|
|
62
|
-
/** The
|
|
50
|
+
/** The id of the database `cwd` is bound to, if its binding can be read. */
|
|
63
51
|
export async function boundDatabaseId(cwd) {
|
|
64
52
|
const binding = await boundDatabase(cwd);
|
|
65
53
|
return binding.kind === 'ok' ? binding.value?.id : undefined;
|
|
66
54
|
}
|
|
67
|
-
/** The database
|
|
55
|
+
/** The database `cwd` is bound to, as a plan names it. */
|
|
68
56
|
async function boundDatabase(cwd) {
|
|
69
|
-
const binding = await readBinding(
|
|
57
|
+
const binding = await readBinding(cwd);
|
|
70
58
|
if (binding.kind === 'failed')
|
|
71
59
|
return binding;
|
|
72
|
-
const
|
|
73
|
-
return { kind: 'ok', value:
|
|
60
|
+
const { database } = binding.value;
|
|
61
|
+
return { kind: 'ok', value: database ? { name: database.name ?? '', id: database.id } : undefined };
|
|
74
62
|
}
|
|
75
63
|
/**
|
|
76
64
|
* The backend and the account a provision runs with, or why it cannot run.
|
|
@@ -89,7 +77,7 @@ async function provisionAccess(host) {
|
|
|
89
77
|
const noBackend = noBackendFailure(host.signInHint);
|
|
90
78
|
return { kind: 'failed', failure: { ...noBackend, message: `Cannot provision a database: ${noBackend.message}` } };
|
|
91
79
|
}
|
|
92
|
-
const accountRead = await readAccount(host);
|
|
80
|
+
const accountRead = await readAccount(host, backendRead.value);
|
|
93
81
|
if (accountRead.kind === 'failed')
|
|
94
82
|
return { kind: 'failed', failure: { ...accountRead.failure, code: 'signed-out' } };
|
|
95
83
|
const credential = selectProvisionCredential(accountRead.value, host.signInHint);
|
|
@@ -210,16 +198,14 @@ async function provision(input, cwd, exec, viaTool) {
|
|
|
210
198
|
return refuse(code, why);
|
|
211
199
|
}
|
|
212
200
|
const { apiEndpoint, modulesEndpoint, credential } = access.value;
|
|
213
|
-
const
|
|
214
|
-
const binding = await readBinding(envPath);
|
|
201
|
+
const binding = await readBinding(cwd);
|
|
215
202
|
if (binding.kind === 'failed')
|
|
216
203
|
return refuse('missing-credentials', binding.failure);
|
|
217
|
-
const
|
|
218
|
-
const bound =
|
|
204
|
+
const file = binding.value;
|
|
205
|
+
const bound = file.database?.id;
|
|
219
206
|
const r = {
|
|
220
207
|
host,
|
|
221
208
|
cwd,
|
|
222
|
-
envPath,
|
|
223
209
|
name,
|
|
224
210
|
mode: input.mode ?? 'ensure',
|
|
225
211
|
apiEndpoint,
|
|
@@ -229,7 +215,7 @@ async function provision(input, cwd, exec, viaTool) {
|
|
|
229
215
|
viaTool,
|
|
230
216
|
executor: createProvisionExecutor({ apiEndpoint, modulesEndpoint, bearer: credential.bearer }),
|
|
231
217
|
// The probe carries the account bearer, so it only ever targets the
|
|
232
|
-
// app-configured backend
|
|
218
|
+
// app-configured backend.
|
|
233
219
|
probe: (databaseId) => probeDatabase({ endpoint: apiEndpoint, bearer: credential.bearer, databaseId, signInHint: host.signInHint }),
|
|
234
220
|
};
|
|
235
221
|
let replaced;
|
|
@@ -240,30 +226,30 @@ async function provision(input, cwd, exec, viaTool) {
|
|
|
240
226
|
replaced = bound;
|
|
241
227
|
}
|
|
242
228
|
else if (bound) {
|
|
243
|
-
return keepBinding(r,
|
|
229
|
+
return keepBinding(r, file, bound, input.adopt);
|
|
244
230
|
}
|
|
245
231
|
if (input.adopt) {
|
|
246
232
|
const prewarm = startPrewarm(r, exec);
|
|
247
233
|
return afterPrewarm(await bindDatabase(r, { databaseId: input.adopt, replaced, adopted: true }, prewarm), prewarm);
|
|
248
234
|
}
|
|
249
|
-
return requestAndBind(r, input,
|
|
235
|
+
return requestAndBind(r, input, file, replaced, exec);
|
|
250
236
|
}
|
|
251
237
|
// ---- ensure: keep the binding --------------------------------------------
|
|
252
|
-
async function keepBinding(r,
|
|
238
|
+
async function keepBinding(r, file, bound, adopt) {
|
|
253
239
|
const probe = await r.probe(bound);
|
|
254
240
|
if (probe.status === 'unreachable') {
|
|
255
|
-
return unanswered(probe, `Cannot verify the
|
|
241
|
+
return unanswered(probe, `Cannot verify the database this project is bound to (ID ${bound}): ${probe.detail}.`, "Retry once the backend answers; don't reprovision on an unreachable backend.", { databaseId: bound });
|
|
256
242
|
}
|
|
257
243
|
if (probe.status === 'missing') {
|
|
258
244
|
return refuse('db-missing', {
|
|
259
|
-
message: `
|
|
245
|
+
message: `This project is bound to a database (ID ${bound}) that no longer exists on this backend, or that this account lost access to.`,
|
|
260
246
|
hint: reprovisionAdvice(r.host),
|
|
261
247
|
...replaceCall(r.host),
|
|
262
248
|
}, { databaseId: bound });
|
|
263
249
|
}
|
|
264
250
|
if (probe.ownerId && probe.ownerId !== r.ownerId) {
|
|
265
251
|
return refuse('account-mismatch', {
|
|
266
|
-
message: `
|
|
252
|
+
message: `This project is bound to a database (ID ${bound}) that was provisioned under a different account than the one signed in.`,
|
|
267
253
|
hint: reprovisionAdvice(r.host),
|
|
268
254
|
...replaceCall(r.host),
|
|
269
255
|
}, { databaseId: bound });
|
|
@@ -273,24 +259,14 @@ async function keepBinding(r, env, bound, adopt) {
|
|
|
273
259
|
}
|
|
274
260
|
if (adopt && adopt !== bound) {
|
|
275
261
|
return refuse('binding-live', {
|
|
276
|
-
message: `
|
|
262
|
+
message: `This project is bound to a live database already (ID ${bound}), so it cannot be bound to another one.`,
|
|
277
263
|
hint: 'Use replace mode to swap it.',
|
|
278
264
|
}, { databaseId: bound });
|
|
279
265
|
}
|
|
280
|
-
//
|
|
281
|
-
const databaseName =
|
|
266
|
+
// The database answered on this backend under this account, so the binding names this backend and that database.
|
|
267
|
+
const databaseName = probe.name || file.database?.name || '';
|
|
282
268
|
const ownerId = probe.ownerId ?? r.ownerId;
|
|
283
|
-
const
|
|
284
|
-
if (env.API_ENDPOINT !== r.apiEndpoint)
|
|
285
|
-
refresh.API_ENDPOINT = r.apiEndpoint;
|
|
286
|
-
if (env.MODULES_ENDPOINT !== r.modulesEndpoint)
|
|
287
|
-
refresh.MODULES_ENDPOINT = r.modulesEndpoint;
|
|
288
|
-
if (!env.DATABASE_NAME && databaseName)
|
|
289
|
-
refresh.DATABASE_NAME = databaseName;
|
|
290
|
-
if (!env.PGDATABASE && databaseName)
|
|
291
|
-
refresh.PGDATABASE = databaseName;
|
|
292
|
-
if (!env.OWNER_ID)
|
|
293
|
-
refresh.OWNER_ID = ownerId;
|
|
269
|
+
const stale = file.backend !== r.apiEndpoint || file.database?.name !== databaseName || file.database?.ownerId !== ownerId;
|
|
294
270
|
const saved = await saveBinding(r, {
|
|
295
271
|
cwd: r.cwd,
|
|
296
272
|
databaseId: bound,
|
|
@@ -303,20 +279,19 @@ async function keepBinding(r, env, bound, adopt) {
|
|
|
303
279
|
if (saved)
|
|
304
280
|
return saved;
|
|
305
281
|
let note = '';
|
|
306
|
-
if (
|
|
307
|
-
const keys = Object.keys(refresh).join(', ');
|
|
282
|
+
if (stale && databaseName) {
|
|
308
283
|
try {
|
|
309
|
-
await
|
|
310
|
-
note = ` Refreshed in
|
|
284
|
+
await updateProjectFile(r.cwd, (current) => ({ ...current, backend: r.apiEndpoint, database: { id: bound, name: databaseName, ownerId } }));
|
|
285
|
+
note = ` Refreshed the binding in ${PROJECT_FILE}.`;
|
|
311
286
|
}
|
|
312
287
|
catch (err) {
|
|
313
|
-
note = ` Could not refresh ${
|
|
288
|
+
note = ` Could not refresh the binding in ${PROJECT_FILE}: ${thrownText(err)}.`;
|
|
314
289
|
}
|
|
315
290
|
}
|
|
316
291
|
const advice = r.host.toolReprovision === false ? '' : ' Replacing it with a new database is a separate change, only for an explicit clean rebuild.';
|
|
317
292
|
return {
|
|
318
293
|
success: true,
|
|
319
|
-
message: `
|
|
294
|
+
message: `This project is bound already to a live database of this account (ID ${bound}), so nothing was created.${advice}${note}`,
|
|
320
295
|
databaseId: bound,
|
|
321
296
|
databaseName,
|
|
322
297
|
ownerId,
|
|
@@ -325,7 +300,7 @@ async function keepBinding(r, env, bound, adopt) {
|
|
|
325
300
|
}
|
|
326
301
|
function suspendedText(databaseId, probe) {
|
|
327
302
|
const why = probe.suspendedReason ? ` (${probe.suspendedReason})` : '';
|
|
328
|
-
return `The bound
|
|
303
|
+
return `The database this project is bound to (ID ${databaseId}) is suspended${why} since ${probe.suspendedAt}. Its data is kept, so it isn't replaced; nothing can read or change it until the suspension is lifted.`;
|
|
329
304
|
}
|
|
330
305
|
// ---- replace: compare and swap -------------------------------------------
|
|
331
306
|
async function checkReplace(r, input, bound) {
|
|
@@ -338,14 +313,14 @@ async function checkReplace(r, input, bound) {
|
|
|
338
313
|
const expected = input.replaces === undefined ? bound : input.replaces || undefined;
|
|
339
314
|
if ((expected ?? '') !== (bound ?? '')) {
|
|
340
315
|
return refuse('binding-changed', {
|
|
341
|
-
message: `
|
|
316
|
+
message: `This project's binding changed (it names ${bound ? `database ${bound}` : 'no database'}, and the plan expected ${expected ? `database ${expected}` : 'none'}), so nothing was replaced.`,
|
|
342
317
|
}, { databaseId: bound });
|
|
343
318
|
}
|
|
344
319
|
if (!bound)
|
|
345
320
|
return null;
|
|
346
321
|
const probe = await r.probe(bound);
|
|
347
322
|
if (probe.status === 'unreachable') {
|
|
348
|
-
return unanswered(probe, `Cannot verify the
|
|
323
|
+
return unanswered(probe, `Cannot verify the database being replaced (ID ${bound}): ${probe.detail}.`, 'Retry once the backend answers.', { databaseId: bound });
|
|
349
324
|
}
|
|
350
325
|
if (probe.status === 'suspended') {
|
|
351
326
|
return refuse('db-suspended', { message: suspendedText(bound, probe) }, { databaseId: bound });
|
|
@@ -353,7 +328,7 @@ async function checkReplace(r, input, bound) {
|
|
|
353
328
|
// A missing or foreign-owned binding is replaced; a live one of this account
|
|
354
329
|
// only through the tool's explicit rebuild.
|
|
355
330
|
if (probe.status === 'found' && (!probe.ownerId || probe.ownerId === r.ownerId) && !r.viaTool) {
|
|
356
|
-
return refuse('binding-live', { message: `The bound
|
|
331
|
+
return refuse('binding-live', { message: `The database this project is bound to (ID ${bound}) is live under this account, so it wasn't replaced.` }, { databaseId: bound });
|
|
357
332
|
}
|
|
358
333
|
return null;
|
|
359
334
|
}
|
|
@@ -415,21 +390,21 @@ async function afterPrewarm(outcome, prewarm) {
|
|
|
415
390
|
};
|
|
416
391
|
return { ...outcome, failure, message: failureText(failure), appWorkspacePrepared: true };
|
|
417
392
|
}
|
|
418
|
-
async function requestAndBind(r, input,
|
|
419
|
-
const abandoned = abandonedTickets(
|
|
393
|
+
async function requestAndBind(r, input, file, replaced, exec) {
|
|
394
|
+
const abandoned = abandonedTickets(file);
|
|
420
395
|
const abandon = async (ids) => {
|
|
421
396
|
for (const id of ids)
|
|
422
397
|
abandoned.add(id);
|
|
423
|
-
await
|
|
398
|
+
await updateProjectFile(r.cwd, (current) => recordAbandoned(clearPendingTicket(current), ids)).catch(noop);
|
|
424
399
|
};
|
|
425
400
|
// A ticket an earlier call stopped waiting on.
|
|
426
401
|
let current;
|
|
427
402
|
let recovered = false;
|
|
428
|
-
const recorded =
|
|
403
|
+
const recorded = file.pending;
|
|
429
404
|
if (recorded) {
|
|
430
405
|
if (recorded.apiEndpoint !== r.apiEndpoint || recorded.userId !== r.ownerId) {
|
|
431
406
|
// Requested on another backend or by another account: not ours to follow.
|
|
432
|
-
await
|
|
407
|
+
await updateProjectFile(r.cwd, (current) => archivePendingTicket(current, today())).catch(noop);
|
|
433
408
|
}
|
|
434
409
|
else if (input.abandonPending) {
|
|
435
410
|
await abandon([recorded.ticketId]);
|
|
@@ -531,7 +506,7 @@ async function sendRequest(r, request, prewarm) {
|
|
|
531
506
|
recovered = true;
|
|
532
507
|
continue;
|
|
533
508
|
}
|
|
534
|
-
await
|
|
509
|
+
await updateProjectFile(r.cwd, clearPendingTicket).catch(noop);
|
|
535
510
|
const checked = lookup.problem
|
|
536
511
|
? `the backend couldn't be asked for another one (${lookup.problem})`
|
|
537
512
|
: 'no other provision of that name is in progress';
|
|
@@ -543,7 +518,7 @@ async function sendRequest(r, request, prewarm) {
|
|
|
543
518
|
}
|
|
544
519
|
// A definitive failure ends the recorded request, so forget it.
|
|
545
520
|
if (current)
|
|
546
|
-
await
|
|
521
|
+
await updateProjectFile(r.cwd, clearPendingTicket).catch(noop);
|
|
547
522
|
return requestFailure(r, err);
|
|
548
523
|
}
|
|
549
524
|
}
|
|
@@ -563,7 +538,7 @@ async function pendingResult(r, ticket, reason, recovered) {
|
|
|
563
538
|
const { ticketId } = ticket;
|
|
564
539
|
let recordedOk = true;
|
|
565
540
|
try {
|
|
566
|
-
await
|
|
541
|
+
await updateProjectFile(r.cwd, (current) => recordPendingTicket(current, ticket));
|
|
567
542
|
}
|
|
568
543
|
catch {
|
|
569
544
|
recordedOk = false;
|
|
@@ -576,8 +551,8 @@ async function pendingResult(r, ticket, reason, recovered) {
|
|
|
576
551
|
}
|
|
577
552
|
const waiting = `call again with the same name, "${r.name}", to keep waiting on it`;
|
|
578
553
|
const message = recordedOk
|
|
579
|
-
? `Database "${r.name}" is still provisioning (${reason}). The request is recorded in
|
|
580
|
-
: `Database "${r.name}" is still provisioning (${reason}). Recording its ticket in
|
|
554
|
+
? `Database "${r.name}" is still provisioning (${reason}). The request is recorded in ${PROJECT_FILE}; ${waiting}. Don't change the name: that starts a second database.`
|
|
555
|
+
: `Database "${r.name}" is still provisioning (${reason}). Recording its ticket in ${PROJECT_FILE} failed, but the backend still has it: ${waiting}. Don't change the name: that starts a second database.`;
|
|
581
556
|
return {
|
|
582
557
|
success: false,
|
|
583
558
|
message,
|
|
@@ -618,10 +593,10 @@ const anotherName = (r) => suggest(againTool(r), {}, 'Request the database under
|
|
|
618
593
|
// The backend refused a read of the provision because the sign-in ended. The provision may still be running, so its
|
|
619
594
|
// ticket stays recorded, and the next call after a sign-in waits on it instead of requesting another database.
|
|
620
595
|
async function signedOutWaiting(r, ticket, reason) {
|
|
621
|
-
const recorded = await
|
|
596
|
+
const recorded = await updateProjectFile(r.cwd, (current) => recordPendingTicket(current, ticket)).then(() => true, () => false);
|
|
622
597
|
return refuse('signed-out', {
|
|
623
598
|
message: `The backend did not accept the account credential while it read the provision of "${r.name}" (ticket ${ticket.ticketId}): ${reason}. ` +
|
|
624
|
-
`The database may still be on its way${recorded ?
|
|
599
|
+
`The database may still be on its way${recorded ? `, and the request stays recorded in ${PROJECT_FILE}` : ''}.`,
|
|
625
600
|
hint: `${r.host.signInHint ?? 'Sign in again'}, then call again with the same name to keep waiting on it. Don't change the name: that starts a second database.`,
|
|
626
601
|
calls: [again(r, 'Keep waiting on the recorded request once signed in')],
|
|
627
602
|
}, { ticketId: ticket.ticketId });
|
|
@@ -704,9 +679,9 @@ async function saveBinding(r, binding, ticket) {
|
|
|
704
679
|
catch (err) {
|
|
705
680
|
// Keep the ticket recorded, so the next call resumes it and binds it.
|
|
706
681
|
if (ticket)
|
|
707
|
-
await
|
|
682
|
+
await updateProjectFile(r.cwd, (current) => recordPendingTicket(current, ticket)).catch(noop);
|
|
708
683
|
return refuse('binding-not-saved', {
|
|
709
|
-
message: `Database "${binding.databaseName}" (ID ${binding.databaseId}) is ready, but the app couldn't save the binding (${thrownText(err)}), so
|
|
684
|
+
message: `Database "${binding.databaseName}" (ID ${binding.databaseId}) is ready, but the app couldn't save the binding (${thrownText(err)}), so ${PROJECT_FILE} was left unchanged.`,
|
|
710
685
|
...(ticket
|
|
711
686
|
? {
|
|
712
687
|
hint: 'Calling again with the same name binds it.',
|
|
@@ -730,7 +705,7 @@ async function bindDatabase(r, bind, prewarm) {
|
|
|
730
705
|
const visible = owner.status !== 'missing';
|
|
731
706
|
if (!visible || owner.ownerId !== r.ownerId) {
|
|
732
707
|
if (ticket)
|
|
733
|
-
await
|
|
708
|
+
await updateProjectFile(r.cwd, clearPendingTicket).catch(noop);
|
|
734
709
|
const why = visible ? "it isn't owned by" : "it isn't visible to";
|
|
735
710
|
if (bind.adopted) {
|
|
736
711
|
return refuse(visible ? 'account-mismatch' : 'db-missing', {
|
|
@@ -757,19 +732,13 @@ async function bindDatabase(r, bind, prewarm) {
|
|
|
757
732
|
}, ticket);
|
|
758
733
|
if (saved)
|
|
759
734
|
return saved;
|
|
760
|
-
// Write the binding
|
|
761
|
-
//
|
|
735
|
+
// Write the binding, dropping any recorded pending request: the project is bound now. A binding it replaces stays
|
|
736
|
+
// readable in the archive.
|
|
762
737
|
try {
|
|
763
|
-
await
|
|
764
|
-
databaseId,
|
|
765
|
-
databaseName: r.name,
|
|
766
|
-
ownerId: r.ownerId,
|
|
767
|
-
apiEndpoint: r.apiEndpoint,
|
|
768
|
-
modulesEndpoint: r.modulesEndpoint,
|
|
769
|
-
})));
|
|
738
|
+
await updateProjectFile(r.cwd, (current) => bindProject(current, { database: { id: databaseId, name: r.name, ownerId: r.ownerId }, backend: r.apiEndpoint, archivedOn: today() }));
|
|
770
739
|
}
|
|
771
740
|
catch (err) {
|
|
772
|
-
return refuse('
|
|
741
|
+
return refuse('binding-write-failed', { message: `Database provisioned (ID: ${databaseId}) but writing ${PROJECT_FILE} failed: ${thrownText(err)}` }, { databaseId });
|
|
773
742
|
}
|
|
774
743
|
// Settle the concurrent prewarm so the scaffold + install are in place before
|
|
775
744
|
// run_codegen runs. A failure here is non-fatal: run_codegen redoes the work.
|
|
@@ -778,12 +747,12 @@ async function bindDatabase(r, bind, prewarm) {
|
|
|
778
747
|
bind.resumed ? ' Finished an earlier request.' : '',
|
|
779
748
|
bind.recovered ? ' Found it on the backend by name.' : '',
|
|
780
749
|
prewarmed,
|
|
781
|
-
bind.replaced ?
|
|
750
|
+
bind.replaced ? ` The old binding is archived in ${PROJECT_FILE}, and the old database keeps its data. Build the schema again here.` : '',
|
|
782
751
|
].join('');
|
|
783
752
|
const named = `${r.name} (${databaseId.slice(0, 8)})`;
|
|
784
753
|
const message = bind.adopted
|
|
785
|
-
? `Bound this directory to ${named}. Wrote
|
|
786
|
-
: `Created ${named} and bound this directory to it. Wrote
|
|
754
|
+
? `Bound this directory to ${named}. Wrote ${PROJECT_FILE}.${notes}`
|
|
755
|
+
: `Created ${named} and bound this directory to it. Wrote ${PROJECT_FILE}.${notes}`;
|
|
787
756
|
return {
|
|
788
757
|
success: true,
|
|
789
758
|
message,
|
package/esm/ready.d.ts
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import type { PlanTarget } from '@agentic-kit/harness';
|
|
2
2
|
import { type ProjectContext } from './context';
|
|
3
3
|
import { type Result } from './failure';
|
|
4
|
+
/** The app user a change of rows is made as. */
|
|
5
|
+
export type AppUser = {
|
|
6
|
+
userId?: string;
|
|
7
|
+
email?: string;
|
|
8
|
+
};
|
|
4
9
|
/** The bound database a change goes to, at the backend and as the account the context resolved. */
|
|
5
|
-
export declare function databaseTarget(context: ProjectContext,
|
|
10
|
+
export declare function databaseTarget(context: ProjectContext, appUser?: AppUser): Extract<PlanTarget, {
|
|
6
11
|
kind: 'database';
|
|
7
12
|
}>;
|
|
8
13
|
/** A change to what the account owns beside its databases (its templates), at the context's backend. */
|
|
@@ -14,7 +19,6 @@ export declare function ownedProjectReady(cwd: string): Promise<Result<ProjectCo
|
|
|
14
19
|
ownerId: string;
|
|
15
20
|
}>>;
|
|
16
21
|
/** A data-plane token of the person signed in to the app. */
|
|
17
|
-
export declare function appSessionReady(context: ProjectContext): Promise<Result<{
|
|
22
|
+
export declare function appSessionReady(context: ProjectContext): Promise<Result<AppUser & {
|
|
18
23
|
token: string;
|
|
19
|
-
userId?: string;
|
|
20
24
|
}>>;
|
package/esm/ready.js
CHANGED
|
@@ -10,13 +10,13 @@ const accountOf = (context) => ({
|
|
|
10
10
|
...(context.accountAgent ? { agent: context.accountAgent } : {}),
|
|
11
11
|
});
|
|
12
12
|
/** The bound database a change goes to, at the backend and as the account the context resolved. */
|
|
13
|
-
export function databaseTarget(context,
|
|
13
|
+
export function databaseTarget(context, appUser = {}) {
|
|
14
14
|
return {
|
|
15
15
|
kind: 'database',
|
|
16
16
|
database: { name: context.databaseName, id: context.databaseId },
|
|
17
17
|
apiEndpoint: context.controlApiEndpoint,
|
|
18
18
|
account: accountOf(context),
|
|
19
|
-
...(
|
|
19
|
+
...(appUser.userId ? { appUserId: appUser.userId, ...(appUser.email ? { appUserEmail: appUser.email } : {}) } : {}),
|
|
20
20
|
};
|
|
21
21
|
}
|
|
22
22
|
/** A change to what the account owns beside its databases (its templates), at the context's backend. */
|
|
@@ -40,6 +40,6 @@ export async function ownedProjectReady(cwd) {
|
|
|
40
40
|
export async function appSessionReady(context) {
|
|
41
41
|
const token = await resolveDataToken(context);
|
|
42
42
|
return token.token
|
|
43
|
-
? { kind: 'ok', value: { token: token.token, userId: token.userId } }
|
|
43
|
+
? { kind: 'ok', value: { token: token.token, userId: token.userId, email: token.email } }
|
|
44
44
|
: { kind: 'failed', failure: token.failure };
|
|
45
45
|
}
|
package/esm/records/rows.d.ts
CHANGED
package/esm/records/rows.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// What the record tools share: the app tables, read from the app API's `_meta` as the person signed in to the app;
|
|
2
2
|
// each record's keys as the API's field names, with "@<table>[<index>]" as the id of a sample row the host seeded;
|
|
3
3
|
// and one write per row, with what each row's answer was.
|
|
4
|
-
import { listed, nearestName } from '@agentic-kit/harness';
|
|
4
|
+
import { listed, nearestName, plural } from '@agentic-kit/harness';
|
|
5
5
|
import { toCamelCaseSingular } from '@constructive-io/graphql-query/generators';
|
|
6
6
|
import { DESCRIBE_SCHEMA, explainAccessCall, failedResult, failureFromError, failureFromErrors, failureText, NO_NEW_ROW, noRowCreated, noRowsChanged, } from '../failure';
|
|
7
7
|
import { answerText, classifyBackendErrors, statusAdapter, thrownText } from '../graphql-http';
|
|
@@ -48,8 +48,8 @@ export async function appReady(cwd, done) {
|
|
|
48
48
|
kind: 'failed',
|
|
49
49
|
failure: {
|
|
50
50
|
code: 'missing-credentials',
|
|
51
|
-
message: 'Cannot resolve the app data endpoint (
|
|
52
|
-
hint:
|
|
51
|
+
message: 'Cannot resolve the app data endpoint (the project binding names no database).',
|
|
52
|
+
hint: 'Bind this directory to its database again (the person approves it), then retry.',
|
|
53
53
|
},
|
|
54
54
|
};
|
|
55
55
|
}
|
|
@@ -225,7 +225,7 @@ export async function writeRecords(verb, tableName, { adapter, table: rawTable }
|
|
|
225
225
|
};
|
|
226
226
|
const failed = (failure) => recordsFailed(failure, { ...(rows.length > 0 ? details : {}), ...(failedRows.length > 0 ? { failedRows } : {}) });
|
|
227
227
|
if (suspended) {
|
|
228
|
-
const message = rows.length > 0 ? `${UNAVAILABLE} ${rows.length
|
|
228
|
+
const message = rows.length > 0 ? `${UNAVAILABLE} ${plural(rows.length, 'row')} ${rows.length === 1 ? 'was' : 'were'} ${done} before it stopped.` : `${UNAVAILABLE} No rows were ${done}.`;
|
|
229
229
|
return failed({ code: 'database-unavailable', message });
|
|
230
230
|
}
|
|
231
231
|
if (rows.length === 0) {
|
|
@@ -240,11 +240,14 @@ export async function writeRecords(verb, tableName, { adapter, table: rawTable }
|
|
|
240
240
|
hint: `Fix the rows listed in details.failedRows, then call again with only those rows: the ${done} rows stay.`,
|
|
241
241
|
});
|
|
242
242
|
}
|
|
243
|
-
const message = `${words.done} ${rows.length
|
|
243
|
+
const message = `${words.done} ${plural(rows.length, 'row')} ${words.into} ${tableName}.${verb === 'insert' ? keysLine(rows, primaryKeyOf(rawTable)?.name) : ''}`;
|
|
244
244
|
return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
|
|
245
245
|
}
|
|
246
246
|
/** The line that gives the new rows' keys, so a later call can point another row at one. */
|
|
247
247
|
function keysLine(rows, key) {
|
|
248
248
|
const keys = key ? rows.map((row) => row[key]).filter((value) => value !== undefined && value !== null) : [];
|
|
249
|
-
|
|
249
|
+
const values = keys.map((value) => JSON.stringify(value)).join(', ');
|
|
250
|
+
if (keys.length === 0)
|
|
251
|
+
return '';
|
|
252
|
+
return keys.length === 1 ? `\nThe new row's ${key} value: ${values}.` : `\nThe new rows' ${key} values, in insert order: ${values}.`;
|
|
250
253
|
}
|
package/esm/tools/access.js
CHANGED
|
@@ -620,7 +620,7 @@ export const setAccessTool = {
|
|
|
620
620
|
description: 'Replace every access rule of a table with a list of rules, in one change; the grants stay, and the columns the rules need are added. The plan marks each rule as kept, added or removed.',
|
|
621
621
|
promptSnippet: 'set_access: replace the access rules of a table with a list of rules. Gated.',
|
|
622
622
|
parameters: SetAccessZod,
|
|
623
|
-
effect: '
|
|
623
|
+
effect: 'destructive',
|
|
624
624
|
async execute(params, ctx) {
|
|
625
625
|
const ready = await setAccessReady(params, ctx.cwd);
|
|
626
626
|
if (ready.kind === 'failed')
|
|
@@ -89,8 +89,8 @@ export async function createApiKeyReady(params, cwd) {
|
|
|
89
89
|
kind: 'failed',
|
|
90
90
|
failure: {
|
|
91
91
|
code: 'missing-credentials',
|
|
92
|
-
message: 'Cannot resolve the app auth endpoint (
|
|
93
|
-
hint:
|
|
92
|
+
message: 'Cannot resolve the app auth endpoint (the project binding names no database).',
|
|
93
|
+
hint: 'Bind this directory to its database again (the person approves it), then retry.',
|
|
94
94
|
},
|
|
95
95
|
};
|
|
96
96
|
}
|
|
@@ -28,6 +28,6 @@ export type DeleteRecordsDetails = {
|
|
|
28
28
|
code?: 'database-unavailable';
|
|
29
29
|
};
|
|
30
30
|
/** The plan of a records delete: the exact rows as the target, and the card's preview. */
|
|
31
|
-
export declare function deleteRecordsPlan(
|
|
31
|
+
export declare function deleteRecordsPlan(ready: DeleteRecordsReady): Resolved;
|
|
32
32
|
export declare const deleteRecordsTool: HarnessTool<typeof DeleteRecordsZod, DeleteRecordsDetails>;
|
|
33
33
|
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { identifierParam, listed,
|
|
1
|
+
import { identifierParam, listed, plural, strictObject } from '@agentic-kit/harness';
|
|
2
2
|
import { buildPostGraphileDelete, toDeleteMutationName } from '@constructive-io/graphql-query/generators';
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { DESCRIBE_SCHEMA, failureFromErrors, noRowsChanged } from '../failure';
|
|
@@ -30,9 +30,10 @@ const DeleteRecordsZod = strictObject('the input', {
|
|
|
30
30
|
.describe('The tables to delete rows from, each with exactly one of rows, where, sample or all.'),
|
|
31
31
|
});
|
|
32
32
|
/** The plan of a records delete: the exact rows as the target, and the card's preview. */
|
|
33
|
-
export function deleteRecordsPlan(
|
|
33
|
+
export function deleteRecordsPlan(ready) {
|
|
34
|
+
const { context, selection, notes } = ready;
|
|
34
35
|
return {
|
|
35
|
-
target: { ...databaseTarget(context,
|
|
36
|
+
target: { ...databaseTarget(context, ready), rows: selection.tables.map(({ tableName, keys }) => ({ tableName, keys })) },
|
|
36
37
|
preview: { kind: 'delete-records', ...selection },
|
|
37
38
|
...(notes.length ? { notes } : {}),
|
|
38
39
|
};
|
|
@@ -59,7 +60,6 @@ function plannedRows(tables, rows) {
|
|
|
59
60
|
}
|
|
60
61
|
return { kind: 'ok', value: planned };
|
|
61
62
|
}
|
|
62
|
-
const plural = (count, word) => `${count} ${word}${count === 1 ? '' : 's'}`;
|
|
63
63
|
const NO_ROW_DELETED = 'The backend answered without the deleted row, so it does not exist, or this account may not delete it.';
|
|
64
64
|
/** One delete per row, in order, until the database is suspended, and the call's result from each row's answer. */
|
|
65
65
|
async function deleteRows({ adapter, tables }, planned, kept) {
|
|
@@ -154,9 +154,9 @@ export const deleteRecordsTool = {
|
|
|
154
154
|
description: "Delete rows from one or more tables in the project's app database: rows named by primary key, the rows whose columns have given values, the sample rows seeded when the app was built, or every row. One call for every table: the person sees the exact rows first and can keep any table.",
|
|
155
155
|
promptSnippet: 'delete_records: delete rows from one or many tables, by key, by column values, the sample rows, or all rows. Gated.',
|
|
156
156
|
parameters: DeleteRecordsZod,
|
|
157
|
-
effect: '
|
|
157
|
+
effect: 'destructive',
|
|
158
158
|
async execute(params, ctx) {
|
|
159
|
-
const approved = ctx.
|
|
159
|
+
const approved = ctx.approved?.kind === 'database' ? ctx.approved : undefined;
|
|
160
160
|
const fail = (failure) => recordsFailed(failure, { deletedCount: 0, tables: [] });
|
|
161
161
|
if (!approved?.rows) {
|
|
162
162
|
// The same checks as the gate, so a call that cannot run fails the same way; a call that can still deletes
|
|
@@ -172,7 +172,7 @@ export const deleteRecordsTool = {
|
|
|
172
172
|
const ready = await appReady(ctx.cwd, 'deleted');
|
|
173
173
|
if (ready.kind === 'failed')
|
|
174
174
|
return fail(ready.failure);
|
|
175
|
-
if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value
|
|
175
|
+
if (!sameTarget(approved, databaseTarget(ready.value.context, ready.value))) {
|
|
176
176
|
return fail({
|
|
177
177
|
code: 'failed',
|
|
178
178
|
message: 'The current project or app sign-in does not match the approved delete target, so nothing was deleted.',
|