| 1711 | |
| 1712 | Plan mode note: In plan mode, use this tool to clarify requirements or choose between approaches BEFORE finalizing your plan. Do NOT use this tool to ask "Is my plan ready?" or "Should I proceed?" - use ${TL} for plan approval. IMPORTANT: Do not reference "the plan" in your questions (e.g., "Do you have feedback about the plan?", "Does the plan look good?") because the user cannot see the plan in the UI until you call ${TL}. If you need plan approval, use ${TL} instead. |
| 1713 | `});var BC="TodoWrite";var JM="Skill";var TN="TaskCreate";var Gq6="TaskGet";var Tq6="TaskList";var bL="TaskUpdate";var cN8="EnterWorktree";var lN8="ExitWorktree";function ezz(q,K){let{min:_,max:z}=K,Y=new Set;for(let $ of q.split(",")){let A=$.match(/^\*(?:\/(\d+))?$/);if(A){let j=A[1]?parseInt(A[1],10):1;if(j<1)return null;for(let H=_;H<=z;H+=j)Y.add(H);continue}let O=$.match(/^(\d+)-(\d+)(?:\/(\d+))?$/);if(O){let j=parseInt(O[1],10),H=parseInt(O[2],10),J=O[3]?parseInt(O[3],10):1,M=_===0&&z===6,X=M?7:z;if(j>H||J<1||j<_||H>X)return null;for(let P=j;P<=H;P+=J)Y.add(M&&P===7?0:P);continue}if($.match(/^\d+$/)){let j=parseInt($,10);if(_===0&&z===6&&j===7)j=0;if(j<_||j>z)return null;Y.add(j);continue}return null}if(Y.size===0)return null;return Array.from(Y).sort(($,A)=>$-A)}function Eo6(q){let K=q.trim().split(/\s+/);if(K.length!==5)return null;let _=[];for(let z=0;z<5;z++){let Y=ezz(K[z],tzz[z]);if(!Y)return null;_.push(Y)}return{minute:_[0],hour:_[1],dayOfMonth:_[2],month:_[3],dayOfWeek:_[4]}}function Qy4(q,K){let _=new Set(q.minute),z=new Set(q.hour),Y=new Set(q.dayOfMonth),$=new Set(q.month),A=new Set(q.dayOfWeek),O=q.dayOfMonth.length===31,w=q.dayOfWeek.length===7,j=new Date(K.getTime());j.setSeconds(0,0),j.setMinutes(j.getMinutes()+1);let H=527040;for(let J=0;J<H;J++){let M=j.getMonth()+1;if(!$.has(M)){j.setMonth(j.getMonth()+1,1),j.setHours(0,0,0,0);continue}let X=j.getDate(),P=j.getDay();if(!(O&&w?!0:O?A.has(P):w?Y.has(X):Y.has(X)||A.has(P))){j.setDate(j.getDate()+1),j.setHours(0,0,0,0);continue}if(!z.has(j.getHours())){j.setHours(j.getHours()+1,0,0,0);continue}if(!_.has(j.getMinutes())){j.setMinutes(j.getMinutes()+1);continue}return j}return null}function qYz(q,K){return new Date(2000,0,1,K,q).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"})}function KYz(q,K){let _=new Date;return _.setUTCHours(K,q,0,0),_.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function bV6(q,K){let _=K?.utc??!1,z=q.trim().split(/\s+/);if(z.length!==5)return q;let[Y,$,A,O,w]=z,j=Y.match(/^\*\/(\d+)$/);if(j&&$==="*"&&A==="*"&&O==="*"&&w==="*"){let P=parseInt(j[1],10);return P===1?"Every minute":`Every ${P} minutes`}if(Y.match(/^\d+$/)&&$==="*"&&A==="*"&&O==="*"&&w==="*"){let P=parseInt(Y,10);if(P===0)return"Every hour";return`Every hour at :${P.toString().padStart(2,"0")}`}let H=$.match(/^\*\/(\d+)$/);if(Y.match(/^\d+$/)&&H&&A==="*"&&O==="*"&&w==="*"){let P=parseInt(H[1],10),W=parseInt(Y,10),D=W===0?"":` at :${W.toString().padStart(2,"0")}`;return P===1?`Every hour${D}`:`Every ${P} hours${D}`}if(!Y.match(/^\d+$/)||!$.match(/^\d+$/))return q;let J=parseInt(Y,10),M=parseInt($,10),X=_?KYz:qYz;if(A==="*"&&O==="*"&&w==="*")return`Every day at ${X(J,M)}`;if(A==="*"&&O==="*"&&w.match(/^\d$/)){let P=parseInt(w,10)%7,W;if(_){let D=new Date,f=(P-D.getUTCDay()+7)%7;D.setUTCDate(D.getUTCDate()+f),D.setUTCHours(M,J,0,0),W=Uy4[D.getDay()]}else W=Uy4[P];if(W)return`Every ${W} at ${X(J,M)}`}if(A==="*"&&O==="*"&&w==="1-5")return`Weekdays at ${X(J,M)}`;return q}var tzz,Uy4;var Lo6=y(()=>{tzz=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:6}];Uy4=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]});import{randomUUID as _Yz}from"crypto";import{readFileSync as zYz}from"fs";import{mkdir as YYz,writeFile as $Yz}from"fs/promises";import{join as Op1}from"path";function pr(q){return Op1(q??Fz(),AYz)}async function IV6(q){let K=X8(),_;try{_=await K.readFile(pr(q),{encoding:"utf-8"})}catch(A){if(e3(A))return[];return H6(A),[]}let z=m5(_,!1);if(!z||typeof z!=="object")return[];let Y=z;if(!Array.isArray(Y.tasks))return[];let $=[];for(let A of Y.tasks){if(!A||typeof A.id!=="string"||typeof A.cron!=="string"||typeof A.prompt!=="string"||typeof A.createdAt!=="number"){N(`[ScheduledTasks] skipping malformed task: ${g6(A)}`);continue}if(!Eo6(A.cron)){N(`[ScheduledTasks] skipping task ${A.id} with invalid cron '${A.cron}'`);continue}$.push({id:A.id,cron:A.cron,prompt:A.prompt,createdAt:A.createdAt,...typeof A.lastFiredAt==="number"?{lastFiredAt:A.lastFiredAt}:{},...A.recurring?{recurring:!0}:{},...A.permanent?{permanent:!0}:{}})}return $}function nN8(q){let K;try{K=zYz(pr(q),"utf-8")}catch{return!1}let _=m5(K,!1);if(!_||typeof _!=="object")return!1;let z=_.tasks;return Array.isArray(z)&&z.length>0}async function wp1(q,K){let _=K??Fz();await YYz(Op1(_,".claude"),{recursive:!0});let z={tasks:q.map(({durable:Y,...$})=>$)};await $Yz(pr(_),g6(z,null,2)+` |
| 1714 | `,"utf-8")}async function dy4(q,K,_,z,Y){let $=_Yz().slice(0,8),A={id:$,cron:q,prompt:K,createdAt:Date.now(),..._?{recurring:!0}:{}};if(!z)return mi8({...A,...Y?{agentId:Y}:{}}),$;let O=await IV6();return O.push(A),await wp1(O),$}async function Jw6(q,K){if(q.length===0)return;if(K===void 0&&ob6(q)===q.length)return;let _=new Set(q),z=await IV6(K),Y=z.filter(($)=>!_.has($.id));if(Y.length===z.length)return;await wp1(Y,K)}async function cy4(q,K,_){if(q.length===0)return;let z=new Set(q),Y=await IV6(_),$=!1;for(let A of Y)if(z.has(A.id))A.lastFiredAt=K,$=!0;if(!$)return;await wp1(Y,_)}async function uV6(q){let K=await IV6(q);if(q!==void 0)return K;let _=rb6().map((z)=>({...z,durable:!1}));return[...K,..._]}function xV6(q,K){let _=Eo6(q);if(!_)return null;let z=Qy4(_,new Date(K));return z?z.getTime():null}function ly4(q){let K=parseInt(q.slice(0,8),16)/4294967296;return Number.isFinite(K)?K:0}function jp1(q,K,_,z=kU){let Y=xV6(q,K);if(Y===null)return null;let $=xV6(q,Y);if($===null)return Y;let A=Math.min(ly4(_)*z.recurringFrac*($-Y),z.recurringCapMs);return Y+A}function ny4(q,K,_,z=kU){let Y=xV6(q,K);if(Y===null)return null;if(new Date(Y).getMinutes()%z.oneShotMinuteMod!==0)return Y;let $=z.oneShotFloorMs+ly4(_)*(z.oneShotMaxMs-z.oneShotFloorMs);return Math.max(Y-$,K)}function iy4(q,K){return q.filter((_)=>{let z=xV6(_.cron,_.createdAt);return z!==null&&z<K})}var AYz,kU;var vq6=y(()=>{v8();Lo6();_8();y8();e7();vO();E8();l8();AYz=Op1(".claude","scheduled_tasks.json");kU={recurringFrac:0.1,recurringCapMs:900000,oneShotMaxMs:90000,oneShotFloorMs:0,oneShotMinuteMod:30,recurringMaxAgeMs:604800000}});var oy4={};T8(oy4,{isKairosCronEnabled:()=>vN,isDurableCronEnabled:()=>Br,buildCronListPrompt:()=>Wp1,buildCronDeletePrompt:()=>Xp1,buildCronCreatePrompt:()=>Jp1,buildCronCreateDescription:()=>Hp1,DEFAULT_MAX_AGE_DAYS:()=>kq6,CRON_LIST_TOOL_NAME:()=>Ro6,CRON_LIST_DESCRIPTION:()=>Pp1,CRON_DELETE_TOOL_NAME:()=>Vq6,CRON_DELETE_DESCRIPTION:()=>Mp1,CRON_CREATE_TOOL_NAME:()=>xL});function vN(){return!i6(process.env.CLAUDE_CODE_DISABLE_CRON)&&gV("tengu_kairos_cron",!0,ry4)}function Br(){return gV("tengu_kairos_cron_durable",!0,ry4)}function Hp1(q){return q?"Schedule a prompt to run at a future time — either recurring on a cron schedule, or once at a specific time. Pass durable: true to persist to .claude/scheduled_tasks.json; otherwise session-only.":"Schedule a prompt to run at a future time within this Claude session — either recurring on a cron schedule, or once at a specific time."}function Jp1(q){return`Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders. |
| 1715 | |
| 1716 | Uses standard 5-field cron in the user's local timezone: minute hour day-of-month month day-of-week. "0 9 * * *" means 9am local — no timezone conversion needed. |
| 1717 | |
| 1718 | ## One-shot tasks (recurring: false) |
| 1719 | |
| 1720 | For "remind me at X" or "at <time>, do Y" requests — fire once then auto-delete. |
| 1721 | Pin minute/hour/day-of-month/month to specific values: |
| 1722 | "remind me at 2:30pm today to check the deploy" → cron: "30 14 <today_dom> <today_month> *", recurring: false |
| 1723 | "tomorrow morning, run the smoke test" → cron: "57 8 <tomorrow_dom> <tomorrow_month> *", recurring: false |
| 1724 | |
| 1725 | ## Recurring jobs (recurring: true, the default) |
| 1726 | |
| 1727 | For "every N minutes" / "every hour" / "weekdays at 9am" requests: |
| 1728 | "*/5 * * * *" (every 5 min), "0 * * * *" (hourly), "0 9 * * 1-5" (weekdays at 9am local) |
| 1729 | |
| 1730 | ## Avoid the :00 and :30 minute marks when the task allows it |
| 1731 | |
| 1732 | Every user who asks for "9am" gets \`0 9\`, and every user who asks for "hourly" gets \`0 *\` — which means requests from across the planet land on the API at the same instant. When the user's request is approximate, pick a minute that is NOT 0 or 30: |
| 1733 | "every morning around 9" → "57 8 * * *" or "3 9 * * *" (not "0 9 * * *") |
| 1734 | "hourly" → "7 * * * *" (not "0 * * * *") |
| 1735 | "in an hour or so, remind me to..." → pick whatever minute you land on, don't round |
| 1736 | |
| 1737 | Only use minute 0 or 30 when the user names that exact time and clearly means it ("at 9:00 sharp", "at half past", coordinating with a meeting). When in doubt, nudge a few minutes early or late — the user will not notice, and the fleet will. |
| 1738 | |
| 1739 | ${q?`## Durability |
| 1740 | |
| 1741 | By default (durable: false) the job lives only in this Claude session — nothing is written to disk, and the job is gone when Claude exits. Pass durable: true to write to .claude/scheduled_tasks.json so the job survives restarts. Only use durable: true when the user explicitly asks for the task to persist ("keep doing this every day", "set this up permanently"). Most "remind me in 5 minutes" / "check back in an hour" requests should stay session-only.`:`## Session-only |
| 1742 | |
| 1743 | Jobs live only in this Claude session — nothing is written to disk, and the job is gone when Claude exits.`} |
| 1744 | |
| 1745 | ## Runtime behavior |
| 1746 | |
| 1747 | Jobs only fire while the REPL is idle (not mid-query). ${q?"Durable jobs persist to .claude/scheduled_tasks.json and survive session restarts — on next launch they resume automatically. One-shot durable tasks that were missed while the REPL was closed are surfaced for catch-up. Session-only jobs die with the process. ":""}The scheduler adds a small deterministic jitter on top of whatever you pick: recurring tasks fire up to 10% of their period late (max 15 min); one-shot tasks landing on :00 or :30 fire up to 90 s early. Picking an off-minute is still the bigger lever. |
| 1748 | |
| 1749 | Recurring tasks auto-expire after ${kq6} days — they fire one final time, then are deleted. This bounds session lifetime. Tell the user about the ${kq6}-day limit when scheduling recurring jobs. |
| 1750 | |
| 1751 | Returns a job ID you can pass to ${Vq6}.`}function Xp1(q){return q?`Cancel a cron job previously scheduled with ${xL}. Removes it from .claude/scheduled_tasks.json (durable jobs) or the in-memory session store (session-only jobs).`:`Cancel a cron job previously scheduled with ${xL}. Removes it from the in-memory session store.`}function Wp1(q){return q?`List all cron jobs scheduled via ${xL}, both durable (.claude/scheduled_tasks.json) and session-only.`:`List all cron jobs scheduled via ${xL} in this session.`}var ry4=300000,kq6,xL="CronCreate",Vq6="CronDelete",Ro6="CronList",Mp1="Cancel a scheduled cron job by ID",Pp1="List scheduled cron jobs";var gr=y(()=>{o1();vq6();m8();kq6=kU.recurringMaxAgeMs/86400000});var mV6,Dp1,iN8,ay4;var ho6=y(()=>{Z$();vU();IY();NO6();qM();Hr();E2();rF();GU();gr();mV6=new Set([ak,kX,Zq6,v4,a$,zI]),Dp1=new Set([...mV6]),iN8=new Set([Cq,$N,BC,n3,Sj,i9,...jr,X4,tK,nW,JM,MD,CP,cN8,lN8]),ay4=new Set([TN,Gq6,Tq6,bL,wD,xL,Vq6,Ro6])});var au="TeamCreate";var Mw6="TeamDelete";function pV6(){return!1}var So6=y(()=>{ho6();o1();k8();Z$();IY();GU();m8()});class fp1{constructor(q){this._client=q}async*callToolStream(q,K=MB,_){let z=this._client,Y={..._,task:_?.task??(z.isToolTask(q.name)?{}:void 0)},$=z.requestStream({method:"tools/call",params:q},K,Y),A=z.getToolOutputValidator(q.name);for await(let O of $){if(O.type==="result"&&A){let w=O.result;if(!w.structuredContent&&!w.isError){yield{type:"error",error:new MK($5.InvalidRequest,`Tool ${q.name} has an output schema but did not return structured content`)};return}if(w.structuredContent)try{let j=A(w.structuredContent);if(!j.valid){yield{type:"error",error:new MK($5.InvalidParams,`Structured content does not match the tool's output schema: ${j.errorMessage}`)};return}}catch(j){if(j instanceof MK){yield{type:"error",error:j};return}yield{type:"error",error:new MK($5.InvalidParams,`Failed to validate structured content: ${j instanceof Error?j.message:String(j)}`)};return}}yield O}}async getTask(q,K){return this._client.getTask({taskId:q},K)}async getTaskResult(q,K,_){return this._client.getTaskResult({taskId:q},K,_)}async listTasks(q,K){return this._client.listTasks(q?{cursor:q}:void 0,K)}async cancelTask(q,K){return this._client.cancelTask({taskId:q},K)}requestStream(q,K,_){return this._client.requestStream(q,K,_)}}var sy4=y(()=>{lM()});function rN8(q,K){if(!q||K===null||typeof K!=="object")return;if(q.type==="object"&&q.properties&&typeof q.properties==="object"){let _=K,z=q.properties;for(let Y of Object.keys(z)){let $=z[Y];if(_[Y]===void 0&&Object.prototype.hasOwnProperty.call($,"default"))_[Y]=$.default;if(_[Y]!==void 0)rN8($,_[Y])}}if(Array.isArray(q.anyOf)){for(let _ of q.anyOf)if(typeof _!=="boolean")rN8(_,K)}if(Array.isArray(q.oneOf)){for(let _ of q.oneOf)if(typeof _!=="boolean")rN8(_,K)}}function wYz(q){if(!q)return{supportsFormMode:!1,supportsUrlMode:!1};let K=q.form!==void 0,_=q.url!==void 0;return{supportsFormMode:K||!K&&!_,supportsUrlMode:_}}var oN8;var ty4=y(()=>{V81();lM();y11();Yu6();sy4();oN8=class oN8 extends bu6{constructor(q,K){super(K);if(this._clientInfo=q,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=K?.capabilities??{},this._jsonSchemaValidator=K?.jsonSchemaValidator??new _m6,K?.listChanged)this._pendingListChangedConfig=K.listChanged}_setupListChangedHandlers(q){if(q.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",Lu6,q.tools,async()=>{return(await this.listTools()).tools});if(q.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",yu6,q.prompts,async()=>{return(await this.listPrompts()).prompts});if(q.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",Vu6,q.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new fp1(this)};return this._experimental}registerCapabilities(q){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=wz8(this._capabilities,q)}setRequestHandler(q,K){let z=BP6(q)?.method;if(!z)throw Error("Schema is missing a method literal");let Y;if(Oe(z)){let A=z;Y=A._zod?.def?.value??A.value}else{let A=z;Y=A._def?.value??A.value}if(typeof Y!=="string")throw Error("Schema method literal must be a string");let $=Y;if($==="elicitation/create"){let A=async(O,w)=>{let j=IT(sc,O);if(!j.success){let f=j.error instanceof Error?j.error.message:String(j.error);throw new MK($5.InvalidParams,`Invalid elicitation request: ${f}`)}let{params:H}=j.data;H.mode=H.mode??"form";let{supportsFormMode:J,supportsUrlMode:M}=wYz(this._capabilities.elicitation);if(H.mode==="form"&&!J)throw new MK($5.InvalidParams,"Client does not support form-mode elicitation requests");if(H.mode==="url"&&!M)throw new MK($5.InvalidParams,"Client does not support URL-mode elicitation requests");let X=await Promise.resolve(K(O,w));if(H.task){let f=IT(oc,X);if(!f.success){let G=f.error instanceof Error?f.error.message:String(f.error);throw new MK($5.InvalidParams,`Invalid task creation result: ${G}`)}return f.data}let P=IT(He,X);if(!P.success){let f=P.error instanceof Error?P.error.message:String(P.error);throw new MK($5.InvalidParams,`Invalid elicitation result: ${f}`)}let W=P.data,D=H.mode==="form"?H.requestedSchema:void 0;if(H.mode==="form"&&W.action==="accept"&&W.content&&D){if(this._capabilities.elicitation?.form?.applyDefaults)try{rN8(D,W.content)}catch{}}return W};return super.setRequestHandler(q,A)}if($==="sampling/createMessage"){let A=async(O,w)=>{let j=IT(r61,O);if(!j.success){let W=j.error instanceof Error?j.error.message:String(j.error);throw new MK($5.InvalidParams,`Invalid sampling request: ${W}`)}let{params:H}=j.data,J=await Promise.resolve(K(O,w));if(H.task){let W=IT(oc,J);if(!W.success){let D=W.error instanceof Error?W.error.message:String(W.error);throw new MK($5.InvalidParams,`Invalid task creation result: ${D}`)}return W.data}let X=H.tools||H.toolChoice?hu6:C96,P=IT(X,J);if(!P.success){let W=P.error instanceof Error?P.error.message:String(P.error);throw new MK($5.InvalidParams,`Invalid sampling result: ${W}`)}return P.data};return super.setRequestHandler(q,A)}return super.setRequestHandler(q,K)}assertCapability(q,K){if(!this._serverCapabilities?.[q])throw Error(`Server does not support ${q} (required for ${K})`)}async connect(q,K){if(await super.connect(q),q.sessionId!==void 0)return;try{let _=await this.request({method:"initialize",params:{protocolVersion:we,capabilities:this._capabilities,clientInfo:this._clientInfo}},B61,K);if(_===void 0)throw Error(`Server sent invalid initialize result: ${_}`);if(!c_8.includes(_.protocolVersion))throw Error(`Server's protocol version is not supported: ${_.protocolVersion}`);if(this._serverCapabilities=_.capabilities,this._serverVersion=_.serverInfo,q.setProtocolVersion)q.setProtocolVersion(_.protocolVersion);if(this._instructions=_.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(_){throw this.close(),_}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(q){switch(q){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${q})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${q})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${q})`);if(q==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${q})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${q})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${q})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(q){switch(q){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${q})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(q){if(!this._capabilities)return;switch(q){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${q})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${q})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${q})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${q})`);break;case"ping":break}}assertTaskCapability(q){nz8(this._serverCapabilities?.tasks?.requests,q,"Server")}assertTaskHandlerCapability(q){if(!this._capabilities)return;iz8(this._capabilities.tasks?.requests,q,"Client")}async ping(q){return this.request({method:"ping"},rc,q)}async complete(q,K){return this.request({method:"completion/complete",params:q},o61,K)}async setLoggingLevel(q,K){return this.request({method:"logging/setLevel",params:{level:q}},rc,K)}async getPrompt(q,K){return this.request({method:"prompts/get",params:q},n61,K)}async listPrompts(q,K){return this.request({method:"prompts/list",params:q},Nu6,K)}async listResources(q,K){return this.request({method:"resources/list",params:q},vu6,K)}async listResourceTemplates(q,K){return this.request({method:"resources/templates/list",params:q},F61,K)}async readResource(q,K){return this.request({method:"resources/read",params:q},ku6,K)}async subscribeResource(q,K){return this.request({method:"resources/subscribe",params:q},rc,K)}async unsubscribeResource(q,K){return this.request({method:"resources/unsubscribe",params:q},rc,K)}async callTool(q,K=MB,_){if(this.isToolTaskRequired(q.name))throw new MK($5.InvalidRequest,`Tool "${q.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let z=await this.request({method:"tools/call",params:q},K,_),Y=this.getToolOutputValidator(q.name);if(Y){if(!z.structuredContent&&!z.isError)throw new MK($5.InvalidRequest,`Tool ${q.name} has an output schema but did not return structured content`);if(z.structuredContent)try{let $=Y(z.structuredContent);if(!$.valid)throw new MK($5.InvalidParams,`Structured content does not match the tool's output schema: ${$.errorMessage}`)}catch($){if($ instanceof MK)throw $;throw new MK($5.InvalidParams,`Failed to validate structured content: ${$ instanceof Error?$.message:String($)}`)}}return z}isToolTask(q){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has(q)}isToolTaskRequired(q){return this._cachedRequiredTaskTools.has(q)}cacheToolMetadata(q){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let K of q){if(K.outputSchema){let z=this._jsonSchemaValidator.getValidator(K.outputSchema);this._cachedToolOutputValidators.set(K.name,z)}let _=K.execution?.taskSupport;if(_==="required"||_==="optional")this._cachedKnownTaskTools.add(K.name);if(_==="required")this._cachedRequiredTaskTools.add(K.name)}}getToolOutputValidator(q){return this._cachedToolOutputValidators.get(q)}async listTools(q,K){let _=await this.request({method:"tools/list",params:q},Eu6,K);return this.cacheToolMetadata(_.tools),_}_setupListChangedHandler(q,K,_,z){let Y=eW7.safeParse(_);if(!Y.success)throw Error(`Invalid ${q} listChanged options: ${Y.error.message}`);if(typeof _.onChanged!=="function")throw Error(`Invalid ${q} listChanged options: onChanged must be a function`);let{autoRefresh:$,debounceMs:A}=Y.data,{onChanged:O}=_,w=async()=>{if(!$){O(null,null);return}try{let H=await z();O(null,H)}catch(H){let J=H instanceof Error?H:Error(String(H));O(J,null)}},j=()=>{if(A){let H=this._listChangedDebounceTimers.get(q);if(H)clearTimeout(H);let J=setTimeout(w,A);this._listChangedDebounceTimers.set(q,J)}else w()};this.setNotificationHandler(K,j)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}});function Zp1(q){}function aN8(q){if(typeof q=="function")throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:K=Zp1,onError:_=Zp1,onRetry:z=Zp1,onComment:Y}=q,$="",A=!0,O,w="",j="";function H(W){let D=A?W.replace(/^\xEF\xBB\xBF/,""):W,[f,G]=jYz(`${$}${D}`);for(let Z of f)J(Z);$=G,A=!1}function J(W){if(W===""){X();return}if(W.startsWith(":")){Y&&Y(W.slice(W.startsWith(": ")?2:1));return}let D=W.indexOf(":");if(D!==-1){let f=W.slice(0,D),G=W[D+1]===" "?2:1,Z=W.slice(D+G);M(f,Z,W);return}M(W,"",W)}function M(W,D,f){switch(W){case"event":j=D;break;case"data":w=`${w}${D} |
| 1752 | `;break;case"id":O=D.includes("\x00")?void 0:D;break;case"retry":/^\d+$/.test(D)?z(parseInt(D,10)):_(new Gp1(`Invalid \`retry\` value: "${D}"`,{type:"invalid-retry",value:D,line:f}));break;default:_(new Gp1(`Unknown field "${W.length>20?`${W.slice(0,20)}…`:W}"`,{type:"unknown-field",field:W,value:D,line:f}));break}}function X(){w.length>0&&K({id:O,event:j||void 0,data:w.endsWith(` |
| 1753 | `)?w.slice(0,-1):w}),O=void 0,w="",j=""}function P(W={}){$&&W.consume&&J($),A=!0,O=void 0,w="",j="",$=""}return{feed:H,reset:P}}function jYz(q){let K=[],_="",z=0;for(;z<q.length;){let Y=q.indexOf("\r",z),$=q.indexOf(` |