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.
- package/README.md +31 -18
- package/package.json +2 -7
- package/packages/build/package.json +1 -1
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/commands/available.ts +63 -22
- package/packages/cli/src/commands/install.ts +86 -28
- package/packages/cli/src/index.ts +3 -2
- package/packages/cli/src/local.ts +6 -0
- package/packages/cli/src/premade.ts +80 -0
- package/packages/core/package.json +1 -1
- package/packages/hub/package.json +1 -1
- package/packages/hub/src/link/process.ts +6 -1
- package/packages/sdk/package.json +1 -1
- package/packages/web/package.json +1 -1
- package/premade/claude.zip +0 -0
- package/premade/database.zip +0 -0
- package/premade/web.zip +0 -0
- package/scripts/dev-env.ts +4 -4
- package/scripts/stack.ts +42 -27
- package/scripts/start.ts +26 -16
- package/systems/api/package.json +1 -1
- package/systems/code/package.json +1 -1
- package/systems/embedder/package.json +1 -1
- package/systems/fs/package.json +1 -1
- package/systems/google-calendar/package.json +1 -1
- package/systems/input/package.json +1 -1
- package/systems/mcp/package.json +1 -1
- package/systems/ollama/package.json +1 -1
- package/systems/schedule/package.json +1 -1
- package/systems/template/package.json +1 -1
- package/systems/widgets/package.json +1 -1
- package/systems/claude/client/FleetPage.vue +0 -132
- package/systems/claude/client/NewSessionForm.vue +0 -62
- package/systems/claude/client/SessionList.vue +0 -64
- package/systems/claude/client/SessionPage.vue +0 -199
- package/systems/claude/client/TaskList.vue +0 -61
- package/systems/claude/client/fakes.ts +0 -186
- package/systems/claude/client/host.ts +0 -23
- package/systems/claude/client/index.ts +0 -15
- package/systems/claude/client/logic.ts +0 -270
- package/systems/claude/client/state.ts +0 -344
- package/systems/claude/package.json +0 -23
- package/systems/claude/server/agent-sdk.ts +0 -379
- package/systems/claude/server/driver.ts +0 -153
- package/systems/claude/server/env.ts +0 -64
- package/systems/claude/server/fake-driver.ts +0 -112
- package/systems/claude/server/fleet.ts +0 -376
- package/systems/claude/server/impl.ts +0 -568
- package/systems/claude/server/index.ts +0 -8
- package/systems/claude/server/main.ts +0 -38
- package/systems/claude/server/preview.ts +0 -76
- package/systems/claude/server/questions.ts +0 -117
- package/systems/claude/server/transcript.ts +0 -83
- package/systems/claude/shared/index.ts +0 -262
- package/systems/claude/shared/session.ts +0 -284
- package/systems/claude/shared/shapes.ts +0 -106
- package/systems/claude/system.json +0 -18
- package/systems/claude/tsconfig.json +0 -6
- package/systems/database/package.json +0 -25
- package/systems/database/server/author.ts +0 -41
- package/systems/database/server/authoring.ts +0 -322
- package/systems/database/server/catalog.ts +0 -117
- package/systems/database/server/compile.ts +0 -332
- package/systems/database/server/dialects.ts +0 -17
- package/systems/database/server/drivers/database.ts +0 -71
- package/systems/database/server/drivers/index.ts +0 -23
- package/systems/database/server/drivers/postgres.ts +0 -157
- package/systems/database/server/drivers/sqlite.ts +0 -151
- package/systems/database/server/drivers/sqlserver.ts +0 -176
- package/systems/database/server/env.ts +0 -35
- package/systems/database/server/fixture.ts +0 -169
- package/systems/database/server/impl.ts +0 -793
- package/systems/database/server/index.ts +0 -7
- package/systems/database/server/instance.ts +0 -398
- package/systems/database/server/main.ts +0 -47
- package/systems/database/server/pick.ts +0 -97
- package/systems/database/server/queries.ts +0 -390
- package/systems/database/server/results.ts +0 -39
- package/systems/database/server/schema.ts +0 -59
- package/systems/database/server/table-fns.ts +0 -237
- package/systems/database/server/types.ts +0 -253
- package/systems/database/shared/index.ts +0 -544
- package/systems/database/shared/shapes.ts +0 -413
- package/systems/database/system.json +0 -14
- package/systems/database/tsconfig.json +0 -6
- package/systems/web/client/ReadView.vue +0 -110
- package/systems/web/client/SearchView.vue +0 -215
- package/systems/web/client/StatusChip.vue +0 -38
- package/systems/web/client/fakes.ts +0 -48
- package/systems/web/client/index.ts +0 -15
- package/systems/web/client/view.ts +0 -131
- package/systems/web/package.json +0 -22
- package/systems/web/server/chrome.ts +0 -121
- package/systems/web/server/crawl.ts +0 -333
- package/systems/web/server/env.ts +0 -63
- package/systems/web/server/guard.ts +0 -60
- package/systems/web/server/http.ts +0 -89
- package/systems/web/server/impl.ts +0 -203
- package/systems/web/server/index.ts +0 -71
- package/systems/web/server/loader.ts +0 -104
- package/systems/web/server/main.ts +0 -70
- package/systems/web/server/mentions.ts +0 -111
- package/systems/web/server/problem.ts +0 -72
- package/systems/web/server/renderer.ts +0 -243
- package/systems/web/server/robots.ts +0 -75
- package/systems/web/server/searches.ts +0 -29
- package/systems/web/server/tavily.ts +0 -144
- package/systems/web/server/testing.ts +0 -165
- package/systems/web/server/uploads.ts +0 -33
- package/systems/web/shared/index.ts +0 -343
- package/systems/web/shared/urls.ts +0 -60
- package/systems/web/system.json +0 -15
- package/systems/web/tsconfig.json +0 -6
|
@@ -1,322 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The query authoring agent behind `get_query` and `edit_query`, on the SDK's `authoringAgent` (product's query agent,
|
|
3
|
-
* ported): the chat model only describes what it wants; this agent works through a forced workflow on `ctx.ai()` and
|
|
4
|
-
* the chat gets back the saved fn and its run, never the working context.
|
|
5
|
-
*
|
|
6
|
-
* - **find:** `find_queries` searches the saved queries of this database (the hub's search) and lists its tables by
|
|
7
|
-
* name; `use_saved` answers with a saved query that already does it.
|
|
8
|
-
* - **inspect (progressive disclosure):** `load_tables` shows only the tables asked for, `load_query` one saved
|
|
9
|
-
* query's JSON, and `query_syntax` the expressions, functions and worked examples for the loaded tables.
|
|
10
|
-
* - **draft → check → fix:** the draft's `query` arg is `@aeye/query`'s grammar (`QueryGrammar`) bound over the loaded
|
|
11
|
-
* tables, so the model writes against the real types; each draft is checked (it compiles, a write only where writes
|
|
12
|
-
* are allowed, the args for this request fit its signature) and a clean read shows its first rows.
|
|
13
|
-
* - **save:** the clean draft is kept in the hub as a `database/query` fn of this instance (a new version when editing).
|
|
14
|
-
*/
|
|
15
|
-
import { describeExprs, describeFunctions, describeQueryExamples, describeTypes, QueryGrammar, type BuildSchemasOptions, type QueryDef, type Registry, type Type } from '@aeye/query';
|
|
16
|
-
import { a, type Bound, type Bundle } from '@aeye/schema';
|
|
17
|
-
import { Json, type FnSearchPage, type FnSearchQuery } from '@harness/core';
|
|
18
|
-
import { authoringAgent, authoringTool, type AuthoredFn, type AuthoringSession, type ShowArgs } from '@harness/sdk/server';
|
|
19
|
-
import { QueryDraft, QueryPayload, type QueryHow } from '../shared/shapes.ts';
|
|
20
|
-
import { QUERY_KIND } from '../shared/index.ts';
|
|
21
|
-
import { argsTypeOf, signatureOf } from './compile.ts';
|
|
22
|
-
import type { DatabaseInstance } from './instance.ts';
|
|
23
|
-
import { queryInstance, type QueryRunCtx, type QueryService } from './queries.ts';
|
|
24
|
-
|
|
25
|
-
/** A draft as the agent writes it: a saved query's draft, its `query` typed by the loaded tables, and this request's args. */
|
|
26
|
-
export interface AuthoringDraft {
|
|
27
|
-
readonly name: string;
|
|
28
|
-
readonly title: string;
|
|
29
|
-
readonly description: string;
|
|
30
|
-
readonly query: QueryDef;
|
|
31
|
-
readonly sorters?: string[];
|
|
32
|
-
readonly args?: Record<string, Json>;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** A saved query being changed (`edit_query`). */
|
|
36
|
-
export interface EditedQuery {
|
|
37
|
-
readonly fn: string;
|
|
38
|
-
/** Its name within the instance (`orders_by_status`); an edit keeps it. */
|
|
39
|
-
readonly local: string;
|
|
40
|
-
readonly payload: QueryPayload;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
/** How the run ended up with its fn, and the args to run it with for this request. */
|
|
44
|
-
export interface Chosen {
|
|
45
|
-
readonly how: QueryHow;
|
|
46
|
-
readonly why: string;
|
|
47
|
-
readonly args: Record<string, Json>;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** One authoring run's own state: the database, its query service, the run's hub side, and what was chosen. */
|
|
51
|
-
export class QueryAuthoring {
|
|
52
|
-
readonly here: DatabaseInstance;
|
|
53
|
-
readonly queries: QueryService;
|
|
54
|
-
readonly run: QueryRunCtx;
|
|
55
|
-
readonly search: (query: FnSearchQuery) => Promise<FnSearchPage>;
|
|
56
|
-
readonly editing: EditedQuery | undefined;
|
|
57
|
-
/** Rows a clean read's check shows the agent. */
|
|
58
|
-
readonly sampleRows: number;
|
|
59
|
-
#chosen: Chosen | undefined;
|
|
60
|
-
|
|
61
|
-
constructor(input: { here: DatabaseInstance; queries: QueryService; run: QueryRunCtx; search: (query: FnSearchQuery) => Promise<FnSearchPage>; editing?: EditedQuery | undefined; sampleRows: number }) {
|
|
62
|
-
this.here = input.here;
|
|
63
|
-
this.queries = input.queries;
|
|
64
|
-
this.run = input.run;
|
|
65
|
-
this.search = input.search;
|
|
66
|
-
this.editing = input.editing;
|
|
67
|
-
this.sampleRows = input.sampleRows;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** How the fn was come by, once it was saved or reused. */
|
|
71
|
-
get chosen(): Chosen | undefined {
|
|
72
|
-
return this.#chosen;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
choose(chosen: Chosen): void {
|
|
76
|
-
this.#chosen = chosen;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** The engine's types of these tables (all of them when none are named). */
|
|
80
|
-
types(names: readonly string[]): Type[] {
|
|
81
|
-
const all = this.here.catalog.engine.registry.typeList();
|
|
82
|
-
return names.length === 0 ? all : all.filter((type) => names.includes(type.name));
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
/** The table names the agent may load: the engine's type names. */
|
|
86
|
-
tableNames(): string[] {
|
|
87
|
-
return this.here.catalog.engine.registry.typeList().map((type) => type.name);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
type Session = AuthoringSession<QueryAuthoring, AuthoringDraft>;
|
|
92
|
-
|
|
93
|
-
/** A query's param values, by name, as the model writes them. */
|
|
94
|
-
const ParamArgs = a.record(a.json());
|
|
95
|
-
|
|
96
|
-
/** A call written the way the chat model writes one. */
|
|
97
|
-
export function callText(fn: string, args: Readonly<Record<string, Json>>): string {
|
|
98
|
-
return `${fn}(${JSON.stringify(args)})`;
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** The draft as the instance checks and keeps it (`QueryService.check` / `save`). */
|
|
102
|
-
function asDraft(draft: AuthoringDraft): QueryDraft {
|
|
103
|
-
return { name: draft.name, title: draft.title, description: draft.description, query: Json.parse(draft.query), ...(draft.sorters === undefined ? {} : { sorters: draft.sorters }) };
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** The query draft the examples write: orders with a status and their customer, biggest first. */
|
|
107
|
-
export const EXAMPLE_DRAFT = {
|
|
108
|
-
name: 'orders_by_status', title: 'Orders by status', description: 'Orders with a given status and their customer, biggest first; the status is a param.', sorters: ['total', 'customer'],
|
|
109
|
-
query: {
|
|
110
|
-
kind: 'select',
|
|
111
|
-
fields: [
|
|
112
|
-
{ expr: { kind: 'field-ref', source: 'orders', field: 'id' }, as: 'id' },
|
|
113
|
-
{ expr: { kind: 'field-ref', source: 'orders', field: 'total' }, as: 'total' },
|
|
114
|
-
{ expr: { kind: 'field-ref', source: 'customers', field: 'name' }, as: 'customer' },
|
|
115
|
-
],
|
|
116
|
-
from: { kind: 'type', type: 'orders' },
|
|
117
|
-
joins: [{ on: { kind: 'relation', source: 'orders', field: 'customer', as: 'customers' }, joinType: 'inner' }],
|
|
118
|
-
where: [{ kind: 'comparison', op: '=', left: { kind: 'field-ref', source: 'orders', field: 'status' }, right: { kind: 'param', name: 'status' } }],
|
|
119
|
-
order: [{ expr: { kind: 'field-ref', source: 'orders', field: 'total' }, dir: 'desc' }],
|
|
120
|
-
},
|
|
121
|
-
args: { status: 'paid' },
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
/** An insert the examples write: one new customer, its name and email as params and a fixed tier. */
|
|
125
|
-
export const EXAMPLE_INSERT_DRAFT = {
|
|
126
|
-
name: 'add_customer', title: 'Add a customer', description: 'Adds one customer with a name and an email; the tier starts as basic.', sorters: [],
|
|
127
|
-
query: {
|
|
128
|
-
kind: 'insert',
|
|
129
|
-
into: 'customers',
|
|
130
|
-
rows: [{ name: { kind: 'param', name: 'name' }, email: { kind: 'param', name: 'email' }, tier: { kind: 'literal', value: 'basic' } }],
|
|
131
|
-
},
|
|
132
|
-
args: { name: 'Dee', email: 'dee@example.com' },
|
|
133
|
-
};
|
|
134
|
-
|
|
135
|
-
/** A date window the examples write: orders placed between two date params, so both ends are checked. */
|
|
136
|
-
export const EXAMPLE_RANGE_DRAFT = {
|
|
137
|
-
name: 'orders_placed_between', title: 'Orders placed between two days', description: 'Orders placed from a start day to an end day (both included), newest first; the two days are params.', sorters: ['placed', 'total'],
|
|
138
|
-
query: {
|
|
139
|
-
kind: 'select',
|
|
140
|
-
fields: [
|
|
141
|
-
{ expr: { kind: 'field-ref', source: 'orders', field: 'id' }, as: 'id' },
|
|
142
|
-
{ expr: { kind: 'field-ref', source: 'orders', field: 'placed' }, as: 'placed' },
|
|
143
|
-
{ expr: { kind: 'field-ref', source: 'orders', field: 'total' }, as: 'total' },
|
|
144
|
-
],
|
|
145
|
-
from: { kind: 'type', type: 'orders' },
|
|
146
|
-
where: [{ kind: 'between', value: { kind: 'field-ref', source: 'orders', field: 'placed' }, lower: { kind: 'param', name: 'from' }, upper: { kind: 'param', name: 'to' } }],
|
|
147
|
-
order: [{ expr: { kind: 'field-ref', source: 'orders', field: 'placed' }, dir: 'desc' }],
|
|
148
|
-
},
|
|
149
|
-
args: { from: '2026-10-01', to: '2026-10-31' },
|
|
150
|
-
};
|
|
151
|
-
|
|
152
|
-
/** The agent's job, step by step, with worked examples, each written as the model writes the draft tool's args (`ShowArgs`). */
|
|
153
|
-
const INSTRUCTIONS = (show: ShowArgs): string => [
|
|
154
|
-
'You write one saved database query for the request below, and nothing else. Work through the tools in order; each step unlocks the next.',
|
|
155
|
-
'',
|
|
156
|
-
'1. find_queries with the request in plain words. It lists saved queries of this database that may fit, and the database\'s tables.',
|
|
157
|
-
' A saved query that returns the same rows (other param values are fine) is the answer: call use_saved with its name and the args for this request.',
|
|
158
|
-
' When editing a saved query, it is listed first: load it with load_query.',
|
|
159
|
-
'2. load_tables with only the tables the query needs (and load_query for a saved query you change). Call query_syntax once if you are unsure how to write an expression, a join, a group or a function.',
|
|
160
|
-
'3. draft the whole query. Rules:',
|
|
161
|
-
' - Use only the loaded tables and their fields. A field is { "kind": "field-ref", "source": "<table>", "field": "<field>" }.',
|
|
162
|
-
' - Join over a relation field: "joins": [{ "on": { "kind": "relation", "source": "orders", "field": "customer", "as": "customers" } }], then read joined fields with source "customers".',
|
|
163
|
-
' - Every value the request leaves open (a name, a date, a status) is a { "kind": "param", "name": "<name>" }, so the query is reused with other values; give this request\'s values in "args". Fixed values are literals.',
|
|
164
|
-
' - Name output fields with "as". No "limit" for a list (callers page it); only a fixed top-N ("the 5 largest") has its own limit.',
|
|
165
|
-
' - "name" is snake_case, "title" a few words, "description" one sentence on what it returns and what its params are for (later requests are matched against it). "sorters" lists output fields a caller may sort by.',
|
|
166
|
-
' - Inserts, updates and deletes only when the request asks to change data; each run waits for the person\'s approval. An insert is { "kind": "insert", "into": "<table>", "rows": [{ "<field>": <value or param>, ... }] }: leave out the id (it fills itself in) and give every required field.',
|
|
167
|
-
' - A time window ("last 30 days", "this month", "between May and June") needs both ends: a "between" with a "from" and a "to" param (or two comparisons). Give this request\'s dates in "args" as "YYYY-MM-DD", as the request states them. Look at the preview rows: if a window that should hold rows holds none, the condition is probably wrong.',
|
|
168
|
-
'4. The draft is checked at once (and a read is run on a few rows for a preview). Fix every problem listed and draft again, whole.',
|
|
169
|
-
' A problem names where it is (a path such as "query.where.0.right"): change only what it names and keep the rest. Never send the same draft twice; if the same problem comes back, try another way of writing that part (query_syntax shows each one).',
|
|
170
|
-
'5. Once it is clean, call save. Then answer in one line.',
|
|
171
|
-
'',
|
|
172
|
-
'Example. For "orders with a given status (paid now), biggest first, with the customer\'s name", after loading orders and customers, the draft is:',
|
|
173
|
-
show('draft', EXAMPLE_DRAFT, 'draft'),
|
|
174
|
-
'Example. For "add a customer with a name and an email (Dee, dee@example.com)", after loading customers, the draft is:',
|
|
175
|
-
show('draft', EXAMPLE_INSERT_DRAFT, 'draft'),
|
|
176
|
-
'Example. For "orders placed in October 2026, newest first", after loading orders, the draft is:',
|
|
177
|
-
show('draft', EXAMPLE_RANGE_DRAFT, 'draft'),
|
|
178
|
-
].join('\n');
|
|
179
|
-
|
|
180
|
-
/** `find_queries`: the saved queries of this database that may fit, and its tables by name. */
|
|
181
|
-
const findQueries = authoringTool<QueryAuthoring, AuthoringDraft, { text: string }>({
|
|
182
|
-
name: 'find_queries',
|
|
183
|
-
stage: 'find',
|
|
184
|
-
description: 'Search the saved queries of this database by what the request wants, and list the database\'s tables.',
|
|
185
|
-
instructions: 'Call it first, with the request in a few plain words.',
|
|
186
|
-
schema: a.object({ text: a.string().min(1).describe('What the request wants, in plain words.') }),
|
|
187
|
-
async call({ text }, session) {
|
|
188
|
-
const state = session.state;
|
|
189
|
-
const page = await state.search({ text, kinds: [QUERY_KIND], instance: state.here.instance, items: ['fn'], available: false, limit: 6 });
|
|
190
|
-
const hits = page.items.filter((hit) => hit.name !== state.editing?.fn);
|
|
191
|
-
const found = [...(state.editing === undefined ? [] : [state.editing.fn]), ...hits.map((hit) => hit.name)];
|
|
192
|
-
session.disclosure.markSearched('fn');
|
|
193
|
-
session.disclosure.markAware('fn', found);
|
|
194
|
-
session.disclosure.markAware('table', state.tableNames());
|
|
195
|
-
const tables = state.here.catalog.tableList();
|
|
196
|
-
return [
|
|
197
|
-
state.editing === undefined ? '' : `Editing ${state.editing.fn}: ${state.editing.payload.description}`,
|
|
198
|
-
hits.length === 0 ? 'No saved query fits.' : 'Saved queries that may fit:',
|
|
199
|
-
...hits.map((hit) => `- ${hit.name}${hit.signature === undefined ? '' : ` ${hit.signature}`}: ${hit.description}`),
|
|
200
|
-
`Tables of the ${state.here.config.label} database (${state.here.writes ? 'writes allowed, each after approval' : 'read-only'}): ${tables.join('; ')}.`,
|
|
201
|
-
'Load the tables you need with load_tables.',
|
|
202
|
-
].filter((line) => line !== '').join('\n');
|
|
203
|
-
},
|
|
204
|
-
});
|
|
205
|
-
|
|
206
|
-
/** `use_saved`: a saved query already does it; it runs with this request's args. */
|
|
207
|
-
const useSaved = authoringTool<QueryAuthoring, AuthoringDraft, { fn: string; args?: Record<string, Json> }>({
|
|
208
|
-
name: 'use_saved',
|
|
209
|
-
stage: 'find',
|
|
210
|
-
description: 'Answer with a saved query find_queries listed that returns what was asked, run with this request\'s args.',
|
|
211
|
-
schema: a.object({ fn: a.string().min(1), args: ParamArgs.optional().describe('The values for its params, by name.') }),
|
|
212
|
-
when: (session) => session.disclosure.searched('fn') && session.state.editing === undefined,
|
|
213
|
-
async call({ fn, args }, session) {
|
|
214
|
-
const state = session.state;
|
|
215
|
-
if (!session.disclosure.awareUnloaded('fn').includes(fn) && !session.disclosure.isLoaded('fn', fn)) { throw new Error(`${fn} was not listed by find_queries.`); }
|
|
216
|
-
const stored = await state.run.getFn(fn);
|
|
217
|
-
const payload = QueryPayload.safeParse(stored.payload);
|
|
218
|
-
if (stored.kind !== QUERY_KIND || !payload.success || payload.data.instance !== state.here.instance) { throw new Error(`${fn} is not a saved query of this database.`); }
|
|
219
|
-
const compiled = state.here.compile(payload.data);
|
|
220
|
-
if (!('query' in compiled)) { throw new Error(`${fn} no longer fits the tables: ${compiled.problems.join(' ')} Write a new query instead.`); }
|
|
221
|
-
const given = args ?? {};
|
|
222
|
-
const signature = signatureOf(stored.fn, argsTypeOf(compiled, payload.data.sorters, { page: 1, max: 1 }, payload.data.optional));
|
|
223
|
-
state.choose({ how: 'reused', why: `The saved ${stored.fn} already does this.`, args: given });
|
|
224
|
-
const result: AuthoredFn = { fn: stored.fn, version: stored.version, signature, about: payload.data.description, reused: true, call: callText(stored.fn, given) };
|
|
225
|
-
session.finish(result);
|
|
226
|
-
return `Using ${stored.fn}. Now answer in one line.`;
|
|
227
|
-
},
|
|
228
|
-
});
|
|
229
|
-
|
|
230
|
-
/** `load_tables`: the named tables in full (fields, types, relations), only those. */
|
|
231
|
-
const loadTables = authoringTool<QueryAuthoring, AuthoringDraft, { names: string[] }>({
|
|
232
|
-
name: 'load_tables',
|
|
233
|
-
stage: 'inspect',
|
|
234
|
-
description: 'Show tables in full: their fields with types, choices and ranges, and their relations. Load only the tables the query needs.',
|
|
235
|
-
schema: a.object({ names: a.array(a.string().min(1)).min(1).describe('Table names as find_queries listed them.') }),
|
|
236
|
-
when: (session) => session.disclosure.awareUnloaded('table').length > 0,
|
|
237
|
-
call({ names }, session) {
|
|
238
|
-
const known = session.state.tableNames();
|
|
239
|
-
const unknown = names.filter((name) => !known.includes(name));
|
|
240
|
-
if (unknown.length > 0) { throw new Error(`No table ${unknown.join(', ')}; the tables are ${known.join(', ')}.`); }
|
|
241
|
-
session.disclosure.markLoaded('table', names);
|
|
242
|
-
return describeTypes(session.state.here.catalog.engine, session.state.types(names));
|
|
243
|
-
},
|
|
244
|
-
});
|
|
245
|
-
|
|
246
|
-
/** `load_query`: a saved query's description, sorters and JSON, to change it or write one like it. */
|
|
247
|
-
const loadQuery = authoringTool<QueryAuthoring, AuthoringDraft, { fn: string }>({
|
|
248
|
-
name: 'load_query',
|
|
249
|
-
stage: 'inspect',
|
|
250
|
-
description: 'Show a saved query find_queries listed: its description, sorters and its query JSON.',
|
|
251
|
-
schema: a.object({ fn: a.string().min(1) }),
|
|
252
|
-
when: (session) => session.disclosure.awareUnloaded('fn').length > 0,
|
|
253
|
-
async call({ fn }, session) {
|
|
254
|
-
const state = session.state;
|
|
255
|
-
const payload = state.editing?.fn === fn ? state.editing.payload : QueryPayload.safeParse((await state.run.getFn(fn)).payload).data;
|
|
256
|
-
if (payload === undefined) { throw new Error(`${fn} is not a saved database query.`); }
|
|
257
|
-
session.disclosure.markLoaded('fn', [fn]);
|
|
258
|
-
return [`${fn}: ${payload.description}`, `Sorters: ${payload.sorters.join(', ') || 'none'}`, `Query: ${JSON.stringify(payload.query)}`].join('\n');
|
|
259
|
-
},
|
|
260
|
-
});
|
|
261
|
-
|
|
262
|
-
/** `query_syntax`: the expressions, functions and worked examples usable on the loaded tables, once tables are loaded. */
|
|
263
|
-
const querySyntax = authoringTool<QueryAuthoring, AuthoringDraft, Record<string, never>>({
|
|
264
|
-
name: 'query_syntax',
|
|
265
|
-
stage: 'inspect',
|
|
266
|
-
description: 'Show the query language for the loaded tables: every expression kind, the functions, and worked example queries.',
|
|
267
|
-
schema: a.object({}),
|
|
268
|
-
when: (session) => session.disclosure.loaded('table').length > 0 && !session.disclosure.isLoaded('docs', 'syntax'),
|
|
269
|
-
call(_input, session) {
|
|
270
|
-
const engine = session.state.here.catalog.engine;
|
|
271
|
-
const types = session.state.types(session.disclosure.loaded('table'));
|
|
272
|
-
session.disclosure.markLoaded('docs', ['syntax']);
|
|
273
|
-
return [describeExprs(engine, types, 'all', 1), describeFunctions(engine, 'all', 1), describeQueryExamples(engine, 1)].join('\n\n');
|
|
274
|
-
},
|
|
275
|
-
});
|
|
276
|
-
|
|
277
|
-
/** The draft: a saved query's draft whose `query` is in the query grammar, and this request's args. */
|
|
278
|
-
export const AuthoringDraftSchema: Bundle<AuthoringDraft, [Registry, BuildSchemasOptions?]> = QueryGrammar.result(QueryDraft.extend({
|
|
279
|
-
query: a.ref('Query').describe('The query, typed by the loaded tables.'),
|
|
280
|
-
args: ParamArgs.optional().describe('This request\'s values for the query\'s params, by name.'),
|
|
281
|
-
}));
|
|
282
|
-
|
|
283
|
-
/** The draft's schema for this session: the query grammar bound over the loaded tables. */
|
|
284
|
-
function draftSchema(session: Session): Bound<AuthoringDraft> {
|
|
285
|
-
const state = session.state;
|
|
286
|
-
return AuthoringDraftSchema.bind(state.here.catalog.engine.registry, { types: state.types(session.disclosure.loaded('table')) });
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/** The query authoring agent. Run it with the run's `ctx.ai()` and a `QueryAuthoring`. */
|
|
290
|
-
export const queryAuthoring = authoringAgent<QueryAuthoring, AuthoringDraft>({
|
|
291
|
-
name: 'query_author',
|
|
292
|
-
description: 'Find or write one saved database query for a request.',
|
|
293
|
-
instructions: INSTRUCTIONS,
|
|
294
|
-
tools: [findQueries, useSaved, loadTables, loadQuery, querySyntax],
|
|
295
|
-
draft: { description: 'a saved query: name, title, description, the query, sorters, and this request\'s args.', schema: draftSchema },
|
|
296
|
-
async check(draft, session) {
|
|
297
|
-
const state = session.state;
|
|
298
|
-
const problems: string[] = [];
|
|
299
|
-
if (state.editing !== undefined && draft.name !== state.editing.local) { problems.push(`Keep the name "${state.editing.local}": this edits that query.`); }
|
|
300
|
-
const trial = await state.queries.tryDraft(state.here, asDraft(draft), draft.args ?? {}, state.sampleRows);
|
|
301
|
-
problems.push(...trial.check.problems);
|
|
302
|
-
const note = [trial.check.sql === undefined ? '' : `SQL: ${trial.check.sql}`, trial.check.signature === undefined ? '' : `Fn: ${trial.check.signature}`].filter((line) => line !== '').join('\n');
|
|
303
|
-
return { problems, ...(trial.sample === undefined ? {} : { preview: [...trial.sample] }), ...(note === '' ? {} : { note }) };
|
|
304
|
-
},
|
|
305
|
-
async save(draft, session) {
|
|
306
|
-
const state = session.state;
|
|
307
|
-
const args = draft.args ?? {};
|
|
308
|
-
const saved = await state.queries.save(state.here, asDraft(draft), { args, askedFor: session.request, ...(state.editing === undefined ? {} : { replace: true }) }, state.run);
|
|
309
|
-
if (!('fn' in saved)) { throw new Error('invalid' in saved ? saved.invalid : saved.failed); }
|
|
310
|
-
state.choose(state.editing === undefined
|
|
311
|
-
? { how: 'created', why: `No saved query did this, so ${saved.fn} was written: ${draft.description}`, args }
|
|
312
|
-
: { how: 'edited', why: `Changed as asked; version ${saved.version}. ${draft.description}`, args });
|
|
313
|
-
const preview = session.lastCheck?.preview;
|
|
314
|
-
return { fn: saved.fn, version: saved.version, signature: saved.signature, about: draft.description, reused: false, ...(preview === undefined ? {} : { preview }), call: callText(saved.fn, args) };
|
|
315
|
-
},
|
|
316
|
-
});
|
|
317
|
-
|
|
318
|
-
/** A saved query's name within its instance, from its fn (`database/main.orders` → `orders`). */
|
|
319
|
-
export function localName(fn: string): string | undefined {
|
|
320
|
-
const local = queryInstance(fn)?.local;
|
|
321
|
-
return local === undefined ? undefined : local.slice(local.indexOf('.') + 1);
|
|
322
|
-
}
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* One database's tables as the system knows them after a scan: the query engine over their types (what queries are
|
|
3
|
-
* checked against and emitted from), the hub's type of each table, and the schema text the query agent writes
|
|
4
|
-
* against. Each hub type carries its `TableMeta`, so the enrichment is kept with the type in the hub.
|
|
5
|
-
*/
|
|
6
|
-
import { QueryEngine, createRegistry, describeEngine, tableToQueryType, type Dialect, type TableSpec, type TypeBacking } from '@aeye/query';
|
|
7
|
-
import { JsonObject, type GinTypeDef, type InstanceName, type TypeDecl } from '@harness/core';
|
|
8
|
-
import type { DatabaseConfig, DialectName } from '../shared/shapes.ts';
|
|
9
|
-
import { dialectFor } from './dialects.ts';
|
|
10
|
-
import { schemaHash, type ScannedTable } from './schema.ts';
|
|
11
|
-
import { engineTypeOf, hubTypeOf, identifierOf, titleOf, typeNameOf, type TableEnrichment, type TableMeta } from './types.ts';
|
|
12
|
-
|
|
13
|
-
/** The meta a table type carries to the hub: its schema hash and enrichment. */
|
|
14
|
-
function metaOf(table: CatalogTable): JsonObject {
|
|
15
|
-
const meta: TableMeta = { schemaHash: table.hash, ...(table.enrichment === undefined ? {} : { enrichment: table.enrichment }) };
|
|
16
|
-
// through JSON, so the optional fields a model left out are dropped rather than kept as undefined
|
|
17
|
-
return JsonObject.parse(JSON.parse(JSON.stringify(meta)));
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
/** One table: its scan, hash, enrichment (when there is one) and hub type. */
|
|
21
|
-
export interface CatalogTable {
|
|
22
|
-
readonly scanned: ScannedTable;
|
|
23
|
-
readonly hash: string;
|
|
24
|
-
readonly enrichment: TableEnrichment | undefined;
|
|
25
|
-
/** Its hub type's local name (`main.orders`). */
|
|
26
|
-
readonly typeName: string;
|
|
27
|
-
readonly hubType: GinTypeDef;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** A database's tables, typed for the hub and for the query engine. */
|
|
31
|
-
export class TableCatalog {
|
|
32
|
-
readonly instance: InstanceName;
|
|
33
|
-
readonly dialectName: DialectName;
|
|
34
|
-
readonly dialect: Dialect;
|
|
35
|
-
readonly engine: QueryEngine;
|
|
36
|
-
/**
|
|
37
|
-
* The engine over `@aeye/query`'s own table types (`tableToQueryType`), which the generated table fns are written
|
|
38
|
-
* against: a foreign key column is itself the relation there, where `engine` keeps it a value and adds a relation
|
|
39
|
-
* named after it. Made on first use.
|
|
40
|
-
*/
|
|
41
|
-
#tableEngine: QueryEngine | undefined;
|
|
42
|
-
readonly tables: readonly CatalogTable[];
|
|
43
|
-
|
|
44
|
-
constructor(instance: InstanceName, dialectName: DialectName, scanned: readonly ScannedTable[], enrichments: ReadonlyMap<string, TableEnrichment>) {
|
|
45
|
-
this.instance = instance;
|
|
46
|
-
this.dialectName = dialectName;
|
|
47
|
-
this.dialect = dialectFor(dialectName);
|
|
48
|
-
this.tables = scanned.map((table) => {
|
|
49
|
-
const enrichment = enrichments.get(schemaHash(table.spec));
|
|
50
|
-
return { scanned: table, hash: schemaHash(table.spec), enrichment, typeName: typeNameOf(instance, table.spec.name), hubType: hubTypeOf(table.spec, enrichment) };
|
|
51
|
-
});
|
|
52
|
-
const registry = createRegistry();
|
|
53
|
-
const types = this.tables.map((table) => engineTypeOf(table.scanned, table.enrichment));
|
|
54
|
-
const backings: Record<string, TypeBacking> = {};
|
|
55
|
-
for (const type of types) {
|
|
56
|
-
registry.registerType(registry.parseType(type.def));
|
|
57
|
-
backings[type.def.name] = type.backing;
|
|
58
|
-
}
|
|
59
|
-
this.engine = new QueryEngine(registry, { backings });
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** The engine the generated table fns run on (see `#tableEngine`). */
|
|
63
|
-
get tableEngine(): QueryEngine {
|
|
64
|
-
if (this.#tableEngine === undefined) {
|
|
65
|
-
const specs = this.tables.map((table) => table.scanned.spec);
|
|
66
|
-
const registry = createRegistry();
|
|
67
|
-
for (const spec of specs) { registry.registerType(registry.parseType(tableToQueryType(spec, { tables: specs, rowCount: Math.max(1, this.tables.find((table) => table.scanned.spec === spec)?.scanned.rows ?? 1) }))); }
|
|
68
|
-
this.#tableEngine = new QueryEngine(registry);
|
|
69
|
-
}
|
|
70
|
-
return this.#tableEngine;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** The table with this name (physical or as a type), if there is one. */
|
|
74
|
-
table(name: string): CatalogTable | undefined {
|
|
75
|
-
return this.tables.find((table) => table.scanned.spec.name === name || identifierOf(table.scanned.spec.name) === name || table.typeName === name);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** The current shape of a table, if it exists. */
|
|
79
|
-
spec(name: string): TableSpec | undefined {
|
|
80
|
-
return this.table(name)?.scanned.spec;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* The hub's declaration of each table's type, belonging to this instance and seen only by the database's audience
|
|
85
|
-
* (the descriptions carry sample values from its rows).
|
|
86
|
-
*/
|
|
87
|
-
typeDecls({ label, audience }: Pick<DatabaseConfig, 'label' | 'audience'>): TypeDecl[] {
|
|
88
|
-
return this.tables.map((table) => {
|
|
89
|
-
const title = titleOf(table.scanned.spec);
|
|
90
|
-
return {
|
|
91
|
-
name: table.typeName,
|
|
92
|
-
description: `${table.enrichment?.description ?? `A row of ${table.scanned.spec.name} in ${label}.`} Columns: ${table.scanned.spec.columns.map((column) => column.name).join(', ')}.`,
|
|
93
|
-
def: table.hubType,
|
|
94
|
-
display: { label: table.scanned.spec.name, icon: 'table', ...(title === undefined ? {} : { title }) },
|
|
95
|
-
methods: [],
|
|
96
|
-
instance: this.instance,
|
|
97
|
-
audience,
|
|
98
|
-
meta: metaOf(table),
|
|
99
|
-
};
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** The schema as the query agent reads it: every table type, the expressions and functions it may use. */
|
|
104
|
-
describe(): string {
|
|
105
|
-
return describeEngine(this.engine, { maxExamples: 1 });
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
/** Its tables, each with what it holds when known (`orders (one per checkout)`). */
|
|
109
|
-
tableList(): string[] {
|
|
110
|
-
return this.tables.map((table) => `${table.scanned.spec.name}${table.enrichment === undefined ? '' : ` (${table.enrichment.description})`}`);
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
/** A few words on what the database holds, for matching descriptions to databases. */
|
|
114
|
-
summary(label: string): string {
|
|
115
|
-
return `${label}: ${this.tables.map((table) => `${table.scanned.spec.name} (${table.scanned.spec.columns.map((column) => column.name).join(', ')})${table.enrichment === undefined ? '' : ` — ${table.enrichment.description}`}`).join('; ')}`;
|
|
116
|
-
}
|
|
117
|
-
}
|