fnloom 0.1.0 → 0.2.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.
Files changed (113) hide show
  1. package/README.md +31 -18
  2. package/package.json +2 -7
  3. package/packages/build/package.json +1 -1
  4. package/packages/cli/package.json +1 -1
  5. package/packages/cli/src/commands/available.ts +63 -22
  6. package/packages/cli/src/commands/install.ts +86 -28
  7. package/packages/cli/src/index.ts +3 -2
  8. package/packages/cli/src/local.ts +6 -0
  9. package/packages/cli/src/premade.ts +80 -0
  10. package/packages/core/package.json +1 -1
  11. package/packages/hub/package.json +1 -1
  12. package/packages/hub/src/link/process.ts +6 -1
  13. package/packages/sdk/package.json +1 -1
  14. package/packages/web/package.json +1 -1
  15. package/premade/claude.zip +0 -0
  16. package/premade/database.zip +0 -0
  17. package/premade/web.zip +0 -0
  18. package/scripts/dev-env.ts +4 -4
  19. package/scripts/stack.ts +42 -27
  20. package/scripts/start.ts +26 -16
  21. package/systems/api/package.json +1 -1
  22. package/systems/code/package.json +1 -1
  23. package/systems/embedder/package.json +1 -1
  24. package/systems/fs/package.json +1 -1
  25. package/systems/google-calendar/package.json +1 -1
  26. package/systems/input/package.json +1 -1
  27. package/systems/mcp/package.json +1 -1
  28. package/systems/ollama/package.json +1 -1
  29. package/systems/schedule/package.json +1 -1
  30. package/systems/template/package.json +1 -1
  31. package/systems/widgets/package.json +1 -1
  32. package/systems/claude/client/FleetPage.vue +0 -132
  33. package/systems/claude/client/NewSessionForm.vue +0 -62
  34. package/systems/claude/client/SessionList.vue +0 -64
  35. package/systems/claude/client/SessionPage.vue +0 -199
  36. package/systems/claude/client/TaskList.vue +0 -61
  37. package/systems/claude/client/fakes.ts +0 -186
  38. package/systems/claude/client/host.ts +0 -23
  39. package/systems/claude/client/index.ts +0 -15
  40. package/systems/claude/client/logic.ts +0 -270
  41. package/systems/claude/client/state.ts +0 -344
  42. package/systems/claude/package.json +0 -23
  43. package/systems/claude/server/agent-sdk.ts +0 -379
  44. package/systems/claude/server/driver.ts +0 -153
  45. package/systems/claude/server/env.ts +0 -64
  46. package/systems/claude/server/fake-driver.ts +0 -112
  47. package/systems/claude/server/fleet.ts +0 -376
  48. package/systems/claude/server/impl.ts +0 -568
  49. package/systems/claude/server/index.ts +0 -8
  50. package/systems/claude/server/main.ts +0 -38
  51. package/systems/claude/server/preview.ts +0 -76
  52. package/systems/claude/server/questions.ts +0 -117
  53. package/systems/claude/server/transcript.ts +0 -83
  54. package/systems/claude/shared/index.ts +0 -262
  55. package/systems/claude/shared/session.ts +0 -284
  56. package/systems/claude/shared/shapes.ts +0 -106
  57. package/systems/claude/system.json +0 -18
  58. package/systems/claude/tsconfig.json +0 -6
  59. package/systems/database/package.json +0 -25
  60. package/systems/database/server/author.ts +0 -41
  61. package/systems/database/server/authoring.ts +0 -322
  62. package/systems/database/server/catalog.ts +0 -117
  63. package/systems/database/server/compile.ts +0 -332
  64. package/systems/database/server/dialects.ts +0 -17
  65. package/systems/database/server/drivers/database.ts +0 -71
  66. package/systems/database/server/drivers/index.ts +0 -23
  67. package/systems/database/server/drivers/postgres.ts +0 -157
  68. package/systems/database/server/drivers/sqlite.ts +0 -151
  69. package/systems/database/server/drivers/sqlserver.ts +0 -176
  70. package/systems/database/server/env.ts +0 -35
  71. package/systems/database/server/fixture.ts +0 -169
  72. package/systems/database/server/impl.ts +0 -793
  73. package/systems/database/server/index.ts +0 -7
  74. package/systems/database/server/instance.ts +0 -398
  75. package/systems/database/server/main.ts +0 -47
  76. package/systems/database/server/pick.ts +0 -97
  77. package/systems/database/server/queries.ts +0 -390
  78. package/systems/database/server/results.ts +0 -39
  79. package/systems/database/server/schema.ts +0 -59
  80. package/systems/database/server/table-fns.ts +0 -237
  81. package/systems/database/server/types.ts +0 -253
  82. package/systems/database/shared/index.ts +0 -544
  83. package/systems/database/shared/shapes.ts +0 -413
  84. package/systems/database/system.json +0 -14
  85. package/systems/database/tsconfig.json +0 -6
  86. package/systems/web/client/ReadView.vue +0 -110
  87. package/systems/web/client/SearchView.vue +0 -215
  88. package/systems/web/client/StatusChip.vue +0 -38
  89. package/systems/web/client/fakes.ts +0 -48
  90. package/systems/web/client/index.ts +0 -15
  91. package/systems/web/client/view.ts +0 -131
  92. package/systems/web/package.json +0 -22
  93. package/systems/web/server/chrome.ts +0 -121
  94. package/systems/web/server/crawl.ts +0 -333
  95. package/systems/web/server/env.ts +0 -63
  96. package/systems/web/server/guard.ts +0 -60
  97. package/systems/web/server/http.ts +0 -89
  98. package/systems/web/server/impl.ts +0 -203
  99. package/systems/web/server/index.ts +0 -71
  100. package/systems/web/server/loader.ts +0 -104
  101. package/systems/web/server/main.ts +0 -70
  102. package/systems/web/server/mentions.ts +0 -111
  103. package/systems/web/server/problem.ts +0 -72
  104. package/systems/web/server/renderer.ts +0 -243
  105. package/systems/web/server/robots.ts +0 -75
  106. package/systems/web/server/searches.ts +0 -29
  107. package/systems/web/server/tavily.ts +0 -144
  108. package/systems/web/server/testing.ts +0 -165
  109. package/systems/web/server/uploads.ts +0 -33
  110. package/systems/web/shared/index.ts +0 -343
  111. package/systems/web/shared/urls.ts +0 -60
  112. package/systems/web/system.json +0 -15
  113. package/systems/web/tsconfig.json +0 -6
@@ -1,390 +0,0 @@
1
- /**
2
- * Queries on one instance, as the query tools and the query authoring agent use them: the tables to write against, checking a draft, keeping
3
- * a checked one in the hub as a `database/query` fn of this instance (`hub/fns_save`), and running a saved one into
4
- * what the model reads. Saved queries are the hub's: their payload is read back with `hub/fns_get`, as the run's
5
- * person, so who may use one is always the hub's to say. Reads run straight away, their rows attached for the person;
6
- * a write is proposed as a run of its fn that waits for the person's approval, with a preview of what it would do.
7
- */
8
- import { CallFailed, SAVE_FN_TAKEN, type Log, type ResultBlock } from '@harness/sdk';
9
- import { Json, QualifiedName, qualify, slashedName, type InstanceName, type ApprovalPreview, type FnExample, type ProposedRun, type ResultDrill, type ResultTable, type RunInfo, type ShareRule, type UserInfo } from '@harness/core';
10
- import { resultBlock } from '@harness/sdk/server';
11
- import { QUERY_KIND, database } from '../shared/index.ts';
12
- import { QueryPayload, SortArg, type DrillArgs, type QueryCheck, type QueryDraft, type QueryRun, type SavedQueryRef, type TablesInfo, type WriteResult } from '../shared/shapes.ts';
13
- import { argProblems, argsTypeOf, drillOf, signatureOf, type CallPlan, type CompiledQuery, type Refusal } from './compile.ts';
14
-
15
- /** Where an authoring draft stands: the draft check with the request's args checked too, and the first rows a clean read gives. */
16
- export interface DraftTrial {
17
- readonly check: QueryCheck;
18
- readonly sample?: ReadonlyArray<Record<string, Json>>;
19
- }
20
-
21
- /** How rows read reach the person and the model: attached for the person, worded for whether anyone is watching. */
22
- export type ReadCtx = Pick<QueryRunCtx, 'attach'> & { readonly watched: boolean | undefined };
23
- import type { DatabaseSettings } from './env.ts';
24
- import type { DatabaseInstance } from './instance.ts';
25
- import { resultTable } from './results.ts';
26
-
27
- /** A saved fn as `hub/fns_get` gives it (the parts a query needs). */
28
- export interface StoredQuery {
29
- readonly fn: string;
30
- readonly kind: string;
31
- readonly payload?: Json | undefined;
32
- readonly version: number;
33
- }
34
-
35
- /** What `hub/fns_save` is given for a query. */
36
- export interface SaveQuery {
37
- readonly kind: string;
38
- readonly name: string;
39
- readonly description: string;
40
- readonly instructions: string;
41
- readonly payload: Json;
42
- readonly examples: FnExample[];
43
- readonly tags: string[];
44
- readonly share: ShareRule;
45
- readonly routing: { to: 'instance'; instance: InstanceName };
46
- readonly replace?: boolean;
47
- }
48
-
49
- /** What running and saving a query need from the run they are part of. */
50
- export interface QueryRunCtx {
51
- readonly run: RunInfo;
52
- readonly log: Log;
53
- propose(fn: string, args: Json, options: { preview: ApprovalPreview; approver?: 'person' | 'admins' }): Promise<ProposedRun>;
54
- /** Attach rows for the person. */
55
- attach(table: ResultTable, title: string): void;
56
- /** `hub/fns_get`: a saved fn, as the run's person may see it. */
57
- getFn(fn: string): Promise<StoredQuery>;
58
- /** `hub/fns_save`. */
59
- saveFn(save: SaveQuery): Promise<{ fn: QualifiedName; version: number; created: boolean }>;
60
- }
61
-
62
- /** Why a request couldn't be answered: the caller's to fix (`invalid`), or a failure. */
63
- export type QueryProblem = { invalid: string } | { failed: string };
64
-
65
- /**
66
- * Whether a person may use a database with this audience (`DatabaseConfig.audience`): anyone when it is public; admins
67
- * always; otherwise the people and groups it names.
68
- */
69
- export function mayUse(audience: ShareRule, user: UserInfo): boolean {
70
- if (audience.visibility === 'public' || user.role === 'admin') { return true; }
71
- return audience.visibility === 'shared' && (audience.with.includes(user.id) || user.groups.some((group) => audience.with.includes(group.id)));
72
- }
73
-
74
- /** What a person who may not use a database is told. */
75
- export function notYours(label: string): { invalid: string } {
76
- return { invalid: `You may not use the ${label} database; an admin chooses who may on its config.` };
77
- }
78
-
79
- /** A fn's local name from a saved name (`Overdue invoices!` becomes `overdue_invoices`). */
80
- export function slugOf(name: string): string {
81
- const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 48);
82
- return slug === '' || /^[0-9]/.test(slug) ? `query_${slug}` : slug;
83
- }
84
-
85
- /**
86
- * Where a saved query's name points: its instance and its stored name (`<instance>.<name>`). Takes the qualified name
87
- * (`database/main.orders`), the stored one (`main.orders`), or a bare one (`orders`), which means this instance.
88
- */
89
- export function savedQueryName(name: string, here: string): { instance: string; stored: string } {
90
- const unqualified = name.replace(/^database\//, '');
91
- const dot = unqualified.indexOf('.');
92
- return dot <= 0 ? { instance: here, stored: `${here}.${unqualified}` } : { instance: unqualified.slice(0, dot), stored: unqualified };
93
- }
94
-
95
- /** The call's args a saved query's fn takes, read out of JSON: its params, the page and the sort. */
96
- export function callArgs(args: Json): { values: Record<string, Json>; sort: SortArg } {
97
- const values: Record<string, Json> = {};
98
- if (typeof args === 'object' && args !== null && !Array.isArray(args)) {
99
- for (const [key, value] of Object.entries(args)) { if (key !== 'sort') { values[key] = value; } }
100
- }
101
- const sort = SortArg.safeParse(typeof args === 'object' && args !== null && !Array.isArray(args) ? args['sort'] : undefined);
102
- return { values, sort: sort.success ? sort.data : [] };
103
- }
104
-
105
- /** A call's args again from its param values and sort (the sort left out when there is none). */
106
- export function callOf(values: Readonly<Record<string, Json>>, sort: SortArg): Record<string, Json> {
107
- return sort.length === 0 ? { ...values } : { ...values, sort: sort.map((entry) => ({ column: entry.column, dir: entry.dir })) };
108
- }
109
-
110
- /** The fn that reads the rows behind one group of a saved grouped read (`drill_down`). */
111
- export const DRILL_FN = QualifiedName.parse(qualify(database.name, 'drill_down'));
112
-
113
- /**
114
- * The `drill` a saved read's result carries when its query can be drilled into (`drillOf`): `drill_down` with the fn
115
- * and the params it ran with (no paging or sort), and the group key columns a click takes its values from.
116
- */
117
- export function drillFor(compiled: CompiledQuery, fn: string, values: Readonly<Record<string, Json>>): ResultDrill | undefined {
118
- const drill = drillOf(compiled);
119
- if (drill === undefined) { return undefined; }
120
- const params: Record<string, Json> = {};
121
- for (const param of compiled.params) {
122
- const value = values[param.name];
123
- if (value !== undefined) { params[param.name] = value; }
124
- }
125
- return { fn: DRILL_FN, args: { fn, args: params }, keys: drill.keys.map((key) => key.column) };
126
- }
127
-
128
- /** Whether an answer is a problem rather than what was asked for. */
129
- export function isProblem<T extends object>(answer: T | QueryProblem): answer is QueryProblem {
130
- return 'invalid' in answer || 'failed' in answer;
131
- }
132
-
133
- /** Whether a hub call failed because the name is taken. */
134
- function nameTaken(error: unknown): boolean {
135
- return error instanceof CallFailed && error.error.class !== 'cancelled' && error.error.code === SAVE_FN_TAKEN;
136
- }
137
-
138
- /** Where a saved query fn points: its instance and its local name (`database/main.orders` gives `main`, `main.orders`). */
139
- export function queryInstance(fn: string): { instance: string; local: string } | undefined {
140
- // the tools' spelling (`database__main__expenses_create`) is read by the rule, as the hub reads a fn name the model wrote
141
- const given = fn.trim();
142
- const local = (given.startsWith('database__') ? slashedName(given) : given).replace(/^database\//, '');
143
- const dot = local.indexOf('.');
144
- return dot <= 0 ? undefined : { instance: local.slice(0, dot), local };
145
- }
146
-
147
- /** One instance's queries, for the query tools and the query authoring agent. */
148
- export class QueryService {
149
- readonly #instance: () => DatabaseInstance | undefined;
150
- readonly #settings: DatabaseSettings;
151
-
152
- readonly #refresh: (instance: DatabaseInstance, payload: QueryPayload) => QueryPayload;
153
-
154
- /** `refresh` rebuilds a generated fn's payload from the tables as they are now (`TableFnService.refreshPayload`). */
155
- constructor(deps: { instance: () => DatabaseInstance | undefined; settings: DatabaseSettings; refresh: (instance: DatabaseInstance, payload: QueryPayload) => QueryPayload }) {
156
- this.#instance = deps.instance;
157
- this.#settings = deps.settings;
158
- this.#refresh = deps.refresh;
159
- }
160
-
161
- /** The configured instance the person may use, or why not. */
162
- instance(user: UserInfo): DatabaseInstance | QueryProblem {
163
- const instance = this.#instance();
164
- if (instance === undefined) { return { failed: 'This database is not configured yet: an admin sets its connection on the system\'s page.' }; }
165
- return mayUse(instance.config.audience, user) ? instance : notYours(instance.config.label);
166
- }
167
-
168
- /** `tables`: what a query is written against. */
169
- tables(instance: DatabaseInstance): TablesInfo {
170
- return { database: instance.info, writes: instance.writes, schemaChanges: instance.schemaChanges, schema: instance.catalog.describe() };
171
- }
172
-
173
- /** Whether a draft runs here, its SQL and signature, or what to fix. */
174
- check(instance: DatabaseInstance, draft: QueryDraft): QueryCheck {
175
- const compiled = instance.compile(this.#payload(instance, draft));
176
- if (!('query' in compiled)) { return { ok: false, problems: compiled.problems }; }
177
- const problems = compiled.writes && !instance.writes ? [`${instance.config.label} is read-only: only select queries.`] : [];
178
- const plan = instance.plan(compiled, {}, []);
179
- const fn = qualify(database.name, `${instance.instance}.${draft.name}`);
180
- return { ok: problems.length === 0, problems, sql: plan.sql, signature: signatureOf(fn, argsTypeOf(compiled, draft.sorters ?? [], this.#limits())), writes: compiled.writes };
181
- }
182
-
183
- /** Keep a checked draft in the hub as this instance's query fn; a taken name gets the next free one. */
184
- async save(
185
- instance: DatabaseInstance, draft: QueryDraft,
186
- extra: { args?: Readonly<Record<string, Json>> | undefined; askedFor?: string | undefined; replace?: boolean | undefined }, ctx: QueryRunCtx,
187
- ): Promise<SavedQueryRef | QueryProblem> {
188
- const compiled = instance.compile(this.#payload(instance, draft));
189
- if (!('query' in compiled)) { return { invalid: `The draft doesn't run here: ${compiled.problems.join(' ')} Fix the draft first.` }; }
190
- if (compiled.writes && !instance.writes) { return { invalid: `${instance.config.label} is read-only: a query that writes can't be saved.` }; }
191
- const payload = this.#payload(instance, draft, compiled);
192
- const example: FnExample = { args: Json.parse({ ...extra.args }), ...(extra.askedFor === undefined ? {} : { note: extra.askedFor }) };
193
- for (let attempt = 0; attempt < this.#settings.DATABASE_NAME_TRIES; attempt += 1) {
194
- const name = `${instance.instance}.${attempt === 0 ? draft.name : `${draft.name}_${attempt + 1}`}`;
195
- try {
196
- const saved = await ctx.saveFn({
197
- kind: QUERY_KIND, name, payload: Json.parse(payload),
198
- description: compiled.writes ? `${draft.description} (Writes: waits for approval.)` : draft.description,
199
- instructions: `${draft.title}, on the ${instance.config.label} database. ${compiled.writes ? 'A write: every run waits for the person to approve it.' : 'You get the columns, counts and first rows; a person watching the chat is shown the rows too. Page with limit and offset.'}`,
200
- examples: [example],
201
- tags: ['database', 'query', ...(compiled.writes ? ['write'] : [])],
202
- share: instance.config.audience,
203
- // a saved query reads its own database, so it always runs on that instance
204
- routing: { to: 'instance', instance: instance.instance },
205
- ...(extra.replace === true ? { replace: true } : {}),
206
- });
207
- ctx.log.info('database.saved', { query: saved.fn, version: saved.version, writes: compiled.writes });
208
- return { fn: saved.fn, signature: signatureOf(saved.fn, argsTypeOf(compiled, payload.sorters, this.#limits())), version: saved.version, created: saved.created };
209
- } catch (error) {
210
- if (extra.replace === true || !nameTaken(error)) { throw error; }
211
- }
212
- }
213
- return { invalid: `Every name tried for ${draft.name} is taken; choose another name.` };
214
- }
215
-
216
- /** `run_query`: run a saved query for the model: a read's result, or a write proposed for approval. */
217
- async run(instance: DatabaseInstance, fn: string, args: Readonly<Record<string, Json>>, ctx: QueryRunCtx): Promise<QueryRun | QueryProblem> {
218
- const stored = await ctx.getFn(fn);
219
- const parsed = QueryPayload.safeParse(stored.payload);
220
- if (stored.kind !== QUERY_KIND || !parsed.success) { return { invalid: `${fn} is not a saved database query.` }; }
221
- if (parsed.data.instance !== instance.instance) { return { invalid: `${fn} runs on the ${parsed.data.instance} database, not this one.` }; }
222
- const payload = this.#refresh(instance, parsed.data);
223
- const compiled = instance.compile(payload);
224
- if (!('query' in compiled)) { return this.#stale(fn, compiled); }
225
- const argsType = argsTypeOf(compiled, payload.sorters, this.#limits(), payload.optional);
226
- const called = { name: stored.fn, signature: signatureOf(stored.fn, argsType) };
227
- // the hub checks a direct call's args against the fn's type; through run_query they are checked here the same way
228
- const problems = argProblems(argsType, Json.parse({ ...args }));
229
- if (problems.length > 0) { return { invalid: `The args don't fit ${called.signature}: ${problems.join('; ')}` }; }
230
- const { values, sort } = callArgs(Json.parse({ ...args }));
231
- const plan = instance.plan(compiled, values, sort);
232
- const base = { database: instance.info, fn: called, query: { sql: plan.sql, structured: Json.parse(compiled.def), params: plan.bound, writes: compiled.writes } };
233
- if (compiled.writes) {
234
- if (!instance.writes) { return { invalid: `${instance.config.label} is read-only now.` }; }
235
- const preview = await this.preview(instance, compiled, plan, payload.description);
236
- const local = queryInstance(stored.fn)?.local ?? stored.fn;
237
- const proposed = await ctx.propose(local, Json.parse(callOf(values, sort)), { preview, approver: 'person' });
238
- return {
239
- ...base,
240
- approval: { run: proposed.run, state: 'waiting', says: `${preview.title}: this waits for the person to approve it in the chat. Tell them what it will do and end your turn; once approved it runs and its result shows, and if they decline you are told why.` },
241
- };
242
- }
243
- return { ...base, result: await this.read(instance, compiled, plan, called, callOf(values, sort), { attach: (table, title) => { ctx.attach(table, title); }, watched: ctx.run.watched }) };
244
- }
245
-
246
- /**
247
- * Read rows as a result table: a saved query run directly (its output is the table; the hub words it for the model).
248
- * `drill` says how its groups are drilled into, when they can be.
249
- */
250
- async table(instance: DatabaseInstance, compiled: CompiledQuery, plan: CallPlan, drill?: ResultDrill): Promise<ResultTable> {
251
- const table = resultTable(await instance.read(plan), compiled.columns, plan);
252
- return drill === undefined ? table : { ...table, drill };
253
- }
254
-
255
- /**
256
- * `drill_down`: the rows behind one group of a saved grouped read, a page at a time. The saved query is read as the
257
- * person (`hub/fns_get`), its args checked as a call's are, its select un-ravelled (`drillOf`) with each group key
258
- * pinned to the clicked group's value; a query that can't be drilled into, or a group without a value for a key
259
- * (NULL included: it pins no rows), is the caller's to fix.
260
- */
261
- async drill(instance: DatabaseInstance, args: DrillArgs, ctx: Pick<QueryRunCtx, 'getFn'>): Promise<ResultTable | QueryProblem> {
262
- const stored = await ctx.getFn(args.fn);
263
- const parsed = QueryPayload.safeParse(stored.payload);
264
- if (stored.kind !== QUERY_KIND || !parsed.success) { return { invalid: `${args.fn} is not a saved database query.` }; }
265
- if (parsed.data.instance !== instance.instance) { return { invalid: `${args.fn} runs on the ${parsed.data.instance} database, not this one.` }; }
266
- const payload = this.#refresh(instance, parsed.data);
267
- const compiled = instance.compile(payload);
268
- if (!('query' in compiled)) { return this.#stale(args.fn, compiled); }
269
- const given = Json.parse({ ...args.args });
270
- const problems = argProblems(argsTypeOf(compiled, payload.sorters, this.#limits(), payload.optional), given);
271
- if (problems.length > 0) { return { invalid: `The args don't fit ${args.fn}: ${problems.join('; ')}` }; }
272
- const drill = drillOf(compiled);
273
- if (drill === undefined) { return { invalid: `${args.fn} can't be drilled into: its query doesn't group rows in a way that un-ravels.` }; }
274
- const { values } = callArgs(given);
275
- const bound: Record<string, Json> = {};
276
- for (const param of compiled.params) {
277
- const value = values[param.name];
278
- if (value !== undefined) { bound[param.name] = value; }
279
- }
280
- for (const key of drill.keys) {
281
- const value = args.group[key.column];
282
- if (value === undefined || value === null || Array.isArray(value)) { return { invalid: `The group has no value for ${key.column} to drill into.` }; }
283
- bound[key.param] = value;
284
- }
285
- const drilled = instance.compile({
286
- instance: payload.instance, description: payload.description, query: Json.parse(drill.def), sorters: [], list: true,
287
- ...(payload.generated === undefined ? {} : { generated: payload.generated }),
288
- });
289
- if (!('query' in drilled)) { return { failed: `The rows behind that group can't be read: ${drilled.problems.join(' ')}` }; }
290
- const page = { ...(args.limit === undefined ? {} : { limit: args.limit }), ...(args.offset === undefined ? {} : { offset: args.offset }) };
291
- const plan = instance.plan(drilled, { ...bound, ...page }, []);
292
- return resultTable(await instance.read(plan), drilled.columns, plan);
293
- }
294
-
295
- /** Read rows for a call: attach them for the person, and give the model its result block (`args` as called, sort too, for the next page's call). */
296
- async read(instance: DatabaseInstance, compiled: CompiledQuery, plan: CallPlan, fn: { name: string; signature: string }, args: Readonly<Record<string, Json>>, ctx: ReadCtx): Promise<ResultBlock> {
297
- const read = resultTable(await instance.read(plan), compiled.columns, plan);
298
- const drill = drillFor(compiled, fn.name, callArgs(Json.parse({ ...args })).values);
299
- const table = drill === undefined ? read : { ...read, drill };
300
- ctx.attach(table, fn.name);
301
- return resultBlock(table, { fn, args, watched: ctx.watched === true });
302
- }
303
-
304
- /**
305
- * Try an authoring draft: the draft check, then the args for this request against the fn it would be (a
306
- * missing required param is a problem, never NULL), then, for a clean read, its first `rows` rows with those args.
307
- */
308
- async tryDraft(instance: DatabaseInstance, draft: QueryDraft, args: Readonly<Record<string, Json>>, rows: number): Promise<DraftTrial> {
309
- const check = this.check(instance, draft);
310
- const compiled = instance.compile(this.#payload(instance, draft));
311
- if (!check.ok || !('query' in compiled)) { return { check }; }
312
- const problems = argProblems(argsTypeOf(compiled, draft.sorters ?? [], this.#limits()), Json.parse({ ...args }));
313
- if (problems.length > 0) { return { check: { ...check, ok: false, problems: problems.map((problem) => `The args for this request: ${problem}`) } }; }
314
- if (compiled.writes) { return { check }; }
315
- const { values, sort } = callArgs(Json.parse({ ...args }));
316
- const plan = instance.plan(compiled, compiled.list ? { ...values, limit: rows, offset: 0 } : values, sort);
317
- const table = resultTable(await instance.read(plan), compiled.columns, plan);
318
- const sample = table.rows.slice(0, rows).map((row) => Object.fromEntries(table.columns.map((column, at) => [column.name, row[at] ?? null])));
319
- return { check, sample };
320
- }
321
-
322
- /** Run an approved write, and what the model reads about it. */
323
- async write(instance: DatabaseInstance, compiled: CompiledQuery, plan: CallPlan, fn: { name: string; signature: string }, ctx: ReadCtx): Promise<WriteResult> {
324
- const written = await instance.write(plan);
325
- const shown = `${written.affected} ${written.affected === 1 ? 'row' : 'rows'} changed.`;
326
- if (written.columns.length === 0) { return { shown, affected: written.affected }; }
327
- // rows a write returns show what it changed: the view of them is read-only
328
- const table = { ...resultTable(written, compiled.columns, { offset: 0, limit: undefined, sort: [], cap: this.#settings.DATABASE_MAX_ROWS }), write: { affected: written.affected } };
329
- ctx.attach(table, fn.name);
330
- return { shown, affected: written.affected, returned: resultBlock(table, { fn, watched: ctx.watched === true }) };
331
- }
332
-
333
- /** What a write would do: its SQL, how many rows (from a rolled-back run), and the rows it matches now. */
334
- async preview(instance: DatabaseInstance, compiled: CompiledQuery, plan: CallPlan, description: string): Promise<ApprovalPreview> {
335
- const dry = await instance.dryRun(plan);
336
- const verb = compiled.def.kind === 'insert' ? 'Insert' : compiled.def.kind === 'delete' ? 'Delete' : 'Change';
337
- const target = compiled.tables[0] ?? 'rows';
338
- const parts: ApprovalPreview['parts'] = [
339
- { type: 'text', text: description },
340
- { type: 'code', language: 'sql', code: plan.sql, title: 'SQL' },
341
- ];
342
- const matched = await this.#matched(instance, compiled, plan);
343
- if (matched !== undefined) { parts.push({ type: 'table', title: compiled.def.kind === 'delete' ? 'Rows it deletes' : 'Rows it changes', table: matched }); }
344
- return { title: `${verb} ${dry.affected} ${dry.affected === 1 ? 'row' : 'rows'} in ${target} (${instance.config.label} database)`, parts, irreversible: compiled.def.kind === 'delete' };
345
- }
346
-
347
- #limits(): { page: number; max: number } {
348
- return { page: this.#settings.DATABASE_PAGE_ROWS, max: this.#settings.DATABASE_MAX_ROWS };
349
- }
350
-
351
- /** A saved query the tables no longer fit. */
352
- #stale(fn: string, refusal: Refusal): QueryProblem {
353
- return { invalid: `The saved query ${fn} no longer fits the tables: ${refusal.problems.join(' ')} Fix it with edit_query.` };
354
- }
355
-
356
- /** The rows an update or delete matches now, read with the same joins and conditions. */
357
- async #matched(instance: DatabaseInstance, compiled: CompiledQuery, plan: CallPlan): Promise<ResultTable | undefined> {
358
- const def = compiled.def;
359
- const target = def.kind === 'update' ? def.type : def.kind === 'delete' ? def.from : undefined;
360
- if (target === undefined || (def.kind !== 'update' && def.kind !== 'delete')) { return undefined; }
361
- const spec = instance.catalog.spec(target);
362
- if (spec === undefined) { return undefined; }
363
- const match = instance.compile({
364
- instance: instance.instance, description: 'matched rows', sorters: [], list: true,
365
- query: Json.parse({
366
- kind: 'select',
367
- fields: spec.columns.map((column) => ({ expr: { kind: 'field-ref', source: target, field: column.name }, as: column.name })),
368
- from: { kind: 'type', type: target },
369
- ...(def.joins === undefined ? {} : { joins: def.joins }),
370
- ...(def.where === undefined ? {} : { where: def.where }),
371
- }),
372
- });
373
- if (!('query' in match)) { return undefined; }
374
- const values: Record<string, Json> = { ...plan.bound, limit: this.#settings.DATABASE_PREVIEW_ROWS };
375
- const matchPlan = instance.plan(match, values, []);
376
- return resultTable(await instance.read(matchPlan), match.columns, matchPlan);
377
- }
378
-
379
- /** The payload of a draft: checked against the tables when `compiled` is given (only its output columns kept as sorters). */
380
- #payload(instance: DatabaseInstance, draft: QueryDraft, compiled?: CompiledQuery): QueryPayload {
381
- const sorters = draft.sorters ?? [];
382
- return QueryPayload.parse({
383
- instance: instance.instance,
384
- description: draft.description,
385
- query: compiled === undefined ? draft.query : Json.parse(compiled.def),
386
- sorters: compiled === undefined ? sorters : sorters.filter((name) => compiled.columns.some((column) => column.name === name)),
387
- list: compiled?.list ?? true,
388
- });
389
- }
390
- }
@@ -1,39 +0,0 @@
1
- /**
2
- * Rows read by a query as the `ResultTable` the person is shown (the `result` attachment): the query's columns, the
3
- * engine's `$total` taken out as the table's total, and whether more rows exist past the page. No table holds more than
4
- * the plan's cap (`DATABASE_MAX_ROWS`); rows past it are cut and the table says it is truncated. The model's view of it
5
- * is the SDK's `resultBlock`, worded for whether a person is watching.
6
- */
7
- import type { Json, ResultColumn, ResultTable } from '@harness/core';
8
- import type { CallPlan } from './compile.ts';
9
- import type { Rows } from './drivers/index.ts';
10
-
11
- /** The engine's total column, present on a counted list. */
12
- const TOTAL_COLUMN = '$total';
13
-
14
- /** Rows as a result table: the query's columns (by name where it knows them), and the total split off. */
15
- export function resultTable(read: Rows, columns: readonly ResultColumn[], plan: Pick<CallPlan, 'offset' | 'limit' | 'sort' | 'cap'>): ResultTable {
16
- const totalAt = read.columns.indexOf(TOTAL_COLUMN);
17
- const keep = read.columns.map((_, index) => index).filter((index) => index !== totalAt);
18
- const known = new Map(columns.map((column) => [column.name, column]));
19
- const tableColumns: ResultColumn[] = keep.map((index) => {
20
- const name = read.columns[index] ?? `column_${index + 1}`;
21
- return known.get(name) ?? { name, kind: 'text', nullable: true };
22
- });
23
- const cut = read.rows.length > plan.cap;
24
- const rows: Json[][] = read.rows.slice(0, plan.cap).map((row) => keep.map((index) => row[index] ?? null));
25
- const firstTotal = totalAt < 0 ? undefined : read.rows[0]?.[totalAt];
26
- // an empty page has no row to carry the count: past the end, or nothing matched
27
- const total = totalAt < 0 ? undefined : typeof firstTotal === 'number' ? firstTotal : plan.offset === 0 ? 0 : undefined;
28
- const more = cut || (total === undefined ? plan.limit !== undefined && rows.length >= plan.limit : plan.offset + rows.length < total);
29
- return {
30
- columns: tableColumns,
31
- rows,
32
- offset: plan.offset,
33
- ...(plan.limit === undefined ? {} : { limit: plan.limit }),
34
- ...(total === undefined ? {} : { total }),
35
- truncated: more,
36
- sort: [...plan.sort],
37
- };
38
- }
39
-
@@ -1,59 +0,0 @@
1
- /**
2
- * A database's schema as the system reads it: `@aeye/query`'s `TableSpec` per table (the same shape its DDL writers
3
- * take), with a row estimate beside it. Each table hashes to a stable digest of its shape, so enrichment and type
4
- * patches only happen when it changes.
5
- */
6
- import { createHash } from 'node:crypto';
7
- import type { ColumnKind } from '@harness/core';
8
- import { TableSpec, type ColumnType } from '@aeye/query';
9
- import { z } from 'zod';
10
-
11
- /** One table as scanned: its shape and roughly how many rows it has (for cost estimates; not part of its hash). */
12
- export const ScannedTable = z.object({ spec: TableSpec, rows: z.number().int().min(0) });
13
- export type ScannedTable = z.infer<typeof ScannedTable>;
14
-
15
- /** A stable digest of a table's shape. */
16
- export function schemaHash(spec: TableSpec): string {
17
- return createHash('sha256').update(JSON.stringify(spec)).digest('hex').slice(0, 24);
18
- }
19
-
20
- /** The kind of value a column holds, as results report it. */
21
- export function columnKind(type: ColumnType): ColumnKind {
22
- switch (type.kind) {
23
- case 'text': return 'text';
24
- case 'integer': return 'integer';
25
- case 'decimal': case 'float': return 'number';
26
- case 'bool': return 'boolean';
27
- case 'date': return 'date';
28
- case 'timestamp': return 'datetime';
29
- case 'uuid': return 'uuid';
30
- case 'json': return 'json';
31
- case 'bytes': return 'binary';
32
- case 'other': return /^time/i.test(type.native) ? 'time' : 'text';
33
- }
34
- }
35
-
36
- /** The values of a check constraint like `CHECK (status IN ('open', 'paid'))` for a column, if it has one. */
37
- export function checkValues(checkSql: string, column: string): string[] | undefined {
38
- const name = column.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
39
- const match = new RegExp(`["\`\\[]?${name}["\`\\]]?\\s+IN\\s*\\(([^)]*)\\)`, 'i').exec(checkSql);
40
- if (match?.[1] === undefined) { return undefined; }
41
- const values = [...match[1].matchAll(/'((?:[^']|'')*)'/g)].map((value) => (value[1] ?? '').replace(/''/g, '\''));
42
- return values.length > 0 ? values : undefined;
43
- }
44
-
45
- /** The values of SQL Server's spelling of an IN check: `([status]='open' OR [status]='paid')`. */
46
- export function orValues(definition: string, column: string): string[] | undefined {
47
- const name = column.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
48
- const values = [...definition.matchAll(new RegExp(`\\[${name}\\]\\s*=\\s*N?'((?:[^']|'')*)'`, 'gi'))].map((match) => (match[1] ?? '').replace(/''/g, '\''));
49
- return values.length > 0 ? values : undefined;
50
- }
51
-
52
- /** The values of Postgres's spelling of an IN check: `(tier)::text = ANY ((ARRAY['basic'::character varying, …])::text[])`. */
53
- export function anyValues(definition: string, column: string): string[] | undefined {
54
- const name = column.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
- const match = new RegExp(`\\(?"?${name}"?\\)?(?:::[\\w ]+)?\\s*=\\s*ANY\\s*\\(+ARRAY\\[([^\\]]*)\\]`, 'i').exec(definition);
56
- if (match?.[1] === undefined) { return undefined; }
57
- const values = [...match[1].matchAll(/'((?:[^']|'')*)'/g)].map((value) => (value[1] ?? '').replace(/''/g, '\''));
58
- return values.length > 0 ? values : undefined;
59
- }