@caldrix-ai/aerix 0.0.0-stage → 0.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ Format after [Keep a Changelog](https://keepachangelog.com/); versions are independent semver, tagged
4
+ `aerix-js-v<version>`.
5
+
6
+ ## 0.1.1 — 2026-11-03
7
+
8
+ ### Changed
9
+
10
+ - The `@caldrix-ai/caldrix` peer range is `^0.3.0`, the caldrix.js that reads a model's `chat_template.jinja`; the loop itself is unchanged.
11
+
12
+ ## 0.1.0 — 2026-10-30
13
+
14
+ ### Added
15
+
16
+ - `Agent`: Aerix's turn loop on a caldrix.js `Model`, with `tool()`, hooks, limits and named endings.
17
+ - `Agent` refuses a hand-built tool without `input`, and any own hooks key that looks like a misspelled hook (`before*`, `after*`, `on*`), with an `options` error; other own keys on a hooks object are instance state. `tool()` refuses the field names `__proto__`, `constructor` and `prototype`. A tool that returns `undefined` or `null` gives the model an empty result.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ aerix.js (the npm package @caldrix-ai/aerix)
2
+ Copyright 2026 Jyothsna Muttineni, for Caldrix GmbH (in formation)
package/README.md CHANGED
@@ -1,3 +1,142 @@
1
- # Temporary Holding Version
1
+ # aerix.js
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
+ Aerix's turn loop in the browser: an agent with tools, hooks and named limits, running on a
4
+ caldrix.js engine. On npm it is [`@caldrix-ai/aerix`](https://www.npmjs.com/package/@caldrix-ai/aerix).
5
+
6
+ aerix.js loads nothing itself. You load a model with caldrix.js and hand its `Engine` to an `Agent`.
7
+ The loop asks the engine for one turn at a time, runs the tools the turn calls, and feeds the results
8
+ back until the model answers with a final or a limit is reached.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @caldrix-ai/caldrix @caldrix-ai/aerix
14
+ ```
15
+
16
+ `@caldrix-ai/caldrix` is a peer dependency (`^0.3.0`, the caldrix.js that reads a model's `chat_template.jinja`).
17
+
18
+ ## Example
19
+
20
+ ```ts
21
+ import { Caldrix } from "@caldrix-ai/caldrix";
22
+ import { Agent, tool } from "@caldrix-ai/aerix";
23
+
24
+ const engine = await Caldrix.load("smollm2-instruct");
25
+
26
+ const weather = tool({
27
+ name: "weather",
28
+ description: "Today's forecast for a city.",
29
+ input: {
30
+ city: { type: "string", description: "City name", required: true },
31
+ unit: { type: "string", enum: ["c", "f"] },
32
+ },
33
+ run: async ({ city, unit }) => `Sunny in ${city}, 21°${unit ?? "c"}`,
34
+ });
35
+
36
+ const agent = new Agent({
37
+ model: engine,
38
+ instructions: "You are a travel helper. Use the tools to answer.",
39
+ tools: [weather],
40
+ limits: { turns: 8, retries: 2, maxTokens: 384, resultChars: 4000 },
41
+ generation: { temperature: 0 },
42
+ hooks: { beforeCall: (call) => (call.tool === "weather" ? undefined : { deny: "not allowed" }) },
43
+ });
44
+
45
+ const controller = new AbortController();
46
+ for await (const ev of agent.run("Should I pack an umbrella for Lisbon?", { signal: controller.signal })) {
47
+ if (ev.type === "final") console.log(ev.text);
48
+ }
49
+ const { text } = await agent.ask("And for Porto?"); // the same conversation
50
+ console.log(text);
51
+ agent.reset();
52
+ ```
53
+
54
+ ## API
55
+
56
+ The package exports `Agent`, `tool` and `AerixError`, and the types `AgentOptions`, `Limits`, `Hooks`,
57
+ `AgentEvent`, `Call`, `EndReason`, `Model`, `Tool`, `ToolDef`, `Field` and `FieldType`.
58
+
59
+ **`Model`** is `{ chat(messages, opts?): AsyncIterable<Delta> }` over caldrix.js's types. A caldrix.js
60
+ `Engine` satisfies it.
61
+
62
+ **`tool(def)`** defines a tool:
63
+
64
+ - `name` matches `^[a-z][a-z0-9_]{0,63}$` and is unique in the agent (a duplicate is refused when the
65
+ agent is built).
66
+ - `description` is the text the model sees.
67
+ - `input` is a flat field map. Each field has a `type` (`string`, `number`, `integer` or `boolean`)
68
+ and an optional `description`, `required` and `enum`. An empty map means no input.
69
+ - `run(input, { signal, callId })` returns a string, or a value that goes through `JSON.stringify`.
70
+ The input is checked against the fields before `run`; a failed check or a throw becomes the result
71
+ `error: …`, and a tool error never ends the run.
72
+
73
+ **`new Agent(options)`** takes `AgentOptions`:
74
+
75
+ - `model` (required), `instructions` (default `""`), `tools` (default none; then the only answer is
76
+ a final).
77
+ - `limits`, each a named bound: `turns` (8, generations per run, retries included), `retries` (2,
78
+ extra attempts after a bad or cut turn), `maxTokens` (512, per generation) and `resultChars` (4000,
79
+ one tool result is cut to this with a note).
80
+ - `generation`: caldrix.js's `GenerationOptions` without `maxTokens` and `constraint`, which aerix.js
81
+ sets.
82
+ - `constrain` (default `true`): send the turn schema as the `constraint` of every generation. Set
83
+ `false` for a `Model` without constrained decoding; then only parse-and-retry applies.
84
+ - `hooks`, each optional and awaited: `beforeCall(call)` may return `{ deny: reason }` (the result
85
+ becomes `refused: <reason>`) or `{ input }` (replaces the call's input); `afterCall(call, result)`
86
+ may return `{ result }`; `onFinal(text)` may return `{ continue: text }`, which gives the agent
87
+ another turn with that text as a user message, within `turns`.
88
+
89
+ **`agent.run(prompt, { signal })`** yields `AgentEvent`s and continues the agent's conversation:
90
+
91
+ - `{ type: "text", text }`: raw streamed model text.
92
+ - `{ type: "usage", promptTokens, completionTokens }`: one per generation.
93
+ - `{ type: "turn", turn, thought?, calls }`, then per call `{ type: "call", id, tool, input }` and
94
+ `{ type: "result", id, tool, text, error }`.
95
+ - `{ type: "retry", turn, reason }`: a cut or bad turn is asked again.
96
+ - Exactly one ending: `{ type: "final", text, thought? }`, or `{ type: "end", reason, message? }`
97
+ where `reason` is `"turns"`, `"retries"`, `"abort"` or `"error"` (an engine failure or a throwing
98
+ hook, with its message). An engine failure is this event, never a throw.
99
+
100
+ **`agent.ask(prompt, { signal })`** runs to the end and resolves `{ text, events }` on a final; any
101
+ other ending rejects with `AerixError` kind `end`, carrying `reason` and `events`.
102
+ **`agent.reset()`** forgets the conversation. **`agent.messages`** is the conversation so far.
103
+
104
+ One run at a time: a second concurrent `run` throws `AerixError` kind `busy`, and bad options throw
105
+ kind `options`.
106
+
107
+ ## The turn contract
108
+
109
+ Every turn is one JSON object, either `{"calls":[{"tool":"…","input":{…}}]}` or `{"final":"…"}`, with an
110
+ optional `thought`. The system message states this contract and lists the tools; it is the same
111
+ contract and the same tool rendering as Aerix's.
112
+
113
+ Every turn is constrained (unless `constrain: false`): the engine decodes under a schema built from
114
+ the tools, so a turn that ends on its own is a valid turn with a known tool and an input of the right
115
+ shape, with one exception: an empty `calls` list passes the constraint, and parsing refuses it
116
+ and retries. A turn cut by `maxTokens` before its JSON closes is dropped and asked again, shorter, as a
117
+ retry. At most 8 calls of one turn are kept, a `thought` is cut at 600 characters, and calls run in
118
+ order, one at a time.
119
+
120
+ Each turn's prompt is the system message plus every earlier turn and result. The engine keeps what the
121
+ previous generation processed, so a turn that only appends to the conversation prefills the new part;
122
+ the done delta's `usage.cachedTokens` says how much was reused.
123
+
124
+ ## Not built
125
+
126
+ - Per-option scores for routing (the browser engine returns `logprobs`; nothing here reads them).
127
+ - Subagents and a verifier, compaction and a context tool, sessions kept in IndexedDB.
128
+
129
+ ## What has run
130
+
131
+ - The unit tests, against a scripted fake `Model`: the turn parsing, the system rendering and the turn
132
+ schema (golden), the turn contract pinned to Aerix's, input checks, each hook, each ending and each limit.
133
+ - One end-to-end test in Playwright's headless Chromium on the wasm tier: an `Agent` with one tool
134
+ on the built caldrix.js, loading a tiny test model whose output is noise, from a loopback server.
135
+ It checks that the engine receives the turn schema on every generation, that every retry follows a
136
+ cut turn, and that the run ends with a named outcome.
137
+
138
+ Nothing more is claimed: no real model, no other browser or tier, and no quality or speed figure.
139
+
140
+ ## License
141
+
142
+ aerix.js (the npm package `@caldrix-ai/aerix`) is under Apache-2.0 (`LICENSE`, `NOTICE`).
@@ -0,0 +1,150 @@
1
+ import { ChatMessage, GenerateOptions, Delta, GenerationOptions } from '@caldrix-ai/caldrix';
2
+
3
+ /** Why a run ended without a final. */
4
+ type EndReason = "turns" | "retries" | "abort" | "error";
5
+ /** One tool call of a turn. */
6
+ interface Call {
7
+ id: string;
8
+ tool: string;
9
+ input: Record<string, unknown>;
10
+ }
11
+ /** One event of a run. Every run ends with exactly one `final` or `end`. */
12
+ type AgentEvent = {
13
+ type: "text";
14
+ text: string;
15
+ } | {
16
+ type: "usage";
17
+ promptTokens: number;
18
+ completionTokens: number;
19
+ } | {
20
+ type: "turn";
21
+ turn: number;
22
+ thought?: string;
23
+ calls: Call[];
24
+ } | {
25
+ type: "call";
26
+ id: string;
27
+ tool: string;
28
+ input: Record<string, unknown>;
29
+ } | {
30
+ type: "result";
31
+ id: string;
32
+ tool: string;
33
+ text: string;
34
+ error: boolean;
35
+ } | {
36
+ type: "retry";
37
+ turn: number;
38
+ reason: string;
39
+ } | {
40
+ type: "final";
41
+ text: string;
42
+ thought?: string;
43
+ } | {
44
+ type: "end";
45
+ reason: EndReason;
46
+ message?: string;
47
+ };
48
+
49
+ /** What the loop generates with. A caldrix.js `Engine` satisfies it. */
50
+ interface Model {
51
+ chat(messages: ChatMessage[], opts?: GenerateOptions): AsyncIterable<Delta>;
52
+ }
53
+
54
+ type FieldType = "string" | "number" | "integer" | "boolean";
55
+ interface Field {
56
+ type: FieldType;
57
+ description?: string;
58
+ required?: boolean;
59
+ enum?: readonly (string | number | boolean)[];
60
+ }
61
+ interface ToolDef<I> {
62
+ name: string;
63
+ description: string;
64
+ input: Record<string, Field>;
65
+ run(input: I, cx: {
66
+ signal: AbortSignal;
67
+ callId: string;
68
+ }): unknown | Promise<unknown>;
69
+ }
70
+ /** A defined tool: the frozen definition and its compiled input schema. */
71
+ interface Tool extends Readonly<ToolDef<any>> {
72
+ readonly schema: object;
73
+ }
74
+ declare function tool<I = Record<string, unknown>>(def: ToolDef<I>): Tool;
75
+
76
+ interface Limits {
77
+ /** Generations per run, retries and cut turns included. */
78
+ turns?: number;
79
+ /** Extra attempts after a bad or cut turn, per turn. */
80
+ retries?: number;
81
+ /** Tokens per generation. */
82
+ maxTokens?: number;
83
+ /** Characters of one tool result; the rest is cut with a note. */
84
+ resultChars?: number;
85
+ }
86
+ type Awaitable<T> = T | Promise<T>;
87
+ type BeforeCall = void | {
88
+ deny: string;
89
+ } | {
90
+ input: Record<string, unknown>;
91
+ };
92
+ type AfterCall = void | {
93
+ result: string;
94
+ };
95
+ type OnFinal = void | {
96
+ continue: string;
97
+ };
98
+ interface Hooks {
99
+ /** A deny becomes the result `refused: <reason>`; `input` replaces the call's input. */
100
+ beforeCall?(c: Call): Awaitable<BeforeCall>;
101
+ /** `result` replaces the tool's result. */
102
+ afterCall?(c: Call, result: string): Awaitable<AfterCall>;
103
+ /** `continue` gives the agent another turn with that text as a user message (bounded by `turns`). */
104
+ onFinal?(text: string): Awaitable<OnFinal>;
105
+ }
106
+ interface AgentOptions {
107
+ model: Model;
108
+ instructions?: string;
109
+ tools?: Tool[];
110
+ limits?: Limits;
111
+ generation?: Omit<GenerationOptions, "maxTokens" | "constraint">;
112
+ /** Send the turn schema as `constraint.json` on each generation (default `true`). */
113
+ constrain?: boolean;
114
+ hooks?: Hooks;
115
+ }
116
+ /** Runs Aerix's turn loop on a `Model`: one run at a time, over one conversation. */
117
+ declare class Agent {
118
+ #private;
119
+ constructor(o: AgentOptions);
120
+ /** The conversation so far: the system message, then every prompt, turn and result. */
121
+ get messages(): readonly ChatMessage[];
122
+ /** Forgets the conversation (and restarts call ids at `c1`). */
123
+ reset(): void;
124
+ /**
125
+ * Runs the loop on `prompt`, continuing the conversation. Ends with exactly one `final` or `end`
126
+ * event; it throws only `AerixError` kind `busy` (a run is already going) or `options`.
127
+ */
128
+ run(prompt: string, o?: {
129
+ signal?: AbortSignal;
130
+ }): AsyncGenerator<AgentEvent, void, undefined>;
131
+ /** Runs to the end: resolves on a final, else rejects with `AerixError` kind `end`. */
132
+ ask(prompt: string, o?: {
133
+ signal?: AbortSignal;
134
+ }): Promise<{
135
+ text: string;
136
+ events: AgentEvent[];
137
+ }>;
138
+ }
139
+
140
+ declare class AerixError extends Error {
141
+ readonly kind: "options" | "busy" | "end";
142
+ readonly reason?: EndReason;
143
+ readonly events?: AgentEvent[];
144
+ constructor(kind: "options" | "busy" | "end", message: string, extra?: {
145
+ reason?: EndReason;
146
+ events?: AgentEvent[];
147
+ });
148
+ }
149
+
150
+ export { AerixError, Agent, type AgentEvent, type AgentOptions, type Call, type EndReason, type Field, type FieldType, type Hooks, type Limits, type Model, type Tool, type ToolDef, tool };
package/dist/index.js ADDED
@@ -0,0 +1,544 @@
1
+ // src/errors.ts
2
+ var AerixError = class extends Error {
3
+ kind;
4
+ reason;
5
+ events;
6
+ constructor(kind, message2, extra = {}) {
7
+ super(message2);
8
+ this.name = "AerixError";
9
+ this.kind = kind;
10
+ if (extra.reason !== void 0) this.reason = extra.reason;
11
+ if (extra.events !== void 0) this.events = extra.events;
12
+ }
13
+ };
14
+
15
+ // src/turn_contract.ts
16
+ var TURN_CONTRACT = `Every turn you answer with exactly one JSON object and nothing else. There are two shapes.
17
+
18
+ To use tools, answer: {"calls":[{"tool":"read","input":{"path":"src/main.rs"}}]}
19
+ Each call has a "tool" name and an "input" object. You may list several calls in one turn. They run in order, except agent calls, which run at the same time.
20
+
21
+ When the task is done, answer: {"final":"what you did and what you found"}
22
+ `;
23
+
24
+ // src/render.ts
25
+ function typeLabel(p) {
26
+ if (Array.isArray(p.enum)) {
27
+ return `one of ${p.enum.map(String).join("|")}`;
28
+ }
29
+ return typeof p.type === "string" ? p.type : "any";
30
+ }
31
+ function fieldList(t) {
32
+ const names = Object.keys(t.input);
33
+ if (names.length === 0) return "none (pass an empty object)";
34
+ const req = (n) => t.input[n]?.required === true;
35
+ names.sort((a, b) => Number(!req(a)) - Number(!req(b)) || (a < b ? -1 : a > b ? 1 : 0));
36
+ return names.map((n) => {
37
+ const kind = typeLabel(t.input[n]);
38
+ return req(n) ? `${n} (${kind}, required)` : `${n} (${kind})`;
39
+ }).join(", ");
40
+ }
41
+ function describe(tools) {
42
+ if (tools.length === 0) return "(no tools; answer with a final)";
43
+ return tools.map((t) => `## ${t.name}
44
+ ${t.description}
45
+
46
+ Input: ${fieldList(t)}`).join("\n\n");
47
+ }
48
+ function systemText(instructions, tools) {
49
+ return `${instructions.trimEnd()}
50
+
51
+ # Turns
52
+ ${TURN_CONTRACT.trimEnd()}
53
+
54
+ # Tools
55
+ ${describe(tools)}`;
56
+ }
57
+
58
+ // src/schema.ts
59
+ var MAX_THOUGHT = 600;
60
+ function inputSchema(input) {
61
+ const properties = {};
62
+ const required = [];
63
+ for (const [name, f] of Object.entries(input)) {
64
+ const p = { type: f.type };
65
+ if (f.description !== void 0) p.description = f.description;
66
+ if (f.enum !== void 0) p.enum = [...f.enum];
67
+ properties[name] = p;
68
+ if (f.required === true) required.push(name);
69
+ }
70
+ return { type: "object", properties, required, additionalProperties: false };
71
+ }
72
+ function envelopeSchema(tools) {
73
+ return {
74
+ oneOf: tools.map((t) => ({
75
+ type: "object",
76
+ properties: {
77
+ tool: { enum: [t.name], description: "the tool to call" },
78
+ input: t.schema
79
+ },
80
+ required: ["tool", "input"],
81
+ additionalProperties: false
82
+ }))
83
+ };
84
+ }
85
+ function turnSchema(tools) {
86
+ const thought = { type: "string", maxLength: MAX_THOUGHT };
87
+ const finalBranch = {
88
+ type: "object",
89
+ properties: { thought, final: { type: "string" } },
90
+ required: ["final"],
91
+ additionalProperties: false
92
+ };
93
+ if (tools.length === 0) return finalBranch;
94
+ return {
95
+ oneOf: [
96
+ {
97
+ type: "object",
98
+ properties: { thought, calls: { type: "array", items: envelopeSchema(tools) } },
99
+ required: ["calls"],
100
+ additionalProperties: false
101
+ },
102
+ finalBranch
103
+ ]
104
+ };
105
+ }
106
+
107
+ // src/tool.ts
108
+ var NAME = /^[a-z][a-z0-9_]{0,63}$/;
109
+ var RESERVED = ["__proto__", "constructor", "prototype"];
110
+ var TYPES = ["string", "number", "integer", "boolean"];
111
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
112
+ function tool(def) {
113
+ if (!isObject(def)) throw new AerixError("options", "a tool definition must be an object");
114
+ if (typeof def.name !== "string" || !NAME.test(def.name)) {
115
+ throw new AerixError("options", `tool name ${JSON.stringify(def.name)} must match ${NAME.source}`);
116
+ }
117
+ if (typeof def.description !== "string") {
118
+ throw new AerixError("options", `tool ${def.name}: description must be a string`);
119
+ }
120
+ if (typeof def.run !== "function") {
121
+ throw new AerixError("options", `tool ${def.name}: run must be a function`);
122
+ }
123
+ if (!isObject(def.input)) {
124
+ throw new AerixError("options", `tool ${def.name}: input must be a field map (an object)`);
125
+ }
126
+ const proto = Object.getPrototypeOf(def.input);
127
+ if (proto !== Object.prototype && proto !== null) {
128
+ throw new AerixError(
129
+ "options",
130
+ `tool ${def.name}: input has a prototype of its own (a literal __proto__ key sets it instead of adding a field)`
131
+ );
132
+ }
133
+ const input = {};
134
+ for (const [field, f] of Object.entries(def.input)) {
135
+ if (RESERVED.includes(field)) {
136
+ throw new AerixError("options", `tool ${def.name}: field name ${field} is reserved`);
137
+ }
138
+ if (!isObject(f)) throw new AerixError("options", `tool ${def.name}: field ${field} must be an object`);
139
+ if (!TYPES.includes(f.type)) {
140
+ throw new AerixError("options", `tool ${def.name}: field ${field} has an unknown type`);
141
+ }
142
+ for (const v of f.enum ?? []) {
143
+ const ok = f.type === "integer" ? Number.isInteger(v) : f.type === "number" ? typeof v === "number" && Number.isFinite(v) : typeof v === f.type;
144
+ if (!ok) {
145
+ throw new AerixError("options", `tool ${def.name}: field ${field} has an enum value that is not a ${f.type}`);
146
+ }
147
+ }
148
+ input[field] = Object.freeze({ ...f, ...f.enum ? { enum: Object.freeze([...f.enum]) } : {} });
149
+ }
150
+ Object.freeze(input);
151
+ return Object.freeze({
152
+ name: def.name,
153
+ description: def.description,
154
+ input,
155
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
156
+ run: def.run,
157
+ schema: inputSchema(input)
158
+ });
159
+ }
160
+ function checkInput(t, input) {
161
+ for (const key of Object.keys(input)) {
162
+ if (!Object.hasOwn(t.input, key)) return `unknown field ${key}`;
163
+ }
164
+ for (const [name, f] of Object.entries(t.input)) {
165
+ const v = Object.hasOwn(input, name) ? input[name] : void 0;
166
+ if (v === void 0 || v === null) {
167
+ if (f.required === true) return `missing required field ${name}`;
168
+ continue;
169
+ }
170
+ const ok = f.type === "integer" ? typeof v === "number" && Number.isInteger(v) : typeof v === f.type && (f.type !== "number" || Number.isFinite(v));
171
+ if (!ok) return `field ${name} must be ${f.type === "integer" ? "an integer" : `a ${f.type}`}`;
172
+ if (f.enum !== void 0 && !f.enum.includes(v)) {
173
+ return `field ${name} must be one of ${f.enum.map(String).join("|")}`;
174
+ }
175
+ }
176
+ return null;
177
+ }
178
+
179
+ // src/turn.ts
180
+ var MAX_CALLS = 8;
181
+ var bad = (error) => ({ ok: false, error });
182
+ var isObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
183
+ function parseTurn(text, tools, nextId) {
184
+ let value;
185
+ try {
186
+ value = JSON.parse(text.trim());
187
+ } catch (e) {
188
+ return bad(`the answer is not valid JSON (${e instanceof Error ? e.message : String(e)})`);
189
+ }
190
+ if (!isObject2(value)) return bad("the answer must be one JSON object");
191
+ const has = (k) => Object.hasOwn(value, k);
192
+ let thought;
193
+ const raw = has("thought") ? value.thought : void 0;
194
+ if (raw === void 0 || raw === null) {
195
+ thought = void 0;
196
+ } else if (typeof raw === "string") {
197
+ const chars = Array.from(raw);
198
+ thought = chars.length > MAX_THOUGHT ? `${chars.slice(0, MAX_THOUGHT).join("")} (thought cut to ${MAX_THOUGHT} characters)` : raw;
199
+ } else {
200
+ return bad("thought must be a string");
201
+ }
202
+ if (has("calls")) {
203
+ const items = value.calls;
204
+ if (!Array.isArray(items)) return bad("calls must be an array");
205
+ if (items.length === 0) return bad("calls is empty; give at least one call, or a final");
206
+ const parsed = [];
207
+ for (const [i, item] of items.entries()) {
208
+ const name = isObject2(item) && typeof item.tool === "string" ? item.tool : void 0;
209
+ if (name === void 0) return bad(`call ${i + 1} needs a tool name in "tool"`);
210
+ if (!tools.some((t) => t.name === name)) return bad(`unknown tool ${name}`);
211
+ const input = item.input;
212
+ if (!isObject2(input)) return bad(`the input of call ${i + 1} (${name}) must be an object`);
213
+ parsed.push({ tool: name, input });
214
+ }
215
+ const total = parsed.length;
216
+ if (total > MAX_CALLS) {
217
+ parsed.length = MAX_CALLS;
218
+ const note = `(${MAX_CALLS} of ${total} calls kept)`;
219
+ thought = thought !== void 0 && thought !== "" ? `${thought} ${note}` : note;
220
+ }
221
+ const calls = parsed.map((c) => ({ id: `c${nextId.n++}`, ...c }));
222
+ return { ok: true, turn: { kind: "calls", ...thought !== void 0 && { thought }, calls } };
223
+ }
224
+ if (has("final")) {
225
+ if (typeof value.final !== "string") return bad("final must be a string");
226
+ return {
227
+ ok: true,
228
+ turn: { kind: "final", ...thought !== void 0 && { thought }, text: value.final }
229
+ };
230
+ }
231
+ return bad(`expected calls or final, found keys [${Object.keys(value).sort().join(", ")}]`);
232
+ }
233
+
234
+ // src/agent.ts
235
+ var DEFAULT_LIMITS = { turns: 8, retries: 2, maxTokens: 512, resultChars: 4e3 };
236
+ var LIMIT_MIN = { turns: 1, retries: 0, maxTokens: 1, resultChars: 1 };
237
+ var CUT_NOTE = "Your last turn hit the token limit before the JSON closed; answer again, shorter.";
238
+ var badNote = (error) => `Your last turn was not valid: ${error}. Answer again as JSON.`;
239
+ var isObject3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
240
+ var message = (e) => e instanceof Error ? e.message : String(e);
241
+ var msg = (role, content) => Object.freeze({ role, content });
242
+ var refuse = (text) => new AerixError("options", text);
243
+ function checkLimits(limits) {
244
+ if (limits === void 0) return { ...DEFAULT_LIMITS };
245
+ if (!isObject3(limits)) throw refuse("limits must be an object");
246
+ const out = { ...DEFAULT_LIMITS };
247
+ for (const [k, v] of Object.entries(limits)) {
248
+ if (!Object.hasOwn(DEFAULT_LIMITS, k)) throw refuse(`unknown limit ${k}`);
249
+ if (v === void 0) continue;
250
+ const min = LIMIT_MIN[k];
251
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min) {
252
+ throw refuse(`limits.${k} must be an integer of at least ${min}`);
253
+ }
254
+ out[k] = v;
255
+ }
256
+ return out;
257
+ }
258
+ function checkTools(tools) {
259
+ if (tools === void 0) return [];
260
+ if (!Array.isArray(tools)) throw refuse("tools must be an array");
261
+ const names = /* @__PURE__ */ new Set();
262
+ for (const t of tools) {
263
+ if (!isObject3(t) || typeof t.name !== "string" || typeof t.run !== "function" || !isObject3(t.schema)) {
264
+ throw refuse("each tool must be made with tool()");
265
+ }
266
+ if (!isObject3(t.input)) throw refuse(`tool ${t.name}: input must be a field map (an object)`);
267
+ if (names.has(t.name)) throw refuse(`two tools are named ${t.name}`);
268
+ names.add(t.name);
269
+ }
270
+ return Object.freeze([...tools]);
271
+ }
272
+ function checkGeneration(generation) {
273
+ if (generation === void 0) return {};
274
+ if (!isObject3(generation)) throw refuse("generation must be an object");
275
+ for (const k of ["maxTokens", "constraint", "signal"]) {
276
+ if (Object.hasOwn(generation, k)) {
277
+ throw refuse(`generation.${k} is set by the agent (use limits.maxTokens, constrain or run's signal)`);
278
+ }
279
+ }
280
+ return { ...generation };
281
+ }
282
+ var HOOK_NAMES = ["beforeCall", "afterCall", "onFinal"];
283
+ function checkHooks(hooks) {
284
+ if (hooks === void 0) return {};
285
+ if (!isObject3(hooks)) throw refuse("hooks must be an object");
286
+ for (const k of Object.keys(hooks)) {
287
+ if (!HOOK_NAMES.includes(k) && /^(before|after|on)[A-Z]/.test(k)) {
288
+ throw refuse(`unknown hook ${k} (hooks are ${HOOK_NAMES.join(", ")})`);
289
+ }
290
+ }
291
+ const out = {};
292
+ for (const k of HOOK_NAMES) {
293
+ const f = hooks[k];
294
+ if (f === void 0) continue;
295
+ if (typeof f !== "function") throw refuse(`hooks.${k} must be a function`);
296
+ out[k] = f.bind(hooks);
297
+ }
298
+ return out;
299
+ }
300
+ function capResult(text, cap) {
301
+ if (text.length <= cap) return text;
302
+ const chars = Array.from(text);
303
+ if (chars.length <= cap) return text;
304
+ return `${chars.slice(0, cap).join("")}
305
+ [result cut to ${cap} of ${chars.length} characters]`;
306
+ }
307
+ var resultText = (v) => typeof v === "string" ? v : v === void 0 || v === null ? "" : JSON.stringify(v) ?? String(v);
308
+ var ABORTED = /* @__PURE__ */ Symbol("aborted");
309
+ async function untilAbort(fn, signal) {
310
+ let onAbort = () => {
311
+ };
312
+ const aborted = new Promise((resolve) => {
313
+ onAbort = () => resolve(ABORTED);
314
+ if (signal.aborted) onAbort();
315
+ else signal.addEventListener("abort", onAbort, { once: true });
316
+ });
317
+ const ran = Promise.resolve().then(fn).then(
318
+ (value) => ({ value }),
319
+ (e) => ({ thrown: e })
320
+ );
321
+ try {
322
+ return await Promise.race([ran, aborted]);
323
+ } finally {
324
+ signal.removeEventListener("abort", onAbort);
325
+ }
326
+ }
327
+ async function hook(fn, signal) {
328
+ if (fn === void 0) return void 0;
329
+ const out = await untilAbort(fn, signal);
330
+ if (out === ABORTED) return ABORTED;
331
+ if ("thrown" in out) throw out.thrown;
332
+ return out.value;
333
+ }
334
+ var Agent = class {
335
+ #model;
336
+ #tools;
337
+ #limits;
338
+ #generation;
339
+ #constraint;
340
+ #hooks;
341
+ #system;
342
+ #messages;
343
+ #nextId = { n: 1 };
344
+ #busy = false;
345
+ constructor(o) {
346
+ if (!isObject3(o)) throw refuse("options must be an object");
347
+ if (!isObject3(o.model) || typeof o.model.chat !== "function") {
348
+ throw refuse("model must have a chat method (a caldrix.js Engine does)");
349
+ }
350
+ if (o.instructions !== void 0 && typeof o.instructions !== "string") {
351
+ throw refuse("instructions must be a string");
352
+ }
353
+ if (o.constrain !== void 0 && typeof o.constrain !== "boolean") throw refuse("constrain must be a boolean");
354
+ this.#model = o.model;
355
+ this.#tools = checkTools(o.tools);
356
+ this.#limits = checkLimits(o.limits);
357
+ this.#generation = checkGeneration(o.generation);
358
+ this.#hooks = checkHooks(o.hooks);
359
+ this.#constraint = o.constrain === false ? void 0 : { json: turnSchema(this.#tools) };
360
+ this.#system = msg("system", systemText(o.instructions ?? "", this.#tools));
361
+ this.#messages = [this.#system];
362
+ }
363
+ /** The conversation so far: the system message, then every prompt, turn and result. */
364
+ get messages() {
365
+ return Object.freeze([...this.#messages]);
366
+ }
367
+ /** Forgets the conversation (and restarts call ids at `c1`). */
368
+ reset() {
369
+ if (this.#busy) throw new AerixError("busy", "a run is going on this agent");
370
+ this.#messages = [this.#system];
371
+ this.#nextId = { n: 1 };
372
+ }
373
+ /**
374
+ * Runs the loop on `prompt`, continuing the conversation. Ends with exactly one `final` or `end`
375
+ * event; it throws only `AerixError` kind `busy` (a run is already going) or `options`.
376
+ */
377
+ async *run(prompt, o = {}) {
378
+ if (this.#busy) throw new AerixError("busy", "a run is already going on this agent");
379
+ if (typeof prompt !== "string") throw refuse("prompt must be a string");
380
+ const signal = o?.signal;
381
+ if (signal !== void 0 && (!isObject3(signal) || typeof signal.addEventListener !== "function")) {
382
+ throw refuse("signal must be an AbortSignal");
383
+ }
384
+ this.#busy = true;
385
+ try {
386
+ yield* this.#loop(prompt, signal ?? new AbortController().signal);
387
+ } finally {
388
+ this.#busy = false;
389
+ }
390
+ }
391
+ /** Runs to the end: resolves on a final, else rejects with `AerixError` kind `end`. */
392
+ async ask(prompt, o = {}) {
393
+ const events = [];
394
+ for await (const ev of this.run(prompt, o)) {
395
+ events.push(ev);
396
+ if (ev.type === "final") return { text: ev.text, events };
397
+ if (ev.type === "end") {
398
+ throw new AerixError("end", ev.message ?? `the run ended without a final (${ev.reason})`, {
399
+ reason: ev.reason,
400
+ events
401
+ });
402
+ }
403
+ }
404
+ throw new AerixError("end", "the run ended without a final", { events });
405
+ }
406
+ async *#loop(prompt, signal) {
407
+ const msgs = this.#messages;
408
+ const limits = this.#limits;
409
+ msgs.push(msg("user", prompt));
410
+ let turnStart = msgs.length;
411
+ let done = false;
412
+ const end = (reason, text) => {
413
+ done = true;
414
+ msgs.length = turnStart;
415
+ return text === void 0 ? { type: "end", reason } : { type: "end", reason, message: text };
416
+ };
417
+ const spent = () => end("turns", `the turn budget (${limits.turns}) is spent`);
418
+ let turn = 0;
419
+ try {
420
+ for (; ; ) {
421
+ turnStart = msgs.length;
422
+ let attempt = 0;
423
+ let text = "";
424
+ let parsed;
425
+ for (; ; ) {
426
+ if (signal.aborted) return yield end("abort");
427
+ if (turn >= limits.turns) return yield spent();
428
+ turn++;
429
+ const opts = {
430
+ ...this.#generation,
431
+ maxTokens: limits.maxTokens,
432
+ ...this.#constraint && { constraint: this.#constraint },
433
+ signal
434
+ };
435
+ text = "";
436
+ let finish;
437
+ for await (const d of this.#model.chat([...msgs], opts)) {
438
+ if (typeof d.text === "string" && d.text !== "") {
439
+ text += d.text;
440
+ yield { type: "text", text: d.text };
441
+ }
442
+ if (d.done) {
443
+ finish = d.finishReason;
444
+ if (d.usage) {
445
+ const { promptTokens, completionTokens } = d.usage;
446
+ yield { type: "usage", promptTokens, completionTokens };
447
+ }
448
+ break;
449
+ }
450
+ }
451
+ if (signal.aborted || finish === "abort") return yield end("abort");
452
+ parsed = parseTurn(text, this.#tools, this.#nextId);
453
+ if (parsed.ok) break;
454
+ if (turn >= limits.turns) return yield spent();
455
+ if (attempt >= limits.retries) {
456
+ return yield end("retries", `no valid turn after ${limits.retries} retries: ${parsed.error}`);
457
+ }
458
+ attempt++;
459
+ if (finish === "length") {
460
+ yield { type: "retry", turn, reason: "the turn hit the token limit before the JSON closed" };
461
+ msgs.push(msg("user", CUT_NOTE));
462
+ } else {
463
+ yield { type: "retry", turn, reason: parsed.error };
464
+ msgs.push(msg("assistant", text), msg("user", badNote(parsed.error)));
465
+ }
466
+ }
467
+ msgs.length = turnStart;
468
+ msgs.push(msg("assistant", text));
469
+ const t = parsed.turn;
470
+ if (t.kind === "final") {
471
+ const onFinal = this.#hooks.onFinal;
472
+ const next = await hook(onFinal && (() => onFinal(t.text)), signal);
473
+ if (next === ABORTED) return yield end("abort");
474
+ if (isObject3(next) && typeof next.continue === "string") {
475
+ msgs.push(msg("user", next.continue));
476
+ continue;
477
+ }
478
+ done = true;
479
+ return yield { type: "final", text: t.text, ...t.thought !== void 0 && { thought: t.thought } };
480
+ }
481
+ yield {
482
+ type: "turn",
483
+ turn,
484
+ ...t.thought !== void 0 && { thought: t.thought },
485
+ calls: t.calls.map((c) => ({ ...c, input: { ...c.input } }))
486
+ };
487
+ for (const c of t.calls) {
488
+ if (signal.aborted) return yield end("abort");
489
+ if ((yield* this.#call(c, signal)) === ABORTED) return yield end("abort");
490
+ }
491
+ }
492
+ } catch (e) {
493
+ yield signal.aborted ? end("abort") : end("error", message(e));
494
+ } finally {
495
+ if (!done) msgs.length = turnStart;
496
+ }
497
+ }
498
+ /** One call: the hooks, the input check and the tool, then its result appended to the conversation. */
499
+ async *#call(c, signal) {
500
+ const t = this.#tools.find((x) => x.name === c.tool);
501
+ let input = c.input;
502
+ const { beforeCall, afterCall } = this.#hooks;
503
+ const before = await hook(beforeCall && (() => beforeCall({ ...c, input: { ...input } })), signal);
504
+ if (before === ABORTED) return ABORTED;
505
+ let text;
506
+ let error = true;
507
+ if (isObject3(before) && typeof before.deny === "string") {
508
+ yield { type: "call", id: c.id, tool: c.tool, input: { ...input } };
509
+ text = `refused: ${before.deny}`;
510
+ } else {
511
+ if (isObject3(before) && isObject3(before.input)) input = { ...before.input };
512
+ yield { type: "call", id: c.id, tool: c.tool, input: { ...input } };
513
+ const bad2 = checkInput(t, input);
514
+ if (bad2 !== null) {
515
+ text = `error: ${bad2}`;
516
+ } else {
517
+ const cx = { signal, callId: c.id };
518
+ const out = await untilAbort(async () => resultText(await t.run(input, cx)), signal);
519
+ if (out === ABORTED || signal.aborted) return ABORTED;
520
+ if ("value" in out) {
521
+ text = out.value;
522
+ error = false;
523
+ } else {
524
+ text = `error: ${message(out.thrown)}`;
525
+ }
526
+ const ran = text;
527
+ const after = await hook(afterCall && (() => afterCall({ ...c, input: { ...input } }, ran)), signal);
528
+ if (after === ABORTED) return ABORTED;
529
+ if (isObject3(after) && typeof after.result === "string") text = after.result;
530
+ }
531
+ }
532
+ text = capResult(text, this.#limits.resultChars);
533
+ this.#messages.push(msg("user", `[${c.tool} ${c.id}]
534
+ ${text}`));
535
+ yield { type: "result", id: c.id, tool: c.tool, text, error };
536
+ return void 0;
537
+ }
538
+ };
539
+ export {
540
+ AerixError,
541
+ Agent,
542
+ tool
543
+ };
544
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/turn_contract.ts","../src/render.ts","../src/schema.ts","../src/tool.ts","../src/turn.ts","../src/agent.ts"],"sourcesContent":["import type { AgentEvent, EndReason } from \"./events.js\";\n\nexport class AerixError extends Error {\n readonly kind: \"options\" | \"busy\" | \"end\";\n readonly reason?: EndReason;\n readonly events?: AgentEvent[];\n\n constructor(\n kind: \"options\" | \"busy\" | \"end\",\n message: string,\n extra: { reason?: EndReason; events?: AgentEvent[] } = {},\n ) {\n super(message);\n this.name = \"AerixError\";\n this.kind = kind;\n if (extra.reason !== undefined) this.reason = extra.reason;\n if (extra.events !== undefined) this.events = extra.events;\n }\n}\n","// Verbatim copy of aerix/crates/aerix-core/src/turn_contract.md; tests/unit/turn_contract.test.ts fails on drift.\nexport const TURN_CONTRACT = `Every turn you answer with exactly one JSON object and nothing else. There are two shapes.\n\nTo use tools, answer: {\"calls\":[{\"tool\":\"read\",\"input\":{\"path\":\"src/main.rs\"}}]}\nEach call has a \"tool\" name and an \"input\" object. You may list several calls in one turn. They run in order, except agent calls, which run at the same time.\n\nWhen the task is done, answer: {\"final\":\"what you did and what you found\"}\n`;\n","import { TURN_CONTRACT } from \"./turn_contract.js\";\nimport type { Tool } from \"./tool.js\";\n\ntype Prop = { type?: unknown; enum?: unknown; items?: Prop };\n\n/**\n * aerix-core's type_label: an enum reads `one of a|b`, else the type. Non-string enum values render\n * with `String(v)` (`one of 1|2`): a deliberate departure, since aerix-core never has them.\n */\nfunction typeLabel(p: Prop): string {\n if (Array.isArray(p.enum)) {\n return `one of ${p.enum.map(String).join(\"|\")}`;\n }\n return typeof p.type === \"string\" ? p.type : \"any\";\n}\n\n/** `city (string, required), unit (string)`: required fields first, then the rest by name. */\nfunction fieldList(t: Tool): string {\n const names = Object.keys(t.input);\n if (names.length === 0) return \"none (pass an empty object)\";\n const req = (n: string) => t.input[n]?.required === true;\n names.sort((a, b) => Number(!req(a)) - Number(!req(b)) || (a < b ? -1 : a > b ? 1 : 0));\n return names\n .map((n) => {\n const kind = typeLabel(t.input[n] as Prop);\n return req(n) ? `${n} (${kind}, required)` : `${n} (${kind})`;\n })\n .join(\", \");\n}\n\nfunction describe(tools: readonly Tool[]): string {\n if (tools.length === 0) return \"(no tools; answer with a final)\";\n return tools.map((t) => `## ${t.name}\\n${t.description}\\n\\nInput: ${fieldList(t)}`).join(\"\\n\\n\");\n}\n\n/** The system message: instructions, the turn contract, then the tools. */\nexport function systemText(instructions: string, tools: readonly Tool[]): string {\n return `${instructions.trimEnd()}\\n\\n# Turns\\n${TURN_CONTRACT.trimEnd()}\\n\\n# Tools\\n${describe(tools)}`;\n}\n","import type { Field, Tool } from \"./tool.js\";\n\nexport const MAX_THOUGHT = 600;\n\n/** The JSON schema of a flat field map, inside the engine's subset. */\nexport function inputSchema(input: Record<string, Field>): object {\n const properties: Record<string, object> = {};\n const required: string[] = [];\n for (const [name, f] of Object.entries(input)) {\n const p: Record<string, unknown> = { type: f.type };\n if (f.description !== undefined) p.description = f.description;\n if (f.enum !== undefined) p.enum = [...f.enum];\n properties[name] = p;\n if (f.required === true) required.push(name);\n }\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n/** `oneOf` over the tools: `{tool: {enum: [name]}, input: <schema>}` (aerix-core's envelope_schema). */\nfunction envelopeSchema(tools: readonly Tool[]): object {\n return {\n oneOf: tools.map((t) => ({\n type: \"object\",\n properties: {\n tool: { enum: [t.name], description: \"the tool to call\" },\n input: t.schema,\n },\n required: [\"tool\", \"input\"],\n additionalProperties: false,\n })),\n };\n}\n\n/** The schema of a turn: calls to the tools, or a final. With no tools, the final alone. */\nexport function turnSchema(tools: readonly Tool[]): Record<string, unknown> {\n const thought = { type: \"string\", maxLength: MAX_THOUGHT };\n const finalBranch = {\n type: \"object\",\n properties: { thought, final: { type: \"string\" } },\n required: [\"final\"],\n additionalProperties: false,\n };\n if (tools.length === 0) return finalBranch;\n return {\n oneOf: [\n {\n type: \"object\",\n properties: { thought, calls: { type: \"array\", items: envelopeSchema(tools) } },\n required: [\"calls\"],\n additionalProperties: false,\n },\n finalBranch,\n ],\n };\n}\n","import { AerixError } from \"./errors.js\";\nimport { inputSchema } from \"./schema.js\";\n\nexport type FieldType = \"string\" | \"number\" | \"integer\" | \"boolean\";\n\nexport interface Field {\n type: FieldType;\n description?: string;\n required?: boolean;\n enum?: readonly (string | number | boolean)[];\n}\n\nexport interface ToolDef<I> {\n name: string;\n description: string;\n input: Record<string, Field>;\n run(input: I, cx: { signal: AbortSignal; callId: string }): unknown | Promise<unknown>;\n}\n\n/** A defined tool: the frozen definition and its compiled input schema. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface Tool extends Readonly<ToolDef<any>> {\n readonly schema: object;\n}\n\nconst NAME = /^[a-z][a-z0-9_]{0,63}$/;\nconst RESERVED: readonly string[] = [\"__proto__\", \"constructor\", \"prototype\"];\nconst TYPES: readonly string[] = [\"string\", \"number\", \"integer\", \"boolean\"];\n\nconst isObject = (v: unknown): v is object => typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nexport function tool<I = Record<string, unknown>>(def: ToolDef<I>): Tool {\n if (!isObject(def)) throw new AerixError(\"options\", \"a tool definition must be an object\");\n if (typeof def.name !== \"string\" || !NAME.test(def.name)) {\n throw new AerixError(\"options\", `tool name ${JSON.stringify(def.name)} must match ${NAME.source}`);\n }\n if (typeof def.description !== \"string\") {\n throw new AerixError(\"options\", `tool ${def.name}: description must be a string`);\n }\n if (typeof def.run !== \"function\") {\n throw new AerixError(\"options\", `tool ${def.name}: run must be a function`);\n }\n if (!isObject(def.input)) {\n throw new AerixError(\"options\", `tool ${def.name}: input must be a field map (an object)`);\n }\n const proto: unknown = Object.getPrototypeOf(def.input);\n if (proto !== Object.prototype && proto !== null) {\n throw new AerixError(\n \"options\",\n `tool ${def.name}: input has a prototype of its own (a literal __proto__ key sets it instead of adding a field)`,\n );\n }\n const input: Record<string, Field> = {};\n for (const [field, f] of Object.entries(def.input)) {\n if (RESERVED.includes(field)) {\n throw new AerixError(\"options\", `tool ${def.name}: field name ${field} is reserved`);\n }\n if (!isObject(f)) throw new AerixError(\"options\", `tool ${def.name}: field ${field} must be an object`);\n if (!TYPES.includes(f.type)) {\n throw new AerixError(\"options\", `tool ${def.name}: field ${field} has an unknown type`);\n }\n for (const v of f.enum ?? []) {\n const ok =\n f.type === \"integer\"\n ? Number.isInteger(v)\n : f.type === \"number\"\n ? typeof v === \"number\" && Number.isFinite(v)\n : typeof v === f.type;\n if (!ok) {\n throw new AerixError(\"options\", `tool ${def.name}: field ${field} has an enum value that is not a ${f.type}`);\n }\n }\n input[field] = Object.freeze({ ...f, ...(f.enum ? { enum: Object.freeze([...f.enum]) } : {}) });\n }\n Object.freeze(input);\n return Object.freeze({\n name: def.name,\n description: def.description,\n input,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n run: def.run as ToolDef<any>[\"run\"],\n schema: inputSchema(input),\n });\n}\n\n/** The error text naming the offending field, or null when the input fits the tool's fields. */\nexport function checkInput(t: Tool, input: Record<string, unknown>): string | null {\n for (const key of Object.keys(input)) {\n if (!Object.hasOwn(t.input, key)) return `unknown field ${key}`;\n }\n for (const [name, f] of Object.entries(t.input)) {\n const v = Object.hasOwn(input, name) ? input[name] : undefined;\n if (v === undefined || v === null) {\n if (f.required === true) return `missing required field ${name}`;\n continue;\n }\n const ok =\n f.type === \"integer\"\n ? typeof v === \"number\" && Number.isInteger(v)\n : typeof v === f.type && (f.type !== \"number\" || Number.isFinite(v));\n if (!ok) return `field ${name} must be ${f.type === \"integer\" ? \"an integer\" : `a ${f.type}`}`;\n if (f.enum !== undefined && !f.enum.includes(v as string | number | boolean)) {\n return `field ${name} must be one of ${f.enum.map(String).join(\"|\")}`;\n }\n }\n return null;\n}\n","import { MAX_THOUGHT } from \"./schema.js\";\nimport type { Tool } from \"./tool.js\";\n\nexport { MAX_THOUGHT };\n/** A turn names at most this many calls; the rest are dropped with a note. */\nexport const MAX_CALLS = 8;\n\nexport type Turn =\n | {\n kind: \"calls\";\n thought?: string;\n calls: { id: string; tool: string; input: Record<string, unknown> }[];\n }\n | { kind: \"final\"; thought?: string; text: string };\n\ntype Parsed = { ok: true; turn: Turn } | { ok: false; error: string };\nconst bad = (error: string): Parsed => ({ ok: false, error });\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * Reads one turn (aerix-core's parse_turn, check for check). Call ids (`c<n>`) are taken from\n * `nextId.n` only when the turn parses.\n */\nexport function parseTurn(text: string, tools: readonly Tool[], nextId: { n: number }): Parsed {\n let value: unknown;\n try {\n value = JSON.parse(text.trim());\n } catch (e) {\n return bad(`the answer is not valid JSON (${e instanceof Error ? e.message : String(e)})`);\n }\n if (!isObject(value)) return bad(\"the answer must be one JSON object\");\n const has = (k: string) => Object.hasOwn(value, k);\n\n let thought: string | undefined;\n const raw = has(\"thought\") ? value.thought : undefined;\n if (raw === undefined || raw === null) {\n thought = undefined;\n } else if (typeof raw === \"string\") {\n const chars = Array.from(raw);\n thought =\n chars.length > MAX_THOUGHT\n ? `${chars.slice(0, MAX_THOUGHT).join(\"\")} (thought cut to ${MAX_THOUGHT} characters)`\n : raw;\n } else {\n return bad(\"thought must be a string\");\n }\n\n if (has(\"calls\")) {\n const items = value.calls;\n if (!Array.isArray(items)) return bad(\"calls must be an array\");\n if (items.length === 0) return bad(\"calls is empty; give at least one call, or a final\");\n const parsed: { tool: string; input: Record<string, unknown> }[] = [];\n for (const [i, item] of items.entries()) {\n const name = isObject(item) && typeof item.tool === \"string\" ? item.tool : undefined;\n if (name === undefined) return bad(`call ${i + 1} needs a tool name in \"tool\"`);\n if (!tools.some((t) => t.name === name)) return bad(`unknown tool ${name}`);\n const input = (item as Record<string, unknown>).input;\n if (!isObject(input)) return bad(`the input of call ${i + 1} (${name}) must be an object`);\n parsed.push({ tool: name, input });\n }\n const total = parsed.length;\n if (total > MAX_CALLS) {\n parsed.length = MAX_CALLS;\n const note = `(${MAX_CALLS} of ${total} calls kept)`;\n thought = thought !== undefined && thought !== \"\" ? `${thought} ${note}` : note;\n }\n const calls = parsed.map((c) => ({ id: `c${nextId.n++}`, ...c }));\n return { ok: true, turn: { kind: \"calls\", ...(thought !== undefined && { thought }), calls } };\n }\n if (has(\"final\")) {\n if (typeof value.final !== \"string\") return bad(\"final must be a string\");\n return {\n ok: true,\n turn: { kind: \"final\", ...(thought !== undefined && { thought }), text: value.final },\n };\n }\n return bad(`expected calls or final, found keys [${Object.keys(value).sort().join(\", \")}]`);\n}\n","import type { ChatMessage, GenerateOptions, GenerationOptions } from \"@caldrix-ai/caldrix\";\nimport { AerixError } from \"./errors.js\";\nimport type { AgentEvent, Call, EndReason } from \"./events.js\";\nimport type { Model } from \"./model.js\";\nimport { systemText } from \"./render.js\";\nimport { turnSchema } from \"./schema.js\";\nimport { checkInput, type Tool } from \"./tool.js\";\nimport { parseTurn } from \"./turn.js\";\n\nexport interface Limits {\n /** Generations per run, retries and cut turns included. */\n turns?: number;\n /** Extra attempts after a bad or cut turn, per turn. */\n retries?: number;\n /** Tokens per generation. */\n maxTokens?: number;\n /** Characters of one tool result; the rest is cut with a note. */\n resultChars?: number;\n}\n\ntype Awaitable<T> = T | Promise<T>;\ntype BeforeCall = void | { deny: string } | { input: Record<string, unknown> };\ntype AfterCall = void | { result: string };\ntype OnFinal = void | { continue: string };\n\nexport interface Hooks {\n /** A deny becomes the result `refused: <reason>`; `input` replaces the call's input. */\n beforeCall?(c: Call): Awaitable<BeforeCall>;\n /** `result` replaces the tool's result. */\n afterCall?(c: Call, result: string): Awaitable<AfterCall>;\n /** `continue` gives the agent another turn with that text as a user message (bounded by `turns`). */\n onFinal?(text: string): Awaitable<OnFinal>;\n}\n\nexport interface AgentOptions {\n model: Model;\n instructions?: string;\n tools?: Tool[];\n limits?: Limits;\n generation?: Omit<GenerationOptions, \"maxTokens\" | \"constraint\">;\n /** Send the turn schema as `constraint.json` on each generation (default `true`). */\n constrain?: boolean;\n hooks?: Hooks;\n}\n\nconst DEFAULT_LIMITS: Required<Limits> = { turns: 8, retries: 2, maxTokens: 512, resultChars: 4000 };\nconst LIMIT_MIN: Required<Limits> = { turns: 1, retries: 0, maxTokens: 1, resultChars: 1 };\n\n// aerix-core's generate_turn wording.\nconst CUT_NOTE = \"Your last turn hit the token limit before the JSON closed; answer again, shorter.\";\nconst badNote = (error: string) => `Your last turn was not valid: ${error}. Answer again as JSON.`;\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\nconst message = (e: unknown) => (e instanceof Error ? e.message : String(e));\nconst msg = (role: ChatMessage[\"role\"], content: string): ChatMessage => Object.freeze({ role, content });\nconst refuse = (text: string) => new AerixError(\"options\", text);\n\nfunction checkLimits(limits: unknown): Required<Limits> {\n if (limits === undefined) return { ...DEFAULT_LIMITS };\n if (!isObject(limits)) throw refuse(\"limits must be an object\");\n const out = { ...DEFAULT_LIMITS };\n for (const [k, v] of Object.entries(limits)) {\n if (!Object.hasOwn(DEFAULT_LIMITS, k)) throw refuse(`unknown limit ${k}`);\n if (v === undefined) continue;\n const min = LIMIT_MIN[k as keyof Limits];\n if (typeof v !== \"number\" || !Number.isInteger(v) || v < min) {\n throw refuse(`limits.${k} must be an integer of at least ${min}`);\n }\n out[k as keyof Limits] = v;\n }\n return out;\n}\n\nfunction checkTools(tools: unknown): readonly Tool[] {\n if (tools === undefined) return [];\n if (!Array.isArray(tools)) throw refuse(\"tools must be an array\");\n const names = new Set<string>();\n for (const t of tools) {\n if (!isObject(t) || typeof t.name !== \"string\" || typeof t.run !== \"function\" || !isObject(t.schema)) {\n throw refuse(\"each tool must be made with tool()\");\n }\n if (!isObject(t.input)) throw refuse(`tool ${t.name}: input must be a field map (an object)`);\n if (names.has(t.name)) throw refuse(`two tools are named ${t.name}`);\n names.add(t.name);\n }\n return Object.freeze([...(tools as Tool[])]);\n}\n\nfunction checkGeneration(generation: unknown): Record<string, unknown> {\n if (generation === undefined) return {};\n if (!isObject(generation)) throw refuse(\"generation must be an object\");\n for (const k of [\"maxTokens\", \"constraint\", \"signal\"]) {\n if (Object.hasOwn(generation, k)) {\n throw refuse(`generation.${k} is set by the agent (use limits.maxTokens, constrain or run's signal)`);\n }\n }\n return { ...generation };\n}\n\nconst HOOK_NAMES: readonly string[] = [\"beforeCall\", \"afterCall\", \"onFinal\"];\n\nfunction checkHooks(hooks: unknown): Hooks {\n if (hooks === undefined) return {};\n if (!isObject(hooks)) throw refuse(\"hooks must be an object\");\n // An own key that looks like a hook name (`beforeCal`, `onDone`: the prefix, then a capital) is a typo, whatever its value; any\n // other own key is the instance's state.\n for (const k of Object.keys(hooks)) {\n if (!HOOK_NAMES.includes(k) && /^(before|after|on)[A-Z]/.test(k)) {\n throw refuse(`unknown hook ${k} (hooks are ${HOOK_NAMES.join(\", \")})`);\n }\n }\n // Read by name, not by own keys, so a hook on a class instance's prototype is kept.\n const out: Record<string, unknown> = {};\n for (const k of HOOK_NAMES) {\n const f: unknown = hooks[k];\n if (f === undefined) continue;\n if (typeof f !== \"function\") throw refuse(`hooks.${k} must be a function`);\n out[k] = f.bind(hooks);\n }\n return out as Hooks;\n}\n\n/** `text` cut to `cap` characters, with the note naming how long it was. */\nfunction capResult(text: string, cap: number): string {\n if (text.length <= cap) return text;\n const chars = Array.from(text);\n if (chars.length <= cap) return text;\n return `${chars.slice(0, cap).join(\"\")}\\n[result cut to ${cap} of ${chars.length} characters]`;\n}\n\nconst resultText = (v: unknown): string =>\n typeof v === \"string\" ? v : v === undefined || v === null ? \"\" : (JSON.stringify(v) ?? String(v));\n\nconst ABORTED = Symbol(\"aborted\");\n\n/** Settles with `fn`'s outcome, or with ABORTED as soon as `signal` aborts. */\nasync function untilAbort<T>(\n fn: () => T | Promise<T>,\n signal: AbortSignal,\n): Promise<{ value: T } | { thrown: unknown } | typeof ABORTED> {\n let onAbort = () => {};\n const aborted = new Promise<typeof ABORTED>((resolve) => {\n onAbort = () => resolve(ABORTED);\n if (signal.aborted) onAbort();\n else signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n const ran = Promise.resolve()\n .then(fn)\n .then(\n (value) => ({ value }),\n (e: unknown) => ({ thrown: e }),\n );\n try {\n return await Promise.race([ran, aborted]);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\n/** A hook's answer, or ABORTED if the signal aborts first; a throwing hook ends the run with `error`. */\nasync function hook(fn: (() => unknown) | undefined, signal: AbortSignal): Promise<unknown> {\n if (fn === undefined) return undefined;\n const out = await untilAbort(fn, signal);\n if (out === ABORTED) return ABORTED;\n if (\"thrown\" in out) throw out.thrown;\n return out.value;\n}\n\n/** Runs Aerix's turn loop on a `Model`: one run at a time, over one conversation. */\nexport class Agent {\n readonly #model: Model;\n readonly #tools: readonly Tool[];\n readonly #limits: Required<Limits>;\n readonly #generation: Record<string, unknown>;\n readonly #constraint: GenerationOptions[\"constraint\"];\n readonly #hooks: Hooks;\n readonly #system: ChatMessage;\n #messages: ChatMessage[];\n #nextId = { n: 1 };\n #busy = false;\n\n constructor(o: AgentOptions) {\n if (!isObject(o)) throw refuse(\"options must be an object\");\n if (!isObject(o.model) || typeof (o.model as Partial<Model>).chat !== \"function\") {\n throw refuse(\"model must have a chat method (a caldrix.js Engine does)\");\n }\n if (o.instructions !== undefined && typeof o.instructions !== \"string\") {\n throw refuse(\"instructions must be a string\");\n }\n if (o.constrain !== undefined && typeof o.constrain !== \"boolean\") throw refuse(\"constrain must be a boolean\");\n this.#model = o.model;\n this.#tools = checkTools(o.tools);\n this.#limits = checkLimits(o.limits);\n this.#generation = checkGeneration(o.generation);\n this.#hooks = checkHooks(o.hooks);\n this.#constraint = o.constrain === false ? undefined : { json: turnSchema(this.#tools) };\n this.#system = msg(\"system\", systemText(o.instructions ?? \"\", this.#tools));\n this.#messages = [this.#system];\n }\n\n /** The conversation so far: the system message, then every prompt, turn and result. */\n get messages(): readonly ChatMessage[] {\n return Object.freeze([...this.#messages]);\n }\n\n /** Forgets the conversation (and restarts call ids at `c1`). */\n reset(): void {\n if (this.#busy) throw new AerixError(\"busy\", \"a run is going on this agent\");\n this.#messages = [this.#system];\n this.#nextId = { n: 1 };\n }\n\n /**\n * Runs the loop on `prompt`, continuing the conversation. Ends with exactly one `final` or `end`\n * event; it throws only `AerixError` kind `busy` (a run is already going) or `options`.\n */\n async *run(prompt: string, o: { signal?: AbortSignal } = {}): AsyncGenerator<AgentEvent, void, undefined> {\n if (this.#busy) throw new AerixError(\"busy\", \"a run is already going on this agent\");\n if (typeof prompt !== \"string\") throw refuse(\"prompt must be a string\");\n const signal: unknown = o?.signal;\n if (signal !== undefined && (!isObject(signal) || typeof signal.addEventListener !== \"function\")) {\n throw refuse(\"signal must be an AbortSignal\");\n }\n this.#busy = true;\n try {\n yield* this.#loop(prompt, (signal as AbortSignal | undefined) ?? new AbortController().signal);\n } finally {\n this.#busy = false;\n }\n }\n\n /** Runs to the end: resolves on a final, else rejects with `AerixError` kind `end`. */\n async ask(prompt: string, o: { signal?: AbortSignal } = {}): Promise<{ text: string; events: AgentEvent[] }> {\n const events: AgentEvent[] = [];\n for await (const ev of this.run(prompt, o)) {\n events.push(ev);\n if (ev.type === \"final\") return { text: ev.text, events };\n if (ev.type === \"end\") {\n throw new AerixError(\"end\", ev.message ?? `the run ended without a final (${ev.reason})`, {\n reason: ev.reason,\n events,\n });\n }\n }\n throw new AerixError(\"end\", \"the run ended without a final\", { events });\n }\n\n async *#loop(prompt: string, signal: AbortSignal): AsyncGenerator<AgentEvent, void, undefined> {\n const msgs = this.#messages;\n const limits = this.#limits;\n msgs.push(msg(\"user\", prompt));\n let turnStart = msgs.length;\n let done = false; // an ending event was yielded (or is about to be)\n const end = (reason: EndReason, text?: string): AgentEvent => {\n done = true;\n msgs.length = turnStart; // a turn that did not complete is not kept\n return text === undefined ? { type: \"end\", reason } : { type: \"end\", reason, message: text };\n };\n const spent = () => end(\"turns\", `the turn budget (${limits.turns}) is spent`);\n let turn = 0;\n try {\n for (;;) {\n // One turn: a generation, plus up to `retries` more after a bad or cut one.\n turnStart = msgs.length;\n let attempt = 0;\n let text = \"\";\n let parsed: ReturnType<typeof parseTurn>;\n for (;;) {\n if (signal.aborted) return yield end(\"abort\");\n if (turn >= limits.turns) return yield spent();\n turn++;\n const opts: GenerateOptions = {\n ...this.#generation,\n maxTokens: limits.maxTokens,\n ...(this.#constraint && { constraint: this.#constraint }),\n signal,\n };\n text = \"\";\n let finish: string | undefined;\n for await (const d of this.#model.chat([...msgs], opts)) {\n if (typeof d.text === \"string\" && d.text !== \"\") {\n text += d.text;\n yield { type: \"text\", text: d.text };\n }\n if (d.done) {\n finish = d.finishReason;\n if (d.usage) {\n const { promptTokens, completionTokens } = d.usage;\n yield { type: \"usage\", promptTokens, completionTokens };\n }\n break;\n }\n }\n if (signal.aborted || finish === \"abort\") return yield end(\"abort\");\n parsed = parseTurn(text, this.#tools, this.#nextId);\n if (parsed.ok) break;\n // Both spent on the same generation: the turn budget ran out first.\n if (turn >= limits.turns) return yield spent();\n if (attempt >= limits.retries) {\n return yield end(\"retries\", `no valid turn after ${limits.retries} retries: ${parsed.error}`);\n }\n attempt++;\n if (finish === \"length\") {\n // The partial turn leaves the conversation; the model is asked for a shorter one.\n yield { type: \"retry\", turn, reason: \"the turn hit the token limit before the JSON closed\" };\n msgs.push(msg(\"user\", CUT_NOTE));\n } else {\n yield { type: \"retry\", turn, reason: parsed.error };\n msgs.push(msg(\"assistant\", text), msg(\"user\", badNote(parsed.error)));\n }\n }\n // A good turn: the bad answers and the notes leave the conversation.\n msgs.length = turnStart;\n msgs.push(msg(\"assistant\", text));\n const t = parsed.turn;\n\n if (t.kind === \"final\") {\n const onFinal = this.#hooks.onFinal;\n const next = await hook(onFinal && (() => onFinal(t.text)), signal);\n if (next === ABORTED) return yield end(\"abort\");\n if (isObject(next) && typeof next.continue === \"string\") {\n msgs.push(msg(\"user\", next.continue));\n continue;\n }\n done = true;\n return yield { type: \"final\", text: t.text, ...(t.thought !== undefined && { thought: t.thought }) };\n }\n\n yield {\n type: \"turn\",\n turn,\n ...(t.thought !== undefined && { thought: t.thought }),\n calls: t.calls.map((c) => ({ ...c, input: { ...c.input } })),\n };\n // Calls run in order, one at a time; at most MAX_CALLS per turn (parseTurn).\n for (const c of t.calls) {\n if (signal.aborted) return yield end(\"abort\");\n if ((yield* this.#call(c, signal)) === ABORTED) return yield end(\"abort\");\n }\n }\n } catch (e) {\n // An engine failure or a throwing hook ends the run; it is never thrown from the iterator.\n yield signal.aborted ? end(\"abort\") : end(\"error\", message(e));\n } finally {\n // The caller left before an ending event: the unfinished turn is not kept.\n if (!done) msgs.length = turnStart;\n }\n }\n\n /** One call: the hooks, the input check and the tool, then its result appended to the conversation. */\n async *#call(c: Call, signal: AbortSignal): AsyncGenerator<AgentEvent, typeof ABORTED | undefined, undefined> {\n const t = this.#tools.find((x) => x.name === c.tool)!; // parseTurn admits known tools only\n let input = c.input;\n const { beforeCall, afterCall } = this.#hooks;\n const before = await hook(beforeCall && (() => beforeCall({ ...c, input: { ...input } })), signal);\n if (before === ABORTED) return ABORTED;\n let text: string;\n let error = true;\n if (isObject(before) && typeof before.deny === \"string\") {\n yield { type: \"call\", id: c.id, tool: c.tool, input: { ...input } };\n text = `refused: ${before.deny}`;\n } else {\n if (isObject(before) && isObject(before.input)) input = { ...before.input };\n yield { type: \"call\", id: c.id, tool: c.tool, input: { ...input } };\n const bad = checkInput(t, input);\n if (bad !== null) {\n text = `error: ${bad}`;\n } else {\n const cx = { signal, callId: c.id };\n const out = await untilAbort(async () => resultText(await t.run(input, cx)), signal);\n if (out === ABORTED || signal.aborted) return ABORTED;\n if (\"value\" in out) {\n text = out.value;\n error = false;\n } else {\n text = `error: ${message(out.thrown)}`;\n }\n const ran = text;\n const after = await hook(afterCall && (() => afterCall({ ...c, input: { ...input } }, ran)), signal);\n if (after === ABORTED) return ABORTED;\n if (isObject(after) && typeof after.result === \"string\") text = after.result;\n }\n }\n text = capResult(text, this.#limits.resultChars);\n this.#messages.push(msg(\"user\", `[${c.tool} ${c.id}]\\n${text}`));\n yield { type: \"result\", id: c.id, tool: c.tool, text, error };\n return undefined;\n }\n}\n"],"mappings":";AAEO,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACAA,UACA,QAAuD,CAAC,GACxD;AACA,UAAMA,QAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,QAAI,MAAM,WAAW,OAAW,MAAK,SAAS,MAAM;AACpD,QAAI,MAAM,WAAW,OAAW,MAAK,SAAS,MAAM;AAAA,EACtD;AACF;;;ACjBO,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQ7B,SAAS,UAAU,GAAiB;AAClC,MAAI,MAAM,QAAQ,EAAE,IAAI,GAAG;AACzB,WAAO,UAAU,EAAE,KAAK,IAAI,MAAM,EAAE,KAAK,GAAG,CAAC;AAAA,EAC/C;AACA,SAAO,OAAO,EAAE,SAAS,WAAW,EAAE,OAAO;AAC/C;AAGA,SAAS,UAAU,GAAiB;AAClC,QAAM,QAAQ,OAAO,KAAK,EAAE,KAAK;AACjC,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,QAAM,MAAM,CAAC,MAAc,EAAE,MAAM,CAAC,GAAG,aAAa;AACpD,QAAM,KA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AC9B,YAAID,UAAS,KAAK,KAAK,OAAO,MAAM,WAAW,SAAU,QAAO,MAAM;AAAA,MACxE;AAAA,IACF;AACA,WAAO,UAAU,MAAM,KAAK,QAAQ,WAAW;AAC/C,SAAK,UAAU,KAAK,IAAI,QAAQ,IAAI,EAAE,IAAI,IAAI,EAAE,EAAE;AAAA,EAAM,IAAI,EAAE,CAAC;AAC/D,UAAM,EAAE,MAAM,UAAU,IAAI,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,MAAM;AAC5D,WAAO;AAAA,EACT;AACF;","names":["message","isObject","isObject","bad"]}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@caldrix-ai/aerix",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "private": false,
5
+ "description": "Aerix's turn loop on a caldrix.js engine, in the browser.",
6
+ "license": "Apache-2.0",
7
+ "homepage": "https://caldrix.ai",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/100xeng/caldrix.git",
11
+ "directory": "aerix-js"
12
+ },
13
+ "keywords": [
14
+ "llm",
15
+ "agent",
16
+ "tools",
17
+ "browser"
18
+ ],
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "CHANGELOG.md",
25
+ "LICENSE",
26
+ "NOTICE"
27
+ ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "types": "./dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js"
36
+ }
37
+ },
38
+ "peerDependencies": {
39
+ "@caldrix-ai/caldrix": "^0.3.0"
40
+ },
41
+ "devDependencies": {
42
+ "@arethetypeswrong/cli": "0.18.5",
43
+ "@caldrix-ai/caldrix": "link:../caldrix-js",
44
+ "@eslint/js": "^9.39.5",
45
+ "@playwright/test": "1.63.0",
46
+ "@types/node": "^26.1.1",
47
+ "eslint": "^9.39.5",
48
+ "publint": "0.3.25",
49
+ "tsup": "^8.5.0",
50
+ "typescript": "^5.9.3",
51
+ "typescript-eslint": "^8.46.0",
52
+ "vitest": "^4.1.10"
53
+ },
54
+ "scripts": {
55
+ "build": "tsup",
56
+ "build:test": "tsup --config tsup.test.config.ts",
57
+ "lint": "eslint . && tsc --noEmit",
58
+ "test": "vitest run",
59
+ "test:e2e": "playwright test",
60
+ "pack:check": "publint && attw --pack . --ignore-rules cjs-resolves-to-esm"
61
+ }
6
62
  }