@redtuma/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 +202 -0
- package/dist/agent/index.d.ts +87 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +145 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +11 -0
- package/dist/llm/index.d.ts +22 -0
- package/dist/llm/index.d.ts.map +1 -0
- package/dist/llm/index.js +46 -0
- package/dist/llm/index.js.map +1 -0
- package/dist/logger.d.ts +17 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +38 -0
- package/dist/logger.js.map +1 -0
- package/dist/message-list.d.ts +37 -0
- package/dist/message-list.d.ts.map +1 -0
- package/dist/message-list.js +61 -0
- package/dist/message-list.js.map +1 -0
- package/dist/redtuma.d.ts +35 -0
- package/dist/redtuma.d.ts.map +1 -0
- package/dist/redtuma.js +65 -0
- package/dist/redtuma.js.map +1 -0
- package/dist/store/index.d.ts +57 -0
- package/dist/store/index.d.ts.map +1 -0
- package/dist/store/index.js +53 -0
- package/dist/store/index.js.map +1 -0
- package/dist/tools/index.d.ts +39 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +36 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +21 -0
- package/dist/types.js.map +1 -0
- package/dist/workflows/index.d.ts +114 -0
- package/dist/workflows/index.d.ts.map +1 -0
- package/dist/workflows/index.js +199 -0
- package/dist/workflows/index.js.map +1 -0
- package/package.json +80 -0
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.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { DynamicArgument, Logger, ModelConfig, RuntimeContext } from "../types.js";
|
|
2
|
+
import { AnyToolAction } from "../tools/index.js";
|
|
3
|
+
import * as ai0 from "ai";
|
|
4
|
+
import { CoreMessage } from "ai";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
//#region src/agent/index.d.ts
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Minimal memory contract the Agent depends on. Implemented by `@redtuma/memory`.
|
|
11
|
+
* Kept in core so the Agent can integrate memory without a hard dependency.
|
|
12
|
+
*/
|
|
13
|
+
interface AgentMemory {
|
|
14
|
+
rememberMessages(args: {
|
|
15
|
+
threadId: string;
|
|
16
|
+
resourceId: string;
|
|
17
|
+
}): Promise<{
|
|
18
|
+
messages: CoreMessage[];
|
|
19
|
+
systemContext?: string;
|
|
20
|
+
}>;
|
|
21
|
+
saveMessages(args: {
|
|
22
|
+
threadId: string;
|
|
23
|
+
resourceId: string;
|
|
24
|
+
messages: {
|
|
25
|
+
role: 'user' | 'assistant';
|
|
26
|
+
content: CoreMessage['content'];
|
|
27
|
+
}[];
|
|
28
|
+
}): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
interface AgentConfig {
|
|
31
|
+
id: string;
|
|
32
|
+
name?: string;
|
|
33
|
+
instructions: DynamicArgument<string>;
|
|
34
|
+
model: ModelConfig;
|
|
35
|
+
tools?: Record<string, AnyToolAction>;
|
|
36
|
+
memory?: AgentMemory;
|
|
37
|
+
defaultGenerateOptions?: Partial<GenerateOptions>;
|
|
38
|
+
}
|
|
39
|
+
interface MemoryScope {
|
|
40
|
+
thread: string;
|
|
41
|
+
resource: string;
|
|
42
|
+
}
|
|
43
|
+
interface GenerateOptions {
|
|
44
|
+
maxSteps?: number;
|
|
45
|
+
temperature?: number;
|
|
46
|
+
toolChoice?: 'auto' | 'none' | 'required';
|
|
47
|
+
/** Zod schema; when set, returns a validated `object` instead of free text. */
|
|
48
|
+
output?: z.ZodTypeAny;
|
|
49
|
+
memory?: MemoryScope;
|
|
50
|
+
runtimeContext?: RuntimeContext;
|
|
51
|
+
abortSignal?: AbortSignal;
|
|
52
|
+
}
|
|
53
|
+
interface GenerateResult<T = unknown> {
|
|
54
|
+
text: string;
|
|
55
|
+
object?: T;
|
|
56
|
+
toolCalls: unknown[];
|
|
57
|
+
toolResults: unknown[];
|
|
58
|
+
steps: unknown[];
|
|
59
|
+
usage: {
|
|
60
|
+
promptTokens: number;
|
|
61
|
+
completionTokens: number;
|
|
62
|
+
totalTokens: number;
|
|
63
|
+
};
|
|
64
|
+
finishReason: string;
|
|
65
|
+
response: unknown;
|
|
66
|
+
}
|
|
67
|
+
declare class Agent {
|
|
68
|
+
readonly id: string;
|
|
69
|
+
readonly name: string;
|
|
70
|
+
private readonly config;
|
|
71
|
+
private logger;
|
|
72
|
+
private memory?;
|
|
73
|
+
constructor(config: AgentConfig);
|
|
74
|
+
/** Called by the Redtuma registry to inject shared deps. */
|
|
75
|
+
__register(deps: {
|
|
76
|
+
logger?: Logger;
|
|
77
|
+
memory?: AgentMemory;
|
|
78
|
+
}): void;
|
|
79
|
+
private resolveInstructions;
|
|
80
|
+
private prepare;
|
|
81
|
+
private persist;
|
|
82
|
+
generate<T = unknown>(input: string | CoreMessage[], options?: GenerateOptions): Promise<GenerateResult<T>>;
|
|
83
|
+
stream(input: string | CoreMessage[], options?: GenerateOptions): Promise<ai0.StreamTextResult<Record<string, ai0.Tool>, never>>;
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
86
|
+
export { Agent, AgentConfig, AgentMemory, GenerateOptions, GenerateResult, MemoryScope };
|
|
87
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/agent/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;AAkBA;AAI0B,UAJT,WAAA,CAIS;EAApB,gBAAA,CAAA,IAAA,EAAA;IAI+C,QAAA,EAAA,MAAA;IAC/C,UAAA,EAAA,MAAA;EAAO,CAAA,CAAA,EALP,OAKO,CAAA;IAGI,QAAA,EARS,WAQE,EAAA;IAGZ,aAAA,CAAA,EAAA,MAAA;EACP,CAAA,CAAA;EACgB,YAAA,CAAA,IAAA,EAAA;IAAf,QAAA,EAAA,MAAA;IACC,UAAA,EAAA,MAAA;IACwB,QAAA,EAAA;MAAR,IAAA,EAAA,MAAA,GAAA,WAAA;MAAO,OAAA,EAXmB,WAWnB,CAAA,SAAA,CAAA;IAGjB,CAAA,EAAA;EAKA,CAAA,CAAA,EAlBX,OAkBW,CAAA,IAAA,CAAA;;AAMN,UArBM,WAAA,CAqBN;EACQ,EAAA,EAAA,MAAA;EACH,IAAA,CAAA,EAAA,MAAA;EAAW,YAAA,EApBX,eAoBW,CAAA,MAAA,CAAA;EAGV,KAAA,EAtBR,WAsBsB;EAWlB,KAAA,CAAA,EAhCH,MAgCQ,CAAA,MAAA,EAhCO,aAgCP,CAAA;EAOI,MAAA,CAAA,EAtCX,WAsCW;EAQQ,sBAAA,CAAA,EA7CH,OA6CG,CA7CK,eA6CL,CAAA;;AAwEV,UAlHH,WAAA,CAkHG;EACP,MAAA,EAAA,MAAA;EACe,QAAA,EAAA,MAAA;;AAAvB,UA/GY,eAAA,CA+GZ;EAiD0B,QAAA,CAAA,EAAA,MAAA;EAAwB,WAAA,CAAA,EAAA,MAAA;EAAoB,UAAA,CAAA,EAAA,MAAA,GAAA,MAAA,GAAA,UAAA;EAAA;EAAA,MAAA,CAAA,EA3JhE,CAAA,CAAE,UA2J8D;EAAA,MAAA,CAAA,EA1JhE,WA0JgE;EAAA,cAAA,CAAA,EAzJxD,cAyJwD;gBAxJ3D;;UAGC;;WAEN;;;;;;;;;;;;cASE,KAAA;;;;;;sBAOS;;;aAQQ;aAAiB;;;;;wCAwE3B,yBACP,kBACR,QAAQ,eAAe;yBAiDG,yBAAwB,kBAAoB,QAAA,GAAA,CAAA,iBAAA,eAAA,GAAA,CAAA,IAAA"}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { resolveModel } from "../llm/index.js";
|
|
2
|
+
import { RuntimeContext } from "../types.js";
|
|
3
|
+
import { buildToolset } from "../tools/index.js";
|
|
4
|
+
import { MessageList } from "../message-list.js";
|
|
5
|
+
import { noopLogger } from "../logger.js";
|
|
6
|
+
import { generateObject, generateText, streamText } from "ai";
|
|
7
|
+
|
|
8
|
+
//#region src/agent/index.ts
|
|
9
|
+
var Agent = class {
|
|
10
|
+
id;
|
|
11
|
+
name;
|
|
12
|
+
config;
|
|
13
|
+
logger = noopLogger;
|
|
14
|
+
memory;
|
|
15
|
+
constructor(config) {
|
|
16
|
+
this.config = config;
|
|
17
|
+
this.id = config.id;
|
|
18
|
+
this.name = config.name ?? config.id;
|
|
19
|
+
this.memory = config.memory;
|
|
20
|
+
}
|
|
21
|
+
/** Called by the Redtuma registry to inject shared deps. */
|
|
22
|
+
__register(deps) {
|
|
23
|
+
if (deps.logger) this.logger = deps.logger;
|
|
24
|
+
if (!this.memory && deps.memory) this.memory = deps.memory;
|
|
25
|
+
}
|
|
26
|
+
async resolveInstructions(runtimeContext) {
|
|
27
|
+
const ins = this.config.instructions;
|
|
28
|
+
return typeof ins === "function" ? await ins({ runtimeContext }) : ins;
|
|
29
|
+
}
|
|
30
|
+
async prepare(input, options) {
|
|
31
|
+
const opts = {
|
|
32
|
+
...this.config.defaultGenerateOptions,
|
|
33
|
+
...options
|
|
34
|
+
};
|
|
35
|
+
const runtimeContext = opts.runtimeContext ?? new RuntimeContext();
|
|
36
|
+
const model = await resolveModel(this.config.model);
|
|
37
|
+
let system = await this.resolveInstructions(runtimeContext);
|
|
38
|
+
const list = new MessageList();
|
|
39
|
+
const scope = opts.memory;
|
|
40
|
+
if (this.memory && scope) {
|
|
41
|
+
const recalled = await this.memory.rememberMessages({
|
|
42
|
+
threadId: scope.thread,
|
|
43
|
+
resourceId: scope.resource
|
|
44
|
+
});
|
|
45
|
+
if (recalled.systemContext) system += `\n\n${recalled.systemContext}`;
|
|
46
|
+
for (const m of recalled.messages) list.add(m, m.role);
|
|
47
|
+
}
|
|
48
|
+
list.add(input);
|
|
49
|
+
return {
|
|
50
|
+
model,
|
|
51
|
+
system,
|
|
52
|
+
messages: list.toCore(),
|
|
53
|
+
tools: buildToolset(this.config.tools, runtimeContext),
|
|
54
|
+
scope,
|
|
55
|
+
runtimeContext
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async persist(scope, userInput, assistantText) {
|
|
59
|
+
if (!this.memory || !scope) return;
|
|
60
|
+
const userContent = typeof userInput === "string" ? userInput : userInput.at(-1)?.content ?? "";
|
|
61
|
+
await this.memory.saveMessages({
|
|
62
|
+
threadId: scope.thread,
|
|
63
|
+
resourceId: scope.resource,
|
|
64
|
+
messages: [{
|
|
65
|
+
role: "user",
|
|
66
|
+
content: userContent
|
|
67
|
+
}, {
|
|
68
|
+
role: "assistant",
|
|
69
|
+
content: assistantText
|
|
70
|
+
}]
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
async generate(input, options = {}) {
|
|
74
|
+
const { model, system, messages, tools, scope } = await this.prepare(input, options);
|
|
75
|
+
const opts = {
|
|
76
|
+
...this.config.defaultGenerateOptions,
|
|
77
|
+
...options
|
|
78
|
+
};
|
|
79
|
+
if (opts.output) {
|
|
80
|
+
const res$1 = await generateObject({
|
|
81
|
+
model,
|
|
82
|
+
system,
|
|
83
|
+
messages,
|
|
84
|
+
schema: opts.output,
|
|
85
|
+
temperature: opts.temperature,
|
|
86
|
+
abortSignal: opts.abortSignal
|
|
87
|
+
});
|
|
88
|
+
await this.persist(scope, input, JSON.stringify(res$1.object));
|
|
89
|
+
return {
|
|
90
|
+
text: JSON.stringify(res$1.object),
|
|
91
|
+
object: res$1.object,
|
|
92
|
+
toolCalls: [],
|
|
93
|
+
toolResults: [],
|
|
94
|
+
steps: [],
|
|
95
|
+
usage: res$1.usage,
|
|
96
|
+
finishReason: res$1.finishReason,
|
|
97
|
+
response: res$1.response
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
const res = await generateText({
|
|
101
|
+
model,
|
|
102
|
+
system,
|
|
103
|
+
messages,
|
|
104
|
+
tools,
|
|
105
|
+
maxSteps: opts.maxSteps ?? 5,
|
|
106
|
+
temperature: opts.temperature,
|
|
107
|
+
toolChoice: opts.toolChoice,
|
|
108
|
+
abortSignal: opts.abortSignal
|
|
109
|
+
});
|
|
110
|
+
await this.persist(scope, input, res.text);
|
|
111
|
+
return {
|
|
112
|
+
text: res.text,
|
|
113
|
+
toolCalls: res.toolCalls,
|
|
114
|
+
toolResults: res.toolResults,
|
|
115
|
+
steps: res.steps,
|
|
116
|
+
usage: res.usage,
|
|
117
|
+
finishReason: res.finishReason,
|
|
118
|
+
response: res.response
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
async stream(input, options = {}) {
|
|
122
|
+
const { model, system, messages, tools, scope } = await this.prepare(input, options);
|
|
123
|
+
const opts = {
|
|
124
|
+
...this.config.defaultGenerateOptions,
|
|
125
|
+
...options
|
|
126
|
+
};
|
|
127
|
+
return streamText({
|
|
128
|
+
model,
|
|
129
|
+
system,
|
|
130
|
+
messages,
|
|
131
|
+
tools,
|
|
132
|
+
maxSteps: opts.maxSteps ?? 5,
|
|
133
|
+
temperature: opts.temperature,
|
|
134
|
+
toolChoice: opts.toolChoice,
|
|
135
|
+
abortSignal: opts.abortSignal,
|
|
136
|
+
onFinish: ({ text }) => {
|
|
137
|
+
this.persist(scope, input, text);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
//#endregion
|
|
144
|
+
export { Agent };
|
|
145
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["res"],"sources":["../../src/agent/index.ts"],"sourcesContent":["import {\n generateText,\n streamText,\n generateObject,\n type CoreMessage,\n type LanguageModel,\n} from 'ai'\nimport type { z } from 'zod'\nimport { resolveModel } from '../llm'\nimport { buildToolset, type AnyToolAction } from '../tools'\nimport { MessageList } from '../message-list'\nimport { RuntimeContext, type DynamicArgument, type Logger, type ModelConfig } from '../types'\nimport { noopLogger } from '../logger'\n\n/**\n * Minimal memory contract the Agent depends on. Implemented by `@redtuma/memory`.\n * Kept in core so the Agent can integrate memory without a hard dependency.\n */\nexport interface AgentMemory {\n rememberMessages(args: {\n threadId: string\n resourceId: string\n }): Promise<{ messages: CoreMessage[]; systemContext?: string }>\n saveMessages(args: {\n threadId: string\n resourceId: string\n messages: { role: 'user' | 'assistant'; content: CoreMessage['content'] }[]\n }): Promise<void>\n}\n\nexport interface AgentConfig {\n id: string\n name?: string\n instructions: DynamicArgument<string>\n model: ModelConfig\n tools?: Record<string, AnyToolAction>\n memory?: AgentMemory\n defaultGenerateOptions?: Partial<GenerateOptions>\n}\n\nexport interface MemoryScope {\n thread: string\n resource: string\n}\n\nexport interface GenerateOptions {\n maxSteps?: number\n temperature?: number\n toolChoice?: 'auto' | 'none' | 'required'\n /** Zod schema; when set, returns a validated `object` instead of free text. */\n output?: z.ZodTypeAny\n memory?: MemoryScope\n runtimeContext?: RuntimeContext\n abortSignal?: AbortSignal\n}\n\nexport interface GenerateResult<T = unknown> {\n text: string\n object?: T\n toolCalls: unknown[]\n toolResults: unknown[]\n steps: unknown[]\n usage: { promptTokens: number; completionTokens: number; totalTokens: number }\n finishReason: string\n response: unknown\n}\n\nexport class Agent {\n readonly id: string\n readonly name: string\n private readonly config: AgentConfig\n private logger: Logger = noopLogger\n private memory?: AgentMemory\n\n constructor(config: AgentConfig) {\n this.config = config\n this.id = config.id\n this.name = config.name ?? config.id\n this.memory = config.memory\n }\n\n /** Called by the Redtuma registry to inject shared deps. */\n __register(deps: { logger?: Logger; memory?: AgentMemory }): void {\n if (deps.logger) this.logger = deps.logger\n if (!this.memory && deps.memory) this.memory = deps.memory\n }\n\n private async resolveInstructions(runtimeContext: RuntimeContext): Promise<string> {\n const ins = this.config.instructions\n return typeof ins === 'function' ? await ins({ runtimeContext }) : ins\n }\n\n private async prepare(\n input: string | CoreMessage[],\n options: GenerateOptions,\n ): Promise<{\n model: LanguageModel\n system: string\n messages: CoreMessage[]\n tools: ReturnType<typeof buildToolset>\n scope?: MemoryScope\n runtimeContext: RuntimeContext\n }> {\n const opts = { ...this.config.defaultGenerateOptions, ...options }\n const runtimeContext = opts.runtimeContext ?? new RuntimeContext()\n const model = await resolveModel(this.config.model)\n\n let system = await this.resolveInstructions(runtimeContext)\n const list = new MessageList()\n\n // Memory recall\n const scope = opts.memory\n if (this.memory && scope) {\n const recalled = await this.memory.rememberMessages({\n threadId: scope.thread,\n resourceId: scope.resource,\n })\n if (recalled.systemContext) system += `\\n\\n${recalled.systemContext}`\n for (const m of recalled.messages) list.add(m, m.role as 'user' | 'assistant')\n }\n\n list.add(input)\n\n return {\n model,\n system,\n messages: list.toCore(),\n tools: buildToolset(this.config.tools, runtimeContext),\n scope,\n runtimeContext,\n }\n }\n\n private async persist(\n scope: MemoryScope | undefined,\n userInput: string | CoreMessage[],\n assistantText: string,\n ): Promise<void> {\n if (!this.memory || !scope) return\n const userContent =\n typeof userInput === 'string'\n ? userInput\n : (userInput.at(-1)?.content ?? '')\n await this.memory.saveMessages({\n threadId: scope.thread,\n resourceId: scope.resource,\n messages: [\n { role: 'user', content: userContent },\n { role: 'assistant', content: assistantText },\n ],\n })\n }\n\n async generate<T = unknown>(\n input: string | CoreMessage[],\n options: GenerateOptions = {},\n ): Promise<GenerateResult<T>> {\n const { model, system, messages, tools, scope } = await this.prepare(input, options)\n const opts = { ...this.config.defaultGenerateOptions, ...options }\n\n if (opts.output) {\n const res = await generateObject({\n model,\n system,\n messages,\n schema: opts.output,\n temperature: opts.temperature,\n abortSignal: opts.abortSignal,\n })\n await this.persist(scope, input, JSON.stringify(res.object))\n return {\n text: JSON.stringify(res.object),\n object: res.object as T,\n toolCalls: [],\n toolResults: [],\n steps: [],\n usage: res.usage,\n finishReason: res.finishReason,\n response: res.response,\n }\n }\n\n const res = await generateText({\n model,\n system,\n messages,\n tools,\n maxSteps: opts.maxSteps ?? 5,\n temperature: opts.temperature,\n toolChoice: opts.toolChoice,\n abortSignal: opts.abortSignal,\n })\n await this.persist(scope, input, res.text)\n\n return {\n text: res.text,\n toolCalls: res.toolCalls,\n toolResults: res.toolResults,\n steps: res.steps,\n usage: res.usage,\n finishReason: res.finishReason,\n response: res.response,\n }\n }\n\n async stream(input: string | CoreMessage[], options: GenerateOptions = {}) {\n const { model, system, messages, tools, scope } = await this.prepare(input, options)\n const opts = { ...this.config.defaultGenerateOptions, ...options }\n\n const result = streamText({\n model,\n system,\n messages,\n tools,\n maxSteps: opts.maxSteps ?? 5,\n temperature: opts.temperature,\n toolChoice: opts.toolChoice,\n abortSignal: opts.abortSignal,\n onFinish: ({ text }) => {\n void this.persist(scope, input, text)\n },\n })\n\n return result\n }\n}\n"],"mappings":";;;;;;;;AAmEA,IAAa,QAAb,MAAmB;CACjB,AAAS;CACT,AAAS;CACT,AAAiB;CACjB,AAAQ,SAAiB;CACzB,AAAQ;CAER,YAAY,QAAqB;AAC/B,OAAK,SAAS;AACd,OAAK,KAAK,OAAO;AACjB,OAAK,OAAO,OAAO,QAAQ,OAAO;AAClC,OAAK,SAAS,OAAO;;;CAIvB,WAAW,MAAuD;AAChE,MAAI,KAAK,OAAQ,MAAK,SAAS,KAAK;AACpC,MAAI,CAAC,KAAK,UAAU,KAAK,OAAQ,MAAK,SAAS,KAAK;;CAGtD,MAAc,oBAAoB,gBAAiD;EACjF,MAAM,MAAM,KAAK,OAAO;AACxB,SAAO,OAAO,QAAQ,aAAa,MAAM,IAAI,EAAE,gBAAgB,CAAC,GAAG;;CAGrE,MAAc,QACZ,OACA,SAQC;EACD,MAAM,OAAO;GAAE,GAAG,KAAK,OAAO;GAAwB,GAAG;GAAS;EAClE,MAAM,iBAAiB,KAAK,kBAAkB,IAAI,gBAAgB;EAClE,MAAM,QAAQ,MAAM,aAAa,KAAK,OAAO,MAAM;EAEnD,IAAI,SAAS,MAAM,KAAK,oBAAoB,eAAe;EAC3D,MAAM,OAAO,IAAI,aAAa;EAG9B,MAAM,QAAQ,KAAK;AACnB,MAAI,KAAK,UAAU,OAAO;GACxB,MAAM,WAAW,MAAM,KAAK,OAAO,iBAAiB;IAClD,UAAU,MAAM;IAChB,YAAY,MAAM;IACnB,CAAC;AACF,OAAI,SAAS,cAAe,WAAU,OAAO,SAAS;AACtD,QAAK,MAAM,KAAK,SAAS,SAAU,MAAK,IAAI,GAAG,EAAE,KAA6B;;AAGhF,OAAK,IAAI,MAAM;AAEf,SAAO;GACL;GACA;GACA,UAAU,KAAK,QAAQ;GACvB,OAAO,aAAa,KAAK,OAAO,OAAO,eAAe;GACtD;GACA;GACD;;CAGH,MAAc,QACZ,OACA,WACA,eACe;AACf,MAAI,CAAC,KAAK,UAAU,CAAC,MAAO;EAC5B,MAAM,cACJ,OAAO,cAAc,WACjB,YACC,UAAU,GAAG,GAAG,EAAE,WAAW;AACpC,QAAM,KAAK,OAAO,aAAa;GAC7B,UAAU,MAAM;GAChB,YAAY,MAAM;GAClB,UAAU,CACR;IAAE,MAAM;IAAQ,SAAS;IAAa,EACtC;IAAE,MAAM;IAAa,SAAS;IAAe,CAC9C;GACF,CAAC;;CAGJ,MAAM,SACJ,OACA,UAA2B,EAAE,EACD;EAC5B,MAAM,EAAE,OAAO,QAAQ,UAAU,OAAO,UAAU,MAAM,KAAK,QAAQ,OAAO,QAAQ;EACpF,MAAM,OAAO;GAAE,GAAG,KAAK,OAAO;GAAwB,GAAG;GAAS;AAElE,MAAI,KAAK,QAAQ;GACf,MAAMA,QAAM,MAAM,eAAe;IAC/B;IACA;IACA;IACA,QAAQ,KAAK;IACb,aAAa,KAAK;IAClB,aAAa,KAAK;IACnB,CAAC;AACF,SAAM,KAAK,QAAQ,OAAO,OAAO,KAAK,UAAUA,MAAI,OAAO,CAAC;AAC5D,UAAO;IACL,MAAM,KAAK,UAAUA,MAAI,OAAO;IAChC,QAAQA,MAAI;IACZ,WAAW,EAAE;IACb,aAAa,EAAE;IACf,OAAO,EAAE;IACT,OAAOA,MAAI;IACX,cAAcA,MAAI;IAClB,UAAUA,MAAI;IACf;;EAGH,MAAM,MAAM,MAAM,aAAa;GAC7B;GACA;GACA;GACA;GACA,UAAU,KAAK,YAAY;GAC3B,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,aAAa,KAAK;GACnB,CAAC;AACF,QAAM,KAAK,QAAQ,OAAO,OAAO,IAAI,KAAK;AAE1C,SAAO;GACL,MAAM,IAAI;GACV,WAAW,IAAI;GACf,aAAa,IAAI;GACjB,OAAO,IAAI;GACX,OAAO,IAAI;GACX,cAAc,IAAI;GAClB,UAAU,IAAI;GACf;;CAGH,MAAM,OAAO,OAA+B,UAA2B,EAAE,EAAE;EACzE,MAAM,EAAE,OAAO,QAAQ,UAAU,OAAO,UAAU,MAAM,KAAK,QAAQ,OAAO,QAAQ;EACpF,MAAM,OAAO;GAAE,GAAG,KAAK,OAAO;GAAwB,GAAG;GAAS;AAgBlE,SAde,WAAW;GACxB;GACA;GACA;GACA;GACA,UAAU,KAAK,YAAY;GAC3B,aAAa,KAAK;GAClB,YAAY,KAAK;GACjB,aAAa,KAAK;GAClB,WAAW,EAAE,WAAW;AACtB,IAAK,KAAK,QAAQ,OAAO,OAAO,KAAK;;GAExC,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { CoreMessage, DynamicArgument, Logger, ModelConfig, RuntimeContext } from "./types.js";
|
|
2
|
+
import { AnyToolAction, ToolAction, ToolExecuteContext, buildToolset, createTool, isToolAction, toAISDKTool } from "./tools/index.js";
|
|
3
|
+
import { Agent, AgentConfig, AgentMemory, GenerateOptions, GenerateResult, MemoryScope } from "./agent/index.js";
|
|
4
|
+
import { Run, RunResult, RunStatus, Step, StepExecuteContext, Workflow, createStep, createWorkflow } from "./workflows/index.js";
|
|
5
|
+
import { MessageInput, MessageList, MessageRole, RedtumaMessage } from "./message-list.js";
|
|
6
|
+
import { GetMessagesArgs, InMemoryStore, Resource, Store, Thread } from "./store/index.js";
|
|
7
|
+
import { Redtuma, RedtumaConfig } from "./redtuma.js";
|
|
8
|
+
import { RedtumaModelError, SUPPORTED_PROVIDERS, isLanguageModel, parseModelString, resolveModel } from "./llm/index.js";
|
|
9
|
+
import { ConsoleLogger, LogLevel, noopLogger } from "./logger.js";
|
|
10
|
+
export { Agent, type AgentConfig, type AgentMemory, type AnyToolAction, ConsoleLogger, type CoreMessage, type DynamicArgument, type GenerateOptions, type GenerateResult, type GetMessagesArgs, InMemoryStore, type LogLevel, type Logger, type MemoryScope, type MessageInput, MessageList, type MessageRole, type ModelConfig, Redtuma, type RedtumaConfig, type RedtumaMessage, RedtumaModelError, type Resource, Run, type RunResult, type RunStatus, RuntimeContext, SUPPORTED_PROVIDERS, type Step, type StepExecuteContext, type Store, type Thread, type ToolAction, type ToolExecuteContext, Workflow, buildToolset, createStep, createTool, createWorkflow, isLanguageModel, isToolAction, noopLogger, parseModelString, resolveModel, toAISDKTool };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { RedtumaModelError, SUPPORTED_PROVIDERS, isLanguageModel, parseModelString, resolveModel } from "./llm/index.js";
|
|
2
|
+
import { RuntimeContext } from "./types.js";
|
|
3
|
+
import { buildToolset, createTool, isToolAction, toAISDKTool } from "./tools/index.js";
|
|
4
|
+
import { MessageList } from "./message-list.js";
|
|
5
|
+
import { ConsoleLogger, noopLogger } from "./logger.js";
|
|
6
|
+
import { Agent } from "./agent/index.js";
|
|
7
|
+
import { Redtuma } from "./redtuma.js";
|
|
8
|
+
import { Run, Workflow, createStep, createWorkflow } from "./workflows/index.js";
|
|
9
|
+
import { InMemoryStore } from "./store/index.js";
|
|
10
|
+
|
|
11
|
+
export { Agent, ConsoleLogger, InMemoryStore, MessageList, Redtuma, RedtumaModelError, Run, RuntimeContext, SUPPORTED_PROVIDERS, Workflow, buildToolset, createStep, createTool, createWorkflow, isLanguageModel, isToolAction, noopLogger, parseModelString, resolveModel, toAISDKTool };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { ModelConfig } from "../types.js";
|
|
2
|
+
import { LanguageModel } from "ai";
|
|
3
|
+
|
|
4
|
+
//#region src/llm/index.d.ts
|
|
5
|
+
declare class RedtumaModelError extends Error {
|
|
6
|
+
name: string;
|
|
7
|
+
}
|
|
8
|
+
declare function isLanguageModel(value: ModelConfig): value is LanguageModel;
|
|
9
|
+
/** Parse a `'provider/model'` string into its parts. */
|
|
10
|
+
declare function parseModelString(model: string): {
|
|
11
|
+
provider: string;
|
|
12
|
+
modelId: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Resolve a {@link ModelConfig} to a concrete AI SDK {@link LanguageModel}.
|
|
16
|
+
* Strings of the form `provider/model` are routed to the matching provider.
|
|
17
|
+
*/
|
|
18
|
+
declare function resolveModel(model: ModelConfig): Promise<LanguageModel>;
|
|
19
|
+
declare const SUPPORTED_PROVIDERS: string[];
|
|
20
|
+
//#endregion
|
|
21
|
+
export { RedtumaModelError, SUPPORTED_PROVIDERS, isLanguageModel, parseModelString, resolveModel };
|
|
22
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/llm/index.ts"],"sourcesContent":[],"mappings":";;;;cA6Ba,iBAAA,SAA0B,KAAA;;AAAvC;AAIgB,iBAAA,eAAA,CAAuB,KAAA,EAAA,WAAuB,CAAA,EAAa,KAAA,IAAb,aAAa;AAM3E;AAcsB,iBAdN,gBAAA,CAckB,KAAA,EAAA,MAAA,CAAA,EAAA;EAAQ,QAAA,EAAA,MAAA;EAAsB,OAAA,EAAA,MAAA;CAAR;;AAexD;;;iBAfsB,YAAA,QAAoB,cAAc,QAAQ;cAenD"}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
//#region src/llm/index.ts
|
|
2
|
+
const PROVIDER_LOADERS = {
|
|
3
|
+
anthropic: async () => {
|
|
4
|
+
const mod = await import("@ai-sdk/anthropic").catch(() => {
|
|
5
|
+
throw new RedtumaModelError(`Model provider "anthropic" requires the "@ai-sdk/anthropic" package. Install it with: pnpm add @ai-sdk/anthropic`);
|
|
6
|
+
});
|
|
7
|
+
return (id) => mod.anthropic(id);
|
|
8
|
+
},
|
|
9
|
+
openai: async () => {
|
|
10
|
+
const mod = await import("@ai-sdk/openai").catch(() => {
|
|
11
|
+
throw new RedtumaModelError(`Model provider "openai" requires the "@ai-sdk/openai" package. Install it with: pnpm add @ai-sdk/openai`);
|
|
12
|
+
});
|
|
13
|
+
return (id) => mod.openai(id);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var RedtumaModelError = class extends Error {
|
|
17
|
+
name = "RedtumaModelError";
|
|
18
|
+
};
|
|
19
|
+
function isLanguageModel(value) {
|
|
20
|
+
return typeof value !== "string";
|
|
21
|
+
}
|
|
22
|
+
/** Parse a `'provider/model'` string into its parts. */
|
|
23
|
+
function parseModelString(model) {
|
|
24
|
+
const idx = model.indexOf("/");
|
|
25
|
+
if (idx <= 0 || idx === model.length - 1) throw new RedtumaModelError(`Invalid model string "${model}". Expected "provider/model", e.g. "anthropic/claude-opus-4-8".`);
|
|
26
|
+
return {
|
|
27
|
+
provider: model.slice(0, idx),
|
|
28
|
+
modelId: model.slice(idx + 1)
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Resolve a {@link ModelConfig} to a concrete AI SDK {@link LanguageModel}.
|
|
33
|
+
* Strings of the form `provider/model` are routed to the matching provider.
|
|
34
|
+
*/
|
|
35
|
+
async function resolveModel(model) {
|
|
36
|
+
if (isLanguageModel(model)) return model;
|
|
37
|
+
const { provider, modelId } = parseModelString(model);
|
|
38
|
+
const loader = PROVIDER_LOADERS[provider];
|
|
39
|
+
if (!loader) throw new RedtumaModelError(`Unknown model provider "${provider}". Supported: ${Object.keys(PROVIDER_LOADERS).join(", ")}. Pass an AI SDK LanguageModel directly to use another provider.`);
|
|
40
|
+
return (await loader())(modelId);
|
|
41
|
+
}
|
|
42
|
+
const SUPPORTED_PROVIDERS = Object.keys(PROVIDER_LOADERS);
|
|
43
|
+
|
|
44
|
+
//#endregion
|
|
45
|
+
export { RedtumaModelError, SUPPORTED_PROVIDERS, isLanguageModel, parseModelString, resolveModel };
|
|
46
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["PROVIDER_LOADERS: Record<string, () => Promise<ProviderFactory>>"],"sources":["../../src/llm/index.ts"],"sourcesContent":["import type { LanguageModel } from 'ai'\nimport type { ModelConfig } from '../types'\n\n/**\n * Map of `provider` prefix -> lazy loader for the AI SDK provider factory.\n * Providers are optional peer deps imported on demand, so installing only one\n * (e.g. `@ai-sdk/anthropic`) is enough.\n */\ntype ProviderFactory = (modelId: string) => LanguageModel\n\nconst PROVIDER_LOADERS: Record<string, () => Promise<ProviderFactory>> = {\n anthropic: async () => {\n const mod = await import('@ai-sdk/anthropic').catch(() => {\n throw new RedtumaModelError(\n `Model provider \"anthropic\" requires the \"@ai-sdk/anthropic\" package. Install it with: pnpm add @ai-sdk/anthropic`,\n )\n })\n return (id) => mod.anthropic(id)\n },\n openai: async () => {\n const mod = await import('@ai-sdk/openai').catch(() => {\n throw new RedtumaModelError(\n `Model provider \"openai\" requires the \"@ai-sdk/openai\" package. Install it with: pnpm add @ai-sdk/openai`,\n )\n })\n return (id) => mod.openai(id)\n },\n}\n\nexport class RedtumaModelError extends Error {\n override name = 'RedtumaModelError'\n}\n\nexport function isLanguageModel(value: ModelConfig): value is LanguageModel {\n // AI SDK v1 model objects are non-string with a specificationVersion field.\n return typeof value !== 'string'\n}\n\n/** Parse a `'provider/model'` string into its parts. */\nexport function parseModelString(model: string): { provider: string; modelId: string } {\n const idx = model.indexOf('/')\n if (idx <= 0 || idx === model.length - 1) {\n throw new RedtumaModelError(\n `Invalid model string \"${model}\". Expected \"provider/model\", e.g. \"anthropic/claude-opus-4-8\".`,\n )\n }\n return { provider: model.slice(0, idx), modelId: model.slice(idx + 1) }\n}\n\n/**\n * Resolve a {@link ModelConfig} to a concrete AI SDK {@link LanguageModel}.\n * Strings of the form `provider/model` are routed to the matching provider.\n */\nexport async function resolveModel(model: ModelConfig): Promise<LanguageModel> {\n if (isLanguageModel(model)) return model\n\n const { provider, modelId } = parseModelString(model)\n const loader = PROVIDER_LOADERS[provider]\n if (!loader) {\n throw new RedtumaModelError(\n `Unknown model provider \"${provider}\". Supported: ${Object.keys(PROVIDER_LOADERS).join(', ')}. ` +\n `Pass an AI SDK LanguageModel directly to use another provider.`,\n )\n }\n const factory = await loader()\n return factory(modelId)\n}\n\nexport const SUPPORTED_PROVIDERS = Object.keys(PROVIDER_LOADERS)\n"],"mappings":";AAUA,MAAMA,mBAAmE;CACvE,WAAW,YAAY;EACrB,MAAM,MAAM,MAAM,OAAO,qBAAqB,YAAY;AACxD,SAAM,IAAI,kBACR,mHACD;IACD;AACF,UAAQ,OAAO,IAAI,UAAU,GAAG;;CAElC,QAAQ,YAAY;EAClB,MAAM,MAAM,MAAM,OAAO,kBAAkB,YAAY;AACrD,SAAM,IAAI,kBACR,0GACD;IACD;AACF,UAAQ,OAAO,IAAI,OAAO,GAAG;;CAEhC;AAED,IAAa,oBAAb,cAAuC,MAAM;CAC3C,AAAS,OAAO;;AAGlB,SAAgB,gBAAgB,OAA4C;AAE1E,QAAO,OAAO,UAAU;;;AAI1B,SAAgB,iBAAiB,OAAsD;CACrF,MAAM,MAAM,MAAM,QAAQ,IAAI;AAC9B,KAAI,OAAO,KAAK,QAAQ,MAAM,SAAS,EACrC,OAAM,IAAI,kBACR,yBAAyB,MAAM,iEAChC;AAEH,QAAO;EAAE,UAAU,MAAM,MAAM,GAAG,IAAI;EAAE,SAAS,MAAM,MAAM,MAAM,EAAE;EAAE;;;;;;AAOzE,eAAsB,aAAa,OAA4C;AAC7E,KAAI,gBAAgB,MAAM,CAAE,QAAO;CAEnC,MAAM,EAAE,UAAU,YAAY,iBAAiB,MAAM;CACrD,MAAM,SAAS,iBAAiB;AAChC,KAAI,CAAC,OACH,OAAM,IAAI,kBACR,2BAA2B,SAAS,gBAAgB,OAAO,KAAK,iBAAiB,CAAC,KAAK,KAAK,CAAC,kEAE9F;AAGH,SADgB,MAAM,QAAQ,EACf,QAAQ;;AAGzB,MAAa,sBAAsB,OAAO,KAAK,iBAAiB"}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Logger } from "./types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/logger.d.ts
|
|
4
|
+
type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent';
|
|
5
|
+
declare class ConsoleLogger implements Logger {
|
|
6
|
+
private readonly level;
|
|
7
|
+
constructor(level?: LogLevel);
|
|
8
|
+
private enabled;
|
|
9
|
+
debug(msg: string, meta?: unknown): void;
|
|
10
|
+
info(msg: string, meta?: unknown): void;
|
|
11
|
+
warn(msg: string, meta?: unknown): void;
|
|
12
|
+
error(msg: string, meta?: unknown): void;
|
|
13
|
+
}
|
|
14
|
+
declare const noopLogger: Logger;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { ConsoleLogger, LogLevel, noopLogger };
|
|
17
|
+
//# sourceMappingURL=logger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.d.ts","names":[],"sources":["../src/logger.ts"],"sourcesContent":[],"mappings":";;;KAEY,QAAA;cAUC,aAAA,YAAyB;EAV1B,iBAAQ,KAAA;EAUP,WAAA,CAAA,KACyB,CADX,EACW,QAAA;EAoBzB,QAAA,OAKZ;;;;;;cALY,YAAY"}
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/logger.ts
|
|
2
|
+
const ORDER = {
|
|
3
|
+
debug: 10,
|
|
4
|
+
info: 20,
|
|
5
|
+
warn: 30,
|
|
6
|
+
error: 40,
|
|
7
|
+
silent: 99
|
|
8
|
+
};
|
|
9
|
+
var ConsoleLogger = class {
|
|
10
|
+
constructor(level = "info") {
|
|
11
|
+
this.level = level;
|
|
12
|
+
}
|
|
13
|
+
enabled(level) {
|
|
14
|
+
return ORDER[level] >= ORDER[this.level];
|
|
15
|
+
}
|
|
16
|
+
debug(msg, meta) {
|
|
17
|
+
if (this.enabled("debug")) console.debug(`[redtuma] ${msg}`, meta ?? "");
|
|
18
|
+
}
|
|
19
|
+
info(msg, meta) {
|
|
20
|
+
if (this.enabled("info")) console.info(`[redtuma] ${msg}`, meta ?? "");
|
|
21
|
+
}
|
|
22
|
+
warn(msg, meta) {
|
|
23
|
+
if (this.enabled("warn")) console.warn(`[redtuma] ${msg}`, meta ?? "");
|
|
24
|
+
}
|
|
25
|
+
error(msg, meta) {
|
|
26
|
+
if (this.enabled("error")) console.error(`[redtuma] ${msg}`, meta ?? "");
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
const noopLogger = {
|
|
30
|
+
debug() {},
|
|
31
|
+
info() {},
|
|
32
|
+
warn() {},
|
|
33
|
+
error() {}
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { ConsoleLogger, noopLogger };
|
|
38
|
+
//# sourceMappingURL=logger.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","names":["ORDER: Record<LogLevel, number>","level: LogLevel","noopLogger: Logger"],"sources":["../src/logger.ts"],"sourcesContent":["import type { Logger } from './types'\n\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'\n\nconst ORDER: Record<LogLevel, number> = {\n debug: 10,\n info: 20,\n warn: 30,\n error: 40,\n silent: 99,\n}\n\nexport class ConsoleLogger implements Logger {\n constructor(private readonly level: LogLevel = 'info') {}\n\n private enabled(level: Exclude<LogLevel, 'silent'>): boolean {\n return ORDER[level] >= ORDER[this.level]\n }\n\n debug(msg: string, meta?: unknown): void {\n if (this.enabled('debug')) console.debug(`[redtuma] ${msg}`, meta ?? '')\n }\n info(msg: string, meta?: unknown): void {\n if (this.enabled('info')) console.info(`[redtuma] ${msg}`, meta ?? '')\n }\n warn(msg: string, meta?: unknown): void {\n if (this.enabled('warn')) console.warn(`[redtuma] ${msg}`, meta ?? '')\n }\n error(msg: string, meta?: unknown): void {\n if (this.enabled('error')) console.error(`[redtuma] ${msg}`, meta ?? '')\n }\n}\n\nexport const noopLogger: Logger = {\n debug() {},\n info() {},\n warn() {},\n error() {},\n}\n"],"mappings":";AAIA,MAAMA,QAAkC;CACtC,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,QAAQ;CACT;AAED,IAAa,gBAAb,MAA6C;CAC3C,YAAY,AAAiBC,QAAkB,QAAQ;EAA1B;;CAE7B,AAAQ,QAAQ,OAA6C;AAC3D,SAAO,MAAM,UAAU,MAAM,KAAK;;CAGpC,MAAM,KAAa,MAAsB;AACvC,MAAI,KAAK,QAAQ,QAAQ,CAAE,SAAQ,MAAM,aAAa,OAAO,QAAQ,GAAG;;CAE1E,KAAK,KAAa,MAAsB;AACtC,MAAI,KAAK,QAAQ,OAAO,CAAE,SAAQ,KAAK,aAAa,OAAO,QAAQ,GAAG;;CAExE,KAAK,KAAa,MAAsB;AACtC,MAAI,KAAK,QAAQ,OAAO,CAAE,SAAQ,KAAK,aAAa,OAAO,QAAQ,GAAG;;CAExE,MAAM,KAAa,MAAsB;AACvC,MAAI,KAAK,QAAQ,QAAQ,CAAE,SAAQ,MAAM,aAAa,OAAO,QAAQ,GAAG;;;AAI5E,MAAaC,aAAqB;CAChC,QAAQ;CACR,OAAO;CACP,OAAO;CACP,QAAQ;CACT"}
|