// @bun
import{Dl as ee,yl as ze,zl as X}from"./chunk-q532xbtw.js";import{Dm as de,Gm as T}from"./chunk-n70kwbk5.js";import{Xn as He,Yn as We}from"./chunk-6wq8tkg7.js";import{Eq as D,Jq as $,Ls as fe,Mq as S,Ms as ke,Oo as M,To as B,aq as ie,at as _,br as v,dt as a,eq as ve,pr as je,rq as qe,sq as P,sr as Ae,ur as Ue,vs as V,wr as Ye,zq as oe}from"./chunk-9fn5qenm.js";import{Ct as K}from"./chunk-g2rmdpb3.js";import{Ax as E,Cy as Q,Oy as G,VA as Y,bD as r,cA as te,dB as he,oy as be,xG as e,xx as me}from"./chunk-bt9y3st3.js";import{KG as or}from"./chunk-vk8psqqh.js";import{LG as rr,NG as ne}from"./chunk-xyhgvt88.js";var W={};ne(W,{layer:()=>ue,defaultLayer:()=>xe,Truncate:()=>W,Service:()=>N,MAX_LINES:()=>I,MAX_BYTES:()=>x,GLOB:()=>Fe,DIR:()=>_e});import F from"path";var Le=e.String.check(e.isStartsWith("tool")).pipe(e.brand("ToolID")),se=Le.pipe(oe((o)=>({ascending:(n)=>o.make(D.ascending("tool",n))})));import Me from"path";var J=Me.join(K.Path.data,"tool-output");var Xe=ie({service:"truncation"}),Be=G.days(7),I=2000,x=51200,_e=J,Fe=F.join(J,"*");function Ie(o){if(!o?.permission)return!1;return _("task","*",o.permission).action!=="deny"}class N extends Q.Service()("@muxcode/Truncate"){}var ue=Y.effect(N,r.gen(function*(){let o=yield*P.Service,n=r.fn("Truncate.cleanup")(function*(){let g=D.timestamp(D.create("tool","ascending",Date.now()-G.toMillis(Be))),w=yield*o.readDirectory(J).pipe(r.map((c)=>c.filter((b)=>b.startsWith("tool_"))),r.catch(()=>r.succeed([])));for(let c of w){if(D.timestamp(c)>=g)continue;yield*o.remove(F.join(J,c)).pipe(r.catch(()=>r.void))}}),s=r.fn("Truncate.write")(function*(g){let w=F.join(J,se.ascending());return yield*o.ensureDir(J).pipe(r.orDie),yield*o.writeFileString(w,g).pipe(r.orDie),w}),u=r.fn("Truncate.limits")(function*(){let g=yield*r.serviceOption(V.Service);if(E.isNone(g))return{maxLines:I,maxBytes:x};let w=yield*g.value.get().pipe(r.catch(()=>r.succeed(void 0)));return{maxLines:w?.tool_output?.max_lines??I,maxBytes:w?.tool_output?.max_bytes??x}}),i=r.fn("Truncate.output")(function*(g,w={},c){let b=yield*u(),j=w.maxLines??b.maxLines,U=w.maxBytes??b.maxBytes,A=w.direction??"head",y=g.split(`
`),p=Buffer.byteLength(g,"utf-8");if(y.length<=j&&p<=U)return{content:g,truncated:!1};let l=[],m=0,k=0,H=!1;if(A==="head")for(m=0;m<y.length&&m<j;m++){let R=Buffer.byteLength(y[m],"utf-8")+(m>0?1:0);if(k+R>U){H=!0;break}l.push(y[m]),k+=R}else for(m=y.length-1;m>=0&&l.length<j;m--){let R=Buffer.byteLength(y[m],"utf-8")+(l.length>0?1:0);if(k+R>U){H=!0;break}l.unshift(y[m]),k+=R}let q=H?p-k:y.length-l.length,h=H?"bytes":"lines",d=l.join(`
`),t=yield*s(g),C=Ie(c)?`The tool call succeeded but the output was truncated. Full output saved to: ${t}
Use the Task tool to have explore agent process this file with Grep and Read (with offset/limit). Do NOT read the full file yourself - delegate to save context.`:`The tool call succeeded but the output was truncated. Full output saved to: ${t}
Use Grep to search the full content or Read with offset/limit to view specific sections.`;return{content:A==="head"?`${d}

...${q} ${h} truncated...

${C}`:`...${q} ${h} truncated...

${C}

${d}`,truncated:!0,outputPath:t}});return yield*n().pipe(r.catchCause((g)=>{return Xe.error("truncation cleanup failed",{cause:te.pretty(g)}),r.void}),r.repeat(he.spaced(G.hours(1))),r.delay(G.minutes(1)),r.forkScoped),N.of({cleanup:n,write:s,output:i,limits:u})})),xe=ue.pipe(Y.provide(P.defaultLayer),Y.provide(de.layer));var L={};ne(L,{use:()=>tr,layer:()=>Ke,defaultLayer:()=>hr,Service:()=>Z,Info:()=>nr,Agent:()=>L});var ae=`You are an elite AI agent architect specializing in crafting high-performance agent configurations. Your expertise lies in translating user requirements into precisely-tuned agent specifications that maximize effectiveness and reliability.

**Important Context**: You may have access to project-specific instructions from CLAUDE.md files and other context that may include coding standards, project structure, and custom requirements. Consider this context when creating agents to ensure they align with the project's established patterns and practices.

When a user describes what they want an agent to do, you will:

1. **Extract Core Intent**: Identify the fundamental purpose, key responsibilities, and success criteria for the agent. Look for both explicit requirements and implicit needs. Consider any project-specific context from CLAUDE.md files. For agents that are meant to review code, you should assume that the user is asking to review recently written code and not the whole codebase, unless the user has explicitly instructed you otherwise.

2. **Design Expert Persona**: Create a compelling expert identity that embodies deep domain knowledge relevant to the task. The persona should inspire confidence and guide the agent's decision-making approach.

3. **Architect Comprehensive Instructions**: Develop a system prompt that:

   - Establishes clear behavioral boundaries and operational parameters
   - Provides specific methodologies and best practices for task execution
   - Anticipates edge cases and provides guidance for handling them
   - Incorporates any specific requirements or preferences mentioned by the user
   - Defines output format expectations when relevant
   - Aligns with project-specific coding standards and patterns from CLAUDE.md

4. **Optimize for Performance**: Include:

   - Decision-making frameworks appropriate to the domain
   - Quality control mechanisms and self-verification steps
   - Efficient workflow patterns
   - Clear escalation or fallback strategies

5. **Create Identifier**: Design a concise, descriptive identifier that:
   - Uses lowercase letters, numbers, and hyphens only
   - Is typically 2-4 words joined by hyphens
   - Clearly indicates the agent's primary function
   - Is memorable and easy to type
   - Avoids generic terms like "helper" or "assistant"

6 **Example agent descriptions**:

- in the 'whenToUse' field of the JSON object, you should include examples of when this agent should be used.
- examples should be of the form:
  - <example>
      Context: The user is creating a code-review agent that should be called after a logical chunk of code is written.
      user: "Please write a function that checks if a number is prime"
      assistant: "Here is the relevant function: "
      <function call omitted for brevity only for this example>
      <commentary>
      Since the user is greeting, use the Task tool to launch the greeting-responder agent to respond with a friendly joke. 
      </commentary>
      assistant: "Now let me use the code-reviewer agent to review the code"
    </example>
  - <example>
      Context: User is creating an agent to respond to the word "hello" with a friendly jok.
      user: "Hello"
      assistant: "I'm going to use the Task tool to launch the greeting-responder agent to respond with a friendly joke"
      <commentary>
      Since the user is greeting, use the greeting-responder agent to respond with a friendly joke. 
      </commentary>
    </example>
- If the user mentioned or implied that the agent should be used proactively, you should include examples of this.
- NOTE: Ensure that in the examples, you are making the assistant use the Agent tool and not simply respond directly to the task.

Your output must be a valid JSON object with exactly these fields:
{
"identifier": "A unique, descriptive identifier using lowercase letters, numbers, and hyphens (e.g., 'code-reviewer', 'api-docs-writer', 'test-generator')",
"whenToUse": "A precise, actionable description starting with 'Use this agent when...' that clearly defines the triggering conditions and use cases. Ensure you include examples as described above.",
"systemPrompt": "The complete system prompt that will govern the agent's behavior, written in second person ('You are...', 'You will...') and structured for maximum clarity and effectiveness"
}

Key principles for your system prompts:

- Be specific rather than generic - avoid vague instructions
- Include concrete examples when they would clarify behavior
- Balance comprehensiveness with clarity - every instruction should add value
- Ensure the agent has enough context to handle variations of the core task
- Make the agent proactive in seeking clarification when needed
- Build in quality assurance and self-correction mechanisms

Remember: The agents you create should be autonomous experts capable of handling their designated tasks with minimal additional guidance. Your system prompts are their complete operational manual.
`;var ce=`You are an anchored context summarization assistant for coding sessions.

Summarize only the conversation history you are given. The newest turns may be kept verbatim outside your summary, so focus on the older context that still matters for continuing the work.

If the prompt includes a <previous-summary> block, treat it as the current anchored summary. Update it with the new history by preserving still-true details, removing stale details, and merging in new facts.

Always follow the exact output structure requested by the user prompt. Keep every section, preserve exact file paths and identifiers when known, and prefer terse bullets over paragraphs.

Do not answer the conversation itself. Do not mention that you are summarizing, compacting, or merging context. Respond in the same language as the conversation.
`;var le=`You are a file search specialist. You excel at thoroughly navigating and exploring codebases.

Your strengths:
- Rapidly finding files using glob patterns
- Searching code and text with powerful regex patterns
- Reading and analyzing file contents

Guidelines:
- Use Glob for broad file pattern matching
- Use Grep for searching file contents with regex
- Use Read when you know the specific file path you need to read
- Use Bash for file operations like copying, moving, or listing directory contents
- Adapt your search approach based on the thoroughness level specified by the caller
- Return file paths as absolute paths in your final response
- For clear communication, avoid using emojis
- Do not create any files, or run bash commands that modify the user's system state in any way

Complete the user's search request efficiently and report your findings clearly.
`;var ge=`You are \`scout\`, a read-only research agent for external libraries, dependency source, and documentation.

Your purpose is to investigate code outside the local workspace and return evidence-backed findings without modifying the user's workspace.

Use this agent when asked to:
- inspect dependency repositories or library source
- compare local code against upstream implementations
- research public GitHub repositories the environment can clone
- explain how a library or framework works by reading its source and docs
- investigate third-party APIs, workflows, or behavior outside the current workspace

Working style:
1. When the task involves a GitHub repository or dependency source, use \`repo_clone\` first.
2. After cloning, use \`Glob\`, \`Grep\`, and \`Read\` to inspect the cloned repository.
3. Use \`WebFetch\` for official documentation pages when source alone is not enough.
4. Prefer direct code and documentation evidence over assumptions.
5. If multiple external repositories are relevant, inspect each one before drawing conclusions.

Research standards:
- cite exact absolute file paths and line references whenever possible
- separate what is verified from what is inferred
- if the answer depends on branch state, note that you are reading the repository's current default clone state unless the caller specifies otherwise
- if a repository cannot be cloned or accessed, say so explicitly and continue with whatever evidence is still available
- call out uncertainty clearly instead of smoothing over gaps

Output expectations:
- start with the direct answer
- then explain the evidence repository by repository or source by source
- include file references when relevant
- keep the explanation organized and easy to scan

Constraints:
- do not modify files or run tools that change the user's workspace
- return absolute file paths for cloned-repo findings in your final response

Complete the user's research request efficiently and report your findings clearly.
`;var we=`Summarize what was done in this conversation. Write like a pull request description.

Rules:
- 2-3 sentences max
- Describe the changes made, not the process
- Do not mention running tests, builds, or other validation steps
- Do not explain what the user asked for
- Write in first person (I added..., I fixed...)
- Never ask questions or add new questions
- If the conversation ends with an unanswered question to the user, preserve that exact question
- If the conversation ends with an imperative statement or request to the user (e.g. "Now please run the command and paste the console output"), always include that exact request in the summary
`;var ye=`You are a title generator. You output ONLY a thread title. Nothing else.

<task>
Generate a brief title that would help the user find this conversation later.

Follow all rules in <rules>
Use the <examples> so you know what a good title looks like.
Your output must be:
- A single line
- \u226450 characters
- No explanations
</task>

<rules>
- you MUST use the same language as the user message you are summarizing
- Title must be grammatically correct and read naturally - no word salad
- Never include tool names in the title (e.g. "read tool", "bash tool", "edit tool")
- Focus on the main topic or question the user needs to retrieve
- Vary your phrasing - avoid repetitive patterns like always starting with "Analyzing"
- When a file is mentioned, focus on WHAT the user wants to do WITH the file, not just that they shared it
- Keep exact: technical terms, numbers, filenames, HTTP codes
- Remove: the, this, my, a, an
- Never assume tech stack
- Never use tools
- NEVER respond to questions, just generate a title for the conversation
- The title should NEVER include "summarizing" or "generating" when generating a title
- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
- Always output something meaningful, even if the input is minimal.
- If the user message is short or conversational (e.g. "hello", "lol", "what's up", "hey"):
  \u2192 create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
</rules>

<examples>
"debug 500 errors in production" \u2192 Debugging production 500 errors
"refactor user service" \u2192 Refactoring user service
"why is app.js failing" \u2192 app.js failure investigation
"implement rate limiting" \u2192 Rate limiting implementation
"how do I connect postgres to my API" \u2192 Postgres API connection
"best practices for React hooks" \u2192 React hooks best practices
"@src/auth.ts can you add refresh token support" \u2192 Auth refresh token support
"@utils/parser.ts this is broken" \u2192 Parser bug fix
"look at @config.json" \u2192 Config review
"@App.tsx add dark mode toggle" \u2192 Dark mode toggle in App
</examples>
`;import z from"path";var f=rr(or(),1);class O extends be()("@effect/opentelemetry/Tracer"){}var Er={internal:f.SpanKind.INTERNAL,client:f.SpanKind.CLIENT,server:f.SpanKind.SERVER,producer:f.SpanKind.PRODUCER,consumer:f.SpanKind.CONSUMER};var nr=e.Struct({name:e.String,description:e.optional(e.String),mode:e.Literals(["subagent","primary","all"]),native:e.optional(e.Boolean),hidden:e.optional(e.Boolean),topP:e.optional(e.Finite),temperature:e.optional(e.Finite),color:e.optional(e.String),permission:a.Ruleset,model:e.optional(e.Struct({modelID:We,providerID:He})),variant:e.optional(e.String),prompt:e.optional(e.String),options:e.Record(e.String,e.Unknown),steps:e.optional(e.Finite)}).annotate({identifier:"Agent"}),pe=e.Struct({identifier:e.String,whenToUse:e.String,systemPrompt:e.String});class Z extends Q.Service()("@muxcode/Agent"){}var tr=qe(Z),Ke=Y.effect(Z,r.gen(function*(){let o=yield*V.Service,n=yield*S.Service,s=yield*ee.Service,u=yield*T.Service,i=yield*X.Service,g=yield*v.Service,w=yield*$.make(r.fn("Agent.state")(function*(c){let b=yield*o.get(),j=yield*u.dirs(),U=[W.GLOB,z.join(K.Path.tmp,"*"),...j.map((h)=>z.join(h,"*"))],A={"*":"ask",...Object.fromEntries(U.map((h)=>[h,"allow"]))},y=a.fromConfig({"*":"allow",doom_loop:"ask",external_directory:{"*":"ask",...Object.fromEntries(U.map((h)=>[h,"allow"]))},question:"deny",plan_enter:"deny",plan_exit:"deny",repo_clone:"deny",repo_overview:"deny",read:{"*":"allow","*.env":"ask","*.env.*":"ask","*.env.example":"allow"}}),p=a.fromConfig(b.permission??{}),l={build:{name:"build",description:"The default agent. Executes tools based on configured permissions.",options:{},permission:a.merge(y,a.fromConfig({question:"allow",plan_enter:"allow"}),p),mode:"primary",native:!0},plan:{name:"plan",description:"Plan mode. Disallows all edit tools.",options:{},permission:a.merge(y,a.fromConfig({question:"allow",plan_exit:"allow",external_directory:{[z.join(K.Path.data,"plans","*")]:"allow"},edit:{"*":"deny",[z.join(".muxcode","plans","*.md")]:"allow",[z.relative(c.worktree,z.join(K.Path.data,z.join("plans","*.md")))]:"allow"}}),p),mode:"primary",native:!0},general:{name:"general",description:"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.",permission:a.merge(y,a.fromConfig({todowrite:"deny"}),p),options:{},mode:"subagent",native:!0},explore:{name:"explore",permission:a.merge(y,a.fromConfig({"*":"deny",grep:"allow",glob:"allow",list:"allow",bash:"allow",webfetch:"allow",websearch:"allow",read:"allow",external_directory:A}),p),description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',prompt:le,options:{},mode:"subagent",native:!0},...g.experimentalScout?{scout:{name:"scout",permission:a.merge(y,a.fromConfig({"*":"deny",grep:"allow",glob:"allow",webfetch:"allow",websearch:"allow",read:"allow",repo_clone:"allow",repo_overview:"allow",external_directory:{...A,[z.join(K.Path.repos,"*")]:"allow"}}),p),description:"Docs and dependency-source specialist. Use this when you need to inspect external documentation, clone dependency repositories into the managed cache, and research library implementation details without modifying the user's workspace.",prompt:ge,options:{},mode:"subagent",native:!0}}:{},compaction:{name:"compaction",mode:"primary",native:!0,hidden:!0,prompt:ce,permission:a.merge(y,a.fromConfig({"*":"deny"}),p),options:{}},title:{name:"title",mode:"primary",options:{},native:!0,hidden:!0,temperature:0.5,permission:a.merge(y,a.fromConfig({"*":"deny"}),p),prompt:ye},summary:{name:"summary",mode:"primary",options:{},native:!0,hidden:!0,permission:a.merge(y,a.fromConfig({"*":"deny"}),p),prompt:we}};for(let[h,d]of Object.entries(b.agent??{})){if(d.disable){delete l[h];continue}let t=l[h];if(!t)t=l[h]={name:h,mode:"all",permission:a.merge(y,p),options:{},native:!1};if(d.model)t.model=X.parseModel(d.model);t.variant=d.variant??t.variant,t.prompt=d.prompt??t.prompt,t.description=d.description??t.description,t.temperature=d.temperature??t.temperature,t.topP=d.top_p??t.topP,t.mode=d.mode??t.mode,t.color=d.color??t.color,t.hidden=d.hidden??t.hidden,t.name=d.name??t.name,t.steps=d.steps??t.steps,t.options=Ye(t.options,d.options??{}),t.permission=a.merge(t.permission,a.fromConfig(d.permission??{}))}for(let h in l){if(l[h].permission.some((C)=>{if(C.permission!=="external_directory")return!1;if(C.action!=="deny")return!1;return C.pattern===W.GLOB}))continue;l[h].permission=a.merge(l[h].permission,a.fromConfig({external_directory:{[W.GLOB]:"allow"}}))}let m=r.fnUntraced(function*(h){return l[h]}),k=r.fnUntraced(function*(){let h=yield*o.get();return je(l,Ae(),Ue([(d)=>h.default_agent?d.name===h.default_agent:d.name==="build","desc"],[(d)=>d.name,"asc"]))}),H=r.fnUntraced(function*(){let h=yield*o.get();if(h.default_agent){let t=l[h.default_agent];if(!t)throw Error(`default agent "${h.default_agent}" not found`);if(t.mode==="subagent")throw Error(`default agent "${h.default_agent}" is a subagent`);if(t.hidden===!0)throw Error(`default agent "${h.default_agent}" is hidden`);return t}let d=Object.values(l).find((t)=>t.mode!=="subagent"&&t.hidden!==!0);if(!d)throw Error("no primary visible agent found");return d}),q=r.fnUntraced(function*(){return(yield*H()).name});return{get:m,list:k,defaultInfo:H,defaultAgent:q}}));return Z.of({get:r.fn("Agent.get")(function*(c){return yield*$.useEffect(w,(b)=>b.get(c))}),list:r.fn("Agent.list")(function*(){return yield*$.useEffect(w,(c)=>c.list())}),defaultInfo:r.fn("Agent.defaultInfo")(function*(){return yield*$.useEffect(w,(c)=>c.defaultInfo())}),defaultAgent:r.fn("Agent.defaultAgent")(function*(){return yield*$.useEffect(w,(c)=>c.defaultAgent())}),generate:r.fn("Agent.generate")(function*(c){let b=yield*o.get(),j=c.model??(yield*i.defaultModel()),U=yield*i.getModel(j.providerID,j.modelID),A=yield*i.getLanguage(U),y=b.experimental?.openTelemetry?me(yield*r.serviceOption(O)):void 0,p=[ae];yield*s.trigger("experimental.chat.system.transform",{model:U},{system:p});let l=yield*$.useEffect(w,(q)=>q.list()),m=yield*n.get(j.providerID).pipe(r.orDie),k=j.providerID==="openai"&&m?.type==="oauth",H={experimental_telemetry:{isEnabled:b.experimental?.openTelemetry,tracer:y,metadata:{userId:b.username??"unknown"}},temperature:0.3,messages:[...k?[]:p.map((q)=>({role:"system",content:q})),{role:"user",content:`Create an agent configuration based on this request: "${c.description}".

IMPORTANT: The following identifiers already exist and must NOT be used: ${l.map((q)=>q.name).join(", ")}
  Return ONLY the JSON object, no other text, do not wrap in backticks`}],model:A,schema:Object.assign(e.toStandardSchemaV1(pe),e.toStandardJSONSchemaV1(pe))};if(k)return yield*r.promise(async()=>{let q=ke({...H,providerOptions:ze.providerOptions(U,{instructions:p.join(`
`),store:!1}),onError:()=>{}});for await(let h of q.fullStream)if(h.type==="error")throw h.error;return q.object});return yield*r.promise(()=>fe(H).then((q)=>q.object))})})})),hr=Ke.pipe(Y.provide(ee.defaultLayer),Y.provide(X.defaultLayer),Y.provide(S.defaultLayer),Y.provide(V.defaultLayer),Y.provide(T.defaultLayer),Y.provide(v.defaultLayer));class Je extends e.TaggedErrorClass()("ToolInvalidArgumentsError",{tool:e.String,detail:e.String}){get message(){return`The ${this.tool} tool was called with invalid arguments: ${this.detail}.
Please rewrite the input so it satisfies the expected schema.`}}function ir(o,n,s,u){return()=>r.gen(function*(){let i=typeof n==="function"?{...yield*n()}:{...n},g=e.decodeUnknownEffect(i.parameters),w=i.execute;return i.execute=(c,b)=>{let j={"tool.name":o,"session.id":b.sessionID,"message.id":b.messageID,...b.callID?{"tool.call_id":b.callID}:{}};return r.gen(function*(){let U=yield*g(c).pipe(r.mapError((l)=>new Je({tool:o,detail:i.formatValidationError?i.formatValidationError(l):String(l)}))),A=yield*w(U,b);if(A.metadata.truncated!==void 0)return A;let y=yield*u.get(b.agent),p=yield*s.output(A.output,{},y);return{...A,output:p.content,metadata:{...A.metadata,truncated:p.truncated,...p.truncated&&{outputPath:p.outputPath}}}}).pipe(r.orDie,r.withSpan("Tool.execute",{attributes:j}))},i})}function $e(o,n){return Object.assign(r.gen(function*(){let s=yield*n,u=yield*N,i=yield*L.Service;return{id:o,init:ir(o,s,u,i)}}),{id:o})}function Uo(o){return r.gen(function*(){return{...yield*o.init(),id:o.id}})}var Ne=process.env.EXA_API_KEY?`https://mcp.exa.ai/mcp?exaApiKey=${encodeURIComponent(process.env.EXA_API_KEY)}`:"https://mcp.exa.ai/mcp",Re="https://search.parallel.ai/mcp",dr=e.Struct({result:e.Struct({content:e.Array(e.Struct({type:e.String,text:e.String}))})}),ur=e.decodeUnknownEffect(e.fromJsonString(dr)),De=(o)=>r.gen(function*(){let n=o.trim();if(!n.startsWith("{"))return;return(yield*ur(n)).result.content.find((u)=>u.text)?.text}),ar=r.fn("McpWebSearch.parseResponse")(function*(o){let n=o.trim(),s=n?yield*De(n):void 0;if(s)return s;for(let u of o.split(`
`)){if(!u.startsWith("data: "))continue;let i=yield*De(u.substring(6));if(i)return i}return}),Ge=e.Struct({query:e.String,type:e.String,numResults:e.Number,livecrawl:e.String,contextMaxCharacters:e.optional(e.Number)}),Qe=e.Struct({objective:e.String,search_queries:e.Array(e.String),session_id:e.optional(e.String),model_name:e.optional(e.String)}),cr=(o)=>e.Struct({jsonrpc:e.Literal("2.0"),id:e.Literal(1),method:e.Literal("tools/call"),params:e.Struct({name:e.String,arguments:o})}),re=(o,n,s,u,i,g,w)=>r.gen(function*(){let c=yield*M.post(n).pipe(M.accept("application/json, text/event-stream"),M.setHeaders(w??{}),M.schemaBodyJson(cr(u))({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:s,arguments:i}})),j=yield*(yield*B.filterStatusOk(o).execute(c).pipe(r.timeoutOrElse({duration:g,orElse:()=>r.die(Error(`${s} request timed out`))}))).text;return yield*ar(j)});var Ve=`- Search the web using the session's web search provider - performs real-time web searches and can scrape content from specific URLs
- Provides up-to-date information for current events and recent data
- Supports configurable result counts and returns the content from the most relevant websites
- Use this tool for accessing information beyond knowledge cutoff
- Searches are performed automatically within a single API call

Usage notes:
  - Supports live crawling modes when available: 'fallback' (backup if cached unavailable) or 'preferred' (prioritize live crawling)
  - Search types when available: 'auto' (balanced), 'fast' (quick results), 'deep' (comprehensive search)
  - Configurable context length for optimal LLM integration
  - Domain filtering and advanced search options available

The current year is {{year}}. You MUST use this year when searching for recent information or current events
- Example: If the current year is 2026 and the user asks for "latest AI news", search for "AI news 2026", NOT "AI news 2025"
`;function Ze(o){if(!o)return;let n=2166136261;for(let s=0;s<o.length;s++)n^=o.charCodeAt(s),n=Math.imul(n,16777619);return(n>>>0).toString(36)}var wr=e.Struct({query:e.String.annotate({description:"Websearch query"}),numResults:e.optional(e.Number).annotate({description:"Number of search results to return (default: 8)"}),livecrawl:e.optional(e.Literals(["fallback","preferred"])).annotate({description:"Live crawl mode - 'fallback': use live crawling as backup if cached content unavailable, 'preferred': prioritize live crawling (default: 'fallback')"}),type:e.optional(e.Literals(["auto","fast","deep"])).annotate({description:"Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"}),contextMaxCharacters:e.optional(e.Number).annotate({description:"Maximum characters for context string optimized for LLMs (default: 10000)"})}),No=e.Literals(["exa","parallel"]);function yr(o,n={exa:!1,parallel:!1}){let s=process.env.MUXCODE_WEBSEARCH_PROVIDER;if(s==="exa"||s==="parallel")return s;if(n.parallel)return"parallel";if(n.exa)return"exa";return Number.parseInt(Ze(o)??"0",36)%2===0?"exa":"parallel"}function br(o){if(o==="parallel")return"Parallel Web Search";if(o==="exa")return"Exa Web Search";return"Web Search"}function pr(o){let n=o?.model;if(!n||typeof n!=="object")return;let s="api"in n&&n.api&&typeof n.api==="object"?n.api:void 0,u=s&&"id"in s&&typeof s.id==="string"?s.id:void 0,i="id"in n&&typeof n.id==="string"?n.id:void 0;return(u??i)?.slice(0,100)}function mr(){let o={"User-Agent":`muxcode/${ve}`};if(!process.env.PARALLEL_API_KEY)return o;return{...o,Authorization:`Bearer ${process.env.PARALLEL_API_KEY}`}}function qr(o,n,s,u){if(n==="parallel")return re(o,Re,"web_search",Qe,{objective:s.query,search_queries:[s.query],session_id:u.sessionID,model_name:pr(u.extra)},"25 seconds",mr());return re(o,Ne,"web_search_exa",Ge,{query:s.query,type:s.type||"auto",numResults:s.numResults||8,livecrawl:s.livecrawl||"fallback",contextMaxCharacters:s.contextMaxCharacters},"25 seconds")}var Ro=$e("websearch",r.gen(function*(){let o=yield*B.HttpClient,n=yield*v.Service;return{get description(){return Ve.replace("{{year}}",new Date().getFullYear().toString())},parameters:wr,execute:(s,u)=>r.gen(function*(){let i=yr(u.sessionID,{exa:n.enableExa,parallel:n.enableParallel}),g=br(i);return yield*u.metadata({title:`${g} "${s.query}"`,metadata:{provider:i}}),yield*u.ask({permission:"websearch",patterns:[s.query],always:["*"],metadata:{query:s.query,numResults:s.numResults,livecrawl:s.livecrawl,type:s.type,contextMaxCharacters:s.contextMaxCharacters,provider:i}}),{output:(yield*qr(o,i,s,u))??"No search results found. Please try a different query.",title:`${g}: ${s.query}`,metadata:{provider:i}}}).pipe(r.orDie)}}));
export{N as Lk,xe as Mk,W as Nk,O as Ok,L as Pk,$e as Qk,Uo as Rk,br as Sk,Ro as Tk};
