@mast-ai/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.
package/LICENSE ADDED
@@ -0,0 +1,193 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any patent
81
+ claim embodied in the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this
83
+ License for that Work shall terminate as of the date such litigation
84
+ is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Contribution, and to permit persons to whom the Contribution is
122
+ furnished to do so.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any conditions of
142
+ TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ workstop, computer failure or malfunction, or all other commercial
156
+ damages or losses), even if such Contributor has been advised of the
157
+ possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may choose to offer,
161
+ and charge a fee for, acceptance of support, warranty, indemnity,
162
+ or other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may act only
164
+ on Your own behalf and on Your sole responsibility, not on behalf
165
+ of any other Contributor, and only if You agree to indemnify,
166
+ defend, and hold each Contributor harmless for any liability
167
+ incurred by, or claims asserted against, such Contributor by reason
168
+ of your accepting any such warranty or additional liability.
169
+
170
+ END OF TERMS AND CONDITIONS
171
+
172
+ APPENDIX: How to apply the Apache License to your work.
173
+
174
+ To apply the Apache License to your work, attach the following
175
+ boilerplate notice, with the fields enclosed by brackets "[]"
176
+ replaced with your own identifying information. (Don't include
177
+ the brackets!) The text should be enclosed in the appropriate
178
+ comment syntax for the programming language used. Source files
179
+ may also indicate a copyright notice separately from the text below.
180
+
181
+ Copyright 2026 Andre Cipriani Bandarra
182
+
183
+ Licensed under the Apache License, Version 2.0 (the "License");
184
+ you may not use this file except in compliance with the License.
185
+ You may obtain a copy of the License at
186
+
187
+ http://www.apache.org/licenses/LICENSE-2.0
188
+
189
+ Unless required by applicable law or agreed to in writing, software
190
+ distributed under the License is distributed on an "AS IS" BASIS,
191
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
192
+ See the License for the specific language governing permissions and
193
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @mast-ai/core
2
+
3
+ Core runtime for [MAST](https://github.com/andreban/mast-ai), a TypeScript library that runs AI agent loops in the browser. The "think-act" loop, tool registry, and conversation state all live client-side; remote backends serve only as stateless reasoning engines.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @mast-ai/core
9
+ ```
10
+
11
+ ## What's in the box
12
+
13
+ - **`AgentRunner`** — drives the think-act loop and emits an `AgentEvent` stream (text deltas, thinking, tool calls, tool results, done, error).
14
+ - **`ToolRegistry`** — browser-side tool store. Tools are plain TypeScript functions with direct access to the DOM, `localStorage`, and any client state.
15
+ - **`createAgent`** — config helper for agents (name, instructions, tool list).
16
+ - **`UrpAdapter`** + **`HttpTransport`** — connect to a Universal Reasoning Protocol (URP) backend over HTTP (JSON or SSE).
17
+ - **`LlmAdapter`** interface — swap in any inference source. See the sister packages `@mast-ai/google-genai` (direct browser-to-Gemini) and `@mast-ai/built-in-ai` (on-device via Chrome Prompt API).
18
+
19
+ ## Quick start (Hybrid Mode)
20
+
21
+ ```typescript
22
+ import { ToolRegistry, HttpTransport, UrpAdapter, AgentRunner, createAgent } from '@mast-ai/core';
23
+
24
+ const registry = new ToolRegistry().register({
25
+ definition: () => ({
26
+ name: 'getScreenResolution',
27
+ description: "Returns the user's current screen width and height.",
28
+ parameters: { type: 'object', properties: {}, required: [] },
29
+ }),
30
+ call: async () => ({ width: window.innerWidth, height: window.innerHeight }),
31
+ });
32
+
33
+ const agent = createAgent({
34
+ name: 'BrowserAssistant',
35
+ instructions: 'You are a helpful UI assistant. Use tools to answer questions about the screen.',
36
+ tools: ['getScreenResolution'],
37
+ });
38
+
39
+ const transport = new HttpTransport({ url: 'http://localhost:3000/api/chat' });
40
+ const adapter = new UrpAdapter(transport);
41
+ const runner = new AgentRunner(adapter, registry);
42
+
43
+ const result = await runner.run(agent, 'How big is my screen?');
44
+ console.log(result.output);
45
+ ```
46
+
47
+ ## Documentation
48
+
49
+ - [Repository README](https://github.com/andreban/mast-ai/blob/main/README.md)
50
+ - [Product Requirements](https://github.com/andreban/mast-ai/blob/main/docs/PRD.md)
51
+ - [URP Protocol Spec](https://github.com/andreban/mast-ai/blob/main/docs/SPEC.md)
52
+
53
+ ## License
54
+
55
+ Apache-2.0. Copyright 2026 Andre Cipriani Bandarra.
@@ -0,0 +1,52 @@
1
+ import type { Message, ToolCall } from '../types';
2
+ import type { ToolDefinition } from '../tool';
3
+ /** Provider-specific model configuration options forwarded verbatim to the adapter. */
4
+ export interface ModelConfig {
5
+ temperature?: number;
6
+ maxTokens?: number;
7
+ topP?: number;
8
+ stopSequences?: string[];
9
+ /** Pass-through for provider-specific fields not covered above. */
10
+ [key: string]: unknown;
11
+ }
12
+ /** Normalised request sent from the runner to an {@link LlmAdapter}. */
13
+ export interface AdapterRequest {
14
+ messages: Message[];
15
+ /** System prompt / instructions for the model. */
16
+ system?: string;
17
+ tools: ToolDefinition[];
18
+ /** JSON Schema for structured output; passed through to adapters that support it. */
19
+ outputSchema?: Record<string, unknown>;
20
+ config?: ModelConfig;
21
+ signal?: AbortSignal;
22
+ }
23
+ /** Normalised response returned by an {@link LlmAdapter} from a non-streaming call. */
24
+ export interface AdapterResponse {
25
+ /** Final text output; `undefined` when the model issued tool calls instead. */
26
+ text?: string;
27
+ /** Empty on a final text response; non-empty when the model wants to call tools. */
28
+ toolCalls: ToolCall[];
29
+ }
30
+ /** A single chunk emitted by a streaming {@link LlmAdapter}. */
31
+ export type AdapterStreamChunk = {
32
+ type: 'text_delta';
33
+ delta: string;
34
+ } | {
35
+ type: 'thinking';
36
+ delta: string;
37
+ } | {
38
+ type: 'tool_call';
39
+ toolCall: ToolCall;
40
+ };
41
+ /**
42
+ * Adapter interface that bridges the runner to a specific LLM provider.
43
+ *
44
+ * Implement this interface to connect any model backend.
45
+ * `generateStream` is optional — the runner falls back to `generate` when absent.
46
+ */
47
+ export interface LlmAdapter {
48
+ /** Generates a response in a single round-trip. */
49
+ generate(request: AdapterRequest): Promise<AdapterResponse>;
50
+ /** Streams response chunks incrementally. Optional — the runner falls back to `generate` if absent. */
51
+ generateStream?(request: AdapterRequest): AsyncIterable<AdapterStreamChunk>;
52
+ }
@@ -0,0 +1,3 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ export {};
@@ -0,0 +1,54 @@
1
+ import type { LlmAdapter, AdapterRequest, AdapterResponse, AdapterStreamChunk } from './index';
2
+ import type { Message } from '../types';
3
+ import type { ToolDefinition } from '../tool';
4
+ /** Wire format for a request sent over the Universal Runtime Protocol (URP). */
5
+ export interface UrpRequest {
6
+ messages: Message[];
7
+ available_tools: ToolDefinition[];
8
+ configuration?: Record<string, unknown>;
9
+ stream?: boolean;
10
+ }
11
+ /** A tool call as represented in the URP wire format. */
12
+ export interface UrpToolCall {
13
+ id: string;
14
+ name: string;
15
+ arguments: unknown;
16
+ }
17
+ /** Wire format for a non-streaming URP response. */
18
+ export interface UrpResponse {
19
+ text_content?: string;
20
+ tool_calls: UrpToolCall[];
21
+ usage_metrics?: Record<string, unknown>;
22
+ }
23
+ /** A single chunk emitted by a streaming URP response. */
24
+ export interface UrpStreamChunk {
25
+ type: 'text_delta' | 'tool_call' | 'thinking';
26
+ delta?: string;
27
+ tool_call?: UrpToolCall;
28
+ }
29
+ /**
30
+ * Low-level transport abstraction for the Universal Runtime Protocol.
31
+ *
32
+ * Implement this to connect `UrpAdapter` to a custom backend (e.g. `HttpTransport`).
33
+ */
34
+ export interface UrpTransport {
35
+ /** Sends a non-streaming request and returns the full response. */
36
+ send(request: UrpRequest, signal?: AbortSignal): Promise<UrpResponse>;
37
+ /** Sends a streaming request and yields response chunks. Optional. */
38
+ sendStream?(request: UrpRequest, signal?: AbortSignal): AsyncIterable<UrpStreamChunk>;
39
+ }
40
+ /**
41
+ * {@link LlmAdapter} implementation backed by any {@link UrpTransport}.
42
+ *
43
+ * Translates between the normalised {@link AdapterRequest}/{@link AdapterResponse} types
44
+ * and the URP wire format.
45
+ */
46
+ export declare class UrpAdapter implements LlmAdapter {
47
+ private transport;
48
+ constructor(transport: UrpTransport);
49
+ private prepareRequest;
50
+ /** {@inheritDoc LlmAdapter.generate} */
51
+ generate(request: AdapterRequest): Promise<AdapterResponse>;
52
+ /** {@inheritDoc LlmAdapter.generateStream} */
53
+ generateStream(request: AdapterRequest): AsyncIterable<AdapterStreamChunk>;
54
+ }
@@ -0,0 +1,80 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * {@link LlmAdapter} implementation backed by any {@link UrpTransport}.
5
+ *
6
+ * Translates between the normalised {@link AdapterRequest}/{@link AdapterResponse} types
7
+ * and the URP wire format.
8
+ */
9
+ export class UrpAdapter {
10
+ transport;
11
+ constructor(transport) {
12
+ this.transport = transport;
13
+ }
14
+ prepareRequest(request, stream) {
15
+ const urpRequest = {
16
+ messages: request.messages,
17
+ available_tools: request.tools,
18
+ stream,
19
+ };
20
+ if (request.config) {
21
+ urpRequest.configuration = request.config;
22
+ }
23
+ // URP has no dedicated system field; inject instructions as a leading user message.
24
+ if (request.system) {
25
+ urpRequest.messages = [
26
+ { role: 'user', content: { type: 'text', text: request.system } },
27
+ ...request.messages,
28
+ ];
29
+ }
30
+ return urpRequest;
31
+ }
32
+ /** {@inheritDoc LlmAdapter.generate} */
33
+ async generate(request) {
34
+ const urpRequest = this.prepareRequest(request, false);
35
+ const response = await this.transport.send(urpRequest, request.signal);
36
+ return {
37
+ text: response.text_content,
38
+ toolCalls: response.tool_calls
39
+ ? response.tool_calls.map((tc) => ({
40
+ id: tc.id,
41
+ name: tc.name,
42
+ args: tc.arguments,
43
+ }))
44
+ : [],
45
+ };
46
+ }
47
+ /** {@inheritDoc LlmAdapter.generateStream} */
48
+ async *generateStream(request) {
49
+ if (!this.transport.sendStream) {
50
+ // Fallback to non-streaming if transport doesn't support it
51
+ const response = await this.generate(request);
52
+ if (response.text) {
53
+ yield { type: 'text_delta', delta: response.text };
54
+ }
55
+ for (const tc of response.toolCalls) {
56
+ yield { type: 'tool_call', toolCall: tc };
57
+ }
58
+ return;
59
+ }
60
+ const urpRequest = this.prepareRequest(request, true);
61
+ for await (const chunk of this.transport.sendStream(urpRequest, request.signal)) {
62
+ if (chunk.type === 'text_delta' && chunk.delta !== undefined) {
63
+ yield { type: 'text_delta', delta: chunk.delta };
64
+ }
65
+ else if (chunk.type === 'thinking' && chunk.delta !== undefined) {
66
+ yield { type: 'thinking', delta: chunk.delta };
67
+ }
68
+ else if (chunk.type === 'tool_call' && chunk.tool_call) {
69
+ yield {
70
+ type: 'tool_call',
71
+ toolCall: {
72
+ id: chunk.tool_call.id,
73
+ name: chunk.tool_call.name,
74
+ args: chunk.tool_call.arguments,
75
+ },
76
+ };
77
+ }
78
+ }
79
+ }
80
+ }
@@ -0,0 +1,9 @@
1
+ import type { AgentConfig } from './types';
2
+ /**
3
+ * Validates and returns an {@link AgentConfig}.
4
+ *
5
+ * Throws {@link AgentError} if `name` or `instructions` are missing.
6
+ * The return value is the same object passed in — use it as a typed
7
+ * constant so TypeScript can narrow the config at call sites.
8
+ */
9
+ export declare function createAgent(config: AgentConfig): AgentConfig;
package/dist/agent.js ADDED
@@ -0,0 +1,19 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { AgentError } from './error';
4
+ /**
5
+ * Validates and returns an {@link AgentConfig}.
6
+ *
7
+ * Throws {@link AgentError} if `name` or `instructions` are missing.
8
+ * The return value is the same object passed in — use it as a typed
9
+ * constant so TypeScript can narrow the config at call sites.
10
+ */
11
+ export function createAgent(config) {
12
+ if (!config.name) {
13
+ throw new AgentError('Agent name is required');
14
+ }
15
+ if (!config.instructions) {
16
+ throw new AgentError('Agent instructions are required');
17
+ }
18
+ return config;
19
+ }
@@ -0,0 +1,26 @@
1
+ import type { AgentConfig } from './types';
2
+ import type { AgentRunner } from './runner';
3
+ import type { Tool } from './tool';
4
+ /** Configuration for {@link createAgentTool}. */
5
+ export interface AgentToolOptions {
6
+ name: string;
7
+ description: string;
8
+ /** JSON Schema object describing the tool's arguments. */
9
+ parameters: Record<string, unknown>;
10
+ /** Whether the tool reads or modifies state. Defaults to `'read'`. */
11
+ scope?: 'read' | 'write';
12
+ /** When true, the tool is sensitive and requires human confirmation before executing. */
13
+ requiresApproval?: boolean;
14
+ /** Build the input string passed to the child agent from the tool args. */
15
+ buildInput: (args: unknown) => string;
16
+ }
17
+ /**
18
+ * Wraps an {@link AgentConfig} as a {@link Tool} so it can be registered as a
19
+ * sub-agent of another agent. The returned tool, when called, runs `agent` on
20
+ * the given `runner`, forwards every non-`done` child event to
21
+ * `context.onEvent`, and returns the child's final output as the tool result.
22
+ *
23
+ * `runner` and `agent` are independent of the parent: the child can use a
24
+ * different adapter, registry, instructions, or tool allowlist.
25
+ */
26
+ export declare function createAgentTool(runner: AgentRunner, agent: AgentConfig, options: AgentToolOptions): Tool;
@@ -0,0 +1,37 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { AgentError } from './error';
4
+ /**
5
+ * Wraps an {@link AgentConfig} as a {@link Tool} so it can be registered as a
6
+ * sub-agent of another agent. The returned tool, when called, runs `agent` on
7
+ * the given `runner`, forwards every non-`done` child event to
8
+ * `context.onEvent`, and returns the child's final output as the tool result.
9
+ *
10
+ * `runner` and `agent` are independent of the parent: the child can use a
11
+ * different adapter, registry, instructions, or tool allowlist.
12
+ */
13
+ export function createAgentTool(runner, agent, options) {
14
+ const definition = {
15
+ name: options.name,
16
+ description: options.description,
17
+ parameters: options.parameters,
18
+ scope: options.scope ?? 'read',
19
+ requiresApproval: options.requiresApproval,
20
+ };
21
+ return {
22
+ definition: () => definition,
23
+ async call(args, context) {
24
+ const input = options.buildInput(args);
25
+ const builder = runner.runBuilder(agent);
26
+ if (context.signal)
27
+ builder.signal(context.signal);
28
+ for await (const event of builder.runStream(input)) {
29
+ if (event.type === 'done') {
30
+ return event.output;
31
+ }
32
+ context.onEvent?.(event);
33
+ }
34
+ throw new AgentError(`Sub-agent '${agent.name}' stream ended without a 'done' event.`);
35
+ },
36
+ };
37
+ }
@@ -0,0 +1,22 @@
1
+ import type { AgentConfig, AgentEvent, AgentResult, Message } from './types';
2
+ import type { AgentRunner } from './runner';
3
+ /**
4
+ * Stateful wrapper around {@link AgentRunner} that automatically accumulates
5
+ * conversation history across multiple turns.
6
+ *
7
+ * Obtain an instance from {@link AgentRunner.conversation} rather than
8
+ * constructing one directly.
9
+ */
10
+ export declare class Conversation {
11
+ private readonly runner;
12
+ private readonly agent;
13
+ /** Full conversation history, including all turns. May be trimmed via direct mutation. */
14
+ history: Message[];
15
+ constructor(runner: AgentRunner, agent: AgentConfig);
16
+ private buildStream;
17
+ /** Runs a single turn and waits for the agent to finish, then returns the result. */
18
+ run(input: string, signal?: AbortSignal): Promise<AgentResult>;
19
+ /** Runs a single turn and returns a stream of {@link AgentEvent} objects. History is updated once the stream is fully consumed. */
20
+ runStream(input: string, signal?: AbortSignal, onToolEvent?: (toolName: string, event: AgentEvent) => void): AsyncIterable<AgentEvent>;
21
+ private _streamWithHistoryUpdate;
22
+ }
@@ -0,0 +1,64 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * Stateful wrapper around {@link AgentRunner} that automatically accumulates
5
+ * conversation history across multiple turns.
6
+ *
7
+ * Obtain an instance from {@link AgentRunner.conversation} rather than
8
+ * constructing one directly.
9
+ */
10
+ export class Conversation {
11
+ runner;
12
+ agent;
13
+ /** Full conversation history, including all turns. May be trimmed via direct mutation. */
14
+ history = [];
15
+ constructor(runner, agent) {
16
+ this.runner = runner;
17
+ this.agent = agent;
18
+ }
19
+ buildStream(input, signal, onToolEvent) {
20
+ const builder = this.runner.runBuilder(this.agent).history([...this.history]);
21
+ if (signal)
22
+ builder.signal(signal);
23
+ if (onToolEvent)
24
+ builder.onToolEvent(onToolEvent);
25
+ return builder.runStream(input);
26
+ }
27
+ /** Runs a single turn and waits for the agent to finish, then returns the result. */
28
+ async run(input, signal) {
29
+ let output = '';
30
+ for await (const event of this.buildStream(input, signal)) {
31
+ if (event.type === 'text_delta') {
32
+ output += event.delta;
33
+ }
34
+ else if (event.type === 'done') {
35
+ this.history = event.history;
36
+ output = event.output;
37
+ }
38
+ }
39
+ return { output };
40
+ }
41
+ /** Runs a single turn and returns a stream of {@link AgentEvent} objects. History is updated once the stream is fully consumed. */
42
+ runStream(input, signal, onToolEvent) {
43
+ return this._streamWithHistoryUpdate(input, signal, onToolEvent);
44
+ }
45
+ async *_streamWithHistoryUpdate(input, signal, onToolEvent) {
46
+ let capturedHistory = null;
47
+ const inner = this.buildStream(input, signal, onToolEvent);
48
+ try {
49
+ for await (const event of inner) {
50
+ if (event.type === 'done') {
51
+ capturedHistory = event.history;
52
+ }
53
+ yield event;
54
+ }
55
+ }
56
+ finally {
57
+ // Only update history when the stream completes fully (done event received).
58
+ // If dropped early, capturedHistory is null and history is unchanged.
59
+ if (capturedHistory !== null) {
60
+ this.history = capturedHistory;
61
+ }
62
+ }
63
+ }
64
+ }
@@ -0,0 +1,14 @@
1
+ /** Thrown by the agent runner for logical errors such as missing tools or aborted runs. */
2
+ export declare class AgentError extends Error {
3
+ readonly cause?: unknown | undefined;
4
+ constructor(message: string, cause?: unknown | undefined);
5
+ }
6
+ /** Thrown by an {@link LlmAdapter} or {@link UrpTransport} when a backend request fails. */
7
+ export declare class AdapterError extends Error {
8
+ /** HTTP status code, when applicable. */
9
+ readonly statusCode?: number | undefined;
10
+ readonly cause?: unknown | undefined;
11
+ constructor(message: string,
12
+ /** HTTP status code, when applicable. */
13
+ statusCode?: number | undefined, cause?: unknown | undefined);
14
+ }
package/dist/error.js ADDED
@@ -0,0 +1,24 @@
1
+ // Copyright 2026 Andre Cipriani Bandarra
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /** Thrown by the agent runner for logical errors such as missing tools or aborted runs. */
4
+ export class AgentError extends Error {
5
+ cause;
6
+ constructor(message, cause) {
7
+ super(message);
8
+ this.cause = cause;
9
+ this.name = 'AgentError';
10
+ }
11
+ }
12
+ /** Thrown by an {@link LlmAdapter} or {@link UrpTransport} when a backend request fails. */
13
+ export class AdapterError extends Error {
14
+ statusCode;
15
+ cause;
16
+ constructor(message,
17
+ /** HTTP status code, when applicable. */
18
+ statusCode, cause) {
19
+ super(message);
20
+ this.statusCode = statusCode;
21
+ this.cause = cause;
22
+ this.name = 'AdapterError';
23
+ }
24
+ }