@uptimizr/agent-core 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 (49) hide show
  1. package/AGENTS.md +40 -0
  2. package/LICENSE +201 -0
  3. package/README.md +125 -0
  4. package/dist/client.d.ts +33 -0
  5. package/dist/client.d.ts.map +1 -0
  6. package/dist/client.js +38 -0
  7. package/dist/client.js.map +1 -0
  8. package/dist/index.d.ts +5 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +4 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/loop.d.ts +47 -0
  13. package/dist/loop.d.ts.map +1 -0
  14. package/dist/loop.js +84 -0
  15. package/dist/loop.js.map +1 -0
  16. package/dist/provider.d.ts +73 -0
  17. package/dist/provider.d.ts.map +1 -0
  18. package/dist/provider.js +12 -0
  19. package/dist/provider.js.map +1 -0
  20. package/dist/providers/anthropic.d.ts +56 -0
  21. package/dist/providers/anthropic.d.ts.map +1 -0
  22. package/dist/providers/anthropic.js +75 -0
  23. package/dist/providers/anthropic.js.map +1 -0
  24. package/dist/providers/config.d.ts +74 -0
  25. package/dist/providers/config.d.ts.map +1 -0
  26. package/dist/providers/config.js +93 -0
  27. package/dist/providers/config.js.map +1 -0
  28. package/dist/providers/hosted.d.ts +50 -0
  29. package/dist/providers/hosted.d.ts.map +1 -0
  30. package/dist/providers/hosted.js +102 -0
  31. package/dist/providers/hosted.js.map +1 -0
  32. package/dist/providers/index.d.ts +16 -0
  33. package/dist/providers/index.d.ts.map +1 -0
  34. package/dist/providers/index.js +16 -0
  35. package/dist/providers/index.js.map +1 -0
  36. package/dist/providers/openai.d.ts +53 -0
  37. package/dist/providers/openai.d.ts.map +1 -0
  38. package/dist/providers/openai.js +79 -0
  39. package/dist/providers/openai.js.map +1 -0
  40. package/dist/providers/webllm.d.ts +128 -0
  41. package/dist/providers/webllm.d.ts.map +1 -0
  42. package/dist/providers/webllm.js +158 -0
  43. package/dist/providers/webllm.js.map +1 -0
  44. package/dist/tools.d.ts +28 -0
  45. package/dist/tools.d.ts.map +1 -0
  46. package/dist/tools.js +327 -0
  47. package/dist/tools.js.map +1 -0
  48. package/llms.txt +20 -0
  49. package/package.json +86 -0
package/AGENTS.md ADDED
@@ -0,0 +1,40 @@
1
+ # AGENTS.md — @uptimizr/agent-core
2
+
3
+ > Packaged agent guide. For the human reference see [README.md](./README.md); for design
4
+ > rationale see the project ADRs at https://github.com/RaananW/Uptimizr/tree/main/docs/adr.
5
+
6
+ ## What this package is
7
+
8
+ The **framework-agnostic, browser-safe core** shared by every Uptimizr analytics agent. It defines
9
+ the agent tool surface **once** (ADR 0050 §1) so `@uptimizr/mcp`, the dashboard assistant, and the
10
+ demo assistant never drift apart. It owns:
11
+
12
+ - the **read-only tool catalog** (`readTools`) — one entry per documented collector query endpoint;
13
+ - a headless **LLM provider-adapter interface** (`LlmProvider`) — messages + tool schemas in, tool
14
+ calls or final text out;
15
+ - the headless **tool-calling loop** (`runAgent`) — LLM ↔ tools ↔ collector.
16
+
17
+ The core ships **no model and no key**. It only ever reads a consumer's **own** collector via the
18
+ `CollectorClient` (`GET`-only, `x-api-key`).
19
+
20
+ ## Rules for agents
21
+
22
+ - **Read-only and privacy-preserving.** Never add ingestion, mutation, or raw per-session event
23
+ tools. The surface is aggregate-only; no data leaves the consumer's infrastructure (ADR 0003 /
24
+ ADR 0017). A new tool = a new entry in `readTools` mapping to a documented query endpoint — no
25
+ aggregation/business logic (that lives in the collector, ADR 0005).
26
+ - **Browser-safe.** No Node dependencies, no `types: ["node"]`; only `zod` at runtime. Anything that
27
+ needs `process.env`, stdio, or the filesystem belongs in a consumer package (e.g. `@uptimizr/mcp`),
28
+ not here.
29
+ - Tool definitions are pure (`buildRequest`) and must stay unit-testable without a live collector.
30
+ - Keep provider adapters thin and out of this package: implement `LlmProvider` in the consumer.
31
+
32
+ ## Programmatic API
33
+
34
+ `readTools`, `createCollectorClient(config)`, `toToolSchemas(tools?)`, `runAgent(options)`, plus the
35
+ `LlmProvider` / `AgentMessage` / `AgentToolCall` / `ProviderResponse` types.
36
+
37
+ ## More
38
+
39
+ - Package reference: [README.md](./README.md)
40
+ - Integration guide: https://github.com/RaananW/Uptimizr/blob/main/docs/integration.md
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions for
125
+ use, reproduction, or distribution of Your modifications, or for any
126
+ such Derivative Works as a whole, provided Your use, reproduction,
127
+ and distribution of the Work otherwise complies with the conditions
128
+ stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Uptimizr Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # @uptimizr/agent-core
2
+
3
+ The **framework-agnostic, browser-safe core** for Uptimizr analytics agents. It defines the agent
4
+ tool surface **once** so every consumer — the [`@uptimizr/mcp`](../mcp/README.md) server, the
5
+ dashboard assistant, and the backend-less demo assistant — asks the same questions of the same
6
+ read-only collector query API (ADR 0050 §1).
7
+
8
+ It owns three things:
9
+
10
+ 1. **The read-only tool catalog** (`readTools`) — one entry per documented aggregate query
11
+ endpoint. Pure Zod shapes, no Node dependencies, unit-testable without a live collector.
12
+ 2. **A headless LLM provider-adapter interface** (`LlmProvider`) — send messages + tool schemas,
13
+ receive tool calls or a final answer. The core ships **no model and no key**; adapters
14
+ (WebLLM/WebGPU, an OpenAI-compatible or Anthropic endpoint) are user-selected and
15
+ user-controlled (ADR 0050 §4).
16
+ 3. **The headless tool-calling loop** (`runAgent`) — drives the LLM ↔ tools ↔ collector round trip,
17
+ framework-agnostic and runnable in a browser, a Node service, a CLI, or a bot.
18
+
19
+ Everything here is **strictly read-only**: the loop only ever issues collector `GET`s through the
20
+ catalog. There are **no** ingestion, mutation, or raw per-session event tools (ADR 0003 / ADR 0017).
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ npm install @uptimizr/agent-core
26
+ ```
27
+
28
+ ## Use
29
+
30
+ ```ts
31
+ import { createCollectorClient, runAgent, type LlmProvider } from "@uptimizr/agent-core";
32
+
33
+ // 1. A read-only client bound to your own collector + project key.
34
+ const client = createCollectorClient({
35
+ collectorUrl: "https://collect.example.com",
36
+ apiKey: "utk_…",
37
+ });
38
+
39
+ // 2. Your chosen LLM backend, adapted to the provider interface.
40
+ const provider: LlmProvider = {
41
+ async complete({ messages, tools }) {
42
+ // Call WebLLM / an OpenAI-compatible or Anthropic endpoint here, passing
43
+ // `tools` as the tool/function schemas, and normalise the reply into either
44
+ // { kind: "tool_calls", toolCalls: [...] } or { kind: "final", content }.
45
+ return { kind: "final", content: "…" };
46
+ },
47
+ };
48
+
49
+ // 3. Run the loop. It executes any tool calls against the collector for you.
50
+ const result = await runAgent({
51
+ provider,
52
+ client,
53
+ messages: [
54
+ { role: "system", content: "You are a 3D analytics assistant." },
55
+ { role: "user", content: "What were the most-clicked meshes this week?" },
56
+ ],
57
+ });
58
+
59
+ console.log(result.content); // the model's final answer
60
+ ```
61
+
62
+ ## Tool catalog (read-only)
63
+
64
+ `list_sessions`, `pointer_heatmap`, `world_heatmap`, `camera_heatmap`, `click_rays`, `flow_links`,
65
+ `top_meshes`, `perf_summary`, `list_scenes`, `timeseries`, `event_counts`, `session_meta`,
66
+ `scene_representation`, `funnel`, `aggregate_paths`, `rendering_technology`, `xr_rotation`,
67
+ `xr_sources`, `xr_abandonment`, `xr_locomotion`. Most accept `since`/`until` (epoch ms) plus
68
+ endpoint-specific filters (`scene`, `session`, `source`, `bins`, `cellSize`, `limit`, `cameraMode`,
69
+ `rapidTurn`, `steps`). Each maps one-to-one to a documented
70
+ collector query endpoint (see the [integration guide](https://github.com/RaananW/Uptimizr/blob/main/docs/integration.md)).
71
+
72
+ ## API
73
+
74
+ | Export | Purpose |
75
+ | ------------------------------ | ----------------------------------------------------------------- |
76
+ | `readTools` | The read-only tool catalog (one entry per query endpoint). |
77
+ | `createCollectorClient(cfg)` | Thin `GET`-only collector client (`fetch`-based, injectable). |
78
+ | `toToolSchemas(tools?)` | Convert catalog tools to JSON-Schema tool descriptors for an LLM. |
79
+ | `runAgent(options)` | The headless tool-calling loop. |
80
+ | `LlmProvider` / `AgentMessage` | The provider-adapter interface and message types. |
81
+
82
+ The loop stops when the provider returns a final answer or after `maxSteps` turns
83
+ (`DEFAULT_MAX_STEPS`, default 8). Unknown tools and invalid arguments are surfaced back to the model
84
+ as tool-error messages so it can recover, never thrown.
85
+
86
+ ## Provider adapters (user-controlled backends)
87
+
88
+ The core ships **no model and no key**. Two ready-made adapters implement `LlmProvider` and are
89
+ exported from **code-split subpaths**, so consumers who never use the assistant pay nothing for
90
+ them:
91
+
92
+ ```ts
93
+ import { createWebLlmProvider } from "@uptimizr/agent-core/providers/webllm";
94
+ import { createHostedProvider } from "@uptimizr/agent-core/providers/hosted";
95
+ // or the barrel (adds backend-selection + localStorage helpers):
96
+ import {
97
+ defaultBackendKind,
98
+ isWebGpuAvailable,
99
+ loadBackendConfig,
100
+ saveBackendConfig,
101
+ } from "@uptimizr/agent-core/providers";
102
+ ```
103
+
104
+ - **`createWebLlmProvider`** — local, in-browser inference on WebGPU via
105
+ [`@mlc-ai/web-llm`](https://github.com/mlc-ai/web-llm). The runtime is an **optional** dependency
106
+ loaded with a lazy `import()` only on first use; model weights download behind an explicit consent
107
+ gate and are cached in the browser's Cache Storage (never precached). **Zero data egress.**
108
+ - **`createHostedProvider`** — bring-your-own **OpenAI-compatible** or **Anthropic** endpoint + key,
109
+ stored only in the browser; the browser calls your provider directly. Only the prompt and
110
+ aggregated results leave, to **your own** provider (ADR 0050 §4/§5).
111
+
112
+ Install the WebLLM runtime alongside the assistant if you use the local backend:
113
+
114
+ ```bash
115
+ npm install @mlc-ai/web-llm
116
+ ```
117
+
118
+ See the [assistant guide](https://uptimizr.com/docs/guides/assistant/) for the curated model list,
119
+ privacy trade-offs, and the provider CORS requirements.
120
+
121
+ ## More
122
+
123
+ - Design rationale: [ADR 0050](https://github.com/RaananW/Uptimizr/blob/main/docs/adr/0050-in-browser-analytics-assistant.md)
124
+ - MCP server built on this catalog: [`@uptimizr/mcp`](../mcp/README.md)
125
+ - Integration & API reference: https://github.com/RaananW/Uptimizr/blob/main/docs/integration.md
@@ -0,0 +1,33 @@
1
+ /** A query-string parameter map. `undefined` values are omitted from the request. */
2
+ export type QueryParams = Record<string, string | number | undefined>;
3
+ /**
4
+ * A minimal **read-only** HTTP client over the collector query API. It performs
5
+ * `GET` requests only and holds no business logic — it is a thin transport that
6
+ * mirrors the dashboard's `CollectorApi` so an agent reads the same aggregated
7
+ * results a human would (ADR 0005 / ADR 0017).
8
+ */
9
+ export interface CollectorClient {
10
+ get(path: string, params?: QueryParams): Promise<unknown>;
11
+ }
12
+ /**
13
+ * The `(collectorUrl, apiKey)` pair a collector client binds to. Every consumer
14
+ * (MCP, dashboard, demo) talks only to its **own** collector, authenticated with
15
+ * its own project API key — nothing is sent to any third party (ADR 0003 / 0017).
16
+ */
17
+ export interface CollectorClientConfig {
18
+ /** Base URL of the consumer's Uptimizr collector (e.g. https://collect.example.com). */
19
+ collectorUrl: string;
20
+ /** Project API key (`x-api-key`) used for read requests. */
21
+ apiKey: string;
22
+ }
23
+ /** Thrown when the collector responds with a non-2xx status. */
24
+ export declare class CollectorError extends Error {
25
+ readonly status: number;
26
+ constructor(message: string, status: number);
27
+ }
28
+ /**
29
+ * Build a read-only collector client bound to one `(collectorUrl, apiKey)` pair.
30
+ * `fetchImpl` is injectable for testing; it defaults to the global `fetch`.
31
+ */
32
+ export declare function createCollectorClient(config: CollectorClientConfig, fetchImpl?: typeof fetch): CollectorClient;
33
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3D;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IACpC,wFAAwF;IACxF,YAAY,EAAE,MAAM,CAAC;IACrB,4DAA4D;IAC5D,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,gEAAgE;AAChE,qBAAa,cAAe,SAAQ,KAAK;IAGrC,QAAQ,CAAC,MAAM,EAAE,MAAM;gBADvB,OAAO,EAAE,MAAM,EACN,MAAM,EAAE,MAAM;CAK1B;AAMD;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,qBAAqB,EAC7B,SAAS,GAAE,OAAO,KAAa,GAC9B,eAAe,CAmBjB"}
package/dist/client.js ADDED
@@ -0,0 +1,38 @@
1
+ /** Thrown when the collector responds with a non-2xx status. */
2
+ export class CollectorError extends Error {
3
+ status;
4
+ constructor(message, status) {
5
+ super(message);
6
+ this.status = status;
7
+ this.name = "CollectorError";
8
+ }
9
+ }
10
+ function ensureTrailingSlash(url) {
11
+ return url.endsWith("/") ? url : `${url}/`;
12
+ }
13
+ /**
14
+ * Build a read-only collector client bound to one `(collectorUrl, apiKey)` pair.
15
+ * `fetchImpl` is injectable for testing; it defaults to the global `fetch`.
16
+ */
17
+ export function createCollectorClient(config, fetchImpl = fetch) {
18
+ const base = ensureTrailingSlash(config.collectorUrl);
19
+ return {
20
+ async get(path, params = {}) {
21
+ const url = new URL(path.replace(/^\//, ""), base);
22
+ for (const [key, value] of Object.entries(params)) {
23
+ if (value != null)
24
+ url.searchParams.set(key, String(value));
25
+ }
26
+ const res = await fetchImpl(url, {
27
+ method: "GET",
28
+ headers: { "x-api-key": config.apiKey },
29
+ });
30
+ if (!res.ok) {
31
+ const body = await res.text().catch(() => "");
32
+ throw new CollectorError(body || res.statusText, res.status);
33
+ }
34
+ return res.json();
35
+ },
36
+ };
37
+ }
38
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAyBA,gEAAgE;AAChE,MAAM,OAAO,cAAe,SAAQ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AAc,CAAC,IAAI,IAAI,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;YAC/D,CAAC;YACD,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;QACpB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { createCollectorClient, CollectorError, type CollectorClient, type CollectorClientConfig, type QueryParams, } from "./client.js";
2
+ export { readTools, type ReadTool, type ReadToolRequest } from "./tools.js";
3
+ export type { AgentMessage, AgentToolCall, AgentToolSchema, LlmProvider, ProviderRequest, ProviderResponse, } from "./provider.js";
4
+ export { runAgent, toToolSchemas, DEFAULT_MAX_STEPS, type RunAgentOptions, type RunAgentResult, } from "./loop.js";
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,EACd,KAAK,eAAe,EACpB,KAAK,qBAAqB,EAC1B,KAAK,WAAW,GACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,KAAK,QAAQ,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAC;AAC5E,YAAY,EACV,YAAY,EACZ,aAAa,EACb,eAAe,EACf,WAAW,EACX,eAAe,EACf,gBAAgB,GACjB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,QAAQ,EACR,aAAa,EACb,iBAAiB,EACjB,KAAK,eAAe,EACpB,KAAK,cAAc,GACpB,MAAM,WAAW,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createCollectorClient, CollectorError, } from "./client.js";
2
+ export { readTools } from "./tools.js";
3
+ export { runAgent, toToolSchemas, DEFAULT_MAX_STEPS, } from "./loop.js";
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,qBAAqB,EACrB,cAAc,GAIf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAuC,MAAM,YAAY,CAAC;AAS5E,OAAO,EACL,QAAQ,EACR,aAAa,EACb,iBAAiB,GAGlB,MAAM,WAAW,CAAC"}
package/dist/loop.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { CollectorClient } from "./client.js";
2
+ import type { AgentMessage, AgentToolSchema, LlmProvider } from "./provider.js";
3
+ import { type ReadTool } from "./tools.js";
4
+ /** Default cap on provider turns before the loop gives up (guards against loops). */
5
+ export declare const DEFAULT_MAX_STEPS = 8;
6
+ /**
7
+ * Convert the read-only tool catalog into provider-facing tool schemas. Each
8
+ * tool's Zod raw shape becomes a JSON-Schema object the model can reason about.
9
+ */
10
+ export declare function toToolSchemas(tools?: readonly ReadTool[]): AgentToolSchema[];
11
+ /** Options for a single {@link runAgent} invocation. */
12
+ export interface RunAgentOptions {
13
+ /** The LLM backend to drive the conversation. */
14
+ provider: LlmProvider;
15
+ /** Read-only collector client used to execute tool calls. */
16
+ client: CollectorClient;
17
+ /** The conversation so far (typically a system + user message to start). */
18
+ messages: AgentMessage[];
19
+ /** Tool catalog to expose; defaults to the shared read-only catalog. */
20
+ tools?: readonly ReadTool[];
21
+ /** Maximum provider turns before returning. Defaults to {@link DEFAULT_MAX_STEPS}. */
22
+ maxSteps?: number;
23
+ /** Optional cancellation signal forwarded to the provider. */
24
+ signal?: AbortSignal;
25
+ }
26
+ /** The outcome of a completed agent run. */
27
+ export interface RunAgentResult {
28
+ /** The model's final natural-language answer (empty if it never produced one). */
29
+ content: string;
30
+ /** The full transcript, including assistant tool calls and tool results. */
31
+ messages: AgentMessage[];
32
+ /** How many provider turns were taken. */
33
+ steps: number;
34
+ /** True when the loop stopped because it hit `maxSteps` rather than a final answer. */
35
+ stoppedOnMaxSteps: boolean;
36
+ }
37
+ /**
38
+ * Run the headless tool-calling loop: ask the provider for the next step, and
39
+ * while it requests tool calls, execute each against the read-only collector
40
+ * client and feed the results back. Returns once the provider yields a final
41
+ * answer or the step cap is reached.
42
+ *
43
+ * The loop only ever issues collector `GET`s through the catalog's
44
+ * `buildRequest` — it can neither ingest nor mutate data (ADR 0003 / 0017).
45
+ */
46
+ export declare function runAgent(options: RunAgentOptions): Promise<RunAgentResult>;
47
+ //# sourceMappingURL=loop.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.d.ts","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAiB,eAAe,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC/F,OAAO,EAAa,KAAK,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtD,qFAAqF;AACrF,eAAO,MAAM,iBAAiB,IAAI,CAAC;AAEnC;;;GAGG;AACH,wBAAgB,aAAa,CAAC,KAAK,GAAE,SAAS,QAAQ,EAAc,GAAG,eAAe,EAAE,CAMvF;AAED,wDAAwD;AACxD,MAAM,WAAW,eAAe;IAC9B,iDAAiD;IACjD,QAAQ,EAAE,WAAW,CAAC;IACtB,6DAA6D;IAC7D,MAAM,EAAE,eAAe,CAAC;IACxB,4EAA4E;IAC5E,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,wEAAwE;IACxE,KAAK,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC;IAC5B,sFAAsF;IACtF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8DAA8D;IAC9D,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,4CAA4C;AAC5C,MAAM,WAAW,cAAc;IAC7B,kFAAkF;IAClF,OAAO,EAAE,MAAM,CAAC;IAChB,4EAA4E;IAC5E,QAAQ,EAAE,YAAY,EAAE,CAAC;IACzB,0CAA0C;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,uFAAuF;IACvF,iBAAiB,EAAE,OAAO,CAAC;CAC5B;AAED;;;;;;;;GAQG;AACH,wBAAsB,QAAQ,CAAC,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CA8BhF"}
package/dist/loop.js ADDED
@@ -0,0 +1,84 @@
1
+ import { z } from "zod";
2
+ import { readTools } from "./tools.js";
3
+ /** Default cap on provider turns before the loop gives up (guards against loops). */
4
+ export const DEFAULT_MAX_STEPS = 8;
5
+ /**
6
+ * Convert the read-only tool catalog into provider-facing tool schemas. Each
7
+ * tool's Zod raw shape becomes a JSON-Schema object the model can reason about.
8
+ */
9
+ export function toToolSchemas(tools = readTools) {
10
+ return tools.map((tool) => ({
11
+ name: tool.name,
12
+ description: tool.description,
13
+ parameters: z.toJSONSchema(z.object(tool.inputSchema)),
14
+ }));
15
+ }
16
+ /**
17
+ * Run the headless tool-calling loop: ask the provider for the next step, and
18
+ * while it requests tool calls, execute each against the read-only collector
19
+ * client and feed the results back. Returns once the provider yields a final
20
+ * answer or the step cap is reached.
21
+ *
22
+ * The loop only ever issues collector `GET`s through the catalog's
23
+ * `buildRequest` — it can neither ingest nor mutate data (ADR 0003 / 0017).
24
+ */
25
+ export async function runAgent(options) {
26
+ const { provider, client, signal } = options;
27
+ const tools = options.tools ?? readTools;
28
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
29
+ const toolsByName = new Map(tools.map((t) => [t.name, t]));
30
+ const toolSchemas = toToolSchemas(tools);
31
+ const messages = [...options.messages];
32
+ let steps = 0;
33
+ while (steps < maxSteps) {
34
+ steps += 1;
35
+ const response = await provider.complete({ messages, tools: toolSchemas, signal });
36
+ if (response.kind === "final") {
37
+ messages.push({ role: "assistant", content: response.content });
38
+ return { content: response.content, messages, steps, stoppedOnMaxSteps: false };
39
+ }
40
+ messages.push({
41
+ role: "assistant",
42
+ content: response.content ?? "",
43
+ toolCalls: response.toolCalls,
44
+ });
45
+ for (const call of response.toolCalls) {
46
+ messages.push(await executeToolCall(client, toolsByName.get(call.name), call));
47
+ }
48
+ }
49
+ return { content: "", messages, steps, stoppedOnMaxSteps: true };
50
+ }
51
+ /**
52
+ * Execute one tool call and return the `tool` result message. Unknown tools and
53
+ * invalid arguments produce an error result (rather than throwing) so the model
54
+ * can see the failure and recover on the next turn. Collector errors are
55
+ * likewise surfaced as text.
56
+ */
57
+ async function executeToolCall(client, tool, call) {
58
+ const result = (content) => ({
59
+ role: "tool",
60
+ toolCallId: call.id,
61
+ name: call.name,
62
+ content,
63
+ });
64
+ if (!tool) {
65
+ return result(`Error: unknown tool "${call.name}".`);
66
+ }
67
+ const parsed = z.object(tool.inputSchema).safeParse(call.arguments ?? {});
68
+ if (!parsed.success) {
69
+ const issues = parsed.error.issues
70
+ .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`)
71
+ .join("; ");
72
+ return result(`Error: invalid arguments for "${call.name}": ${issues}`);
73
+ }
74
+ try {
75
+ const { path, params } = tool.buildRequest(parsed.data);
76
+ const data = await client.get(path, params);
77
+ return result(JSON.stringify(data));
78
+ }
79
+ catch (err) {
80
+ const message = err instanceof Error ? err.message : String(err);
81
+ return result(`Error: ${message}`);
82
+ }
83
+ }
84
+ //# sourceMappingURL=loop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loop.js","sourceRoot":"","sources":["../src/loop.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAAE,SAAS,EAAiB,MAAM,YAAY,CAAC;AAEtD,qFAAqF;AACrF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAEnC;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,QAA6B,SAAS;IAClE,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1B,IAAI,EAAE,IAAI,CAAC,IAAI;QACf,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,UAAU,EAAE,CAAC,CAAC,YAAY,C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