@colin_kerr/query-agent-client 0.0.0-stage → 0.1.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 (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/dist/cjs/agent-client.d.ts +107 -0
  4. package/dist/cjs/agent-client.js +142 -0
  5. package/dist/cjs/agent-client.js.map +1 -0
  6. package/dist/cjs/caps.d.ts +43 -0
  7. package/dist/cjs/caps.js +51 -0
  8. package/dist/cjs/caps.js.map +1 -0
  9. package/dist/cjs/client.d.ts +145 -0
  10. package/dist/cjs/client.js +270 -0
  11. package/dist/cjs/client.js.map +1 -0
  12. package/dist/cjs/index.d.ts +11 -0
  13. package/dist/cjs/index.js +28 -0
  14. package/dist/cjs/index.js.map +1 -0
  15. package/dist/cjs/node/index.d.ts +27 -0
  16. package/dist/cjs/node/index.js +59 -0
  17. package/dist/cjs/node/index.js.map +1 -0
  18. package/dist/cjs/query-runner.d.ts +34 -0
  19. package/dist/cjs/query-runner.js +41 -0
  20. package/dist/cjs/query-runner.js.map +1 -0
  21. package/dist/cjs/result-pages.d.ts +69 -0
  22. package/dist/cjs/result-pages.js +176 -0
  23. package/dist/cjs/result-pages.js.map +1 -0
  24. package/dist/cjs/selection.d.ts +90 -0
  25. package/dist/cjs/selection.js +222 -0
  26. package/dist/cjs/selection.js.map +1 -0
  27. package/dist/cjs/startup-queries.json +182 -0
  28. package/dist/cjs/turn-api.d.ts +156 -0
  29. package/dist/cjs/turn-api.js +19 -0
  30. package/dist/cjs/turn-api.js.map +1 -0
  31. package/dist/esm/agent-client.d.ts +107 -0
  32. package/dist/esm/agent-client.js +134 -0
  33. package/dist/esm/agent-client.js.map +1 -0
  34. package/dist/esm/caps.d.ts +43 -0
  35. package/dist/esm/caps.js +48 -0
  36. package/dist/esm/caps.js.map +1 -0
  37. package/dist/esm/client.d.ts +145 -0
  38. package/dist/esm/client.js +260 -0
  39. package/dist/esm/client.js.map +1 -0
  40. package/dist/esm/index.d.ts +11 -0
  41. package/dist/esm/index.js +12 -0
  42. package/dist/esm/index.js.map +1 -0
  43. package/dist/esm/query-runner.d.ts +34 -0
  44. package/dist/esm/query-runner.js +38 -0
  45. package/dist/esm/query-runner.js.map +1 -0
  46. package/dist/esm/result-pages.d.ts +69 -0
  47. package/dist/esm/result-pages.js +172 -0
  48. package/dist/esm/result-pages.js.map +1 -0
  49. package/dist/esm/selection.d.ts +90 -0
  50. package/dist/esm/selection.js +212 -0
  51. package/dist/esm/selection.js.map +1 -0
  52. package/dist/esm/startup-queries.json +182 -0
  53. package/dist/esm/turn-api.d.ts +156 -0
  54. package/dist/esm/turn-api.js +16 -0
  55. package/dist/esm/turn-api.js.map +1 -0
  56. package/package.json +67 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Colin Kerr
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @colin_kerr/query-agent-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The query agent's client library for iTwin.js apps. The agent answers questions about an iModel
4
+ by writing and running ECSql. This library runs every query on your app's own iModel and drives
5
+ the conversation with the agent function (a separate service that you host and give the URL of).
6
+
7
+ ```ts
8
+ import { AgentClient, queryRunner } from "@colin_kerr/query-agent-client";
9
+
10
+ const client = AgentClient.start({ runQuery: queryRunner(imodel), imodelName: imodel.name, functionUrl });
11
+ const run = await client.ask("How many pipes are there?");
12
+ console.log(run.answer, run.query);
13
+ ```
14
+
15
+ `@colin_kerr/query-agent-client/node` starts iTwin.js's frontend in Node, for tests and scripts.
16
+ It needs the optional peer dependencies `global-jsdom` and `jsdom`.
17
+
18
+ For the React controls, see `@colin_kerr/query-agent-react`. The full guide and the design are in
19
+ the [repository](https://github.com/ColinKerr/query_agent_ui).
20
+
21
+ MIT licence.
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The client a host starts for an open iModel: it runs the startup list when it starts, then
3
+ * answers questions by driving turns with the function.
4
+ *
5
+ * ```ts
6
+ * const client = AgentClient.start({ runQuery: queryRunner(imodel), imodelName, functionUrl });
7
+ * const run = await client.ask("How many pipes are there?", { onStatus });
8
+ * ```
9
+ */
10
+ import { type RunRawQuery } from "./caps.js";
11
+ import { type AgentRun, type AnswerRows, type StartupList, type TurnCall } from "./client.js";
12
+ import { type InstanceKey, type RunSelection } from "./selection.js";
13
+ import type { AnswerMode, EarlierQuestion, QueryRows, ResultCaps, StartupResult } from "./turn-api.js";
14
+ /** The library's startup query list (`startup-queries.json`): what a client runs when it starts. */
15
+ export declare const DEFAULT_STARTUP_LIST: StartupList;
16
+ /** What the client is doing: what a host shows while it waits. */
17
+ export type AgentStatus = {
18
+ phase: "exploring";
19
+ } | {
20
+ phase: "thinking";
21
+ } | {
22
+ phase: "querying";
23
+ ecsql: string;
24
+ };
25
+ /** How much of an answer's rows the client reads for the host to show. */
26
+ export declare const ANSWER_CAPS: ResultCaps;
27
+ /**
28
+ * An answer's query's rows, read once with `ANSWER_CAPS`, or the error it gave; undefined when
29
+ * there is no query. What `AgentClient.ask` keeps on the run, for the host and for later questions.
30
+ */
31
+ export declare function readAnswerRows(runQuery: RunRawQuery, query: string | undefined): Promise<AnswerRows | undefined>;
32
+ export interface AgentClientOptions {
33
+ /** How to run a query on the iModel: `queryRunner(imodel)`. Absent for questions about ECSql alone. */
34
+ runQuery?: RunRawQuery;
35
+ /** The iModel's name, as the agent is told it. */
36
+ imodelName?: string;
37
+ /** The function's base URL; `POST <url>/turn` is called. */
38
+ functionUrl?: string;
39
+ /** In place of `functionUrl`: how to send one turn (a test, or the function in the same process). */
40
+ turns?: TurnCall;
41
+ /** The user's access key for the function, sent with every turn (`FetchTurnsOptions.getAccessToken`). */
42
+ getAccessToken?: () => Promise<string | undefined>;
43
+ /** The startup query list. The library's own list by default. */
44
+ startupList?: StartupList;
45
+ /** Called when the startup list starts and ends. */
46
+ onExploring?: (exploring: boolean) => void;
47
+ /**
48
+ * How answers are to be given, for a host with unified selection (the turn API's `AnswerMode`):
49
+ *
50
+ * - `auto`: the host selects elements from answers. The agent decides, question by question,
51
+ * whether a question asks to select; `AgentRun.resultType` says what each answer is.
52
+ * - `select`: the user's preference that every question is a selection request.
53
+ *
54
+ * Set from the host's settings, never from the question: the client does not scan questions.
55
+ */
56
+ answerMode?: AnswerMode;
57
+ }
58
+ export interface AskOptions {
59
+ /** The text in the host's query editor, if any. */
60
+ editorText?: string;
61
+ /** The chat's earlier questions (`earlierQuestion`), so a follow-up has their context. */
62
+ earlier?: readonly EarlierQuestion[];
63
+ /** The token of the chat's last finished run (`AgentRun.token`). Opaque: kept and sent back, never read. */
64
+ token?: string;
65
+ /** This question's answer mode, in place of the client's (`AgentClientOptions.answerMode`). */
66
+ answerMode?: AnswerMode;
67
+ onStatus?: (status: AgentStatus) => void;
68
+ signal?: AbortSignal;
69
+ }
70
+ export declare class AgentClient {
71
+ private readonly options;
72
+ private readonly turns;
73
+ private explored;
74
+ /** The startup list's rows: undefined when there is no iModel, or when the list could not run. */
75
+ readonly startup: Promise<StartupResult[] | undefined>;
76
+ private constructor();
77
+ /** Start the client: the startup list begins to run at once (see `startup`). */
78
+ static start(options: AgentClientOptions): AgentClient;
79
+ private explore;
80
+ /**
81
+ * Read a query's rows on the iModel, up to the caps given: for a host that shows an answer's
82
+ * results. Throws when there is no iModel, or the query fails.
83
+ */
84
+ read(ecsql: string, caps?: ResultCaps): Promise<Pick<QueryRows, "columns" | "rows" | "clipped" | "truncatedBy">>;
85
+ /** Answer one question. While the startup list still runs, it waits for it, with the status `exploring`. */
86
+ ask(question: string, options?: AskOptions): Promise<AgentRun>;
87
+ /**
88
+ * The elements a query returns, read in full (its `ECInstanceId` or `id` column, and `ClassName`),
89
+ * handed to `onKeys` in chunks as they are read: for selecting all the elements of an answer.
90
+ * Never throws: a failure is the
91
+ * selection's `error`, as when there is no iModel.
92
+ */
93
+ readSelection(ecsql: string, onKeys?: (keys: InstanceKey[]) => void | Promise<void>, signal?: AbortSignal): Promise<RunSelection>;
94
+ /**
95
+ * The instance keys of ids, for selecting them: each element once with its class, read in
96
+ * batches, and how many of the ids were not elements. Throws when there is no iModel.
97
+ */
98
+ instanceKeys(ids: readonly string[]): Promise<{
99
+ keys: InstanceKey[];
100
+ notElements: number;
101
+ }>;
102
+ /**
103
+ * The answer's query's rows, read once when the run ends: the host shows them, and a later
104
+ * question of the chat sends the first of them (`earlierQuestion`).
105
+ */
106
+ private answerRows;
107
+ }
@@ -0,0 +1,142 @@
1
+ "use strict";
2
+ /**
3
+ * The client a host starts for an open iModel: it runs the startup list when it starts, then
4
+ * answers questions by driving turns with the function.
5
+ *
6
+ * ```ts
7
+ * const client = AgentClient.start({ runQuery: queryRunner(imodel), imodelName, functionUrl });
8
+ * const run = await client.ask("How many pipes are there?", { onStatus });
9
+ * ```
10
+ */
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AgentClient = exports.ANSWER_CAPS = exports.DEFAULT_STARTUP_LIST = void 0;
16
+ exports.readAnswerRows = readAnswerRows;
17
+ const caps_js_1 = require("./caps.js");
18
+ const client_js_1 = require("./client.js");
19
+ const selection_js_1 = require("./selection.js");
20
+ const result_pages_js_1 = require("./result-pages.js");
21
+ const startup_queries_json_1 = __importDefault(require("./startup-queries.json"));
22
+ /** The library's startup query list (`startup-queries.json`): what a client runs when it starts. */
23
+ exports.DEFAULT_STARTUP_LIST = startup_queries_json_1.default;
24
+ /** How much of an answer's rows the client reads for the host to show. */
25
+ exports.ANSWER_CAPS = { maxRows: 200, maxChars: 200_000, maxCellChars: 400 };
26
+ /**
27
+ * An answer's query's rows, read once with `ANSWER_CAPS`, or the error it gave; undefined when
28
+ * there is no query. What `AgentClient.ask` keeps on the run, for the host and for later questions.
29
+ */
30
+ async function readAnswerRows(runQuery, query) {
31
+ if (!query)
32
+ return undefined;
33
+ try {
34
+ return await (0, caps_js_1.readCapped)(await runQuery(query), exports.ANSWER_CAPS);
35
+ }
36
+ catch (err) {
37
+ return { error: err instanceof Error ? err.message : String(err) };
38
+ }
39
+ }
40
+ class AgentClient {
41
+ options;
42
+ turns;
43
+ explored = false;
44
+ /** The startup list's rows: undefined when there is no iModel, or when the list could not run. */
45
+ startup;
46
+ constructor(options) {
47
+ this.options = options;
48
+ if (options.turns)
49
+ this.turns = options.turns;
50
+ else if (options.functionUrl)
51
+ this.turns = (0, client_js_1.fetchTurns)(options.functionUrl, { getAccessToken: options.getAccessToken });
52
+ else
53
+ throw new Error("AgentClient needs functionUrl, or turns.");
54
+ this.startup = this.explore();
55
+ }
56
+ /** Start the client: the startup list begins to run at once (see `startup`). */
57
+ static start(options) {
58
+ return new AgentClient(options);
59
+ }
60
+ async explore() {
61
+ const { runQuery } = this.options;
62
+ if (!runQuery)
63
+ return undefined;
64
+ this.options.onExploring?.(true);
65
+ try {
66
+ // A list that cannot run leaves the block out, and the agent works without it.
67
+ return (await (0, client_js_1.runStartupQueries)(this.options.startupList ?? exports.DEFAULT_STARTUP_LIST, runQuery)).results;
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ finally {
73
+ this.explored = true;
74
+ this.options.onExploring?.(false);
75
+ }
76
+ }
77
+ /**
78
+ * Read a query's rows on the iModel, up to the caps given: for a host that shows an answer's
79
+ * results. Throws when there is no iModel, or the query fails.
80
+ */
81
+ async read(ecsql, caps = exports.ANSWER_CAPS) {
82
+ if (!this.options.runQuery)
83
+ throw new Error("No iModel is open.");
84
+ return (0, caps_js_1.readCapped)(await this.options.runQuery(ecsql), caps);
85
+ }
86
+ /** Answer one question. While the startup list still runs, it waits for it, with the status `exploring`. */
87
+ async ask(question, options = {}) {
88
+ const { runQuery, imodelName } = this.options;
89
+ if (!this.explored && this.options.runQuery)
90
+ options.onStatus?.({ phase: "exploring" });
91
+ const startup = await this.startup;
92
+ // The host's choice of mode. The agent decides what each question gets; the client never scans it.
93
+ const answerMode = options.answerMode ?? this.options.answerMode;
94
+ const client = {
95
+ runQuery,
96
+ imodel: imodelName !== undefined ? { name: imodelName, startup } : undefined,
97
+ editorText: options.editorText,
98
+ earlier: options.earlier,
99
+ token: options.token,
100
+ answerMode,
101
+ onPhase: (phase, ecsql) => options.onStatus?.(phase === "querying" ? { phase, ecsql: ecsql ?? "" } : { phase }),
102
+ signal: options.signal,
103
+ };
104
+ const run = await (0, client_js_1.driveTurns)(question, client, this.turns);
105
+ const query = run.structured?.query || run.query;
106
+ const answerRows = await this.answerRows(query);
107
+ // All the rows, for a table: paged by the query reader, starting from the rows already read.
108
+ const results = query && runQuery && answerRows && answerRows.error === undefined
109
+ ? new result_pages_js_1.ResultPages(runQuery, query, { columns: answerRows.columns ?? [], rows: answerRows.rows ?? [], complete: answerRows.truncatedBy === undefined && !answerRows.clipped })
110
+ : undefined;
111
+ return { ...run, ...(answerMode ? { answerMode } : {}), ...(answerRows ? { answerRows } : {}), ...(results ? { results } : {}) };
112
+ }
113
+ /**
114
+ * The elements a query returns, read in full (its `ECInstanceId` or `id` column, and `ClassName`),
115
+ * handed to `onKeys` in chunks as they are read: for selecting all the elements of an answer.
116
+ * Never throws: a failure is the
117
+ * selection's `error`, as when there is no iModel.
118
+ */
119
+ async readSelection(ecsql, onKeys, signal) {
120
+ if (!this.options.runQuery)
121
+ return { error: "No iModel is open." };
122
+ return (0, selection_js_1.readSelection)(this.options.runQuery, ecsql, onKeys, signal);
123
+ }
124
+ /**
125
+ * The instance keys of ids, for selecting them: each element once with its class, read in
126
+ * batches, and how many of the ids were not elements. Throws when there is no iModel.
127
+ */
128
+ async instanceKeys(ids) {
129
+ if (!this.options.runQuery)
130
+ throw new Error("No iModel is open.");
131
+ return (0, selection_js_1.instanceKeys)(this.options.runQuery, ids);
132
+ }
133
+ /**
134
+ * The answer's query's rows, read once when the run ends: the host shows them, and a later
135
+ * question of the chat sends the first of them (`earlierQuestion`).
136
+ */
137
+ async answerRows(query) {
138
+ return this.options.runQuery ? readAnswerRows(this.options.runQuery, query) : undefined;
139
+ }
140
+ }
141
+ exports.AgentClient = AgentClient;
142
+ //# sourceMappingURL=agent-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-client.js","sourceRoot":"","sources":["../../src/agent-client.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;;;;;AAyBH,wCAQC;AA/BD,uCAAyD;AACzD,2CAA6J;AAC7J,iDAAkG;AAClG,uDAAgD;AAChD,kFAAiD;AAGjD,oGAAoG;AACvF,QAAA,oBAAoB,GAAG,8BAA0B,CAAC;AAQ/D,0EAA0E;AAC7D,QAAA,WAAW,GAAe,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC;AAE9F;;;GAGG;AACI,KAAK,UA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,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;IACnI,CAAC;IAED;;;;;OAKG;IACI,KAAK,CAAC,aAAa,CAAC,KAAa,EAAE,MAAsD,EAAE,MAAoB;QACpH,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ;YACxB,OAAO,EAAE,KAAK,EAAE,oBAAoB,EAAE,CAAC;QACzC,OAAO,IAAA,4BAAa,EAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IACrE,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,YAAY,CAAC,GAAsB;QAC9C,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ;YACxB,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;QACxC,OAAO,IAAA,2BAAY,EAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAClD,CAAC;IAED;;;OAGG;IACK,KAAK,CAAC,UAAU,CAAC,KAAyB;QAChD,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1F,CAAC;CACF;AAxGD,kCAwGC"}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Reading a query's rows up to the caps the function sends: the client's half of the row format.
3
+ *
4
+ * The function writes the text the model sees from these rows. The two halves must agree exactly,
5
+ * so the rules here are the turn API's, and the function is tested against them.
6
+ */
7
+ import type { QueryRows, ResultCaps } from "./turn-api.js";
8
+ /**
9
+ * One query's results, streamed, so the reader can stop once a cap is reached: nothing should
10
+ * read two million rows to find that only the first two hundred were wanted.
11
+ *
12
+ * The runner that builds this **must** abbreviate blobs (`abbreviateBlobs` on the reader).
13
+ */
14
+ export interface RawQueryResult {
15
+ columns: string[];
16
+ rows: AsyncIterable<unknown[]>;
17
+ }
18
+ /**
19
+ * Which rows of a result to read, passed to the iTwin.js query reader as its own options
20
+ * (`QueryOptions.limit` and `restartToken`): the reader asks the backend for exactly these rows,
21
+ * so a page of a large result is read without reading the rows before it.
22
+ */
23
+ export interface QueryPageOptions {
24
+ /** The rows to read: `count` rows from `offset`. */
25
+ limit?: {
26
+ offset: number;
27
+ count: number;
28
+ };
29
+ /** A newer query with the same token cancels this one (the reader's `restartToken`). */
30
+ restartToken?: string;
31
+ }
32
+ export type RunRawQuery = (ecsql: string, page?: QueryPageOptions) => Promise<RawQueryResult>;
33
+ /**
34
+ * Read a result up to the caps:
35
+ *
36
+ * 1. stop before a row once there are `maxRows` rows (`truncatedBy: "rows"`);
37
+ * 2. stop before a row whose line would take the total past `maxChars` (`truncatedBy: "chars"`),
38
+ * but always keep the first row. A line is the row as a JSON array, with each long string as
39
+ * the function will show it, plus one character; the total starts at the length of
40
+ * `columns: ` and the column names as a JSON array;
41
+ * 3. cut each string to `maxCellChars`, and add `[row, column, full length]` to `clipped`.
42
+ */
43
+ export declare function readCapped(result: RawQueryResult, caps: ResultCaps): Promise<Pick<QueryRows, "columns" | "rows" | "clipped" | "truncatedBy">>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * Reading a query's rows up to the caps the function sends: the client's half of the row format.
4
+ *
5
+ * The function writes the text the model sees from these rows. The two halves must agree exactly,
6
+ * so the rules here are the turn API's, and the function is tested against them.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.readCapped = readCapped;
10
+ /** A string cut to the cap, as the function will show it: used only to measure the line. */
11
+ function asShown(value, maxCellChars) {
12
+ if (typeof value !== "string" || value.length <= maxCellChars)
13
+ return value;
14
+ return `${value.slice(0, maxCellChars)}…[clipped, ${value.length} chars]`;
15
+ }
16
+ /**
17
+ * Read a result up to the caps:
18
+ *
19
+ * 1. stop before a row once there are `maxRows` rows (`truncatedBy: "rows"`);
20
+ * 2. stop before a row whose line would take the total past `maxChars` (`truncatedBy: "chars"`),
21
+ * but always keep the first row. A line is the row as a JSON array, with each long string as
22
+ * the function will show it, plus one character; the total starts at the length of
23
+ * `columns: ` and the column names as a JSON array;
24
+ * 3. cut each string to `maxCellChars`, and add `[row, column, full length]` to `clipped`.
25
+ */
26
+ async function readCapped(result, caps) {
27
+ let chars = `columns: ${JSON.stringify(result.columns)}`.length;
28
+ const rows = [];
29
+ const clipped = [];
30
+ let truncatedBy;
31
+ for await (const row of result.rows) {
32
+ if (rows.length >= caps.maxRows) {
33
+ truncatedBy = "rows";
34
+ break;
35
+ }
36
+ const line = JSON.stringify(row.map((value) => asShown(value, caps.maxCellChars)));
37
+ if (chars + line.length + 1 > caps.maxChars && rows.length > 0) {
38
+ truncatedBy = "chars";
39
+ break;
40
+ }
41
+ rows.push(row.map((value, column) => {
42
+ if (typeof value !== "string" || value.length <= caps.maxCellChars)
43
+ return value;
44
+ clipped.push([rows.length, column, value.length]);
45
+ return value.slice(0, caps.maxCellChars);
46
+ }));
47
+ chars += line.length + 1;
48
+ }
49
+ return { columns: result.columns, rows, ...(clipped.length > 0 ? { clipped } : {}), ...(truncatedBy ? { truncatedBy } : {}) };
50
+ }
51
+ //# sourceMappingURL=caps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caps.js","sourceRoot":"","sources":["../../src/caps.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AA8CH,gCAwBC;AAzCD,4FAA4F;AAC5F,SAAS,OAAO,CAAC,KAAc,EAAE,YAAoB;IACnD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,IAAI,YAAY;QAC3D,OAAO,KAAK,CAAC;IACf,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,YAAY,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AAC,YAAY,CAAC,CAAC;QAC3C,CAAC,CAAC,CAAC,CAAC;QACJ,KAAK,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;IAC3B,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AAChI,CAAC"}
@@ -0,0 +1,145 @@
1
+ /**
2
+ * The client's half of a turn: running the queries the function asks for and reading their rows,
3
+ * and running the startup query list before the first turn.
4
+ *
5
+ * The function never reaches the iModel. Each response names the queries to run and the caps to
6
+ * read them to; the client runs them on its own iModel and sends the rows with the next turn. The
7
+ * startup list's rows go with every turn, and the function writes them into the instructions.
8
+ */
9
+ import { type RunRawQuery } from "./caps.js";
10
+ import type { ResultPages } from "./result-pages.js";
11
+ import { type AnswerMode, type ResultType, type EarlierQuestion, type QueryRows, type ResultCaps, type StartupResult, type StopReason, type SubmittedAnswer, type TurnRequest, type TurnResponse } from "./turn-api.js";
12
+ /** What the client supplies to a run, wherever the function runs. */
13
+ export interface ClientOptions {
14
+ /** Absent when no iModel is open: the agent is told so and `runQuery` is not offered. */
15
+ runQuery?: RunRawQuery;
16
+ /** The open iModel: its name, and the rows of the startup query list (`runStartupQueries`), run once per iModel. */
17
+ imodel?: {
18
+ name: string;
19
+ startup?: StartupResult[];
20
+ };
21
+ editorText?: string;
22
+ /** The chat's earlier questions, oldest first (`earlierQuestion`). The function shortens them to fit. */
23
+ earlier?: readonly EarlierQuestion[];
24
+ /** The token of the chat's last finished run. Opaque: kept and sent back, never read. */
25
+ token?: string;
26
+ /** How the answer is to be given (`AnswerMode`). Sent with every turn. */
27
+ answerMode?: AnswerMode;
28
+ /** Called before each turn is sent (`thinking`), and before each query runs (`querying`, with its ECSql). */
29
+ onPhase?: (phase: "thinking" | "querying", ecsql?: string) => void;
30
+ signal?: AbortSignal;
31
+ }
32
+ /** The finished run, as the client keeps it: the answer, and what the chat's next question needs. */
33
+ export interface AgentRun {
34
+ /** The final prose answer, which should carry exactly one fenced sql block. */
35
+ answer: string;
36
+ /** The query pulled out of the answer, if there was one. */
37
+ query?: string;
38
+ stoppedBecause: StopReason;
39
+ /** The answer as submitted with `submitAnswer`, when the run ended that way. */
40
+ structured?: SubmittedAnswer;
41
+ /** Names the run's record, where the function keeps one. */
42
+ runId: string;
43
+ /** The token for the chat's next question. Opaque: the agent's own state, sealed. */
44
+ token: string;
45
+ /** The answer mode the run was asked in, as the host sent it. */
46
+ answerMode?: AnswerMode;
47
+ /**
48
+ * In the `auto` and `select` modes: what the answer is (`done.resultType`). `selection`: its
49
+ * query is the selection, and no rows clears it. `answer`: select its rows only when they carry
50
+ * `ECInstanceId` and `ClassName`.
51
+ */
52
+ resultType?: ResultType;
53
+ /** The answer's query's rows, read once when the run ended (`AgentClient.ask`), or its error. */
54
+ answerRows?: AnswerRows;
55
+ /**
56
+ * All the answer's rows, with no limit, read a page at a time as a table asks for them. Present
57
+ * when the answer has a query and there is an iModel. For the host only: never sent to the function.
58
+ */
59
+ results?: ResultPages;
60
+ }
61
+ /** An answer's query's rows, as the client read them, or the error it gave. */
62
+ export type AnswerRows = Pick<QueryRows, "columns" | "rows" | "clipped" | "truncatedBy" | "error">;
63
+ /**
64
+ * An answered question as a later question of the chat sends it: as the user saw it, with the
65
+ * answer's rows cut to `HISTORY_CAPS`.
66
+ */
67
+ export declare function earlierQuestion(question: string, run: AgentRun): Promise<EarlierQuestion>;
68
+ /** One call to the function: over HTTP (`fetchTurns`), or in the same process, for tests. */
69
+ export type TurnCall = (request: TurnRequest, signal?: AbortSignal) => Promise<TurnResponse>;
70
+ /**
71
+ * Drive a run: send a turn, run the queries the response asks for, send their rows with the next
72
+ * turn, until the response says the run is over. When the user stops the run, the next turn says
73
+ * so, and the function ends it.
74
+ */
75
+ export declare function driveTurns(question: string, client: ClientOptions, turn: TurnCall): Promise<AgentRun>;
76
+ /**
77
+ * The function refused a turn for a reason the user can act on. `message` is the function's one
78
+ * sentence, meant to be shown as it is; `status` says which: 401 or 403 ask for an access key, 429
79
+ * means the key is used up, which can happen in the middle of a question, 413 means the request is
80
+ * too long, 400 means the chat must start again.
81
+ */
82
+ export declare class TurnRefused extends Error {
83
+ readonly status: number;
84
+ constructor(status: number, message: string);
85
+ }
86
+ export interface FetchTurnsOptions {
87
+ /**
88
+ * The user's credential for the function, sent with every turn as `Authorization: Bearer <it>`:
89
+ * the access key the owner gave them. A function that checks access refuses a turn without one
90
+ * (`TurnRefused`, 401).
91
+ */
92
+ getAccessToken?: () => Promise<string | undefined>;
93
+ }
94
+ /**
95
+ * Turns over HTTP: `POST <url>/turn`, the same code in a browser and in Node. When the user stops
96
+ * the run while a turn is in flight, the same turn is sent again, saying the run was stopped, so
97
+ * the function ends it with what it has.
98
+ */
99
+ export declare function fetchTurns(url: string, options?: FetchTurnsOptions): TurnCall;
100
+ /**
101
+ * Run one query and read it up to the caps. A failure, at the start or part way through the
102
+ * rows, is sent as the query's error: the function hands it to the model to correct.
103
+ */
104
+ export declare function readQuery(runQuery: RunRawQuery, ecsql: string, caps: ResultCaps): Promise<QueryRows>;
105
+ /** One query of the startup list. */
106
+ export interface StartupQuery {
107
+ rule: string;
108
+ id: string;
109
+ ecsql: string;
110
+ /** Rows sent. The rest are counted, not sent. */
111
+ max?: number;
112
+ /** Run only when these queries of the same rule were empty. */
113
+ onlyIfEmpty?: string[];
114
+ /** A second query run for every row sent, with the row's columns as `{0}`, `{1}`. It always runs to the end. */
115
+ each?: string;
116
+ }
117
+ /** The startup query list (`startup-queries.json`), which the client library carries. */
118
+ export interface StartupList {
119
+ description?: string[];
120
+ lists: Record<string, string[]>;
121
+ queries: StartupQuery[];
122
+ }
123
+ /** One startup query run, for a report of what was asked and how long it took. */
124
+ export interface QueryReport {
125
+ rule: string;
126
+ query: string;
127
+ ecsql: string;
128
+ ms: number;
129
+ rows: number;
130
+ skipped?: boolean;
131
+ /** A failed query is an empty one: the class or schema is not in this file. */
132
+ error?: string;
133
+ }
134
+ /** Expand `{{in:list}}`, `{{like:expr:list}}` and `{{notlike:expr:list}}`. An unknown list throws. */
135
+ export declare function expandLists(ecsql: string, lists: Record<string, string[]>): string;
136
+ /**
137
+ * Run the startup list on the open iModel. Never throws for a query: a failure is an empty
138
+ * result. Only a list that names a list it does not define throws.
139
+ */
140
+ export declare function runStartupQueries(list: StartupList, runQuery: RunRawQuery): Promise<{
141
+ results: StartupResult[];
142
+ reports: QueryReport[];
143
+ }>;
144
+ /** The earlier name of `fetchTurns`. */
145
+ export declare const httpTurns: typeof fetchTurns;