@agentic-kit/db-tools 0.13.1 → 0.14.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 CHANGED
@@ -27,7 +27,7 @@ npm install @agentic-kit/db-tools
27
27
 
28
28
  ## What's inside
29
29
 
30
- - **25 typed db tools** — `provision_database` / `replace_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `retype_field` / `delete_field`, `add_policies`, `add_records`, `list_entity_types` / `create_entity_type` / `delete_entity_type`, `create_api_key`, `run_codegen`, the template suite (`list` / `create` / `apply` / `update` / `delete`), the access tools (`explain_access`, `set_access`), and `describe_policy_type`. `constructiveDbTools` is the list, in registration order. Each states one effect (`read`, `write` or `destructive`) for every call; a change whose effect differs is its own tool (`retype_field` beside `update_field`, `replace_database` beside `provision_database`). Every failing call returns a `failure` (code, message, hint) beside the `details` it always had. A message or hint names no tool and no parameter: the calls that help travel as data (`failure.calls`, `result.calls`). Every object of a tool's own input refuses a key it does not have and names the nearest known one, instead of dropping it; Every change that names a table, a field, a template or an entity type finds it, or finds a new name's stored form free, before there is a plan to approve. A call that did only part of what was asked (a field without its unique constraint, some of the rows) returns the code `partial`, and its `details` hold the errors of the part that failed. Backend errors are read by their `extensions.code` and `extensions.class`, then the HTTP status (`extensions.http` first: the server answers HTTP 200 and puts the status there), then a masked internal error with its `errorId`; message text never decides, because the server masks the text it does not mean to show. `failureFromErrors(errors, action, meaning?)` is that mapping, exported for code that sends its own GraphQL (`postGraphQL`, which takes an `operationName`), and `FailureMeaning` names what a unique violation means for the call.
30
+ - **26 typed db tools** — `provision_database` / `replace_database`, `provision_blueprint`, `describe_schema`, `add_relation`, `delete_table`, `create_field` / `update_field` / `retype_field` / `delete_field`, `add_policies`, `add_records` / `update_records`, `list_entity_types` / `create_entity_type` / `delete_entity_type`, `create_api_key`, `run_codegen`, the template suite (`list` / `create` / `apply` / `update` / `delete`), the access tools (`explain_access`, `set_access`), and `describe_policy_type`. `constructiveDbTools` is the list, in registration order. Each states one effect (`read`, `write` or `destructive`) for every call; a change whose effect differs is its own tool (`retype_field` beside `update_field`, `replace_database` beside `provision_database`). Every failing call returns a `failure` (code, message, hint) beside the `details` it always had. A message or hint names no tool and no parameter: the calls that help travel as data (`failure.calls`, `result.calls`). Every object of a tool's own input refuses a key it does not have and names the nearest known one, instead of dropping it; Every change that names a table, a field, a template or an entity type finds it, or finds a new name's stored form free, before there is a plan to approve. A call that did only part of what was asked (a field without its unique constraint, some of the rows) returns the code `partial`, and its `details` hold the errors of the part that failed. Backend errors are read by their `extensions.code` and `extensions.class`, then the HTTP status (`extensions.http` first: the server answers HTTP 200 and puts the status there), then a masked internal error with its `errorId`; message text never decides, because the server masks the text it does not mean to show. `failureFromErrors(errors, action, meaning?)` is that mapping, exported for code that sends its own GraphQL (`postGraphQL`, which takes an `operationName`), and `FailureMeaning` names what a unique violation means for the call.
31
31
 
32
32
  The public `extensions.context` of the error that decided goes into `failure.context`: a query over the backend's request limits (`QUERY_TOO_COSTLY`, `QUERY_TOO_DEEP`, `PAGE_SIZE_TOO_LARGE`, `REQUEST_TOO_LARGE`) is `query-too-large` with its numbers there, for example `{ cost, limit }`. An update or delete that answers with no row in its payload changed nothing: that is how row-level security answers for a row this account cannot see, so every tool that updates or deletes fails `no-rows-changed` there instead of reporting success. A create that answers without the new row fails `no-rows-changed` as well: the row may not exist, or a policy lets the account create it but not read it, and the hint names the call that shows whether it exists. `STEP_UP_REQUIRED` is `step-up-required`: the change needs a recent sign-in.
33
33
 
@@ -97,6 +97,7 @@ exports.ADDED_FIELDS = {
97
97
  }
98
98
  ],
99
99
  DataEntityMembership: [{ name: { param: 'entity_field_name' }, type: 'uuid', required: true, default: null }],
100
+ DataFileRef: [],
100
101
  DataForceCurrentUser: [],
101
102
  DataGenerated: [
102
103
  {
@@ -91,6 +91,7 @@ export const ADDED_FIELDS = {
91
91
  }
92
92
  ],
93
93
  DataEntityMembership: [{ name: { param: 'entity_field_name' }, type: 'uuid', required: true, default: null }],
94
+ DataFileRef: [],
94
95
  DataForceCurrentUser: [],
95
96
  DataGenerated: [
96
97
  {
package/esm/host.d.ts CHANGED
@@ -177,6 +177,12 @@ export interface ToolsHost {
177
177
  * the call fails with `binding-not-saved`.
178
178
  */
179
179
  persistBinding?(binding: ProjectBinding): Promise<void>;
180
+ /**
181
+ * The ids of the sample rows the host seeded into the project's database, by table name, in seed order (null for
182
+ * a row that did not land). A record value "@<table>[<index>]" in add_records or update_records names one of them.
183
+ * A host that seeds no rows leaves it out, and such a value then fails.
184
+ */
185
+ seededRows?(cwd: string): Promise<Readonly<Record<string, readonly (string | null)[]>> | null>;
180
186
  }
181
187
  export declare const DEFAULT_DATA_TOKEN_SKEW_MS = 30000;
182
188
  /** The advice for a database that is gone or under another account. */
package/esm/index.d.ts CHANGED
@@ -22,12 +22,13 @@ export { loadProvisionManifest, parseProvisionManifest, PROVISION_MANIFEST_FILE,
22
22
  export { allModulePresets, DEFAULT_PROVISION_PRESET, getModulePreset, type ModulePreset, type ProvisionModule, } from './provision-database/presets';
23
23
  export { provisionDatabase, type ProvisionDatabaseDetails, type ProvisionFailureCode, type ProvisionInput, } from './provision-database/provision';
24
24
  export { moduleKey, type ProvisionOverlay, resolveProvisionModules, } from './provision-database/resolve';
25
+ export { type RecordsDetails } from './records/rows';
25
26
  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
27
  export { accessState, asWritten, grantWords, planRule, ruleWords, type WrittenRule } from './table-access';
27
28
  export { toolSchema } from './tool-schema';
28
29
  export { describePolicyTypeTool, explainAccessTool, type ExplainedRule, type ExplainedTable, setAccessTool } from './tools/access';
29
30
  export { type AddPoliciesDetails, addPoliciesTool } from './tools/add-policies';
30
- export { type AddRecordsDetails, addRecordsTool } from './tools/add-records';
31
+ export { addRecordsTool } from './tools/add-records';
31
32
  export { type AddRelationDetails, addRelationTool } from './tools/add-relation';
32
33
  export { type CreateApiKeyDetails, createApiKeyTool } from './tools/create-api-key';
33
34
  export { type DescribeSchemaDetails, describeSchemaTool } from './tools/describe-schema';
@@ -1,5 +1,5 @@
1
1
  import type { Table, TableInflection } from '@constructive-io/graphql-query/types/schema';
2
- export declare const META_QUERY = "\n query DbToolsMeta {\n _meta {\n tables {\n name\n query { all one create update delete }\n inflection {\n allRows\n conditionType\n connection\n createInputType\n createPayloadType\n deletePayloadType\n edge\n filterType\n orderByType\n patchType\n tableType\n updatePayloadType\n }\n fields {\n name\n isNotNull\n hasDefault\n type {\n gqlType\n isArray\n pgType\n subtype\n isNotNull\n hasDefault\n }\n }\n }\n }\n }\n";
2
+ export declare const META_QUERY = "\n query DbToolsMeta {\n _meta {\n tables {\n name\n tableName\n query { all one create update delete }\n inflection {\n allRows\n conditionType\n connection\n createInputType\n createPayloadType\n deletePayloadType\n edge\n filterType\n orderByType\n patchType\n tableType\n updatePayloadType\n }\n fields {\n name\n columnName\n isNotNull\n hasDefault\n isPrimaryKey\n isWritableOnUpdate\n type {\n gqlType\n isArray\n pgType\n subtype\n isNotNull\n hasDefault\n }\n }\n }\n }\n }\n";
3
3
  type RawType = {
4
4
  gqlType: string;
5
5
  isArray: boolean;
@@ -11,10 +11,13 @@ type RawType = {
11
11
  isNotNull?: boolean | null;
12
12
  hasDefault?: boolean | null;
13
13
  };
14
- type RawField = {
14
+ export type RawField = {
15
15
  name: string;
16
+ columnName?: string | null;
16
17
  isNotNull?: boolean | null;
17
18
  hasDefault?: boolean | null;
19
+ isPrimaryKey?: boolean | null;
20
+ isWritableOnUpdate?: boolean | null;
18
21
  type: RawType;
19
22
  };
20
23
  type RawInflection = Partial<Record<keyof TableInflection, string | null>>;
@@ -27,6 +30,8 @@ type RawQuery = {
27
30
  };
28
31
  export type RawMetaTable = {
29
32
  name: string;
33
+ /** The SQL name; `name` is the GraphQL type. */
34
+ tableName?: string | null;
30
35
  query?: RawQuery | null;
31
36
  inflection?: RawInflection | null;
32
37
  fields?: (RawField | null)[] | null;
@@ -13,6 +13,7 @@ export const META_QUERY = `
13
13
  _meta {
14
14
  tables {
15
15
  name
16
+ tableName
16
17
  query { all one create update delete }
17
18
  inflection {
18
19
  allRows
@@ -30,8 +31,11 @@ export const META_QUERY = `
30
31
  }
31
32
  fields {
32
33
  name
34
+ columnName
33
35
  isNotNull
34
36
  hasDefault
37
+ isPrimaryKey
38
+ isWritableOnUpdate
35
39
  type {
36
40
  gqlType
37
41
  isArray
@@ -140,24 +144,29 @@ function getTableLookupVariants(value) {
140
144
  }
141
145
  // Resolve a user-supplied table name (snake_case singular or plural) against the
142
146
  // PascalCase-singular `_meta` table names, tolerating pluralization differences.
147
+ // Every table's GraphQL names are indexed before any SQL name, so a GraphQL name always finds its own table.
143
148
  export function findMetaTable(tables, requested) {
144
149
  const index = new Map();
150
+ const add = (table, keys) => {
151
+ for (const key of keys) {
152
+ for (const variant of getTableLookupVariants(key)) {
153
+ if (!index.has(variant))
154
+ index.set(variant, table);
155
+ }
156
+ }
157
+ };
145
158
  for (const table of tables) {
146
- const keys = [
159
+ add(table, [
147
160
  table.name,
148
161
  table.query?.all,
149
162
  table.query?.one,
150
163
  table.inflection?.tableType,
151
164
  table.inflection?.tableFieldName,
152
165
  table.inflection?.allRows,
153
- ];
154
- for (const key of keys) {
155
- for (const variant of getTableLookupVariants(key)) {
156
- if (!index.has(variant))
157
- index.set(variant, table);
158
- }
159
- }
166
+ ]);
160
167
  }
168
+ for (const table of tables)
169
+ add(table, [table.tableName]);
161
170
  for (const variant of getTableLookupVariants(requested)) {
162
171
  const match = index.get(variant);
163
172
  if (match)
@@ -0,0 +1,59 @@
1
+ import { type HarnessToolResult, type ToolFailure } from '@agentic-kit/harness';
2
+ import type { ProjectContext } from '../context';
3
+ import { type Result } from '../failure';
4
+ import { statusAdapter } from '../graphql-http';
5
+ import { type RawField, type RawMetaTable } from './meta';
6
+ export type RecordsDetails = {
7
+ success: boolean;
8
+ message: string;
9
+ tableName?: string;
10
+ columns?: string[];
11
+ rows?: Record<string, unknown>[];
12
+ createdCount?: number;
13
+ updatedCount?: number;
14
+ asOf?: string;
15
+ needsAuth?: boolean;
16
+ code?: 'database-unavailable';
17
+ /** The rows that were not written: their place in `records` and what the backend said. */
18
+ failedRows?: {
19
+ index: number;
20
+ message: string;
21
+ }[];
22
+ };
23
+ type Verb = 'insert' | 'update';
24
+ export declare function recordsFailed(failure: ToolFailure, extra?: Partial<RecordsDetails>): HarnessToolResult<RecordsDetails>;
25
+ export declare const invalid: (message: string) => Result<never>;
26
+ export type RecordsReady = {
27
+ context: ProjectContext;
28
+ token: string;
29
+ userId?: string;
30
+ /** The app's own API, as the person signed in to the app. */
31
+ adapter: ReturnType<typeof statusAdapter>;
32
+ tables: RawMetaTable[];
33
+ table: RawMetaTable;
34
+ /** The records with each key as the API's field name. */
35
+ records: Record<string, unknown>[];
36
+ };
37
+ /**
38
+ * What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
39
+ * sign-in, the table on the app's API, and every record's keys and seeded-row values.
40
+ */
41
+ export declare function recordsReady(verb: Verb, params: {
42
+ table_name: string;
43
+ records: Record<string, unknown>[];
44
+ }, cwd: string): Promise<Result<RecordsReady>>;
45
+ export declare const fieldsOf: (table: RawMetaTable) => RawField[];
46
+ export declare const columnOf: (field: RawField) => string;
47
+ /** The table's single-column primary key, or undefined for none or a composite one. */
48
+ export declare function primaryKeyOf(table: RawMetaTable): RawField | undefined;
49
+ type SeededIds = ReadonlyMap<string, readonly (string | null)[]>;
50
+ /**
51
+ * A record with each key as the API's field name. A key may be a field name or a column name, and the field name's
52
+ * value wins when both carry one; an empty value never replaces a given one. With nothing but empty values, a column
53
+ * is left out so the server's default applies, or set to null when `clear`. A "@<table>[<index>]" value becomes that
54
+ * seeded row's id.
55
+ */
56
+ export declare function recordAsFields(table: RawMetaTable, tableName: string, index: number, record: Record<string, unknown>, seeded: SeededIds, clear: boolean): Result<Record<string, unknown>>;
57
+ /** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
58
+ export declare function writeRecords(verb: Verb, tableName: string, { adapter, table: rawTable }: RecordsReady, mutation: string, mutationName: string, inputs: readonly Record<string, unknown>[]): Promise<HarnessToolResult<RecordsDetails>>;
59
+ export {};
@@ -0,0 +1,233 @@
1
+ // What add_records and update_records share: the app table a call names, read from the app API's `_meta` as the
2
+ // person signed in to the app; each record's keys as the API's field names, with "@<table>[<index>]" as the id of a
3
+ // sample row the host seeded; and one write per row, with what each row's answer was.
4
+ import { listed, nearestName } from '@agentic-kit/harness';
5
+ import { toCamelCaseSingular } from '@constructive-io/graphql-query/generators';
6
+ import { DESCRIBE_SCHEMA, explainAccessCall, failedResult, failureFromError, failureFromErrors, failureText, NO_NEW_ROW, noRowCreated, noRowsChanged, } from '../failure';
7
+ import { answerText, classifyBackendErrors, statusAdapter, thrownText } from '../graphql-http';
8
+ import { getHost } from '../host';
9
+ import { appSessionReady, projectReady } from '../ready';
10
+ import { cleanTable, findMetaTable, META_QUERY } from './meta';
11
+ const WORDS = {
12
+ insert: {
13
+ done: 'Inserted',
14
+ into: 'into',
15
+ action: 'Failed to insert into',
16
+ count: 'createdCount',
17
+ noRow: NO_NEW_ROW,
18
+ // A row the backend answers without was refused by, or is hidden by, the read rule.
19
+ noRows: (action, tableName) => ({
20
+ ...noRowCreated(action),
21
+ hint: "The table's read rules may hide the new row from this person: read the rules of the table to see who they let read.",
22
+ calls: [explainAccessCall(tableName)],
23
+ }),
24
+ },
25
+ update: {
26
+ done: 'Updated',
27
+ into: 'in',
28
+ action: 'Failed to update',
29
+ count: 'updatedCount',
30
+ noRow: 'The backend answered without the row, so it does not exist, or this account may not change or read it.',
31
+ noRows: (action, tableName) => noRowsChanged(action, explainAccessCall(tableName)),
32
+ },
33
+ };
34
+ const UNAVAILABLE = "The app database is unavailable: the backend answered ACCESS_SUSPENDED, so it was deleted or is suspended. Retrying won't help until it is restored.";
35
+ const isSuspended = (errors) => classifyBackendErrors(errors) === 'suspended';
36
+ export function recordsFailed(failure, extra = {}) {
37
+ const flag = failure.code === 'app-signed-out' ? { needsAuth: true } : failure.code === 'database-unavailable' ? { code: failure.code } : {};
38
+ return failedResult(failure, { success: false, message: failureText(failure), ...flag, ...extra });
39
+ }
40
+ export const invalid = (message) => ({ kind: 'failed', failure: { code: 'invalid-input', message, calls: [DESCRIBE_SCHEMA] } });
41
+ /**
42
+ * What a records call checks before it writes anything: rows to write, the project, its data endpoint, an app
43
+ * sign-in, the table on the app's API, and every record's keys and seeded-row values.
44
+ */
45
+ export async function recordsReady(verb, params, cwd) {
46
+ if (params.records.length === 0)
47
+ return { kind: 'failed', failure: { code: 'invalid-input', message: 'No records provided.' } };
48
+ const ready = await projectReady(cwd);
49
+ if (ready.kind === 'failed')
50
+ return ready;
51
+ if (!ready.value.dataEndpoint) {
52
+ return {
53
+ kind: 'failed',
54
+ failure: {
55
+ code: 'missing-credentials',
56
+ message: 'Cannot resolve the app data endpoint (DATABASE_NAME missing from .env).',
57
+ hint: "Add DATABASE_NAME with the database's name to .env, then retry.",
58
+ },
59
+ };
60
+ }
61
+ const session = await appSessionReady(ready.value);
62
+ if (session.kind === 'failed')
63
+ return session;
64
+ // Keeps the status and extensions.code that the SDK adapter drops.
65
+ const adapter = statusAdapter(ready.value.dataEndpoint, { Authorization: `Bearer ${session.value.token}` });
66
+ let tables;
67
+ try {
68
+ const meta = await adapter.execute(META_QUERY);
69
+ if (!meta.ok) {
70
+ const failure = isSuspended(meta.errors)
71
+ ? { code: 'database-unavailable', message: `${UNAVAILABLE} No rows were ${WORDS[verb].done.toLowerCase()}.` }
72
+ : failureFromErrors(meta.errors, 'Failed to read schema from the app database');
73
+ return { kind: 'failed', failure };
74
+ }
75
+ tables = (meta.data._meta?.tables ?? []).filter((t) => Boolean(t));
76
+ }
77
+ catch (err) {
78
+ return { kind: 'failed', failure: failureFromError(err, 'Failed to query the app database schema') };
79
+ }
80
+ const table = findMetaTable(tables, params.table_name);
81
+ if (!table) {
82
+ return {
83
+ kind: 'failed',
84
+ failure: {
85
+ code: 'not-found',
86
+ message: `Table "${params.table_name}" was not found in the app database.`,
87
+ hint: 'Check the table names that exist, then retry.',
88
+ calls: [DESCRIBE_SCHEMA],
89
+ },
90
+ };
91
+ }
92
+ const seeded = await seededIds(params.records, cwd);
93
+ if (seeded.kind === 'failed')
94
+ return seeded;
95
+ const records = [];
96
+ for (const [index, record] of params.records.entries()) {
97
+ const row = recordAsFields(table, params.table_name, index, record, seeded.value, verb === 'update');
98
+ if (row.kind === 'failed')
99
+ return row;
100
+ records.push(row.value);
101
+ }
102
+ return { kind: 'ok', value: { context: ready.value, ...session.value, adapter, tables, table, records } };
103
+ }
104
+ export const fieldsOf = (table) => (table.fields ?? []).filter((f) => Boolean(f));
105
+ export const columnOf = (field) => field.columnName ?? field.name;
106
+ /** The table's single-column primary key, or undefined for none or a composite one. */
107
+ export function primaryKeyOf(table) {
108
+ const keys = fieldsOf(table).filter((field) => field.isPrimaryKey);
109
+ return keys.length === 1 ? keys[0] : undefined;
110
+ }
111
+ const ROW_REF = /^@([a-z][a-z0-9_]*)\[(\d+)\]$/i;
112
+ const tableKey = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, '');
113
+ /** The ids of the sample rows the host seeded, by `tableKey`, read only when a record names one. */
114
+ async function seededIds(records, cwd) {
115
+ const named = records.some((record) => Object.values(record).some((value) => typeof value === 'string' && ROW_REF.test(value)));
116
+ const host = getHost();
117
+ if (!named || !host.seededRows)
118
+ return { kind: 'ok', value: new Map() };
119
+ try {
120
+ const rows = (await host.seededRows(cwd)) ?? {};
121
+ return { kind: 'ok', value: new Map(Object.entries(rows).map(([table, ids]) => [tableKey(table), ids])) };
122
+ }
123
+ catch (err) {
124
+ return { kind: 'failed', failure: { code: 'failed', message: `Could not read the sample rows seeded for this project: ${thrownText(err)}` } };
125
+ }
126
+ }
127
+ const isEmpty = (value) => value === undefined || value === null || value === '';
128
+ /**
129
+ * A record with each key as the API's field name. A key may be a field name or a column name, and the field name's
130
+ * value wins when both carry one; an empty value never replaces a given one. With nothing but empty values, a column
131
+ * is left out so the server's default applies, or set to null when `clear`. A "@<table>[<index>]" value becomes that
132
+ * seeded row's id.
133
+ */
134
+ export function recordAsFields(table, tableName, index, record, seeded, clear) {
135
+ const fields = fieldsOf(table);
136
+ const names = new Set(fields.flatMap((field) => [field.name, columnOf(field)]));
137
+ const unknown = Object.keys(record).find((key) => !names.has(key));
138
+ if (unknown !== undefined) {
139
+ const columns = fields.map(columnOf);
140
+ const nearest = nearestName(unknown, columns);
141
+ const next = nearest ? `use "${nearest}".` : `its columns are ${listed(columns.map((c) => `"${c}"`))}.`;
142
+ return invalid(`Row ${index} names "${unknown}", which is not a column of ${tableName}: ${next}`);
143
+ }
144
+ const row = {};
145
+ for (const field of fields) {
146
+ const given = [field.name, columnOf(field)].filter((key) => Object.hasOwn(record, key)).map((key) => record[key]);
147
+ if (given.length === 0)
148
+ continue;
149
+ const value = given.find((v) => !isEmpty(v));
150
+ if (value === undefined) {
151
+ if (clear)
152
+ row[field.name] = null;
153
+ continue;
154
+ }
155
+ const ref = typeof value === 'string' ? value.match(ROW_REF) : null;
156
+ if (!ref) {
157
+ row[field.name] = value;
158
+ continue;
159
+ }
160
+ const id = seeded.get(tableKey(ref[1]))?.[Number(ref[2])];
161
+ if (!id)
162
+ return invalid(`Row ${index} names "${value}", but no sample row was seeded there: use the row's id.`);
163
+ row[field.name] = id;
164
+ }
165
+ return { kind: 'ok', value: row };
166
+ }
167
+ /** One write per input, in order, until the database is suspended, and the call's result from each row's answer. */
168
+ export async function writeRecords(verb, tableName, { adapter, table: rawTable }, mutation, mutationName, inputs) {
169
+ const words = WORDS[verb];
170
+ const table = cleanTable(rawTable);
171
+ const singularName = toCamelCaseSingular(table.name, table);
172
+ const rows = [];
173
+ const errors = [];
174
+ const failedRows = [];
175
+ let suspended = false;
176
+ for (const [index, input] of inputs.entries()) {
177
+ let rowErrors;
178
+ try {
179
+ const result = await adapter.execute(mutation, { input });
180
+ if (result.ok) {
181
+ const row = result.data?.[mutationName]?.[singularName];
182
+ if (row)
183
+ rows.push(row);
184
+ else
185
+ failedRows.push({ index, message: words.noRow });
186
+ continue;
187
+ }
188
+ if (isSuspended(result.errors)) {
189
+ suspended = true;
190
+ break;
191
+ }
192
+ rowErrors = result.errors;
193
+ }
194
+ catch (err) {
195
+ // The request threw before any answer came back, so the error is the local one.
196
+ rowErrors = [{ message: thrownText(err), extensions: { code: 'NETWORK' } }];
197
+ }
198
+ errors.push(...rowErrors);
199
+ failedRows.push({ index, message: answerText(rowErrors) });
200
+ }
201
+ const done = words.done.toLowerCase();
202
+ const details = {
203
+ tableName: rawTable.name,
204
+ columns: table.fields.map((f) => f.name),
205
+ rows,
206
+ [words.count]: rows.length,
207
+ asOf: new Date().toISOString(),
208
+ };
209
+ const failed = (failure) => recordsFailed(failure, { ...(rows.length > 0 ? details : {}), ...(failedRows.length > 0 ? { failedRows } : {}) });
210
+ if (suspended) {
211
+ const message = rows.length > 0 ? `${UNAVAILABLE} ${rows.length} row(s) were ${done} before it stopped.` : `${UNAVAILABLE} No rows were ${done}.`;
212
+ return failed({ code: 'database-unavailable', message });
213
+ }
214
+ if (rows.length === 0) {
215
+ const action = `${words.action} "${tableName}"`;
216
+ return failed(errors.length ? failureFromErrors(errors, action, { rows: { table: tableName } }) : words.noRows(action, tableName));
217
+ }
218
+ if (failedRows.length > 0) {
219
+ const [first] = failedRows;
220
+ return failed({
221
+ code: 'partial',
222
+ message: `${words.done} ${rows.length} of ${inputs.length} rows ${words.into} ${tableName}; ${failedRows.length} were not ${done} (row ${first.index}: ${first.message}).`,
223
+ hint: `Fix the rows listed in details.failedRows, then call again with only those rows: the ${done} rows stay.`,
224
+ });
225
+ }
226
+ const message = `${words.done} ${rows.length} row(s) ${words.into} ${tableName}.${verb === 'insert' ? keysLine(rows, primaryKeyOf(rawTable)?.name) : ''}`;
227
+ return { content: [{ type: 'text', text: message }], details: { success: true, message, ...details } };
228
+ }
229
+ /** The line that gives the new rows' keys, so a later call can point another row at one. */
230
+ function keysLine(rows, key) {
231
+ const keys = key ? rows.map((row) => row[key]).filter((value) => value !== undefined && value !== null) : [];
232
+ return keys.length ? `\nThe new rows' ${key} values, in insert order: ${keys.map((value) => JSON.stringify(value)).join(', ')}.` : '';
233
+ }
@@ -1,40 +1,13 @@
1
1
  import { type HarnessTool } from '@agentic-kit/harness';
2
2
  import { z } from 'zod';
3
- import type { ProjectContext } from '../context';
4
- import { type Result } from '../failure';
5
- import { statusAdapter } from '../graphql-http';
6
- import { type RawMetaTable } from '../records/meta';
7
- export type AddRecordsDetails = {
8
- success: boolean;
9
- message: string;
10
- tableName?: string;
11
- columns?: string[];
12
- rows?: Record<string, unknown>[];
13
- createdCount?: number;
14
- asOf?: string;
15
- needsAuth?: boolean;
16
- code?: 'database-unavailable';
17
- /** The rows that were not inserted: their place in `records` and what the backend said. */
18
- failedRows?: {
19
- index: number;
20
- message: string;
21
- }[];
22
- };
3
+ import type { Result } from '../failure';
4
+ import { type RecordsDetails, type RecordsReady } from '../records/rows';
23
5
  declare const AddRecordsZod: z.ZodObject<{
24
6
  table_name: z.ZodString;
25
7
  records: z.ZodArray<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
26
8
  }, z.core.$strict>;
27
9
  type AddRecordsParams = z.infer<typeof AddRecordsZod>;
28
- type AddRecordsReady = {
29
- context: ProjectContext;
30
- token: string;
31
- userId?: string;
32
- /** The app's own API, as the person signed in to the app. */
33
- adapter: ReturnType<typeof statusAdapter>;
34
- tables: RawMetaTable[];
35
- table: RawMetaTable;
36
- };
37
- /** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, and the table on the app's API. */
38
- export declare function addRecordsReady(params: AddRecordsParams, cwd: string): Promise<Result<AddRecordsReady>>;
39
- export declare const addRecordsTool: HarnessTool<typeof AddRecordsZod, AddRecordsDetails>;
10
+ /** What add_records checks before it changes anything: rows to add, the project, its data endpoint, an app sign-in, the table on the app's API, and every record's keys and seeded-row values. */
11
+ export declare function addRecordsReady(params: AddRecordsParams, cwd: string): Promise<Result<RecordsReady>>;
12
+ export declare const addRecordsTool: HarnessTool<typeof AddRecordsZod, RecordsDetails>;
40
13
  export {};