@perstack/runtime 0.0.3 → 0.0.4
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/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +12 -21
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 [2025] [Wintermute Technologies Inc.]
|
|
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/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {existsSync}from'fs';import {readFile,writeFile,mkdir,readdir}from'fs/promises';import pe from'path';import {createId}from'@paralleldrive/cuid2';import To from'smol-toml';import {setup,assign,createActor}from'xstate';import {z as z$1,ZodError}from'zod';import {anthropic}from'@ai-sdk/anthropic';import {google}from'@ai-sdk/google';import {openai}from'@ai-sdk/openai';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {SSEClientTransport}from'@modelcontextprotocol/sdk/client/sse.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {McpError}from'@modelcontextprotocol/sdk/types.js';import {generateText,jsonSchema}from'ai';import {dedent}from'ts-dedent';var ft="claude-4-sonnet-20250514",ue=["claude-4-opus-20250514","claude-4-sonnet-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-latest","claude-3-5-sonnet-20241022","claude-3-5-sonnet-20240620","claude-3-5-haiku-latest","claude-3-5-haiku-20241022"],ge=["gemini-2.5-pro-preview-05-06","gemini-2.5-pro-exp-03-25","gemini-2.5-flash-preview-04-17","gemini-2.0-pro-exp-02-05","gemini-2.0-flash-thinking-exp-01-21","gemini-2.0-flash","gemini-2.0-flash-001","gemini-2.0-flash-live-001","gemini-2.0-flash-lite","gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-pro-latest","gemini-1.5-pro-001","gemini-1.5-pro-002","gemini-1.5-flash","gemini-1.5-flash-latest","gemini-1.5-flash-001","gemini-1.5-flash-002","gemini-1.5-flash-8b","gemini-1.5-flash-8b-latest","gemini-1.5-flash-8b-001"],de=["o4-mini","o4-mini-2025-04-16","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18"],ht=Object.fromEntries([...ue,...ge,...de].map(e=>[e,{default:e===ft,model:e}]));function te(){let e=Object.values(ht).find(t=>t.default);if(!e)throw new Error("No default model found");return e.model}function L(e){let t=e??te();if(ue.includes(t))return anthropic(t);if(ge.includes(t))return google(t);if(de.includes(t))return openai(t);throw new Error(`Unsupported model: ${t}`)}var I=z$1.object({id:z$1.string()}),_=I.extend({type:z$1.literal("textPart"),text:z$1.string()}),yt=I.extend({type:z$1.literal("imageUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),fe=I.extend({type:z$1.literal("imageInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),xt=I.extend({type:z$1.literal("imageBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),Tt=I.extend({type:z$1.literal("fileUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),kt=I.extend({type:z$1.literal("fileInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),Rt=I.extend({type:z$1.literal("fileBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),St=I.extend({type:z$1.literal("toolCallPart"),toolCallId:z$1.string(),toolName:z$1.string(),args:z$1.unknown()}),Pt=I.extend({type:z$1.literal("toolResultPart"),toolCallId:z$1.string(),toolName:z$1.string(),contents:z$1.array(z$1.union([_,fe])),isError:z$1.boolean().optional()}),A=z$1.object({id:z$1.string()}),vt=A.extend({type:z$1.literal("instructionMessage"),contents:z$1.array(_),cache:z$1.boolean().optional()}),Ct=A.extend({type:z$1.literal("userMessage"),contents:z$1.array(z$1.union([_,yt,fe,xt,Tt,kt,Rt])),cache:z$1.boolean().optional()}),wt=A.extend({type:z$1.literal("expertMessage"),contents:z$1.array(z$1.union([_,St])),cache:z$1.boolean().optional()}),It=A.extend({type:z$1.literal("toolMessage"),contents:z$1.array(Pt),cache:z$1.boolean().optional()}),he=z$1.union([vt,Ct,wt,It]);var Mt=/^(@[a-z0-9][a-z0-9_-]*\/)?[a-z0-9][a-z0-9_-]*$/,bt=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/,Et=/^[a-z0-9][a-z0-9_-]*$/,D=/^((?:@[a-z0-9][a-z0-9_\.-]*\/)?[a-z0-9][a-z0-9_\.-]*)(?:@((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?)|@([a-z0-9][a-z0-9_\.-]*))?$/,Uo=/^[a-z0-9][a-z0-9._-]*$/,$t=214;function jo(e){let t=e.match(D);if(!t)throw new Error(`Invalid expert key format: ${e}`);let[o,r,a,c]=t;return {key:o,name:r,version:a,tag:c}}var G=z$1.object({type:z$1.literal("mcpStdioSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),command:z$1.string(),args:z$1.array(z$1.string()).optional().default([]),requiredEnv:z$1.array(z$1.string()).optional().default([])}),K=z$1.object({type:z$1.literal("mcpSseSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),endpoint:z$1.string()}),ye=z$1.object({name:z$1.string(),description:z$1.string().optional(),inputJsonSchema:z$1.string()}),q=z$1.object({type:z$1.literal("interactiveSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),tools:z$1.record(z$1.string(),ye.omit({name:true})).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,ye.parse({...o,name:t})])))}),J=z$1.object({key:z$1.string().regex(D).min(1),name:z$1.string().regex(Mt).min(1).max($t),version:z$1.string().regex(bt),description:z$1.string().min(1).max(1024*2).optional(),instruction:z$1.string().min(1).max(1024*20),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])).optional().default({"@perstack/base":{type:"mcpStdioSkill",description:"Base skill",command:"npx",args:["-y","@perstack/base"]}}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,z$1.discriminatedUnion("type",[G,K,q]).parse({...o,name:t})]))),delegates:z$1.array(z$1.string().regex(D).min(1)).optional().default([]),tags:z$1.array(z$1.string().regex(Et).min(1)).optional().default([])}),Nt=z$1.object({promptTokens:z$1.number(),completionTokens:z$1.number(),totalTokens:z$1.number(),cacheCreationInputTokens:z$1.number(),cacheReadInputTokens:z$1.number()}),Ft=z$1.enum(["init","proceeding","completed","stoppedByInteractiveTool","stoppedByDelegate","stoppedByExceededMaxSteps","stoppedByError"]),oe=z$1.object({id:z$1.string(),runId:z$1.string(),status:Ft,stepNumber:z$1.number(),messages:z$1.array(he),expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),delegateTo:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),query:z$1.string()}).optional(),delegatedBy:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),checkpointId:z$1.string()}).optional(),usage:Nt}),Te=z$1.object({setting:z$1.object({runId:z$1.string().optional().transform(e=>e??createId()),expertKey:z$1.string().regex(D).min(1),input:z$1.object({text:z$1.string().optional(),interactiveToolCallResult:z$1.object({toolCallId:z$1.string(),toolName:z$1.string(),text:z$1.string()}).optional()}),experts:z$1.record(z$1.string().regex(D).min(1),J.omit({key:true})).optional().default({}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,J.parse({...o,key:t})]))),model:z$1.string().optional().default(te()),temperature:z$1.number().min(0).max(1).optional().default(.3),maxSteps:z$1.number().min(1).optional(),maxRetries:z$1.number().min(0).optional().default(10),workspace:z$1.string().optional(),startedAt:z$1.number().optional().default(Date.now()),updatedAt:z$1.number().optional().default(Date.now())}),checkpoint:oe.optional()});function T(e){return (t,o,r)=>({type:e,id:createId(),expertKey:o.expert.key,timestamp:Date.now(),runId:t.runId,stepNumber:o.stepNumber,...r})}var ne=T("startRun"),ke=T("startGeneration"),re=T("retry"),Re=T("callTool"),Se=T("callInteractiveTool"),Pe=T("callDelegate"),ve=T("resolveToolResult"),Ce=T("resolveThought"),we=T("resolvePdfFile"),Ie=T("resolveImageFile"),Me=T("attemptCompletion"),$=T("finishToolCall"),be=T("completeRun"),Ee=T("stopRunByInteractiveTool"),$e=T("stopRunByDelegate"),Ne=T("stopRunByExceededMaxSteps"),Fe=T("continueToNextStep");async function De(e,t){let o=O(e),a=(await readdir(o,{withFileTypes:true}).then(s=>s.filter(u=>u.isFile()&&u.name.startsWith("checkpoint-")))).find(s=>s.name.endsWith(`-${t}.json`));if(!a)throw new Error(`checkpoint not found: ${e} ${t}`);let c=`${o}/${a.name}`,m=await readFile(c,"utf8");return oe.parse(JSON.parse(m))}async function Oe(e,t){let{id:o,runId:r,stepNumber:a}=e,c=O(r),m=`${c}/checkpoint-${t}-${a}-${o}.json`;await mkdir(c,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}async function Be(e){let{timestamp:t,runId:o,stepNumber:r,type:a}=e,c=O(o),m=`${c}/event-${t}-${r}-${a}.json`;await mkdir(c,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}var ze={version:"0.0.3"};var p=console.info,Le=console.debug,g=e=>{let t=new Date().toISOString(),o=e.stepNumber,r=e.expertKey;return `${t} ${o} ${r}`};async function se(e){switch(await Be(e),e.type){case "startRun":{p(`${g(e)} \u{1F99C} Perstack@${ze.version} started`);let{inputMessages:t}=e;for(let o of t)o.type==="userMessage"?Ot(o):o.type==="toolMessage"&&Bt(o);break}case "startGeneration":{p(`${g(e)} \u{1F99C} Generating tool call`);break}case "retry":{B(e),p(`${g(e)} \u{1F99C} Retrying tool call generation`);break}case "callTool":{if(B(e),p(`${g(e)} \u{1F99C} Calling tool`),e.toolCall.skillName==="@perstack/base")switch(e.toolCall.toolName){case "think":{let t=e.toolCall.args.thought;p(`${g(e)} \u{1F4AD} Thought Updated:`),Le(t);break}case "readPdfFile":{let t=e.toolCall.args.path;p(`${g(e)} \u{1F4C4} Reading PDF: ${t}`);break}case "readImageFile":{let t=e.toolCall.args.path;p(`${g(e)} \u{1F5BC}\uFE0F Reading Image: ${t}`);break}default:{p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}}else p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callInteractiveTool":{B(e),p(`${g(e)} \u{1F99C} Calling interactive tool`),p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callDelegate":{B(e),p(`${g(e)} \u{1F99C} Calling delegate`),p(`${g(e)} \u{1F527} Tool: ${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "resolveToolResult":{if(p(`${g(e)} \u{1F527} Resolved Tool Result`),e.toolResult.skillName==="@perstack/base")switch(e.toolResult.toolName){case "todo":{let t=e.toolResult.result.find(r=>r.type==="textPart")?.text,{todos:o}=JSON.parse(t??"{}");p(`${g(e)} \u{1F4C4} Todo:`);for(let r of o)Le(`${r.completed?"[x]":"[ ]"} ${r.id}: ${r.title}`);break}default:{p(`${g(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),p(`${g(e)} \u{1F527} Result: ${e.toolResult.result}`);break}}else p(`${g(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),p(`${g(e)} \u{1F527} Result: ${e.toolResult.result}`);break}case "resolveThought":{p(`${g(e)} \u{1F4AD} Resolved Thought:`,e.toolResult);break}case "resolvePdfFile":{p(`${g(e)} \u{1F4C4} Resolved PDF:`,e.toolResult);break}case "resolveImageFile":{p(`${g(e)} \u{1F5BC}\uFE0F Resolved Image:`,e.toolResult);break}case "attemptCompletion":{p(`${g(e)} \u2705 Attempting completion`);break}case "completeRun":{B(e),p(`${g(e)} \u{1F99C} Completing run`),p(`${g(e)} \u{1F99C} Result:`,e.text);break}case "stopRunByInteractiveTool":{p(`${g(e)} \u{1F99C} Stopping run by interactive tool`);break}case "stopRunByDelegate":{p(`${g(e)} \u{1F99C} Stopping run by delegate`);break}case "stopRunByExceededMaxSteps":{p(`${g(e)} \u{1F99C} Stopping run by exceeded max steps`);break}case "continueToNextStep":{p(`${g(e)} \u{1F99C} Continuing to next step`);break}}}function Ot(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)r.type==="textPart"?p(`${t} \u{1F4AC} User: ${r.text}`):r.type==="imageUrlPart"?p(`${t} \u{1F5BC}\uFE0F User: ${r.url}`):r.type==="imageInlinePart"?p(`${t} \u{1F5BC}\uFE0F User: Inline image`):r.type==="imageBinaryPart"?p(`${t} \u{1F5BC}\uFE0F User: Binary image`):r.type==="fileUrlPart"?p(`${t} \u{1F4C4} User: ${r.url}`):r.type==="fileInlinePart"?p(`${t} \u{1F4C4} User: Inline file`):r.type==="fileBinaryPart"&&p(`${t} \u{1F4C4} User: Binary file`);}function Bt(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)if(r.type==="toolResultPart"){let{contents:a}=r;for(let c of a)c.type==="textPart"?p(`${t} \u{1F4AC} Tool Result: ${c.text}`):c.type==="imageInlinePart"&&p(`${t} \u{1F5BC}\uFE0F Tool Result: Inline image`);}}function B(e){let t=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");p(`${g(e)} \u{1F4CA} Tokens usage: ${t}`);let o=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");p(`${g(e)} \u{1F4CA} Total usage: ${o}`);}var V=class{listeners=[];subscribe(t){this.listeners.push(t);}async emit(t){for(let o of this.listeners)await o({...t,id:createId(),timestamp:Date.now()});}};var Lt=z$1.object({name:z$1.string(),version:z$1.string(),minRuntimeVersion:z$1.string(),description:z$1.string(),instruction:z$1.string(),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])),delegates:z$1.array(z$1.string()),tags:z$1.array(z$1.string()),status:z$1.string(),owner:z$1.object({name:z$1.string()}),createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()}),_e=z$1.object({data:z$1.object({expert:Lt})});var Y=class{baseUrl;registry;apiKey;constructor(t){this.baseUrl=t?.baseUrl??process.env.PERSTACK_API_BASE_URL??"https://api.perstack.ai",this.apiKey=t?.apiKey??process.env.PERSTACK_API_KEY,this.registry=new ae(this);}},ae=class{client;endpoint;constructor(t){this.client=t,this.endpoint="/api/registry/v1/experts";}async get(t){let o=encodeURIComponent(t),r=new URL(`${this.endpoint}/${o}`,this.client.baseUrl),a={"Content-Type":"application/json",Authorization:`Bearer ${this.client.apiKey}`},c=await fetch(r.toString(),{headers:a});if(!c.ok)throw new Error(`Registry returned non-200 status code: ${c.status}, reason: ${c.statusText}`);let m=await c.json();return _e.parse(m)}};async function ie(e,t){if(t[e])return t[e];let o=new Y,{data:r}=await o.registry.get(e),a=J.parse({...r.expert,key:e});return t[e]=a,a}var z=class{_toolDefinitions=[];_initialized=false;name;type;skill;interactiveSkill;expert;_mcpClient;_params;constructor(t){switch(this._params=t,this.type=t.type,t.type){case "mcp":this.name=t.skill.name,this.skill=t.skill;break;case "interactive":this.name=t.interactiveSkill.name,this.interactiveSkill=t.interactiveSkill;break;case "delegate":this.name=t.expert.name,this.expert=t.expert;break}}async init(){switch(this._params.type){case "mcp":{await this._initMcpSkill(this._params);break}case "interactive":{await this._initInteractiveSkill(this._params);break}case "delegate":{await this._initDelegate(this._params);break}}}async _initMcpSkill(t){switch(this._mcpClient=new Client({name:`${t.skill.name}-mcp-client`,version:"1.0.0"}),t.skill.type){case "mcpStdioSkill":{if(!t.skill.command)throw new Error(`Skill ${t.skill.name} has no command`);let{command:r,args:a,requiredEnv:c}=t.skill,m=new StdioClientTransport({command:r,args:a,env:Object.fromEntries(Object.entries(process.env).filter(([s,u])=>u!==void 0&&u!=="").map(([s,u])=>[s,u]))});await this._mcpClient.connect(m);break}case "mcpSseSkill":{if(!t.skill.endpoint)throw new Error(`Skill ${t.skill.name} has no endpoint`);let r=new SSEClientTransport(new URL(t.skill.endpoint));await this._mcpClient.connect(r);break}}let{tools:o}=await this._mcpClient.listTools();this._toolDefinitions=o.map(r=>({skillName:t.skill.name,name:r.name,description:r.description,inputSchema:r.inputSchema,interactive:false})),this._initialized=true;}async _initInteractiveSkill(t){this._toolDefinitions=Object.values(t.interactiveSkill.tools).map(o=>({skillName:t.interactiveSkill.name,name:o.name,description:o.description,inputSchema:JSON.parse(o.inputJsonSchema),interactive:true})),this._initialized=true;}async _initDelegate(t){this._toolDefinitions=[{skillName:t.expert.name,name:t.expert.name.split("/").pop()??t.expert.name,description:t.expert.description,inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]},interactive:false}],this._initialized=true;}async close(){this._mcpClient&&await this._mcpClient.close();}async getToolDefinitions(){if(!this._initialized)throw new Error(`${this.name} is not initialized`);if(this._params.type==="mcp"){let t=this._params.skill.omit??[],o=this._params.skill.pick??[];return this._toolDefinitions.filter(r=>t.length>0?!t.includes(r.name):true).filter(r=>o.length>0?o.includes(r.name):true)}return this._toolDefinitions}async callTool(t,o){switch(this._params.type){case "mcp":{if(!this._mcpClient)throw new Error(`${this.name} is not initialized`);try{let r=await this._mcpClient.callTool({name:t,arguments:o});return this._convertToolResult(r,t,o)}catch(r){return this._handleToolError(r,t)}}case "interactive":return [];case "delegate":return []}}_handleToolError(t,o){if(t instanceof McpError)return [{type:"textPart",text:`Error calling tool ${o}: ${t.message}`,id:createId()}];if(t instanceof ZodError)return [{type:"textPart",text:`Invalid tool call arguments: ${t}`,id:createId()}];throw t}_convertToolResult(t,o,r){return !t.content||t.content.length===0?[{type:"textPart",text:`Tool ${o} returned nothing with arguments: ${JSON.stringify(r)}`,id:createId()}]:t.content.filter(a=>a.type!=="audio"&&a.type!=="resource_link").map(a=>this._convertPart(a))}_convertPart(t){switch(t.type){case "text":return !t.text||t.text===""?{type:"textPart",text:"Error: No content",id:createId()}:{type:"textPart",text:t.text,id:createId()};case "image":if(!t.data||!t.mimeType)throw new Error("Image part must have both data and mimeType");return {type:"imageInlinePart",encodedData:t.data,mimeType:t.mimeType,id:createId()};case "resource":if(!t.resource)throw new Error("Resource part must have resource content");return this._convertResource(t.resource)}}_convertResource(t){if(!t.mimeType)throw new Error(`Resource ${JSON.stringify(t)} has no mimeType`);if(t.text&&typeof t.text=="string")return {type:"textPart",text:t.text,id:createId()};if(t.blob&&typeof t.blob=="string")return {type:"fileInlinePart",encodedData:t.blob,mimeType:t.mimeType,id:createId()};throw new Error(`Unsupported resource type: ${JSON.stringify(t)}`)}};async function Ae(e,t){let o={},{skills:r}=e;r["@perstack/base"]||(r["@perstack/base"]={type:"mcpStdioSkill",name:"@perstack/base",description:"The base skill for Perstack",pick:[],omit:[],command:"npx",args:["-y","@perstack/base"],requiredEnv:[]});let a=await Promise.all(Object.values(r).filter(s=>s.type==="mcpStdioSkill"||s.type==="mcpSseSkill").map(async s=>{let u=new z({type:"mcp",skill:s});return await u.init(),u})),c=await Promise.all(Object.values(r).filter(s=>s.type==="interactiveSkill").map(async s=>{let u=new z({type:"interactive",interactiveSkill:s});return await u.init(),u})),m=await Promise.all(e.delegates.map(async s=>{let u=t[s],h=new z({type:"delegate",expert:u});return await h.init(),h}));for(let s of a)o[s.name]=s;for(let s of c)o[s.name]=s;for(let s of m)o[s.name]=s;return o}async function Ge(e){for(let t of Object.values(e))await t.close();}async function N(e,t){for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)if(a.name===t)return o}throw new Error(`Tool ${t} not found`)}async function Ke(e){let t={};for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)t[a.name]={description:a.description,parameters:jsonSchema(a.inputSchema)};}return t}async function qe({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,toolName:c,args:m}=o.toolCall,s=await N(r,c);if(!s||!s.expert)throw new Error(`Delegation error: skill manager "${c}" not found`);if(!m||!m.query||typeof m.query!="string")throw new Error("Delegation error: query is undefined");return $e(e,t,{checkpoint:{...t,status:"stoppedByDelegate",delegateTo:{expert:{key:s.expert.key,name:s.expert.name,version:s.expert.version},toolCallId:a,toolName:c,query:m.query}},step:{...o,finishedAt:new Date().getTime()}})}async function Je({setting:e,checkpoint:t,step:o}){return Ee(e,t,{checkpoint:{...t,status:"stoppedByInteractiveTool"},step:{...o,finishedAt:new Date().getTime()}})}async function Ve({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,skillName:c,toolName:m,args:s}=o.toolCall,u=await N(r,m);if(u.type!=="mcp")throw new Error(`Incorrect SkillType, required MCP, got ${u.type}`);let h=await u.callTool(m,s),d={id:a,skillName:c,toolName:m,result:h};if(c==="@perstack/base"){if(m==="think")return Ce(e,t,{toolResult:d});if(m==="attemptCompletion")return Me(e,t,{toolResult:d});if(m==="readPdfFile")return we(e,t,{toolResult:d});if(m==="readImageFile")return Ie(e,t,{toolResult:d})}return ve(e,t,{toolResult:d})}async function Ye({setting:e,checkpoint:t,step:o}){return e.maxSteps!==void 0&&t.stepNumber>e.maxSteps?Ne(e,t,{checkpoint:{...t,status:"stoppedByExceededMaxSteps"},step:{...o,finishedAt:new Date().getTime()}}):Fe(e,t,{checkpoint:{...t},step:{...o,finishedAt:new Date().getTime()},nextCheckpoint:{...t,id:createId(),stepNumber:t.stepNumber+1}})}function F(e){return {type:"userMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function U(e){return {type:"expertMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function v(e){return {type:"toolMessage",contents:e.map(t=>({...t,contents:t.contents.map(o=>({...o,id:createId()})),id:createId()})),id:createId()}}function W(e){switch(e.type){case "instructionMessage":return {role:"system",content:Wt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "userMessage":return {role:"user",content:Ht(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "expertMessage":return {role:"assistant",content:Qt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "toolMessage":return {role:"tool",content:Zt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0}}}function Wt(e){return e.reduce((t,o)=>dedent`
|
|
1
|
+
import {existsSync}from'fs';import {readFile,writeFile,mkdir,readdir}from'fs/promises';import pe from'path';import {createId}from'@paralleldrive/cuid2';import To from'smol-toml';import {setup,assign,createActor}from'xstate';import {z as z$1,ZodError}from'zod';import {anthropic}from'@ai-sdk/anthropic';import {google}from'@ai-sdk/google';import {openai}from'@ai-sdk/openai';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {SSEClientTransport}from'@modelcontextprotocol/sdk/client/sse.js';import {StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {McpError}from'@modelcontextprotocol/sdk/types.js';import {generateText,jsonSchema}from'ai';import {dedent}from'ts-dedent';var ft="claude-4-sonnet-20250514",ue=["claude-4-opus-20250514","claude-4-sonnet-20250514","claude-3-7-sonnet-20250219","claude-3-5-sonnet-latest","claude-3-5-sonnet-20241022","claude-3-5-sonnet-20240620","claude-3-5-haiku-latest","claude-3-5-haiku-20241022"],ge=["gemini-2.5-pro-preview-05-06","gemini-2.5-pro-exp-03-25","gemini-2.5-flash-preview-04-17","gemini-2.0-pro-exp-02-05","gemini-2.0-flash-thinking-exp-01-21","gemini-2.0-flash","gemini-2.0-flash-001","gemini-2.0-flash-live-001","gemini-2.0-flash-lite","gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-pro-latest","gemini-1.5-pro-001","gemini-1.5-pro-002","gemini-1.5-flash","gemini-1.5-flash-latest","gemini-1.5-flash-001","gemini-1.5-flash-002","gemini-1.5-flash-8b","gemini-1.5-flash-8b-latest","gemini-1.5-flash-8b-001"],de=["o4-mini","o4-mini-2025-04-16","o3","o3-2025-04-16","o3-mini","o3-mini-2025-01-31","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-mini","gpt-4o-mini-2024-07-18"],ht=Object.fromEntries([...ue,...ge,...de].map(e=>[e,{default:e===ft,model:e}]));function te(){let e=Object.values(ht).find(t=>t.default);if(!e)throw new Error("No default model found");return e.model}function L(e){let t=e??te();if(ue.includes(t))return anthropic(t);if(ge.includes(t))return google(t);if(de.includes(t))return openai(t);throw new Error(`Unsupported model: ${t}`)}var I=z$1.object({id:z$1.string()}),_=I.extend({type:z$1.literal("textPart"),text:z$1.string()}),yt=I.extend({type:z$1.literal("imageUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),fe=I.extend({type:z$1.literal("imageInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),xt=I.extend({type:z$1.literal("imageBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),Tt=I.extend({type:z$1.literal("fileUrlPart"),url:z$1.string().url(),mimeType:z$1.string()}),kt=I.extend({type:z$1.literal("fileInlinePart"),encodedData:z$1.string(),mimeType:z$1.string()}),Rt=I.extend({type:z$1.literal("fileBinaryPart"),data:z$1.string(),mimeType:z$1.string()}),St=I.extend({type:z$1.literal("toolCallPart"),toolCallId:z$1.string(),toolName:z$1.string(),args:z$1.unknown()}),Pt=I.extend({type:z$1.literal("toolResultPart"),toolCallId:z$1.string(),toolName:z$1.string(),contents:z$1.array(z$1.union([_,fe])),isError:z$1.boolean().optional()}),A=z$1.object({id:z$1.string()}),vt=A.extend({type:z$1.literal("instructionMessage"),contents:z$1.array(_),cache:z$1.boolean().optional()}),Ct=A.extend({type:z$1.literal("userMessage"),contents:z$1.array(z$1.union([_,yt,fe,xt,Tt,kt,Rt])),cache:z$1.boolean().optional()}),wt=A.extend({type:z$1.literal("expertMessage"),contents:z$1.array(z$1.union([_,St])),cache:z$1.boolean().optional()}),It=A.extend({type:z$1.literal("toolMessage"),contents:z$1.array(Pt),cache:z$1.boolean().optional()}),he=z$1.union([vt,Ct,wt,It]);var Mt=/^(@[a-z0-9][a-z0-9_-]*\/)?[a-z0-9][a-z0-9_-]*$/,bt=/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?$/,Et=/^[a-z0-9][a-z0-9_-]*$/,D=/^((?:@[a-z0-9][a-z0-9_\.-]*\/)?[a-z0-9][a-z0-9_\.-]*)(?:@((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\w.-]+)?(?:\+[\w.-]+)?)|@([a-z0-9][a-z0-9_\.-]*))?$/,Uo=/^[a-z0-9][a-z0-9._-]*$/,$t=214;function jo(e){let t=e.match(D);if(!t)throw new Error(`Invalid expert key format: ${e}`);let[o,r,a,c]=t;return {key:o,name:r,version:a,tag:c}}var G=z$1.object({type:z$1.literal("mcpStdioSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),command:z$1.string(),args:z$1.array(z$1.string()).optional().default([]),requiredEnv:z$1.array(z$1.string()).optional().default([])}),K=z$1.object({type:z$1.literal("mcpSseSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),pick:z$1.array(z$1.string()).optional().default([]),omit:z$1.array(z$1.string()).optional().default([]),endpoint:z$1.string()}),ye=z$1.object({name:z$1.string(),description:z$1.string().optional(),inputJsonSchema:z$1.string()}),q=z$1.object({type:z$1.literal("interactiveSkill"),name:z$1.string(),description:z$1.string().optional(),rule:z$1.string().optional(),tools:z$1.record(z$1.string(),ye.omit({name:true})).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,ye.parse({...o,name:t})])))}),J=z$1.object({key:z$1.string().regex(D).min(1),name:z$1.string().regex(Mt).min(1).max($t),version:z$1.string().regex(bt),description:z$1.string().min(1).max(1024*2).optional(),instruction:z$1.string().min(1).max(1024*20),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])).optional().default({"@perstack/base":{type:"mcpStdioSkill",description:"Base skill",command:"npx",args:["-y","@perstack/base"]}}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,z$1.discriminatedUnion("type",[G,K,q]).parse({...o,name:t})]))),delegates:z$1.array(z$1.string().regex(D).min(1)).optional().default([]),tags:z$1.array(z$1.string().regex(Et).min(1)).optional().default([])}),Nt=z$1.object({promptTokens:z$1.number(),completionTokens:z$1.number(),totalTokens:z$1.number(),cacheCreationInputTokens:z$1.number(),cacheReadInputTokens:z$1.number()}),Ft=z$1.enum(["init","proceeding","completed","stoppedByInteractiveTool","stoppedByDelegate","stoppedByExceededMaxSteps","stoppedByError"]),oe=z$1.object({id:z$1.string(),runId:z$1.string(),status:Ft,stepNumber:z$1.number(),messages:z$1.array(he),expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),delegateTo:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),query:z$1.string()}).optional(),delegatedBy:z$1.object({expert:z$1.object({key:z$1.string(),name:z$1.string(),version:z$1.string()}),toolCallId:z$1.string(),toolName:z$1.string(),checkpointId:z$1.string()}).optional(),usage:Nt}),Te=z$1.object({setting:z$1.object({runId:z$1.string().optional().transform(e=>e??createId()),expertKey:z$1.string().regex(D).min(1),input:z$1.object({text:z$1.string().optional(),interactiveToolCallResult:z$1.object({toolCallId:z$1.string(),toolName:z$1.string(),text:z$1.string()}).optional()}),experts:z$1.record(z$1.string().regex(D).min(1),J.omit({key:true})).optional().default({}).transform(e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,J.parse({...o,key:t})]))),model:z$1.string().optional().default(te()),temperature:z$1.number().min(0).max(1).optional().default(.3),maxSteps:z$1.number().min(1).optional(),maxRetries:z$1.number().min(0).optional().default(10),workspace:z$1.string().optional(),startedAt:z$1.number().optional().default(Date.now()),updatedAt:z$1.number().optional().default(Date.now())}),checkpoint:oe.optional()});function T(e){return (t,o,r)=>({type:e,id:createId(),expertKey:o.expert.key,timestamp:Date.now(),runId:t.runId,stepNumber:o.stepNumber,...r})}var ne=T("startRun"),ke=T("startGeneration"),re=T("retry"),Re=T("callTool"),Se=T("callInteractiveTool"),Pe=T("callDelegate"),ve=T("resolveToolResult"),Ce=T("resolveThought"),we=T("resolvePdfFile"),Ie=T("resolveImageFile"),Me=T("attemptCompletion"),$=T("finishToolCall"),be=T("completeRun"),Ee=T("stopRunByInteractiveTool"),$e=T("stopRunByDelegate"),Ne=T("stopRunByExceededMaxSteps"),Fe=T("continueToNextStep");async function De(e,t){let o=O(e),a=(await readdir(o,{withFileTypes:true}).then(s=>s.filter(u=>u.isFile()&&u.name.startsWith("checkpoint-")))).find(s=>s.name.endsWith(`-${t}.json`));if(!a)throw new Error(`checkpoint not found: ${e} ${t}`);let c=`${o}/${a.name}`,m=await readFile(c,"utf8");return oe.parse(JSON.parse(m))}async function Oe(e,t){let{id:o,runId:r,stepNumber:a}=e,c=O(r),m=`${c}/checkpoint-${t}-${a}-${o}.json`;await mkdir(c,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}async function Be(e){let{timestamp:t,runId:o,stepNumber:r,type:a}=e,c=O(o),m=`${c}/event-${t}-${r}-${a}.json`;await mkdir(c,{recursive:true}),await writeFile(m,JSON.stringify(e,null,2));}var ze={version:"0.0.4"};var p=console.info,Le=console.debug,g=e=>{let t=new Date().toISOString(),o=e.stepNumber,r=e.expertKey;return `${t} ${o} ${r}`};async function se(e){switch(await Be(e),e.type){case "startRun":{p(`${g(e)} \u{1F99C} Perstack@${ze.version} started`);let{inputMessages:t}=e;for(let o of t)o.type==="userMessage"?Ot(o):o.type==="toolMessage"&&Bt(o);break}case "startGeneration":{p(`${g(e)} \u{1F99C} Generating tool call`);break}case "retry":{B(e),p(`${g(e)} \u{1F99C} Retrying tool call generation`);break}case "callTool":{if(B(e),p(`${g(e)} \u{1F99C} Calling tool`),e.toolCall.skillName==="@perstack/base")switch(e.toolCall.toolName){case "think":{let t=e.toolCall.args.thought;p(`${g(e)} \u{1F4AD} Thought Updated:`),Le(t);break}case "readPdfFile":{let t=e.toolCall.args.path;p(`${g(e)} \u{1F4C4} Reading PDF: ${t}`);break}case "readImageFile":{let t=e.toolCall.args.path;p(`${g(e)} \u{1F5BC}\uFE0F Reading Image: ${t}`);break}default:{p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}}else p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callInteractiveTool":{B(e),p(`${g(e)} \u{1F99C} Calling interactive tool`),p(`${g(e)} \u{1F527} Tool: ${e.toolCall.skillName}/${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "callDelegate":{B(e),p(`${g(e)} \u{1F99C} Calling delegate`),p(`${g(e)} \u{1F527} Tool: ${e.toolCall.toolName}`),p(`${g(e)} \u{1F527} Args: ${e.toolCall.args}`);break}case "resolveToolResult":{if(p(`${g(e)} \u{1F527} Resolved Tool Result`),e.toolResult.skillName==="@perstack/base")switch(e.toolResult.toolName){case "todo":{let t=e.toolResult.result.find(r=>r.type==="textPart")?.text,{todos:o}=JSON.parse(t??"{}");p(`${g(e)} \u{1F4C4} Todo:`);for(let r of o)Le(`${r.completed?"[x]":"[ ]"} ${r.id}: ${r.title}`);break}default:{p(`${g(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),p(`${g(e)} \u{1F527} Result: ${e.toolResult.result}`);break}}else p(`${g(e)} \u{1F527} Tool: ${e.toolResult.skillName}/${e.toolResult.toolName}`),p(`${g(e)} \u{1F527} Result: ${e.toolResult.result}`);break}case "resolveThought":{p(`${g(e)} \u{1F4AD} Resolved Thought:`,e.toolResult);break}case "resolvePdfFile":{p(`${g(e)} \u{1F4C4} Resolved PDF:`,e.toolResult);break}case "resolveImageFile":{p(`${g(e)} \u{1F5BC}\uFE0F Resolved Image:`,e.toolResult);break}case "attemptCompletion":{p(`${g(e)} \u2705 Attempting completion`);break}case "completeRun":{B(e),p(`${g(e)} \u{1F99C} Completing run`),p(`${g(e)} \u{1F99C} Result:`,e.text);break}case "stopRunByInteractiveTool":{p(`${g(e)} \u{1F99C} Stopping run by interactive tool`);break}case "stopRunByDelegate":{p(`${g(e)} \u{1F99C} Stopping run by delegate`);break}case "stopRunByExceededMaxSteps":{p(`${g(e)} \u{1F99C} Stopping run by exceeded max steps`);break}case "continueToNextStep":{p(`${g(e)} \u{1F99C} Continuing to next step`);break}}}function Ot(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)r.type==="textPart"?p(`${t} \u{1F4AC} User: ${r.text}`):r.type==="imageUrlPart"?p(`${t} \u{1F5BC}\uFE0F User: ${r.url}`):r.type==="imageInlinePart"?p(`${t} \u{1F5BC}\uFE0F User: Inline image`):r.type==="imageBinaryPart"?p(`${t} \u{1F5BC}\uFE0F User: Binary image`):r.type==="fileUrlPart"?p(`${t} \u{1F4C4} User: ${r.url}`):r.type==="fileInlinePart"?p(`${t} \u{1F4C4} User: Inline file`):r.type==="fileBinaryPart"&&p(`${t} \u{1F4C4} User: Binary file`);}function Bt(e){let t=new Date().toISOString(),o=e.contents;for(let r of o)if(r.type==="toolResultPart"){let{contents:a}=r;for(let c of a)c.type==="textPart"?p(`${t} \u{1F4AC} Tool Result: ${c.text}`):c.type==="imageInlinePart"&&p(`${t} \u{1F5BC}\uFE0F Tool Result: Inline image`);}}function B(e){let t=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");p(`${g(e)} \u{1F4CA} Tokens usage: ${t}`);let o=[`In: ${e.usage.promptTokens.toLocaleString()}`,`Out: ${e.usage.completionTokens.toLocaleString()}`,`Total: ${e.usage.totalTokens.toLocaleString()}`,`Cache-read: ${e.usage.cacheReadInputTokens.toLocaleString()}`,`Cache-write: ${e.usage.cacheCreationInputTokens.toLocaleString()}`].join(", ");p(`${g(e)} \u{1F4CA} Total usage: ${o}`);}var V=class{listeners=[];subscribe(t){this.listeners.push(t);}async emit(t){for(let o of this.listeners)await o({...t,id:createId(),timestamp:Date.now()});}};var Lt=z$1.object({name:z$1.string(),version:z$1.string(),minRuntimeVersion:z$1.string(),description:z$1.string(),instruction:z$1.string(),skills:z$1.record(z$1.string(),z$1.discriminatedUnion("type",[G.omit({name:true}),K.omit({name:true}),q.omit({name:true})])),delegates:z$1.array(z$1.string()),tags:z$1.array(z$1.string()),status:z$1.string(),owner:z$1.object({name:z$1.string()}),createdAt:z$1.string().datetime(),updatedAt:z$1.string().datetime()}),_e=z$1.object({data:z$1.object({expert:Lt})});var Y=class{baseUrl;registry;apiKey;constructor(t){this.baseUrl=t?.baseUrl??process.env.PERSTACK_API_BASE_URL??"https://api.perstack.ai",this.apiKey=t?.apiKey??process.env.PERSTACK_API_KEY,this.registry=new ae(this);}},ae=class{client;endpoint;constructor(t){this.client=t,this.endpoint="/api/registry/v1/experts";}async get(t){let o=encodeURIComponent(t),r=new URL(`${this.endpoint}/${o}`,this.client.baseUrl),a={"Content-Type":"application/json",Authorization:`Bearer ${this.client.apiKey}`},c=await fetch(r.toString(),{headers:a});if(!c.ok)throw new Error(`Registry returned non-200 status code: ${c.status}, reason: ${c.statusText}`);let m=await c.json();return _e.parse(m)}};async function ie(e,t){if(t[e])return t[e];let o=new Y,{data:r}=await o.registry.get(e),a=J.parse({...r.expert,key:e});return t[e]=a,a}var z=class{_toolDefinitions=[];_initialized=false;name;type;skill;interactiveSkill;expert;_mcpClient;_params;constructor(t){switch(this._params=t,this.type=t.type,t.type){case "mcp":this.name=t.skill.name,this.skill=t.skill;break;case "interactive":this.name=t.interactiveSkill.name,this.interactiveSkill=t.interactiveSkill;break;case "delegate":this.name=t.expert.name,this.expert=t.expert;break}}async init(){switch(this._params.type){case "mcp":{await this._initMcpSkill(this._params);break}case "interactive":{await this._initInteractiveSkill(this._params);break}case "delegate":{await this._initDelegate(this._params);break}}}async _initMcpSkill(t){switch(this._mcpClient=new Client({name:`${t.skill.name}-mcp-client`,version:"1.0.0"}),t.skill.type){case "mcpStdioSkill":{if(!t.skill.command)throw new Error(`Skill ${t.skill.name} has no command`);let{command:r,args:a,requiredEnv:c}=t.skill,m=new StdioClientTransport({command:r,args:a,env:Object.fromEntries(Object.entries(process.env).filter(([s,u])=>u!==void 0&&u!=="").map(([s,u])=>[s,u]))});await this._mcpClient.connect(m);break}case "mcpSseSkill":{if(!t.skill.endpoint)throw new Error(`Skill ${t.skill.name} has no endpoint`);let r=new SSEClientTransport(new URL(t.skill.endpoint));await this._mcpClient.connect(r);break}}let{tools:o}=await this._mcpClient.listTools();this._toolDefinitions=o.map(r=>({skillName:t.skill.name,name:r.name,description:r.description,inputSchema:r.inputSchema,interactive:false})),this._initialized=true;}async _initInteractiveSkill(t){this._toolDefinitions=Object.values(t.interactiveSkill.tools).map(o=>({skillName:t.interactiveSkill.name,name:o.name,description:o.description,inputSchema:JSON.parse(o.inputJsonSchema),interactive:true})),this._initialized=true;}async _initDelegate(t){this._toolDefinitions=[{skillName:t.expert.name,name:t.expert.name.split("/").pop()??t.expert.name,description:t.expert.description,inputSchema:{type:"object",properties:{query:{type:"string"}},required:["query"]},interactive:false}],this._initialized=true;}async close(){this._mcpClient&&await this._mcpClient.close();}async getToolDefinitions(){if(!this._initialized)throw new Error(`${this.name} is not initialized`);if(this._params.type==="mcp"){let t=this._params.skill.omit??[],o=this._params.skill.pick??[];return this._toolDefinitions.filter(r=>t.length>0?!t.includes(r.name):true).filter(r=>o.length>0?o.includes(r.name):true)}return this._toolDefinitions}async callTool(t,o){switch(this._params.type){case "mcp":{if(!this._mcpClient)throw new Error(`${this.name} is not initialized`);try{let r=await this._mcpClient.callTool({name:t,arguments:o});return this._convertToolResult(r,t,o)}catch(r){return this._handleToolError(r,t)}}case "interactive":return [];case "delegate":return []}}_handleToolError(t,o){if(t instanceof McpError)return [{type:"textPart",text:`Error calling tool ${o}: ${t.message}`,id:createId()}];if(t instanceof ZodError)return [{type:"textPart",text:`Invalid tool call arguments: ${t}`,id:createId()}];throw t}_convertToolResult(t,o,r){return !t.content||t.content.length===0?[{type:"textPart",text:`Tool ${o} returned nothing with arguments: ${JSON.stringify(r)}`,id:createId()}]:t.content.filter(a=>a.type!=="audio"&&a.type!=="resource_link").map(a=>this._convertPart(a))}_convertPart(t){switch(t.type){case "text":return !t.text||t.text===""?{type:"textPart",text:"Error: No content",id:createId()}:{type:"textPart",text:t.text,id:createId()};case "image":if(!t.data||!t.mimeType)throw new Error("Image part must have both data and mimeType");return {type:"imageInlinePart",encodedData:t.data,mimeType:t.mimeType,id:createId()};case "resource":if(!t.resource)throw new Error("Resource part must have resource content");return this._convertResource(t.resource)}}_convertResource(t){if(!t.mimeType)throw new Error(`Resource ${JSON.stringify(t)} has no mimeType`);if(t.text&&typeof t.text=="string")return {type:"textPart",text:t.text,id:createId()};if(t.blob&&typeof t.blob=="string")return {type:"fileInlinePart",encodedData:t.blob,mimeType:t.mimeType,id:createId()};throw new Error(`Unsupported resource type: ${JSON.stringify(t)}`)}};async function Ae(e,t){let o={},{skills:r}=e;r["@perstack/base"]||(r["@perstack/base"]={type:"mcpStdioSkill",name:"@perstack/base",description:"The base skill for Perstack",pick:[],omit:[],command:"npx",args:["-y","@perstack/base"],requiredEnv:[]});let a=await Promise.all(Object.values(r).filter(s=>s.type==="mcpStdioSkill"||s.type==="mcpSseSkill").map(async s=>{let u=new z({type:"mcp",skill:s});return await u.init(),u})),c=await Promise.all(Object.values(r).filter(s=>s.type==="interactiveSkill").map(async s=>{let u=new z({type:"interactive",interactiveSkill:s});return await u.init(),u})),m=await Promise.all(e.delegates.map(async s=>{let u=t[s],h=new z({type:"delegate",expert:u});return await h.init(),h}));for(let s of a)o[s.name]=s;for(let s of c)o[s.name]=s;for(let s of m)o[s.name]=s;return o}async function Ge(e){for(let t of Object.values(e))await t.close();}async function N(e,t){for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)if(a.name===t)return o}throw new Error(`Tool ${t} not found`)}async function Ke(e){let t={};for(let o of Object.values(e)){let r=await o.getToolDefinitions();for(let a of r)t[a.name]={description:a.description,parameters:jsonSchema(a.inputSchema)};}return t}async function qe({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,toolName:c,args:m}=o.toolCall,s=await N(r,c);if(!s||!s.expert)throw new Error(`Delegation error: skill manager "${c}" not found`);if(!m||!m.query||typeof m.query!="string")throw new Error("Delegation error: query is undefined");return $e(e,t,{checkpoint:{...t,status:"stoppedByDelegate",delegateTo:{expert:{key:s.expert.key,name:s.expert.name,version:s.expert.version},toolCallId:a,toolName:c,query:m.query}},step:{...o,finishedAt:new Date().getTime()}})}async function Je({setting:e,checkpoint:t,step:o}){return Ee(e,t,{checkpoint:{...t,status:"stoppedByInteractiveTool"},step:{...o,finishedAt:new Date().getTime()}})}async function Ve({setting:e,checkpoint:t,step:o,skillManagers:r}){if(!o?.toolCall)throw new Error("No tool call found");let{id:a,skillName:c,toolName:m,args:s}=o.toolCall,u=await N(r,m);if(u.type!=="mcp")throw new Error(`Incorrect SkillType, required MCP, got ${u.type}`);let h=await u.callTool(m,s),d={id:a,skillName:c,toolName:m,result:h};if(c==="@perstack/base"){if(m==="think")return Ce(e,t,{toolResult:d});if(m==="attemptCompletion")return Me(e,t,{toolResult:d});if(m==="readPdfFile")return we(e,t,{toolResult:d});if(m==="readImageFile")return Ie(e,t,{toolResult:d})}return ve(e,t,{toolResult:d})}async function Ye({setting:e,checkpoint:t,step:o}){return e.maxSteps!==void 0&&t.stepNumber>e.maxSteps?Ne(e,t,{checkpoint:{...t,status:"stoppedByExceededMaxSteps"},step:{...o,finishedAt:new Date().getTime()}}):Fe(e,t,{checkpoint:{...t},step:{...o,finishedAt:new Date().getTime()},nextCheckpoint:{...t,id:createId(),stepNumber:t.stepNumber+1}})}function F(e){return {type:"userMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function U(e){return {type:"expertMessage",contents:e.map(t=>({...t,id:createId()})),id:createId()}}function v(e){return {type:"toolMessage",contents:e.map(t=>({...t,contents:t.contents.map(o=>({...o,id:createId()})),id:createId()})),id:createId()}}function W(e){switch(e.type){case "instructionMessage":return {role:"system",content:Wt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "userMessage":return {role:"user",content:Ht(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "expertMessage":return {role:"assistant",content:Qt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0};case "toolMessage":return {role:"tool",content:Zt(e.contents),providerOptions:e.cache?{anthropic:{cacheControl:{type:"ephemeral"}}}:void 0}}}function Wt(e){return e.reduce((t,o)=>dedent`
|
|
2
2
|
${t}
|
|
3
3
|
${o.text}
|
|
4
4
|
`.trim(),"")}function Ht(e){return e.map(t=>{switch(t.type){case "textPart":return We(t);case "imageUrlPart":return Xt(t);case "imageInlinePart":return eo(t);case "imageBinaryPart":return to(t);case "fileUrlPart":return oo(t);case "fileInlinePart":return no(t);case "fileBinaryPart":return ro(t)}})}function Qt(e){return e.map(t=>{switch(t.type){case "textPart":return We(t);case "toolCallPart":return so(t)}})}function Zt(e){return e.map(t=>{switch(t.type){case "toolResultPart":return ao(t)}})}function We(e){return {type:"text",text:e.text}}function Xt(e){return {type:"image",image:e.url,mimeType:e.mimeType}}function eo(e){return {type:"image",image:e.encodedData,mimeType:e.mimeType}}function to(e){return {type:"image",image:e.data,mimeType:e.mimeType}}function oo(e){return {type:"file",data:e.url,mimeType:e.mimeType}}function no(e){return {type:"file",data:e.encodedData,mimeType:e.mimeType}}function ro(e){return {type:"file",data:e.data,mimeType:e.mimeType}}function so(e){return {type:"tool-call",toolCallId:e.toolCallId,toolName:e.toolName,args:e.args}}function ao(e){return {type:"tool-result",toolCallId:e.toolCallId,toolName:e.toolName,result:e.contents,experimental_content:e.contents.map(t=>{switch(t.type){case "textPart":return {type:"text",text:t.text};case "imageInlinePart":return {type:"image",data:t.encodedData,mimeType:t.mimeType}}}),isError:e.isError}}function H(){return {promptTokens:0,completionTokens:0,totalTokens:0,cacheCreationInputTokens:0,cacheReadInputTokens:0}}function Q(e){let t=0,o=0;if(e.providerMetadata?.anthropic){let r=e.providerMetadata.anthropic;t=r.cacheCreationInputTokens||0,o=r.cacheReadInputTokens||0;}return {promptTokens:e.usage.promptTokens,completionTokens:e.usage.completionTokens,totalTokens:e.usage.totalTokens,cacheCreationInputTokens:t,cacheReadInputTokens:o}}function C(e,t){return {promptTokens:e.promptTokens+t.promptTokens,completionTokens:e.completionTokens+t.completionTokens,totalTokens:e.totalTokens+t.totalTokens,cacheCreationInputTokens:e.cacheCreationInputTokens+t.cacheCreationInputTokens,cacheReadInputTokens:e.cacheReadInputTokens+t.cacheReadInputTokens}}async function He({setting:e,checkpoint:t,step:o}){if(!o?.toolCall||!o?.toolResult)throw new Error("No tool call or tool result found");let{id:r,toolName:a}=o.toolCall,{result:c}=o.toolResult,m=v([{type:"toolResultPart",toolCallId:r,toolName:a,contents:c.filter(f=>f.type==="textPart"||f.type==="imageInlinePart")}]),s=L(e.model),{messages:u}=t,h=await generateText({model:s,messages:[...u,m].map(W),temperature:e.temperature,maxRetries:e.maxRetries}),d=Q(h),{text:P}=h,R=[m,U(P?[{type:"textPart",text:P}]:[])];return be(e,t,{checkpoint:{...t,messages:[...u,...R],usage:C(t.usage,d),status:"completed"},step:{...o,newMessages:[...o.newMessages,...R],finishedAt:new Date().getTime(),usage:C(o.usage,d)},text:P,usage:d})}async function Qe({setting:e,checkpoint:t,skillManagers:o}){let{messages:r}=t,a=L(e.model),c=await generateText({model:a,messages:r.map(W),temperature:e.temperature,maxRetries:e.maxRetries,tools:await Ke(o),toolChoice:"required"}),m=Q(c),{text:s,toolCalls:u,finishReason:h}=c,d=u[0];if(!d)return re(e,t,{newMessages:[U(s?[{type:"textPart",text:s}]:[]),F([{type:"textPart",text:"You must generate a tool call. Try again."}])],usage:m});if(h!=="tool-calls")switch(h){case "length":return re(e,t,{newMessages:[U([{type:"toolCallPart",toolCallId:d.toolCallId,toolName:d.toolName,args:d.args}]),v([{type:"toolResultPart",toolCallId:d.toolCallId,toolName:d.toolName,contents:[{type:"textPart",text:"Error: Generation length exceeded"}]}])],usage:m});default:throw new Error(`Unexpected finish reason: ${h}`)}let P=[{type:"toolCallPart",toolCallId:d.toolCallId,toolName:d.toolName,args:d.args}];s&&P.push({type:"textPart",text:s});let R=await N(o,d.toolName),f={newMessage:U(P),toolCall:{id:d.toolCallId,skillName:R.name,toolName:d.toolName,args:d.args},usage:m};switch(R.type){case "mcp":return Re(e,t,f);case "interactive":return Se(e,t,f);case "delegate":return Pe(e,t,f)}}var po=dedent`
|