goatchain 0.0.2
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/README.md +526 -0
- package/dist/index.d.ts +3328 -0
- package/dist/index.js +181 -0
- package/package.json +65 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";import{randomUUID as t}from"node:crypto";import{existsSync as n,mkdirSync as r,readFileSync as i,readdirSync as a,rmSync as o,writeFileSync as s}from"node:fs";import c from"node:path";import l from"openai";import{spawn as u}from"node:child_process";import d from"node:process";import{mkdir as f,readFile as p,readdir as m,stat as h,writeFile as g}from"node:fs/promises";function _(e,t){let n=t?.phase;n||=e.shouldContinue?e.pendingToolCalls.length>0?`tool_execution`:`llm_call`:`completed`;let r=t?.status;return r||=n===`completed`?`Completed: ${e.stopReason??`unknown`}`:n===`tool_execution`?`Executing tools: ${e.pendingToolCalls.map(e=>e.toolCall.function.name).join(`, `)}`:n===`approval_pending`?`Waiting for user approval`:`Iteration ${e.iteration}: Calling LLM`,{sessionId:e.sessionId,agentId:e.agentId,agentName:t?.agentName,iteration:e.iteration,phase:n,status:r,modelConfig:t?.modelConfig,requestParams:t?.requestParams,messages:[...e.messages],pendingToolCalls:e.pendingToolCalls.map(e=>({toolCall:{...e.toolCall},result:e.result,isError:e.isError})),currentResponse:e.currentResponse,currentThinking:e.currentThinking,shouldContinue:e.shouldContinue,stopReason:e.stopReason,lastModelStopReason:e.lastModelStopReason,usage:{...e.usage},metadata:{...e.metadata},savedAt:Date.now()}}function v(e){return{sessionId:e.sessionId,agentId:e.agentId,iteration:e.iteration,messages:[...e.messages],pendingToolCalls:e.pendingToolCalls.map(e=>({toolCall:{...e.toolCall},result:e.result,isError:e.isError})),currentResponse:e.currentResponse,currentThinking:e.currentThinking,shouldContinue:e.shouldContinue,stopReason:e.stopReason,lastModelStopReason:e.lastModelStopReason,usage:{...e.usage},metadata:{...e.metadata}}}let y;function b(){if(y!==void 0)return y;try{let t=e(import.meta.url)(`tiktoken`);return y=t,t}catch{return y=null,null}}function x(e,t){if(!e)return 0;let n=b();if(!n)return Math.ceil(e.length/4);let r=null;try{return r=t?n.encoding_for_model(t):n.encoding_for_model(`gpt-4o`),r.encode(e).length}catch(t){console.error(`Error encoding text:`,t);try{return r=n.get_encoding(`cl100k_base`),r.encode(e).length}catch{return Math.ceil(e.length/4)}}finally{r?.free()}}function S(e,t){return typeof e==`string`?x(e,t):Array.isArray(e)?e.reduce((e,n)=>typeof n==`object`&&n&&`text`in n?e+x(String(n.text),t):e,0):0}function C(e,t){try{return x(JSON.stringify(e),t)}catch{return ee(e,t)}}function ee(e,t){let n=4;if(n+=S(e.content,t),e.role===`assistant`&&e.tool_calls)for(let r of e.tool_calls){n+=x(r.function.name,t);let e=typeof r.function.arguments==`string`?r.function.arguments:JSON.stringify(r.function.arguments);n+=x(e,t),n+=10}return e.role===`tool`&&e.name&&(n+=x(e.name,t)),e.role===`assistant`&&e.reasoning_content&&(n+=x(e.reasoning_content,t)),n}function w(e,t){if(!e||e.length===0)return 0;try{return x(JSON.stringify(e),t)}catch{return e.reduce((e,n)=>e+C(n,t),3)}}const T={CHECKPOINT:`checkpoint`,COMPRESSION:`compression`,SESSION:`session`,COMPRESSION_SNAPSHOT:`compression-snapshot`},E=`You are Claude Code, Anthropic's official CLI for Claude.
|
|
2
|
+
|
|
3
|
+
You are a helpful AI assistant tasked with summarizing conversations.
|
|
4
|
+
|
|
5
|
+
Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
6
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
7
|
+
|
|
8
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
9
|
+
|
|
10
|
+
1. Chronologically analyze each message and section of the conversation. For each section thoroughly identify:
|
|
11
|
+
- The user's explicit requests and intents
|
|
12
|
+
- Your approach to addressing the user's requests
|
|
13
|
+
- Key decisions, technical concepts and code patterns
|
|
14
|
+
- Specific details like:
|
|
15
|
+
- file names
|
|
16
|
+
- full code snippets
|
|
17
|
+
- function signatures
|
|
18
|
+
- file edits
|
|
19
|
+
- Errors that you ran into and how you fixed them
|
|
20
|
+
- Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
21
|
+
2. Double-check for technical accuracy and completeness, addressing each required element thoroughly.
|
|
22
|
+
|
|
23
|
+
Your summary should include the following sections:
|
|
24
|
+
|
|
25
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
26
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed.
|
|
27
|
+
3. Files and Code Sections: Enumerate specific files and code sections examined, modified, or created. Pay special attention to the most recent messages and include full code snippets where applicable and include a summary of why this file read or edit is important.
|
|
28
|
+
4. Errors and fixes: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received, especially if the user told you to do something differently.
|
|
29
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting efforts.
|
|
30
|
+
6. All user messages: List ALL user messages that are not tool results. These are critical for understanding the users' feedback and changing intent.
|
|
31
|
+
6. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on.
|
|
32
|
+
7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable.
|
|
33
|
+
8. Optional Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's most recent explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests or really old requests that were already completed without confirming with the user first.
|
|
34
|
+
If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation.
|
|
35
|
+
|
|
36
|
+
Here's an example of how your output should be structured:
|
|
37
|
+
|
|
38
|
+
<example>
|
|
39
|
+
<analysis>
|
|
40
|
+
[Your thought process, ensuring all points are covered thoroughly and accurately]
|
|
41
|
+
</analysis>
|
|
42
|
+
|
|
43
|
+
<summary>
|
|
44
|
+
1. Primary Request and Intent:
|
|
45
|
+
[Detailed description]
|
|
46
|
+
|
|
47
|
+
2. Key Technical Concepts:
|
|
48
|
+
- [Concept 1]
|
|
49
|
+
- [Concept 2]
|
|
50
|
+
- [...]
|
|
51
|
+
|
|
52
|
+
3. Files and Code Sections:
|
|
53
|
+
- [File Name 1]
|
|
54
|
+
- [Summary of why this file is important]
|
|
55
|
+
- [Summary of the changes made to this file, if any]
|
|
56
|
+
- [Important Code Snippet]
|
|
57
|
+
- [File Name 2]
|
|
58
|
+
- [Important Code Snippet]
|
|
59
|
+
- [...]
|
|
60
|
+
|
|
61
|
+
4. Errors and fixes:
|
|
62
|
+
- [Detailed description of error 1]:
|
|
63
|
+
- [How you fixed the error]
|
|
64
|
+
- [User feedback on the error if any]
|
|
65
|
+
- [...]
|
|
66
|
+
|
|
67
|
+
5. Problem Solving:
|
|
68
|
+
[Description of solved problems and ongoing troubleshooting]
|
|
69
|
+
|
|
70
|
+
6. All user messages:
|
|
71
|
+
- [Detailed non tool use user message]
|
|
72
|
+
- [...]
|
|
73
|
+
|
|
74
|
+
7. Pending Tasks:
|
|
75
|
+
- [Task 1]
|
|
76
|
+
- [Task 2]
|
|
77
|
+
- [...]
|
|
78
|
+
|
|
79
|
+
8. Current Work:
|
|
80
|
+
[Precise description of current work]
|
|
81
|
+
|
|
82
|
+
9. Optional Next Step:
|
|
83
|
+
[Optional Next step to take]
|
|
84
|
+
|
|
85
|
+
</summary>
|
|
86
|
+
</example>
|
|
87
|
+
|
|
88
|
+
Please provide your summary based on the conversation so far, following this structure and ensuring precision and thoroughness in your response.
|
|
89
|
+
|
|
90
|
+
There may be additional summarization instructions provided in the included context. If so, remember to follow these instructions when creating the above summary. Examples of instructions include:
|
|
91
|
+
<example>
|
|
92
|
+
## Compact Instructions
|
|
93
|
+
When summarizing the conversation focus on typescript code changes and also remember the mistakes you made and how you fixed them.
|
|
94
|
+
</example>
|
|
95
|
+
|
|
96
|
+
<example>
|
|
97
|
+
# Summary instructions
|
|
98
|
+
When you are using compact - please focus on test output and code changes. Include file reads verbatim.
|
|
99
|
+
</example>
|
|
100
|
+
|
|
101
|
+
Existing summary (may be empty):
|
|
102
|
+
{{existingSummary}}
|
|
103
|
+
|
|
104
|
+
Messages to summarize:
|
|
105
|
+
{{toolOutputs}}
|
|
106
|
+
`;function te(e){let{contextLimit:t,outputLimit:n,protectedTurns:r=2,protectedToolTokens:i=4e4,trimToolOutputThreshold:a=2e4,enableSummary:o=!1,model:s,getModel:c,summaryPrompt:l=E,stateStore:u,getStateStore:d,persistClearedContent:f=!1,onCompressionStart:p,onCompressionEnd:m}=e;if(o&&!s&&!c)throw Error(`ContextCompressionMiddleware: "model" or "getModel" required when enableSummary is true`);let h=t-n;return async(e,t)=>{let n=u??d?.(),g;n&&(g=await n.load(e.sessionId,T.COMPRESSION));let _=e.messages;if(g?.summary&&!_.some(e=>e.role===`user`&&typeof e.content==`string`&&e.content.startsWith(`[Context from cleared tool outputs]`))){let e=_.findIndex(e=>e.role===`system`),t=e>=0?e+1:0;_=[..._.slice(0,t),{role:`user`,content:`[Context from cleared tool outputs]\n${g.summary}`},..._.slice(t)]}if(w(_)>h){let u=o?s??c?.():void 0,{compressedMessages:d,stats:v,summary:y}=await ne(_,{protectedTurns:r,protectedToolTokens:i,trimToolOutputThreshold:a,targetTokens:h,enableSummary:o,summaryPrompt:l},u,g?.summary,p,m),b={...e,messages:d,metadata:{...e.metadata,lastCompression:v}};if(n){let t=Date.now(),r={lastStats:v,history:[...g?.history??[],v],summary:y,updatedAt:t};if(await n.save(e.sessionId,T.COMPRESSION,r),f){let r={messages:d.map(e=>({role:e.role,content:e.content,tool_call_id:e.tool_call_id,name:e.name,tool_calls:`tool_calls`in e?e.tool_calls:void 0})),stats:v,timestamp:t},i=`${T.COMPRESSION_SNAPSHOT}-${t}`;await n.save(e.sessionId,i,r)}}return t(b)}return _===e.messages?t(e):t({...e,messages:_})}}async function ne(e,t,n,r,i,a){let{protectedTurns:o,protectedToolTokens:s,trimToolOutputThreshold:c,enableSummary:l,summaryPrompt:u}=t,d=w(e),{protectedToolIds:f,unprotectedToolMessages:p}=ie(e,re(e,o),s),m={tokensBefore:d,tokensAfter:0,clearedToolOutputs:p.length,trimmedToolOutputs:0,summaryGenerated:!1,timestamp:Date.now()};i?.(m);let h=[],g=0,_=e.map(e=>{if(e.role===`tool`){let t=e;if(f.has(t.tool_call_id)){if(S(t.content)>c)return g++,ae(t,c)}else{let e=typeof t.content==`string`?t.content:JSON.stringify(t.content);return h.push({name:t.name,content:e}),{...t,content:`[Old tool result content cleared]`}}}return e}),v=r;if(l&&n&&h.length>0){let e=(await k(h,n,u,r)).trim();if(e.length>0){v=e;let t=_.findIndex(e=>e.role===`user`&&typeof e.content==`string`&&e.content.startsWith(`[Context from cleared tool outputs]`));t>=0&&_.splice(t,1);let n=_.findIndex(e=>e.role===`system`),r=n>=0?n+1:0;_.splice(r,0,{role:`user`,content:`[Context from cleared tool outputs]\n${v}`})}}let y=D(_),b=w(y);if(l&&v&&b>t.targetTokens){let e=_.findIndex(e=>e.role===`user`&&typeof e.content==`string`&&e.content.startsWith(`[Context from cleared tool outputs]`));if(e>=0){let n=_[e],r=typeof n.content==`string`?n.content:``,i=S(r),a=b-t.targetTokens;if(i>a){let t=Math.max(100,i-a-100)*4,o=r.slice(0,t-43)+`
|
|
107
|
+
|
|
108
|
+
[... summary truncated due to length ...]`;_[e]={...n,content:o}}}}y=D(_);let x=w(y);t.targetTokens;let C={tokensBefore:d,tokensAfter:x,clearedToolOutputs:h.length,trimmedToolOutputs:g,summaryGenerated:l&&h.length>0,timestamp:Date.now()};return a?.(C),{compressedMessages:y,stats:C,summary:v,clearedContents:h}}function re(e,t){if(t<=0)return e.length;let n=0;for(let r=e.length-1;r>=0;r--)if(e[r].role===`user`&&(n++,n>=t))return r;return 0}function ie(e,t,n){let r=new Set,i=[];for(let n=t;n<e.length;n++){let t=e[n];t.role===`tool`&&r.add(t.tool_call_id)}let a=0;for(let i=t-1;i>=0;i--){let t=e[i];if(t.role===`tool`){let e=t,i=S(e.content);a+i<=n&&(r.add(e.tool_call_id),a+=i)}}for(let n=0;n<t;n++){let t=e[n];if(t.role===`tool`){let e=t;r.has(e.tool_call_id)||i.push(e)}}return{protectedToolIds:r,unprotectedToolMessages:i}}function ae(e,t){let n=typeof e.content==`string`?e.content:JSON.stringify(e.content),r=t*4;if(n.length<=r)return e;let i=n.slice(0,r-43)+`
|
|
109
|
+
|
|
110
|
+
[... content truncated due to length ...]`;return{...e,content:i}}function D(e){let t=[],n=e=>e.role===`user`?(typeof e.content==`string`?e.content:``).startsWith(`[Context from cleared tool outputs]`):!1;for(let r of e){if(r.role!==`user`){t.push(r);continue}if(n(r)){t.push(r);continue}let e=t[t.length-1];if(e&&e.role===`user`){if(n(e)){t.push(r);continue}if(e.name===r.name){t[t.length-1]={...e,content:oe(e.content,r.content)};continue}}t.push(r)}return t}function oe(e,t){return[...O(e),...O(t)]}function O(e){if(typeof e==`string`)return e.trim().length>0?[{type:`text`,text:e}]:[];if(Array.isArray(e)){let t=[],n=e;for(let e of n){if(typeof e==`string`){let n=e.trim();n.length>0&&t.push({type:`text`,text:n});continue}if(e&&typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`){let e=n.text;if(typeof e==`string`&&e.trim().length===0)continue}t.push(n);continue}if(e!=null){let n=String(e);n.trim().length>0&&t.push({type:`text`,text:n})}}return t}if(e&&typeof e==`object`&&`type`in e){let t=e;if(t.type===`text`){let e=t.text;if(typeof e==`string`&&e.trim().length===0)return[]}return[t]}let t=String(e);return t.trim().length>0?[{type:`text`,text:t}]:[]}async function k(e,t,n,r){let i=se(n,e.map(({name:e,content:t})=>`## ${e??`unknown_tool`}\n${t.length>5e3?`${t.slice(0,5e3)}...[truncated for summary]`:t}`).join(`
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
`),r),a=await t.invoke([{role:`system`,content:`You are a helpful assistant that creates concise summaries.`},{role:`user`,content:i}],{maxTokens:1e3});return typeof a.message.content==`string`?a.message.content:JSON.stringify(a.message.content)}function se(e,t,n){let r=e.includes(`{{toolOutputs}}`),i=e.includes(`{{existingSummary}}`),a=n??``;return r||i?e.split(`{{toolOutputs}}`).join(t).split(`{{existingSummary}}`).join(a):`${e}\n\n${a.length>0?`Existing summary:\n${a}\n\nTool outputs to summarize:\n${t}`:`Tool outputs to summarize:\n${t}`}`}async function ce(e){let{sessionId:t,fullMessages:n,model:r,stateStore:i,summaryPrompt:a=E}=e,o=[];for(let e of n)if(e.role===`tool`){let t=e,n=typeof t.content==`string`?t.content:JSON.stringify(t.content);o.push({name:t.name,content:n})}let s=o;if(o.length===0){let e=[];for(let t of n)if(t.role===`user`||t.role===`assistant`){let n;n=typeof t.content==`string`?t.content:Array.isArray(t.content)?t.content.map(e=>e.type===`text`?e.text:e.type===`image`?`[Image]`:`[Other content]`).join(`
|
|
115
|
+
`):JSON.stringify(t.content),e.push({name:t.role===`user`?`user_message`:`assistant_message`,content:`${t.role===`user`?`User`:`Assistant`}: ${n}`})}if(e.length===0)return{summary:``,messageCount:n.length,toolOutputCount:0};s=e}let c=(await k(s,r,a,void 0)).trim();if(c.length===0)return{summary:``,messageCount:n.length,toolOutputCount:o.length};let l=await i.load(t,T.COMPRESSION),u=Date.now(),d={lastStats:l?.lastStats,history:l?.history??[],summary:c,updatedAt:u};return await i.save(t,T.COMPRESSION,d),{summary:c,messageCount:n.length,toolOutputCount:o.length}}var A=class{setModelOverride(e){this.configOverride||={},this.configOverride.model=e,this.updatedAt=Date.now()}clearModelOverride(){this.configOverride&&(delete this.configOverride.model,this.updatedAt=Date.now())}setSystemPromptOverride(e){this.configOverride||={},this.configOverride.systemPromptOverride=e,this.updatedAt=Date.now()}clearSystemPromptOverride(){this.configOverride&&(delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now())}disableTools(e){this.configOverride||={},this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...e],this.updatedAt=Date.now()}enableAllTools(){this.configOverride&&(delete this.configOverride.disabledTools,this.updatedAt=Date.now())}setStatus(e,t){this.status=e,this.errorMessage=t,this.updatedAt=Date.now()}markActive(){this.lastActiveAt=Date.now(),this.updatedAt=Date.now()}addMessage(e){this.messages.push(e),this.markActive()}getLastMessagePreview(e=100){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1],n=typeof t.content==`string`?t.content:JSON.stringify(t.content);return n.length>e?`${n.substring(0,e)}...`:n}addUsage(e){this.usage.promptTokens+=e.promptTokens,this.usage.completionTokens+=e.completionTokens,this.usage.totalTokens+=e.totalTokens,this.updatedAt=Date.now()}recordResponse(e){let t=(this.avgResponseTime??0)*this.responseCount;this.responseCount++,this.avgResponseTime=(t+e)/this.responseCount,this.updatedAt=Date.now()}incrementToolCallCount(){this.toolCallCount++,this.updatedAt=Date.now()}toSnapshot(){let e={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},t={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},n={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:e,configOverride:this.configOverride?{...this.configOverride}:void 0,context:t,stats:n}}restoreFromSnapshot(e){this.status=e.state.status,this.updatedAt=e.state.updatedAt,this.lastActiveAt=e.state.lastActiveAt,this.title=e.state.title,this.errorMessage=e.state.errorMessage,this.configOverride=e.configOverride?{...e.configOverride}:void 0,this.messages=[...e.context.messages],this.toolCallCount=e.context.toolCallCount,this.usage={...e.stats.usage},this.responseCount=e.stats.responseCount,this.avgResponseTime=e.stats.avgResponseTime}},le=class{},j=class extends Error{constructor(e=`Agent execution aborted`){super(e),this.name=`AgentAbortError`}},ue=class extends Error{iterations;constructor(e,t){super(t??`Agent exceeded maximum iterations (${e})`),this.name=`AgentMaxIterationsError`,this.iterations=e}},M=class extends Error{constructor(e=`Agent execution paused`){super(e),this.name=`AgentPauseError`}};function N(e,t){if(!e?.aborted)return;let n=e?.reason;throw n instanceof Error?n:new j(typeof n==`string`?n:t?`${t} aborted`:`Agent execution aborted`)}var de=class{},P=class{hooks;constructor(e){this.hooks=e??{}}async executePreToolUse(e){let t=this.hooks.preToolUse;if(!t||t.length===0)return{allow:!0};let n=e.toolCall;for(let r of t){let t=await r({...e,toolCall:n});if(!t.allow)return{allow:!1,modifiedToolCall:t.modifiedToolCall};t.modifiedToolCall&&(n=t.modifiedToolCall)}return n===e.toolCall?{allow:!0}:{allow:!0,modifiedToolCall:n}}async executePostToolUse(e,t){let n=this.hooks.postToolUse;if(!(!n||n.length===0))for(let r of n)await r(e,t)}async executePostToolUseFailure(e,t){let n=this.hooks.postToolUseFailure;if(!(!n||n.length===0))for(let r of n)await r(e,t)}};function F(e){return(t,n)=>{let r=-1,i=async(t,a)=>{if(t<=r)throw Error(`next() called multiple times`);if(r=t,t===e.length)return n?await n(a):a;let o=e[t];return o(a,e=>i(t+1,e))};return i(0,t)}}function I(e,t,n){let r=[{role:`system`,content:n},...e.messages??[],{role:`user`,content:e.input}];return{sessionId:e.sessionId??``,agentId:t,messages:r,iteration:0,pendingToolCalls:[],currentResponse:``,shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}var L=class e extends A{id;agentId;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;_autoSave;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_hasCheckpoint;_checkpointRestored=!1;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;constructor(e,t,n,r){if(super(),this._stateStore=e,this.id=t,n)this.createdAt=n.createdAt,this.restoreFromSnapshot(n);else{let e=Date.now();this.createdAt=e,this.status=`active`,this.updatedAt=e,this.lastActiveAt=e,this.messages=[],this.toolCallCount=0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._modelClient=r?.modelClient,this._tools=r?.tools,this._middlewares=r?.middlewares??[],this._systemPrompt=r?.systemPrompt,this._agentName=r?.agentName,this._onUsage=r?.onUsage,this._hasCheckpoint=r?.hasCheckpoint??!1,this._hooks=r?.hooks,this._modelOverride=r?.model,this._maxIterations=r?.maxIterations,this._requestParams=r?.requestParams}get hasCheckpoint(){return this._hasCheckpoint}send(e,t){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error(`Cannot send while receiving messages`);this._pendingInput={input:e,options:t}}async*receive(){if(this._isReceiving)throw Error(`Cannot receive concurrently`);this._isReceiving=!0;try{if(this._hasCheckpoint&&!this._checkpointRestored&&(yield*this._stream(void 0,this._pendingInput?.options),!this._pendingInput))return;if(this._pendingInput){let{input:e,options:t}=this._pendingInput;this._pendingInput=null,yield*this._stream(e,t)}}finally{this._isReceiving=!1}}resolveModelRef(e){if(e.provider)return{provider:e.provider,modelId:e.modelId};let t=(this._modelClient?.modelRefs??[]).find(t=>t.modelId===e.modelId);if(t)return t;let n=this._modelClient?.modelRef?.provider;if(n)return{provider:n,modelId:e.modelId}}getRuntimeModelOverride(){if(this.configOverride?.model){let e=this.resolveModelRef(this.configOverride.model);if(e)return e}return this._modelOverride}async*_stream(e,t){this._ensureRuntimeConfigured(e!==void 0);let n=Date.now(),r=this.getRuntimeModelOverride(),i;if(this._hasCheckpoint&&!this._checkpointRestored){let e=await this._stateStore.loadCheckpoint(this.id);if(!e)throw Error(`Checkpoint not found for sessionId: ${this.id}`);i=v(e),i.sessionId!==this.id&&(i.sessionId=this.id);let a=this._requestParams??e.requestParams;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,n),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(e===void 0)throw Error(`Input is required to stream`);let a=this.messages.filter(e=>e.role!==`system`);i=I({sessionId:this.id,input:e,messages:a},this.agentId,this._systemPrompt??``),yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:this._requestParams}),await this._finalizeRun(i,n)}_ensureRuntimeConfigured(e){if(!this._modelClient)throw Error(`Session is not configured with a model client`);if(e&&!this._systemPrompt)throw Error(`Session is not configured with a system prompt`)}_recordUsage(e){this._onUsage&&this._onUsage(e)}async executeModelStream(e,t,n,r,i){if(!this._modelClient)throw Error(`Session is not configured with a model client`);let a=[],o=e.sessionId,s=new Map,c=!1,l=!1,u=e=>{let t=s.get(e);if(t)return t;let n={argsText:``,started:!1};return s.set(e,n),n},d=(e,t)=>{let n=u(e);t&&!n.toolName&&(n.toolName=t),n.started||(n.started=!0,a.push({type:`tool_call_start`,callId:e,toolName:n.toolName,sessionId:o}))},f=(e,t,n)=>{let r=u(e);t&&!r.toolName&&(r.toolName=t),typeof n==`string`&&n.length>0&&(r.argsText+=n),d(e,r.toolName),a.push({type:`tool_call_delta`,callId:e,toolName:r.toolName,argsTextDelta:n,sessionId:o})},p=()=>{c||(c=!0,a.push({type:`text_start`,sessionId:o}))},m=()=>{!c||l||(l=!0,a.push({type:`text_end`,content:e.currentResponse,sessionId:o}))},h=()=>{for(let[t,n]of s){if(!n.toolName)continue;let r={id:t,type:`function`,function:{name:n.toolName,arguments:n.argsText}};this._tools&&e.pendingToolCalls.push({toolCall:r}),a.push({type:`tool_call_end`,toolCall:r,sessionId:o})}s.clear()},g=(()=>{if(!i)return;let e={...i};return typeof e.maxOutputTokens!=`number`&&typeof i.maxTokens==`number`&&(e.maxOutputTokens=i.maxTokens),delete e.maxTokens,e})(),_=r?{model:r,messages:e.messages,tools:n,...g??{}}:{messages:e.messages,tools:n,...g??{}};try{for await(let n of this._modelClient.stream(_))if(N(t,`Session streaming`),n.type===`delta`)if(n.chunk.kind===`text`)p(),e.currentResponse+=n.chunk.text,a.push({type:`text_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.chunk.kind===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.chunk.text,a.push({type:`thinking_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_end`){let t=typeof n.chunk.text==`string`?n.chunk.text:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else n.chunk.kind===`tool_call_delta`&&f(n.chunk.callId,n.chunk.toolId,n.chunk.argsTextDelta);else if(n.type===`response_end`){m(),h(),e.lastModelStopReason=n.stopReason;let t=n.usage;if(t&&typeof t==`object`){let n=t;if(n.prompt_tokens||n.completion_tokens||n.total_tokens){let t={promptTokens:n.prompt_tokens??0,completionTokens:n.completion_tokens??0,totalTokens:n.total_tokens??0};e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.totalTokens+=t.totalTokens,this._recordUsage(t)}}}else if(n.type===`error`){let t=n.error?.code??`model_error`,r=n.error?.message??`Model error`,i=Error(`${t}: ${r}`);i.code=t,e.error=i,e.shouldContinue=!1,e.stopReason=`error`}else if(n.type===`text_delta`)p(),e.currentResponse+=n.delta,a.push({type:`text_delta`,delta:n.delta,sessionId:o});else if(n.type===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.type===`thinking_end`){let t=typeof n.content==`string`?n.content:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else if(n.type===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.content,a.push({type:`thinking_delta`,delta:n.content,sessionId:o});else if(n.type===`tool_call`&&this._tools){let t=n.toolCall;a.push({type:`tool_call_start`,callId:t.id,toolName:t.function.name,sessionId:o}),e.pendingToolCalls.push({toolCall:t}),a.push({type:`tool_call_end`,toolCall:t,sessionId:o})}else n.type===`usage`&&(e.usage.promptTokens+=n.usage.promptTokens,e.usage.completionTokens+=n.usage.completionTokens,e.usage.totalTokens+=n.usage.totalTokens,this._recordUsage(n.usage))}catch(t){if(t instanceof j)throw t;e.error=t instanceof Error?t:Error(String(t)),e.shouldContinue=!1,e.stopReason=`error`}finally{m(),s.size>0&&h()}return a}async executeToolCall(e,t,n,r){N(n,`Tool execution: ${e.toolCall.function.name}`);let i=r?new P(r):void 0,a=e.toolCall.id,o=e.toolCall,s=o,c=e=>({sessionId:t.sessionId,agentId:t.agentId,toolCall:e,toolContext:t});if(i){let n=await i.executePreToolUse(c(s));if(!n.allow)return e.result=`Tool execution blocked by PreToolUse hook`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};n.modifiedToolCall&&(s={...n.modifiedToolCall,id:a,type:o.type})}let l=this._tools?.get(s.function.name);if(!l)return e.result=`Tool not found: ${s.function.name}`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};try{let n=typeof s.function.arguments==`string`?JSON.parse(s.function.arguments):s.function.arguments;return e.result=await l.execute(n,t),e.isError=!1,i&&await i.executePostToolUse(c(s),e.result),{type:`tool_result`,tool_call_id:a,result:e.result,sessionId:t.sessionId}}catch(n){let r=n instanceof Error?n:Error(String(n));return e.result=r.message,e.isError=!0,i&&await i.executePostToolUseFailure(c(s),r),{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId}}}createToolExecutionContext(e,t){return{sessionId:e.sessionId,agentId:e.agentId,signal:t,usage:e.usage}}mergeStateResults(e,t){e.currentResponse=t.currentResponse,e.currentThinking=t.currentThinking,e.pendingToolCalls=t.pendingToolCalls,e.usage=t.usage}addToolResultToHistory(e,t){let n=t.result,r,i=t.isError;if(typeof n==`string`)r=n;else if(n&&typeof n==`object`&&`content`in n){let e=n;r=JSON.stringify(e.content),e.isError===!0&&(i=!0)}else r=JSON.stringify(n);e.messages.push({role:`tool`,tool_call_id:t.toolCall.id,content:r,...i?{isError:!0}:{}})}addAssistantMessageWithToolCalls(e){let t=typeof e.currentThinking==`string`?e.currentThinking:void 0;e.messages.push({role:`assistant`,content:e.currentResponse||``,tool_calls:e.pendingToolCalls.map(e=>e.toolCall),...t&&t.length>0?{reasoning_content:t}:{}})}addFinalAssistantMessage(e){e.currentResponse&&e.messages.push({role:`assistant`,content:e.currentResponse})}async*_streamWithState(e,t){let n=t.maxIterations??10,r=t.signal,i=this._tools?.toOpenAIFormat(),a=F(this._middlewares),o=this.createToolExecutionContext(e,r),s=this._stateStore,c=s?.savePoint??`before`,l=s?.deleteOnComplete??!0,u=t.model?{modelId:t.model.modelId,provider:t.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0;for(;e.shouldContinue;){if(N(r,`Session iteration ${e.iteration}`),e.iteration>=n){e.shouldContinue=!1,e.stopReason=`max_iterations`,yield{type:`done`,finalResponse:e.currentResponse,stopReason:`max_iterations`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(yield{type:`iteration_start`,iteration:e.iteration,sessionId:e.sessionId},e.pendingToolCalls.length>0){try{yield*this.handleToolCalls(e,o,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:s,checkpointModelConfig:u,requestParams:t.requestParams})}catch(e){if(e instanceof M)return;throw e}continue}if(e.currentResponse=``,e.currentThinking=void 0,e.pendingToolCalls=[],e.lastModelStopReason=void 0,s&&(c===`before`||c===`both`)){let n=_(e,{agentName:this._agentName,modelConfig:u,requestParams:t.requestParams});await s.saveCheckpoint(n)}let d=[],f=await a(e,async e=>(N(r,`Session model call`),d=await this.executeModelStream(e,r,i,t.model,t.requestParams),e));if(this.mergeStateResults(e,f),s&&(c===`after`||c===`both`)){let n=_(e,{agentName:this._agentName,modelConfig:u,requestParams:t.requestParams});await s.saveCheckpoint(n)}for(let e of d)yield e;if(N(r,`Session iteration ${e.iteration}`),e.stopReason===`error`){yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:e.pendingToolCalls.length,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`error`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(e.pendingToolCalls.length>0)try{yield*this.handleToolCalls(e,o,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:s,checkpointModelConfig:u,requestParams:t.requestParams})}catch(e){if(e instanceof M)return;throw e}else yield*this.handleFinalResponse(e);if(!e.shouldContinue){s&&l&&await s.deleteCheckpoint(e.sessionId);break}}}static APPROVAL_REQUIRED_LEVELS=new Set([`high`,`critical`]);requiresApproval(t){return e.APPROVAL_REQUIRED_LEVELS.has(t)}async*handleToolCalls(e,t,n){let r=e.pendingToolCalls.length,i=n?.signal,a=n?.toolContextInput?.approval,o=a?.strategy??`high_risk`,s=a?.autoApprove!==!0&&(a?.strategy!=null||a?.decisions!=null),c=a?.decisions??{},l=e=>s?o===`all`?!0:this.requiresApproval(e):!1,u=t=>e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)}),d=t=>{u(t)||this.addAssistantMessageWithToolCalls(e)},f=t=>e.messages.some(e=>e&&typeof e==`object`&&e.role===`tool`&&e.tool_call_id===t),p=new Set,m=e=>{try{return typeof e.function.arguments==`string`?JSON.parse(e.function.arguments):e.function.arguments}catch{return{_raw:e.function.arguments}}},h=t=>{let n=[];for(let r=t;r<e.pendingToolCalls.length;r++){let t=e.pendingToolCalls[r];if(f(t.toolCall.id)||p.has(t.toolCall.id)||c[t.toolCall.id])continue;let i=this._tools?.get(t.toolCall.function.name),a=i?.riskLevel??`safe`;!i||!l(a)||(p.add(t.toolCall.id),n.push({type:`tool_approval_requested`,tool_call_id:t.toolCall.id,toolName:t.toolCall.function.name,riskLevel:a,args:m(t.toolCall),sessionId:e.sessionId}))}return n};for(let r=0;r<e.pendingToolCalls.length;r++){let a=e.pendingToolCalls[r];if(f(a.toolCall.id)){e.pendingToolCalls.splice(r,1),r--;continue}let o=this._tools?.get(a.toolCall.function.name),s=o?.riskLevel??`safe`;if(o&&l(s)){let t=a.toolCall.function.name,i=c[a.toolCall.id];if(!i){e.stopReason=`approval_required`;for(let e of h(r))yield e;let i=_(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for approval: ${t}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(i),yield{type:`requires_action`,kind:`tool_approval`,checkpoint:n?.stateStore?void 0:i,checkpointRef:n?.stateStore?{sessionId:i.sessionId,agentId:i.agentId}:void 0,sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new M}if(!i.approved){let t=i.reason??`User denied approval`;a.result=`Tool execution skipped: ${t}`,a.isError=!0,d(a.toolCall.id),yield{type:`tool_skipped`,tool_call_id:a.toolCall.id,toolName:a.toolCall.function.name,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:a.toolCall.id,result:a.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,a),e.pendingToolCalls.splice(r,1),r--;continue}}d(a.toolCall.id),yield await this.executeToolCall(a,t,i,n?.hooks),this.addToolResultToHistory(e,a),e.pendingToolCalls.splice(r,1),r--}e.pendingToolCalls=[],e.iteration++,yield{type:`iteration_end`,iteration:e.iteration-1,willContinue:!0,toolCallCount:r,usage:{...e.usage},sessionId:e.sessionId}}async*handleFinalResponse(e){e.shouldContinue=!1,e.stopReason=`final_response`,this.addFinalAssistantMessage(e),yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:0,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`final_response`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId}}async _finalizeRun(e,t){this.messages=e.messages.filter(e=>e.role!==`system`),e.usage.totalTokens>0&&this.addUsage(e.usage);let n=Date.now()-t;this.recordResponse(n),await this.save()}async save(){let e=this.toSnapshot();await this._stateStore.save(this.id,T.SESSION,e)}async load(){let e=await this._stateStore.load(this.id,T.SESSION);return e?(this.restoreFromSnapshot(e),!0):!1}setStatus(e,t){super.setStatus(e,t),this._autoSave&&this.save().catch(()=>{})}markActive(){super.markActive(),this._autoSave&&this.save().catch(()=>{})}addMessage(e){super.addMessage(e),this._autoSave&&this.save().catch(()=>{})}addUsage(e){super.addUsage(e),this._autoSave&&this.save().catch(()=>{})}recordResponse(e){super.recordResponse(e),this._autoSave&&this.save().catch(()=>{})}incrementToolCallCount(){super.incrementToolCallCount(),this._autoSave&&this.save().catch(()=>{})}setModelOverride(e){super.setModelOverride(e),this._modelOverride=this.resolveModelRef(e)??this._modelOverride,this._autoSave&&this.save().catch(()=>{})}clearModelOverride(){super.clearModelOverride(),this._modelOverride=void 0,this._autoSave&&this.save().catch(()=>{})}setSystemPromptOverride(e){super.setSystemPromptOverride(e),this._autoSave&&this.save().catch(()=>{})}clearSystemPromptOverride(){super.clearSystemPromptOverride(),this._autoSave&&this.save().catch(()=>{})}disableTools(e){super.disableTools(e),this._autoSave&&this.save().catch(()=>{})}enableAllTools(){super.enableAllTools(),this._autoSave&&this.save().catch(()=>{})}setAutoSave(e){this._autoSave=e}},fe=class extends le{_stateStore;constructor(e){super(),this._stateStore=e}async create(){let e=t(),n=Date.now(),r={id:e,createdAt:n,state:{status:`active`,updatedAt:n,lastActiveAt:n},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0}},i=new L(this._stateStore,e,r);return await i.save(),i}async get(e){let t=await this._stateStore.load(e,T.SESSION);if(t)return new L(this._stateStore,e,t)}async list(){let e=await this._stateStore.listSessions(),t=[];for(let n of e){let e=await this._stateStore.load(n,T.SESSION);if(e){let r=new L(this._stateStore,n,e);t.push(r)}}return t}async destroy(e){await this._stateStore.deleteSession(e)}},R=class{savePoint;deleteOnComplete;constructor(e){this.savePoint=e?.savePoint??`before`,this.deleteOnComplete=e?.deleteOnComplete??!0}async save(e,t,n){let r=this.buildPath(e,t),i=JSON.stringify(n,null,2);await this._write(r,i)}async load(e,t){let n=this.buildPath(e,t),r=await this._read(n);if(r!==void 0)try{return JSON.parse(r)}catch{return}}async delete(e,t){let n=this.buildPath(e,t);await this._delete(n)}async deleteSession(e){let t=this.buildPrefix(e),n=await this._list(t);await Promise.all(n.map(e=>this._delete(e)))}async listKeys(e){let t=this.buildPrefix(e);return(await this._list(t)).map(t=>this.extractKey(e,t))}async exists(e,t){let n=this.buildPath(e,t);return this._exists(n)}async saveCheckpoint(e){let t={_meta:{description:`GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY`,savedAt:new Date().toISOString(),agentId:e.agentId,agentName:e.agentName,sessionId:e.sessionId,iteration:e.iteration,phase:e.phase,status:e.status,messageCount:e.messages.length,toolCallsPending:e.pendingToolCalls?.length??0},checkpoint:e};await this.save(e.sessionId,T.CHECKPOINT,t)}async loadCheckpoint(e){return(await this.load(e,T.CHECKPOINT))?.checkpoint}async deleteCheckpoint(e){await this.delete(e,T.CHECKPOINT)}async listCheckpoints(){let e=await this.listSessions(),t=[];for(let n of e){let e=await this.loadCheckpoint(n);e&&t.push(e)}return t}async listSessions(){let e=await this._list(``),t=new Set;for(let n of e){let e=this.extractSessionId(n);e&&t.add(e)}return Array.from(t)}buildPath(e,t){return`${e}/${t}`}buildPrefix(e){return`${e}/`}extractKey(e,t){let n=this.buildPrefix(e);return t.startsWith(n)?t.slice(n.length):t}extractSessionId(e){let t=e.split(`/`);return t.length>0?t[0]:void 0}},z=class extends R{baseDir;constructor(e){super(e),this.baseDir=c.resolve(e.dir),this.ensureDir(this.baseDir)}async _write(e,t){let n=this.toFilePath(e);this.ensureDir(c.dirname(n)),s(n,t,`utf-8`)}async _read(e){let t=this.toFilePath(e);try{return n(t)?i(t,`utf-8`):void 0}catch{return}}async _delete(e){let t=this.toFilePath(e);n(t)&&o(t);let r=c.dirname(t);if(n(r))try{a(r).length===0&&o(r,{recursive:!0})}catch{}}async _exists(e){return n(this.toFilePath(e))}async _list(e){let t=[];if(!n(this.baseDir))return t;let r=a(this.baseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let n of r){if(e&&!n.startsWith(e.split(`/`)[0]))continue;let r=c.join(this.baseDir,n),i=this.listJsonFiles(r);for(let r of i){let i=`${n}/${c.basename(r,`.json`)}`;(!e||i.startsWith(e))&&t.push(i)}}return t}toFilePath(e){return c.join(this.baseDir,`${e}.json`)}ensureDir(e){n(e)||r(e,{recursive:!0})}listJsonFiles(e){return n(e)?a(e).filter(e=>e.endsWith(`.json`)).map(t=>c.join(e,t)):[]}getBaseDir(){return this.baseDir}clear(){n(this.baseDir)&&(o(this.baseDir,{recursive:!0}),r(this.baseDir,{recursive:!0}))}},B=class extends R{store=new Map;constructor(e){super(e)}async _write(e,t){this.store.set(e,t)}async _read(e){return this.store.get(e)}async _delete(e){this.store.delete(e)}async _exists(e){return this.store.has(e)}async _list(e){let t=[];for(let n of this.store.keys())(e===``||n.startsWith(e))&&t.push(n);return t}clear(){this.store.clear()}stats(){let e=new Set;for(let t of this.store.keys()){let n=this.extractSessionId(t);n&&e.add(n)}return{entryCount:this.store.size,sessionCount:e.size}}},pe=class{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];constructor(e){this.id=e.id??crypto.randomUUID(),this.name=e.name,this.systemPrompt=e.systemPrompt,this.createdAt=Date.now(),this._model=e.model,this._tools=e.tools,this._stateStore=e.stateStore??new B,this._sessionManager=new fe(this._stateStore)}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get modelRefs(){let e=this._model.modelRefs;if(Array.isArray(e))return e;let t=this._model.modelRef;return t?[t]:[]}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession(e){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let t=await this._sessionManager.create();if(!this._stateStore)throw Error(`StateStore is required to create sessions`);let n=t.toSnapshot();return new L(this._stateStore,t.id,n,{...e,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares,hasCheckpoint:!1})}async resumeSession(e,t){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let n=await this._sessionManager.get(e);if(!n)throw Error(`Session not found: ${e}`);let r=!!await this._stateStore?.loadCheckpoint(e);if(!this._stateStore)throw Error(`StateStore is required to resume sessions`);let i=n.toSnapshot();return new L(this._stateStore,n.id,i,{...t,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares,hasCheckpoint:r})}use(e){return this._middlewares.push(e),this}setModel(e){(e=>!!(e&&typeof e==`object`&&typeof e.provider==`string`&&typeof e.modelId==`string`&&typeof e.stream!=`function`))(e)?this._modelOverride=e:(this._model=e,this._modelOverride=void 0)}},me=class{},V=class extends Error{code;retryable;status;constructor(e,t){super(e),this.name=`ModelError`,this.code=t.code,this.retryable=t.retryable??!1,this.status=t.status}},he=class{state=new Map;get(e){return this.state.get(this.keyOf(e))||{failures:0,nextRetryAt:0}}markSuccess(e){this.state.set(this.keyOf(e),{failures:0,nextRetryAt:0})}markFailure(e,t){let n=this.get(e).failures+1,r=Math.min(t.maxDelayMs,t.baseDelayMs*2**Math.min(8,n-1));this.state.set(this.keyOf(e),{failures:n,nextRetryAt:t.now+r,lastError:{code:t.code,message:t.message}})}isAvailable(e,t){return this.get(e).nextRetryAt<=t}keyOf(e){return`${e.provider}:${e.modelId}`}},H=class extends he{},ge=class{constructor(e,t){this.health=e,this.fallbackOrder=t}select(e){let{now:t}=e,n=this.fallbackOrder.filter(e=>this.health.isAvailable(e,t));return n.length?n:this.fallbackOrder}},U=class{static isRetryableStatus(e){return e===408||e===409||e===429||e>=500&&e<=599}static async sleep(e,t){return e<=0?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{a(),n()},e);function a(){clearTimeout(i),t&&t.removeEventListener(`abort`,o)}function o(){a(),r(Error(`Aborted`))}if(t){if(t.aborted)return o();t.addEventListener(`abort`,o)}})}};function W(e=`req`){let t=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${t}`}var G=class e{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor(e={}){this.maxAttempts=e.maxAttempts??3,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.strategy=e.strategy??`exponential`,this.jitter=e.jitter??`equal`,this.multiplier=e.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay(e){let t;switch(this.strategy){case`exponential`:t=this.baseDelayMs*this.multiplier**(e-1);break;case`linear`:t=this.baseDelayMs*e;break;case`fixed`:t=this.baseDelayMs;break}return t=Math.min(t,this.maxDelayMs),t=this.applyJitter(t),this._previousDelay=t,Math.floor(t)}applyJitter(e){switch(this.jitter){case`full`:return Math.random()*e;case`equal`:return e/2+Math.random()*e/2;case`decorrelated`:return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case`none`:default:return e}}canRetry(e){return e<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new e;static aggressive=new e({maxAttempts:5,baseDelayMs:1e3,maxDelayMs:6e4});static gentle=new e({maxAttempts:3,baseDelayMs:2e3,maxDelayMs:3e4,jitter:`full`})};function _e(e){let t=new Map(e.adapters.map(e=>[e.provider,e])),n=e.health??new H,r=e.routing?.fallbackOrder??(()=>{let t=[];for(let n of e.adapters)n.defaultModelId&&t.push({provider:n.provider,modelId:n.defaultModelId});if(t.length===0)throw new V(`No routing configuration and no adapter with defaultModelId provided. Either provide options.routing.fallbackOrder or set defaultModelId on your adapters.`,{code:`missing_routing`,retryable:!1});return t})(),i=new ge(n,r),a=new G({maxAttempts:e.retry?.maxAttemptsPerModel??3,baseDelayMs:e.retry?.baseDelayMs??500,maxDelayMs:e.retry?.maxDelayMs??3e4,strategy:e.retry?.strategy??`exponential`,jitter:e.retry?.jitter??`equal`}),o=e.timeoutMs??6e4;function s(e){let n=t.get(e.provider);if(!n)throw new V(`No adapter for provider: ${e.provider}`,{code:`adapter_missing`,retryable:!1});return n}async function*c(t){let r=Date.now(),c=t.requestId||W(`req`),{model:l,...u}=t,d=t.model?[t.model]:i.select({now:r}),f;for(let r of d){let i=s(r),l=t.timeoutMs??o,d=new AbortController,p=t.signal,m=setTimeout(()=>d.abort(),l),h=()=>d.abort();p&&(p.aborted?d.abort():p.addEventListener(`abort`,h));let g={...u,requestId:c,model:r,stream:t.stream??!0,signal:d.signal,timeoutMs:l};try{for(let t=1;t<=a.maxAttempts;t++)try{for await(let e of i.stream({request:g}))yield e;n.markSuccess(r);return}catch(n){f=n;let i=K(n);if(!i.retryable||!a.canRetry(t))throw i;let o=a.getDelay(t);e.retry?.onRetry?.({attempt:t,maxAttempts:a.maxAttempts,delayMs:o,error:{code:i.code,message:i.message,retryable:i.retryable},model:r,request:g}),await U.sleep(o,d.signal)}}catch(e){let t=K(e);n.markFailure(r,{now:Date.now(),baseDelayMs:a.baseDelayMs,maxDelayMs:a.maxDelayMs,code:t.code,message:t.message}),yield{type:`error`,requestId:c,error:{code:t.code,message:t.message,retryable:t.retryable}},f=t;continue}finally{clearTimeout(m),p&&p.removeEventListener(`abort`,h)}}throw K(f||new V(`All models failed`,{code:`all_models_failed`}))}async function l(e){let t=``,n=`error`,r,i,a=e.requestId||``;for await(let o of c({...e,stream:!0}))o.type===`response_start`?(a=o.requestId,i=o.model):o.type===`delta`&&o.chunk.kind===`text`?t+=o.chunk.text:o.type===`text_delta`?t+=o.delta:o.type===`response_end`?(n=o.stopReason,r=o.usage):o.type===`error`&&(n=`error`);if(!i)throw new V(`Missing response_start from adapter`,{code:`protocol_error`,retryable:!1});return{requestId:a,model:i,text:t,stopReason:n,usage:r}}return{get modelId(){return r[0]?.modelId??`unknown`},get modelRef(){return r[0]},get modelRefs(){return[...r]},setModelId(e){let t=r[0];if(!t)throw new V(`No primary model to update`,{code:`no_primary_model`,retryable:!1});r[0]={provider:t.provider,modelId:e}},invoke:async(e,t)=>{let n=await l({messages:e,tools:t?.tools});return{message:{role:`assistant`,content:n.text},usage:n.usage}},stream:((e,t)=>c(Array.isArray(e)?{messages:e,tools:t?.tools}:e)),run:l}}function K(e){if(e instanceof V)return e;if(e&&typeof e==`object`){let t=typeof e.status==`number`?e.status:void 0,n=typeof e.code==`string`?e.code:t?`http_${t}`:`unknown_error`;return new V(typeof e.message==`string`?e.message:`Unknown error`,{code:n,retryable:t?U.isRetryableStatus(t):!1,status:t})}return new V(String(e||`Unknown error`),{code:`unknown_error`,retryable:!1})}function ve(e){function t(e,t){if(typeof e!=`string`)return``;let n=e.trim();return n?/^data:/i.test(n)||/^https?:\/\//i.test(n)?n:typeof t==`string`&&t.trim()?`data:${t.trim()};base64,${n}`:n:``}if(typeof e==`string`)return e.trim().length===0?``:e;if(e==null)return``;if(typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`&&n.text)return n.text;if(n.type===`image`){let e=t(n.data??n.source?.data,n.mimeType??n.source?.media_type??n.source?.mimeType);return e?[{type:`image_url`,image_url:{url:e}}]:``}}if(Array.isArray(e)){let n=[];for(let r of e)if(typeof r==`string`)n.push({type:`text`,text:r});else if(r&&typeof r==`object`&&`type`in r){let e=r;if(e.type===`text`&&e.text)n.push({type:`text`,text:e.text});else if(e.type===`image`){let r=t(e.data??e.source?.data,e.mimeType??e.source?.media_type??e.source?.mimeType);r&&n.push({type:`image_url`,image_url:{url:r}})}}return n.length>0?n:``}return String(e)}function ye(e){return{...e,content:ve(e.content)}}function be(e,t){return typeof t==`string`&&/deepseek/i.test(t)?!0:/^deepseek-/i.test(e)}function xe(e={}){let t=e.baseUrl;function n(){if(typeof e.apiKey==`string`){if(!e.apiKey.trim())throw new V(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return e.apiKey}let t=typeof process<`u`?process.env?.OPENAI_API_KEY:void 0;if(!t)throw new V(`Missing OPENAI_API_KEY`,{code:`missing_api_key`,retryable:!1});return t}function r(){let r=n();return typeof t==`string`&&/\/chat\/completions\/?$/.test(t)?new l({apiKey:r,organization:e.organization,project:e.project,baseURL:`https://api.openai.com/v1`,fetch:(e,n)=>fetch(t,n)}):new l({apiKey:r,organization:e.organization,project:e.project,baseURL:t||void 0})}function i(e){return{provider:`openai`,modelId:e.model.modelId}}function a(e){if(e instanceof V)return e;let t=typeof e?.status==`number`?e.status:void 0;return new V(typeof e?.message==`string`?e.message:`OpenAI error`,{code:typeof e?.code==`string`?e.code:t?`openai_http_${t}`:`openai_error`,retryable:t?U.isRetryableStatus(t):!1,status:t})}async function*o(n){let{request:o}=n,s=o.requestId||W(`req`),c=r(),l=o.model.modelId,u=e.compat?.requireReasoningContentForToolCalls,d=typeof u==`boolean`?u:be(l,t),f=o.stream!==!1,p=[];if(o.messages&&Array.isArray(o.messages))for(let e of o.messages){let t=ye(e);if(!d&&t&&typeof t==`object`)`reasoning_content`in t&&delete t.reasoning_content;else if(d&&t?.role===`assistant`&&Array.isArray(t?.tool_calls)&&t.tool_calls.length>0){let e=t.reasoning_content;(typeof e!=`string`||e.length===0)&&(t.reasoning_content=``)}p.push(t)}else typeof o.instructions==`string`&&o.instructions.length>0&&p.push({role:`system`,content:o.instructions}),p.push({role:`user`,content:o.input});let m=(()=>{let e=o.reasoning?.effort;if(typeof e==`string`&&(e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`))return e})(),h={model:l,messages:p,stream:f,stream_options:f?{include_usage:!0}:void 0,metadata:o.metadata??void 0,reasoning_effort:m,max_completion_tokens:o.maxOutputTokens??void 0,stop:o.stop??void 0,temperature:o.temperature??void 0,top_p:o.topP??void 0,presence_penalty:o.presencePenalty??void 0,frequency_penalty:o.frequencyPenalty??void 0,seed:o.seed??void 0};o.tools&&Array.isArray(o.tools)&&o.tools.length>0&&(h.tools=o.tools);try{if(yield{type:`response_start`,requestId:s,model:i(o)},!f){let e=await c.chat.completions.create({...h,stream:!1},{signal:o.signal,timeout:o.timeoutMs}),t=Array.isArray(e?.choices)?e.choices[0]:void 0,n=t?.message,r=typeof n?.reasoning_content==`string`?n.reasoning_content:``;r.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:r}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:r}});let i=typeof n?.content==`string`?n.content:``;i.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:i}});let a=Array.isArray(n?.tool_calls)?n.tool_calls:[];for(let e=0;e<a.length;e++){let t=a[e],n=typeof t?.id==`string`?t.id:`call_${e}`,r=typeof t?.function?.name==`string`?t.function.name:void 0,i=typeof t?.function?.arguments==`string`?t.function.arguments:void 0;(i||r)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:i}})}yield{type:`response_end`,requestId:s,stopReason:q(t?.finish_reason),usage:e?.usage};return}let e=await c.chat.completions.create({...h,stream:!0},{signal:o.signal,timeout:o.timeoutMs}),t=null,n,r=new Map,a=!1,l=``;for await(let i of e){i?.usage!=null&&(n=i.usage);let e=Array.isArray(i?.choices)?i.choices:[];for(let n of e){n?.finish_reason!=null&&(t=n.finish_reason);let e=n?.delta,i=e?.reasoning_content;typeof i==`string`&&i.length>0&&(a||(a=!0,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}}),l+=i,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:i}});let o=e?.content;typeof o==`string`&&o.length>0&&(a&&(a=!1,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:o}});let c=Array.isArray(e?.tool_calls)?e.tool_calls:[];for(let e of c){let t=typeof e?.index==`number`?e.index:0,n=r.get(t)||(typeof e?.id==`string`?e.id:`call_${t}`);r.set(t,n);let i=typeof e?.function?.name==`string`?e.function.name:void 0,a=typeof e?.function?.arguments==`string`?e.function.arguments:void 0;(i||a)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:i,argsTextDelta:a}})}}}a&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`response_end`,requestId:s,stopReason:q(t),usage:n}}catch(e){throw e?.name===`AbortError`?new V(`Aborted`,{code:`aborted`,retryable:!1}):a(e)}}return{provider:`openai`,defaultModelId:e.defaultModelId,stream:o}}function q(e){return e===`tool_calls`||e===`function_call`?`tool_call`:e===`length`?`length`:e===`content_filter`?`error`:`final`}function Se(e){return{content:[{type:`text`,text:e}]}}function J(e){return{content:[{type:`text`,text:e}],isError:!0}}function Ce(e,t){return{content:[{type:`image`,data:e,mimeType:t}]}}var Y=class{riskLevel=`safe`};const X=1e3;function we(e){let t=``,n=0;for(;n<e.length;){let r=e[n];if(r===`*`)e[n+1]===`*`?e[n+2]===`/`?(t+=`(?:.*\\/)?`,n+=3):(t+=`.*`,n+=2):(t+=`[^/]*`,n++);else if(r===`?`)t+=`[^/]`,n++;else if(r===`{`){let r=e.indexOf(`}`,n);if(r!==-1){let i=e.slice(n+1,r).split(`,`);t+=`(?:${i.map(e=>Te(e)).join(`|`)})`,n=r+1}else t+=`\\{`,n++}else if(r===`[`){let r=e.indexOf(`]`,n);r===-1?(t+=`\\[`,n++):(t+=e.slice(n,r+1),n=r+1)}else r===`.`?(t+=`\\.`,n++):r===`/`?(t+=`\\/`,n++):`()[]{}^$+|\\`.includes(r)?(t+=`\\${r}`,n++):(t+=r,n++)}return RegExp(`^${t}$`)}function Te(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var Ee=class extends Y{name=`Glob`;description=`Fast file pattern matching tool that works with any codebase size.
|
|
116
|
+
|
|
117
|
+
Usage notes:
|
|
118
|
+
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
|
|
119
|
+
- Returns matching file paths sorted by modification time (newest first)
|
|
120
|
+
- Use this tool when you need to find files by name patterns
|
|
121
|
+
- You can call multiple tools in a single response for parallel searches
|
|
122
|
+
|
|
123
|
+
Supported patterns:
|
|
124
|
+
- \`*\` matches any sequence of characters except path separator
|
|
125
|
+
- \`**\` matches any sequence of characters including path separator
|
|
126
|
+
- \`?\` matches any single character
|
|
127
|
+
- \`{a,b}\` matches either a or b
|
|
128
|
+
- \`[abc]\` matches any character in brackets`;parameters={type:`object`,properties:{pattern:{type:`string`,description:`The glob pattern to match files against`},path:{type:`string`,description:`The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior.`}},required:[`pattern`]};cwd;constructor(e){super(),this.cwd=e?.cwd??d.cwd()}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let{pattern:t,path:n}=this.validateArgs(e),r=n?c.isAbsolute(n)?n:c.resolve(this.cwd,n):this.cwd;try{if(!(await h(r)).isDirectory())return J(`Path is not a directory: ${r}`)}catch(e){if(e.code===`ENOENT`)return J(`Directory not found: ${r}`);throw e}let i=t;!t.startsWith(`**/`)&&!t.startsWith(`/`)&&!t.startsWith(`./`)&&(i=`**/${t}`);let a=we(i),o=[];await this.walkDirectory(r,``,a,o,0),o.sort((e,t)=>t.mtime-e.mtime);let s=o.length>X,l=o.slice(0,X).map(e=>e.path),u={files:l,totalMatches:o.length,truncated:s};return{content:[{type:`text`,text:l.length>0?`Found ${o.length} file${o.length===1?``:`s`}${s?` (showing first ${X})`:``}:\n${l.join(`
|
|
129
|
+
`)}`:`No files found matching pattern: ${t}`}],structuredContent:u}}validateArgs(e){let t=e.pattern;if(typeof t!=`string`||!t.trim())throw Error(`Pattern is required and must be a non-empty string`);let n;if(e.path!==void 0&&e.path!==null&&e.path!==`undefined`&&e.path!==`null`){if(typeof e.path!=`string`)throw TypeError(`Path must be a string`);n=e.path.trim()||void 0}return{pattern:t.trim(),path:n}}async walkDirectory(e,t,n,r,i){if(i>20)return;let a=t?c.join(e,t):e,o;try{o=await m(a,{withFileTypes:!0})}catch{return}for(let s of o){if(s.name.startsWith(`.`)||s.name===`node_modules`)continue;let o=t?`${t}/${s.name}`:s.name;if(s.isDirectory())await this.walkDirectory(e,o,n,r,i+1);else if(s.isFile()&&n.test(o))try{let e=await h(c.join(a,s.name));r.push({path:o,mtime:e.mtimeMs})}catch{}}}};const Z=5e4,De=6e4;var Oe=class extends Y{name=`Grep`;description=`A powerful search tool built on ripgrep.
|
|
130
|
+
|
|
131
|
+
Usage notes:
|
|
132
|
+
- Supports full regex syntax (e.g., "log.*Error", "function\\s+\\w+")
|
|
133
|
+
- Filter files with glob parameter (e.g., "*.js", "**/*.tsx") or type parameter (e.g., "js", "py", "rust")
|
|
134
|
+
- Output modes: "content" shows matching lines, "files_with_matches" shows only file paths (default), "count" shows match counts
|
|
135
|
+
- Pattern syntax: Uses ripgrep (not grep) - literal braces need escaping (use \`interface\\{\\}\` to find \`interface{}\` in Go code)
|
|
136
|
+
- Multiline matching: By default patterns match within single lines only. For cross-line patterns, use multiline: true`;parameters={type:`object`,properties:{pattern:{type:`string`,description:`The regular expression pattern to search for in file contents`},path:{type:`string`,description:`File or directory to search in. Defaults to current working directory.`},glob:{type:`string`,description:`Glob pattern to filter files (e.g. "*.js", "*.{ts,tsx}")`},output_mode:{type:`string`,enum:[`content`,`files_with_matches`,`count`],description:`Output mode: "content" shows matching lines, "files_with_matches" shows file paths (default), "count" shows match counts.`},"-B":{type:`number`,description:`Number of lines to show before each match. Requires output_mode: "content".`},"-A":{type:`number`,description:`Number of lines to show after each match. Requires output_mode: "content".`},"-C":{type:`number`,description:`Number of lines to show before and after each match. Requires output_mode: "content".`},"-n":{type:`boolean`,description:`Show line numbers in output. Requires output_mode: "content". Defaults to true.`},"-i":{type:`boolean`,description:`Case insensitive search`},type:{type:`string`,description:`File type to search (e.g., js, py, rust, go, java). More efficient than glob for standard file types.`},head_limit:{type:`number`,description:`Limit output to first N lines/entries. Defaults to 0 (unlimited).`},offset:{type:`number`,description:`Skip first N lines/entries before applying head_limit. Defaults to 0.`},multiline:{type:`boolean`,description:`Enable multiline mode where . matches newlines and patterns can span lines. Default: false.`}},required:[`pattern`]};cwd;rgPath;constructor(e){super(),this.cwd=e?.cwd??d.cwd(),this.rgPath=e?.rgPath??`rg`}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let t=this.validateArgs(e),n=this.buildRgArgs(t),r=await this.runRipgrep(n,t),i=r.output||`[No matches found]`;return r.timedOut&&(i+=`
|
|
137
|
+
[Search timed out]`),r.matchCount!==void 0&&(i=`Found ${r.matchCount} match${r.matchCount===1?``:`es`}\n${i}`),{content:[{type:`text`,text:i}],structuredContent:r,isError:r.exitCode!==0&&r.exitCode!==1}}validateArgs(e){let t=e.pattern;if(typeof t!=`string`||!t.trim())throw Error(`Pattern is required and must be a non-empty string`);let n={pattern:t.trim()};if(e.path!==void 0&&e.path!==null&&e.path!==``){if(typeof e.path!=`string`)throw TypeError(`Path must be a string`);n.path=e.path.trim()}if(e.glob!==void 0&&e.glob!==null&&e.glob!==``){if(typeof e.glob!=`string`)throw TypeError(`Glob must be a string`);n.glob=e.glob.trim()}if(e.type!==void 0&&e.type!==null&&e.type!==``){if(typeof e.type!=`string`)throw TypeError(`Type must be a string`);n.type=e.type.trim()}if(e.output_mode!==void 0){let t=[`content`,`files_with_matches`,`count`];if(!t.includes(e.output_mode))throw Error(`Invalid output_mode. Must be one of: ${t.join(`, `)}`);n.output_mode=e.output_mode}for(let t of[`-B`,`-A`,`-C`,`head_limit`,`offset`])if(e[t]!==void 0&&e[t]!==null){if(typeof e[t]!=`number`)throw TypeError(`${t} must be a number`);n[t]=Math.max(0,Math.floor(e[t]))}for(let t of[`-n`,`-i`,`multiline`])e[t]!==void 0&&e[t]!==null&&(n[t]=!!e[t]);return n}buildRgArgs(e){let t=[],n=e.output_mode??`files_with_matches`;return n===`files_with_matches`?t.push(`-l`):n===`count`&&t.push(`-c`),n===`content`&&(e[`-n`]!==!1&&t.push(`-n`),e[`-B`]!==void 0&&e[`-B`]>0&&t.push(`-B`,String(e[`-B`])),e[`-A`]!==void 0&&e[`-A`]>0&&t.push(`-A`,String(e[`-A`])),e[`-C`]!==void 0&&e[`-C`]>0&&t.push(`-C`,String(e[`-C`]))),e[`-i`]&&t.push(`-i`),e.multiline&&t.push(`-U`,`--multiline-dotall`),e.type&&t.push(`--type`,e.type),e.glob&&t.push(`--glob`,e.glob),t.push(`--color`,`never`),t.push(`--no-heading`),t.push(`--regexp`,e.pattern),e.path&&t.push(`--`,e.path),t}runRipgrep(e,t){return new Promise(n=>{let r=``,i=!1,a=!1,o=u(this.rgPath,e,{cwd:this.cwd,env:d.env,stdio:[`pipe`,`pipe`,`pipe`]}),s=setTimeout(()=>{i=!0,o.kill(`SIGTERM`),setTimeout(()=>{o.killed||o.kill(`SIGKILL`)},5e3)},De);o.stdout?.on(`data`,e=>{let t=e.toString();r.length+t.length>Z?(r+=t.slice(0,Z-r.length),a=!0):r+=t}),o.stderr?.on(`data`,e=>{let t=e.toString();t.includes(`error:`)&&(r+=`\n[stderr]: ${t}`)}),o.on(`close`,e=>{clearTimeout(s);let o=r;if(t.offset||t.head_limit){let e=r.split(`
|
|
138
|
+
`).filter(e=>e.trim()),n=t.offset??0,i=t.head_limit??e.length;o=e.slice(n,n+i).join(`
|
|
139
|
+
`)}let c;t.output_mode===`count`&&(c=o.split(`
|
|
140
|
+
`).filter(e=>e.trim()).reduce((e,t)=>{let n=t.match(/:(\d+)$/);return e+(n?Number.parseInt(n[1],10):0)},0)),n({exitCode:e,output:a?`${o}\n... [output truncated]`:o,truncated:a,timedOut:i,matchCount:c})}),o.on(`error`,e=>{if(clearTimeout(s),e?.code===`ENOENT`){this.runSystemGrep(t).then(n);return}n({exitCode:1,engine:`rg`,output:`Failed to execute ripgrep: ${e.message}. Make sure 'rg' is installed and in PATH.`,truncated:!1,timedOut:!1})})})}runSystemGrep(e){return new Promise(t=>{let n=``,r=!1,i=!1,a=[];a.push(`-R`,`-E`,`-I`);let o=e.output_mode??`files_with_matches`;o===`files_with_matches`?a.push(`-l`):o===`count`?a.push(`-c`):a.push(`-n`),o===`content`&&(e[`-B`]!==void 0&&e[`-B`]>0&&a.push(`-B`,String(e[`-B`])),e[`-A`]!==void 0&&e[`-A`]>0&&a.push(`-A`,String(e[`-A`])),e[`-C`]!==void 0&&e[`-C`]>0&&a.push(`-C`,String(e[`-C`]))),e[`-i`]&&a.push(`-i`),a.push(e.pattern),e.path?a.push(e.path):a.push(`.`);let s=u(`grep`,a,{cwd:this.cwd,env:d.env,stdio:[`pipe`,`pipe`,`pipe`]}),c=setTimeout(()=>{r=!0,s.kill(`SIGTERM`),setTimeout(()=>{s.killed||s.kill(`SIGKILL`)},5e3)},De);s.stdout?.on(`data`,e=>{let t=e.toString();n.length+t.length>Z?(n+=t.slice(0,Z-n.length),i=!0):n+=t}),s.stderr?.on(`data`,e=>{let t=e.toString();t.trim()&&(n+=`\n[stderr]: ${t}`)}),s.on(`close`,a=>{clearTimeout(c);let s=n;if(e.offset||e.head_limit){let t=n.split(`
|
|
141
|
+
`).filter(e=>e.trim()),r=e.offset??0,i=e.head_limit??t.length;s=t.slice(r,r+i).join(`
|
|
142
|
+
`)}let l;o===`count`&&(l=s.split(`
|
|
143
|
+
`).filter(e=>e.trim()).reduce((e,t)=>{let n=t.split(`:`).pop(),r=n?Number.parseInt(n,10):NaN;return e+(Number.isFinite(r)?r:0)},0)),t({exitCode:a,engine:`grep`,output:i?`${s}\n... [output truncated]`:s,truncated:i,timedOut:r,matchCount:l})}),s.on(`error`,e=>{clearTimeout(c),t({exitCode:1,engine:`grep`,output:`Failed to execute grep: ${e.message}.`,truncated:!1,timedOut:!1})})})}};const Q=2e3,$=2e3,ke=new Set(`.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.svg,.pdf,.zip,.tar,.gz,.rar,.7z,.exe,.dll,.so,.dylib,.mp3,.mp4,.avi,.mov,.wav,.woff,.woff2,.ttf,.eot`.split(`,`)),Ae={".png":`image/png`,".jpg":`image/jpeg`,".jpeg":`image/jpeg`,".gif":`image/gif`,".webp":`image/webp`,".svg":`image/svg+xml`,".pdf":`application/pdf`,".json":`application/json`,".js":`text/javascript`,".ts":`text/typescript`,".html":`text/html`,".css":`text/css`,".md":`text/markdown`,".txt":`text/plain`};var je=class extends Y{name=`Read`;_cwd;_allowedDirectory;constructor(e){super(),this._cwd=e?.cwd??d.cwd(),this._allowedDirectory=e?.allowedDirectory}get description(){let e=`Reads a file from the local filesystem. You can access any file directly by using this tool.
|
|
144
|
+
|
|
145
|
+
Usage notes:
|
|
146
|
+
- The file_path parameter must be an absolute path, not a relative path
|
|
147
|
+
- By default, it reads up to ${Q} lines starting from the beginning
|
|
148
|
+
- You can optionally specify a line offset and limit for large files
|
|
149
|
+
- Any lines longer than ${$} characters will be truncated
|
|
150
|
+
- Results are returned with line numbers (like cat -n format)
|
|
151
|
+
- Can read images (PNG, JPG, etc.), PDFs, and Jupyter notebooks
|
|
152
|
+
- You can call multiple tools in parallel to read multiple files at once`;return this._allowedDirectory?`${e}
|
|
153
|
+
- IMPORTANT: Files can ONLY be read from within: ${this._allowedDirectory}
|
|
154
|
+
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`:e}get parameters(){return{type:`object`,properties:{file_path:{type:`string`,description:this._allowedDirectory?`The absolute path to the file to read (must be within ${this._allowedDirectory})`:`The absolute path to the file to read`},offset:{type:`number`,description:`The line number to start reading from (1-based). Only provide if the file is too large to read at once.`},limit:{type:`number`,description:`The number of lines to read. Only provide if the file is too large to read at once.`}},required:[`file_path`]}}setCwd(e){this._cwd=e}getCwd(){return this._cwd}setAllowedDirectory(e){this._allowedDirectory=e}getAllowedDirectory(){return this._allowedDirectory}async execute(e){let{file_path:t,offset:n,limit:r}=this.validateArgs(e),i=c.isAbsolute(t)?t:c.resolve(this._cwd,t);if(this._allowedDirectory){let e=c.resolve(this._allowedDirectory),n=c.resolve(i);if(!n.startsWith(e+c.sep)&&n!==e)return J(`Access denied: ${t}\nFiles can only be read from within: ${this._allowedDirectory}\nPlease use a path like: ${this._allowedDirectory}/<filename>`)}let a;try{a=await h(i)}catch(e){if(e.code===`ENOENT`)return J(`File not found: ${i}`);throw e}if(a.isDirectory())return J(`Path is a directory, not a file: ${i}. Use ls command via Bash tool to read directories.`);let o=c.extname(i).toLowerCase(),s=ke.has(o),l=Ae[o],u;if(s){if(u=await this.handleBinaryFile(i,a.size,l),l?.startsWith(`image/`))return{content:[{type:`image`,data:(await p(i)).toString(`base64`),mimeType:l}],structuredContent:u}}else u=o===`.ipynb`?await this.handleJupyterNotebook(i,a.size,n,r):await this.handleTextFile(i,a.size,n,r);return{content:[{type:`text`,text:u.content}],structuredContent:u}}validateArgs(e){let t=e.file_path;if(typeof t!=`string`||!t.trim())throw Error(`file_path is required and must be a non-empty string`);let n={file_path:t.trim()};if(e.offset!==void 0&&e.offset!==null){if(typeof e.offset!=`number`)throw TypeError(`offset must be a number`);n.offset=Math.max(1,Math.floor(e.offset))}if(e.limit!==void 0&&e.limit!==null){if(typeof e.limit!=`number`)throw TypeError(`limit must be a number`);n.limit=Math.max(1,Math.floor(e.limit))}return n}async handleBinaryFile(e,t,n){let r=(await p(e)).toString(`base64`);return{content:`[Binary file: ${c.basename(e)}]\nSize: ${this.formatSize(t)}\nMIME type: ${n??`unknown`}\nBase64 encoded content:\n${r}`,totalLines:1,linesReturned:1,startLine:1,truncated:!1,fileSize:t,isBinary:!0,mimeType:n}}async handleJupyterNotebook(e,t,n,r){let i=await p(e,`utf-8`),a;try{a=JSON.parse(i)}catch{throw Error(`Invalid Jupyter notebook format: ${e}`)}let o=a.cells||[],s=[];for(let e=0;e<o.length;e++){let t=o[e],n=e+1,r=t.cell_type||`unknown`;s.push(`--- Cell ${n} (${r}) ---`);let i=Array.isArray(t.source)?t.source.join(``):t.source||``;if(s.push(...i.split(`
|
|
155
|
+
`)),t.outputs&&t.outputs.length>0){s.push(`--- Output ---`);for(let e of t.outputs)if(e.text){let t=Array.isArray(e.text)?e.text.join(``):e.text;s.push(...t.split(`
|
|
156
|
+
`))}else if(e.data&&e.data[`text/plain`]){let t=Array.isArray(e.data[`text/plain`])?e.data[`text/plain`].join(``):e.data[`text/plain`];s.push(...t.split(`
|
|
157
|
+
`))}}s.push(``)}return this.formatOutput(s,t,n,r)}async handleTextFile(e,t,n,r){let i=await p(e,`utf-8`);if(i.length===0)return{content:`[File is empty]`,totalLines:0,linesReturned:0,startLine:1,truncated:!1,fileSize:t,isBinary:!1};let a=i.split(`
|
|
158
|
+
`);return this.formatOutput(a,t,n,r)}formatOutput(e,t,n,r){let i=e.length,a=n??1,o=r??Q,s=a-1,c=Math.min(s+o,i),l=e.slice(s,c),u=!1;return{content:l.map((e,t)=>{let n=a+t,r=String(n).padStart(6,` `),i=e;return e.length>$&&(i=`${e.slice(0,$)}... [truncated]`,u=!0),`${r}|${i}`}).join(`
|
|
159
|
+
`),totalLines:i,linesReturned:l.length,startLine:a,truncated:u,fileSize:t,isBinary:!1}}formatSize(e){let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n.toFixed(r===0?0:2)} ${t[r]}`}},Me=class extends Y{name=`Edit`;riskLevel=`high`;description=`Performs exact string replacements in files.
|
|
160
|
+
|
|
161
|
+
Usage notes:
|
|
162
|
+
- When editing, preserve the exact indentation (tabs/spaces) from the original file
|
|
163
|
+
- The edit will FAIL if old_string is not unique in the file unless replace_all is true
|
|
164
|
+
- Use replace_all for replacing/renaming strings across the entire file
|
|
165
|
+
- old_string and new_string must be different
|
|
166
|
+
- ALWAYS prefer editing existing files over creating new ones`;parameters={type:`object`,properties:{file_path:{type:`string`,description:`The absolute path to the file to modify`},old_string:{type:`string`,description:`The text to replace`},new_string:{type:`string`,description:`The text to replace it with (must be different from old_string)`},replace_all:{type:`boolean`,description:`Replace all occurrences of old_string (default false)`}},required:[`file_path`,`old_string`,`new_string`]};cwd;constructor(e){super(),this.cwd=e?.cwd??d.cwd()}setCwd(e){this.cwd=e}getCwd(){return this.cwd}async execute(e){let{file_path:t,old_string:n,new_string:r,replace_all:i}=this.validateArgs(e),a=c.isAbsolute(t)?t:c.resolve(this.cwd,t);try{if((await h(a)).isDirectory())return J(`Path is a directory, not a file: ${a}`)}catch(e){if(e.code===`ENOENT`)return J(`File not found: ${a}`);throw e}let o=await p(a,`utf-8`),s=this.countOccurrences(o,n);if(s===0)return J(`old_string not found in file: ${a}\n\nSearched for:\n${this.truncateForError(n)}`);if(s>1&&!i)return J(`old_string is not unique in the file (found ${s} occurrences). Either provide more context to make it unique, or set replace_all: true to replace all occurrences.`);let l,u;if(i)l=o.split(n).join(r),u=s;else{let e=o.indexOf(n);l=o.slice(0,e)+r+o.slice(e+n.length),u=1}await g(a,l,`utf-8`);let d={success:!0,replacements:u,filePath:a,message:`Successfully replaced ${u} occurrence${u>1?`s`:``} in ${c.basename(a)}`};return{content:[{type:`text`,text:d.message}],structuredContent:d}}validateArgs(e){let t=e.file_path,n=e.old_string,r=e.new_string;if(typeof t!=`string`||!t.trim())throw Error(`file_path is required and must be a non-empty string`);if(typeof n!=`string`)throw TypeError(`old_string is required and must be a string`);if(n===``)throw Error(`old_string cannot be empty`);if(typeof r!=`string`)throw TypeError(`new_string is required and must be a string`);if(n===r)throw Error(`new_string must be different from old_string`);return{file_path:t.trim(),old_string:n,new_string:r,replace_all:e.replace_all===!0}}countOccurrences(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}truncateForError(e,t=200){return e.length<=t?e:`${e.slice(0,t)}... [truncated, ${e.length} chars total]`}},Ne=class extends Y{name=`Write`;riskLevel=`high`;_cwd;_allowedDirectory;constructor(e){super(),this._cwd=e?.cwd??d.cwd(),this._allowedDirectory=e?.allowedDirectory}get description(){let e=`Writes a file to the local filesystem.
|
|
167
|
+
|
|
168
|
+
Usage notes:
|
|
169
|
+
- This tool will overwrite the existing file if there is one at the provided path
|
|
170
|
+
- Parent directories will be created automatically if they don't exist
|
|
171
|
+
- ALWAYS prefer editing existing files over writing new ones
|
|
172
|
+
- NEVER proactively create documentation files (*.md) or README files unless explicitly requested`;return this._allowedDirectory?`${e}
|
|
173
|
+
- IMPORTANT: Files can ONLY be written within: ${this._allowedDirectory}
|
|
174
|
+
- Use absolute paths starting with ${this._allowedDirectory}/ (e.g., ${this._allowedDirectory}/filename.html)`:e}get parameters(){return{type:`object`,properties:{file_path:{type:`string`,description:this._allowedDirectory?`The absolute path to the file to write (must be within ${this._allowedDirectory})`:`The absolute path to the file to write (must be absolute, not relative)`},content:{type:`string`,description:`The content to write to the file`}},required:[`file_path`,`content`]}}setCwd(e){this._cwd=e}getCwd(){return this._cwd}setAllowedDirectory(e){this._allowedDirectory=e}getAllowedDirectory(){return this._allowedDirectory}async execute(e){let{file_path:t,content:n}=this.validateArgs(e),r=c.isAbsolute(t)?t:c.resolve(this._cwd,t);if(this._allowedDirectory){let e=c.resolve(this._allowedDirectory),n=c.resolve(r);if(!n.startsWith(e+c.sep)&&n!==e)return J(`Access denied: ${t}\nFiles can only be written within: ${this._allowedDirectory}\nPlease use a path like: ${this._allowedDirectory}/<filename>`)}let i=!1;try{if((await h(r)).isDirectory())return J(`Path is a directory, not a file: ${r}`);i=!0}catch(e){if(e.code!==`ENOENT`)throw e}await f(c.dirname(r),{recursive:!0}),await g(r,n,`utf-8`);let a=Buffer.byteLength(n,`utf-8`),o={success:!0,filePath:r,bytesWritten:a,overwritten:i,message:i?`Successfully overwrote ${c.basename(r)} (${this.formatSize(a)})`:`Successfully created ${c.basename(r)} (${this.formatSize(a)})`};return{content:[{type:`text`,text:o.message}],structuredContent:o}}validateArgs(e){let t=e.file_path,n=e.content;if(typeof t!=`string`||!t.trim())throw Error(`file_path is required and must be a non-empty string`);if(typeof n!=`string`)throw TypeError(`content is required and must be a string`);return{file_path:t.trim(),content:n}}formatSize(e){let t=[`B`,`KB`,`MB`,`GB`],n=e,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n.toFixed(r===0?0:2)} ${t[r]}`}},Pe=class extends Y{name=`WebSearch`;description=`Allows the agent to search the web and use the results to inform responses.
|
|
175
|
+
|
|
176
|
+
Usage notes:
|
|
177
|
+
- Provides up-to-date information for current events and recent data
|
|
178
|
+
- Returns search results with titles, links, and snippets
|
|
179
|
+
- Use this tool for accessing information beyond the knowledge cutoff
|
|
180
|
+
- After answering, include a "Sources:" section with relevant URLs as markdown hyperlinks`;parameters={type:`object`,properties:{query:{type:`string`,minLength:2,description:`The search query to use`}},required:[`query`]};apiKey;apiEndpoint;numResults;constructor(e){super(),this.apiKey=e?.apiKey??d.env.SERPER_API_KEY??``,this.apiEndpoint=e?.apiEndpoint??`https://google.serper.dev/search?format=json`,this.numResults=e?.numResults??10}setApiKey(e){this.apiKey=e}async execute(e){let{query:t}=this.validateArgs(e);if(!this.apiKey)return J(`Serper API key is not configured. Set SERPER_API_KEY environment variable or pass apiKey in constructor.`);try{let e=await fetch(this.apiEndpoint,{method:`POST`,headers:{"X-API-KEY":this.apiKey,"Content-Type":`application/json`},body:JSON.stringify({q:t,num:this.numResults})});if(!e.ok){let t=await e.text();return J(`Serper API error (${e.status}): ${t}`)}let n=((await e.json()).organic??[]).map((e,t)=>({title:e.title,link:e.link,snippet:e.snippet,position:e.position??t+1})),r=this.formatMarkdown(t,n),i={success:!0,query:t,results:n,totalResults:n.length,markdown:r};return{content:[{type:`text`,text:r}],structuredContent:i}}catch(e){return J(`Failed to execute search: ${e instanceof Error?e.message:String(e)}`)}}validateArgs(e){let t=e.query;if(typeof t!=`string`||t.trim().length<2)throw Error(`query is required and must be at least 2 characters`);return{query:t.trim()}}formatMarkdown(e,t){if(t.length===0)return`No results found for: "${e}"`;let n=[`## Search Results for: "${e}"`,``];for(let e of t)n.push(`### ${e.position}. [${e.title}](${e.link})`),n.push(``),n.push(e.snippet),n.push(``);n.push(`---`),n.push(``),n.push(`**Sources:**`);for(let e of t)n.push(`- [${e.title}](${e.link})`);return n.join(`
|
|
181
|
+
`)}},Fe=class{tools=new Map;register(e){if(this.tools.has(e.name))throw Error(`Tool "${e.name}" already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}list(){return Array.from(this.tools.values())}has(e){return this.tools.has(e)}get size(){return this.tools.size}toOpenAIFormat(){return this.list().map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}};export{pe as Agent,j as AgentAbortError,ue as AgentMaxIterationsError,de as BaseHook,me as BaseModel,A as BaseSession,le as BaseSessionManager,Y as BaseTool,Me as EditTool,z as FileCheckpointStore,z as FileStateStore,Ee as GlobTool,Oe as GrepTool,P as HookManager,B as InMemoryCheckpointStore,B as InMemoryStateStore,H as InMemoryModelHealth,V as ModelError,je as ReadTool,G as RetryPolicy,L as Session,T as StateKeys,R as StateStore,Fe as ToolRegistry,Pe as WebSearchTool,Ne as WriteTool,F as compose,ce as compressSessionManually,te as createContextCompressionMiddleware,I as createInitialLoopState,_e as createModel,xe as createOpenAIAdapter,N as ensureNotAborted,J as errorContent,v as fromLoopCheckpoint,Ce as imageContent,Se as textContent,_ as toLoopCheckpoint};
|
package/package.json
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "goatchain",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.2",
|
|
5
|
+
"description": "",
|
|
6
|
+
"author": "Simon He",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"keywords": [],
|
|
9
|
+
"main": "dist/index.js",
|
|
10
|
+
"types": "dist/index.d.ts",
|
|
11
|
+
"files": [
|
|
12
|
+
"dist/**/*"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=18"
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@anthropic-ai/claude-agent-sdk": "^0.1.76",
|
|
19
|
+
"@modelcontextprotocol/sdk": "^1.17.3",
|
|
20
|
+
"openai": "^6.9.1",
|
|
21
|
+
"tiktoken": "^1.0.22"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"@antfu/eslint-config": "^6.7.1",
|
|
25
|
+
"@changesets/cli": "^2.29.7",
|
|
26
|
+
"@slidev/cli": "^52.1.0",
|
|
27
|
+
"@slidev/theme-default": "^0.25.0",
|
|
28
|
+
"@sxzz/prettier-config": "^2.2.6",
|
|
29
|
+
"@tsconfig/recommended": "^1.0.10",
|
|
30
|
+
"@types/node": "^22.13.5",
|
|
31
|
+
"@vitest/ui": "^2.1.8",
|
|
32
|
+
"bumpp": "^10.3.2",
|
|
33
|
+
"chokidar": "^4.0.1",
|
|
34
|
+
"dotenv": "^17.2.1",
|
|
35
|
+
"eslint": "^9.19.0",
|
|
36
|
+
"picocolors": "^1.1.1",
|
|
37
|
+
"prettier": "^3.6.2",
|
|
38
|
+
"tsdown": "^0.15.12",
|
|
39
|
+
"tsx": "^4.20.5",
|
|
40
|
+
"typescript": "^5.9.2",
|
|
41
|
+
"typescript-eslint": "^8.22.0",
|
|
42
|
+
"vitest": "^4.0.16"
|
|
43
|
+
},
|
|
44
|
+
"prettier": "@sxzz/prettier-config",
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsdown --minify --format esm",
|
|
47
|
+
"dev": "tsc --watch",
|
|
48
|
+
"typecheck": "tsc --noEmit",
|
|
49
|
+
"lint": "eslint --no-error-on-unmatched-pattern src/**/*.ts examples/**/*.ts test/**/*.ts",
|
|
50
|
+
"lint:fix": "eslint --no-error-on-unmatched-pattern src/**/*.ts examples/**/*.ts test/**/*.ts --fix",
|
|
51
|
+
"format": "eslint --fix --no-error-on-unmatched-pattern \"src/**/*.ts\" \"test/**/*.ts\" \"scripts/**/*.ts\" \"examples/**/*.ts\" && prettier --cache --write \"**/*.{json,md,yaml,yml}\"",
|
|
52
|
+
"prettier": "prettier --write \"src/**/*.{ts,js,json,md}\" \"examples/**/*.{ts,js,json,md}\" \"packages/cli/src/**/*.{ts,js,json,md}\"",
|
|
53
|
+
"prettier:check": "prettier --check \"src/**/*.{ts,js,json,md}\" \"examples/**/*.{ts,js,json,md}\" \"packages/cli/src/**/*.{ts,js,json,md}\"",
|
|
54
|
+
"test": "pnpm -r -s build && vitest run",
|
|
55
|
+
"start": "node dist/index.js",
|
|
56
|
+
"build:all": "pnpm -r -s build",
|
|
57
|
+
"cli": "pnpm -C packages/cli -s cli",
|
|
58
|
+
"cli:smoke": "pnpm -C packages/cli -s smoke",
|
|
59
|
+
"cli:publish": "pnpm -C packages/cli publish",
|
|
60
|
+
"slides:gen": "node scripts/gen-slidev-readme.mjs",
|
|
61
|
+
"slides:dev": "pnpm -s slides:gen && slidev slides/README.slides.md",
|
|
62
|
+
"slides:build": "pnpm -s slides:gen && slidev build slides/README.slides.md --out dist/slides",
|
|
63
|
+
"slides:export": "pnpm -s slides:gen && slidev export slides/README.slides.md --output dist/agent-loop-readme.pdf"
|
|
64
|
+
}
|
|
65
|
+
}
|