@reddb-io/red-skills 4.5.0 → 4.6.1
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/bin/build-info.mjs +1 -1
- package/dist/code-nav.bundle.min.mjs +1 -1
- package/dist/opencode-host.bundle.min.mjs +1 -1
- package/dist/redskilled-mcp.bundle.min.mjs +2 -2
- package/dist/redskilled-web.bundle.min.mjs +311 -0
- package/dist/redskilled.bundle.min.mjs +306 -292
- package/dist/release.bundle.min.mjs +1 -1
- package/dist/rsp-core.bundle.min.mjs +1 -1
- package/dist/rsp.bundle.min.mjs +1 -1
- package/dist/statusline.bundle.min.mjs +1 -1
- package/package.json +4 -1
- package/scripts/install-pi.sh +31 -5
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
|
|
3
|
-
var kft=Object.create;var C4=Object.defineProperty;var wft=Object.getOwnPropertyDescriptor;var vft=Object.getOwnPropertyNames;var Eft=Object.getPrototypeOf,Rft=Object.prototype.hasOwnProperty;var $n=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Kn=(e,t)=>{for(var r in t)C4(e,r,{get:t[r],enumerable:!0})},Tft=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vft(t))!Rft.call(e,o)&&o!==r&&C4(e,o,{get:()=>t[o],enumerable:!(n=wft(t,o))||n.enumerable});return e};var Lp=(e,t,r)=>(r=e!=null?kft(Eft(e)):{},Tft(t||!e||!e.__esModule?C4(r,"default",{value:e,enumerable:!0}):r,e));function P4(e){let t={app:e,version:Cft(v_("__RED_BUILD_VERSION__",()=>"4.5.0")??"0.0.0-dev"),gitSha:v_("__RED_BUILD_GIT_SHA__",()=>"d9b92cf35ccd33b6b407f64f98450bda1aba5bfa")??"unknown",buildTime:v_("__RED_BUILD_TIME__",()=>"2026-09-20T10:40:36-03:00")??"unknown",bundleAsset:v_("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=v_("__REDDB_SDK_VERSION__",()=>""),n=v_("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Cft(e){return e.startsWith("v")?e.slice(1):e}function XSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function v_(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var I4=p(()=>{});var Me,sr,A4,O4=p(()=>{Me={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},sr={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},A4={cancel_request:"$/cancel_request"}});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function So(e){return e&&Object.assign(Jy,e),Jy}var e_e,$4,M4,Yl,Jm,Jy,Yy=p(()=>{$4=Object.freeze({status:"aborted"});M4=Symbol("zod_brand"),Yl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(e_e=globalThis).__zod_globalConfig??(e_e.__zod_globalConfig={});Jy=globalThis.__zod_globalConfig});var Re={};Kn(Re,{BIGINT_FORMAT_RANGES:()=>G4,Class:()=>N4,NUMBER_FORMAT_RANGES:()=>q4,aborted:()=>eh,allowsEval:()=>F4,assert:()=>Mft,assertEqual:()=>Ift,assertIs:()=>Oft,assertNever:()=>$ft,assertNotEqual:()=>Aft,assignProp:()=>Qm,base64ToUint8Array:()=>r_e,base64urlToUint8Array:()=>Yft,cached:()=>R_,captureStackTrace:()=>U$,cleanEnum:()=>Jft,cleanRegex:()=>UR,clone:()=>Os,cloneDef:()=>Nft,createTransparentProxy:()=>Hft,defineLazy:()=>Qt,esc:()=>j$,escapeRegex:()=>jc,explicitlyAborted:()=>B4,extend:()=>Bft,finalizeIssue:()=>$s,floatSafeRemainder:()=>L4,getElementAtPath:()=>Lft,getEnumValues:()=>jR,getLengthableOrigin:()=>GR,getParsedType:()=>Uft,getSizableOrigin:()=>qR,hexToUint8Array:()=>Xft,isObject:()=>Qy,isPlainObject:()=>Xm,issue:()=>T_,joinValues:()=>ne,jsonStringifyReplacer:()=>E_,merge:()=>Vft,mergeDefs:()=>zp,normalizeParams:()=>Ie,nullish:()=>Ym,numKeys:()=>jft,objectClone:()=>Dft,omit:()=>Gft,optionalKeys:()=>H4,parsedType:()=>Ee,partial:()=>Kft,pick:()=>qft,prefixIssues:()=>fa,primitiveTypes:()=>U4,promiseAllObject:()=>zft,propertyKeyTypes:()=>HR,randomString:()=>Fft,required:()=>Zft,safeExtend:()=>Wft,shallowClone:()=>j4,slugify:()=>z4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>n_e,uint8ArrayToBase64url:()=>Qft,uint8ArrayToHex:()=>emt,unwrapMessage:()=>FR});function Ift(e){return e}function Aft(e){return e}function Oft(e){}function $ft(e){throw new Error("Unexpected value in exhaustive check")}function Mft(e){}function jR(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function E_(e,t){return typeof t=="bigint"?t.toString():t}function R_(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ym(e){return e==null}function UR(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function L4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Qt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==t_e)return n===void 0&&(n=t_e,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Dft(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Qm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function zp(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Nft(e){return zp(e._zod.def)}function Lft(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function zft(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Fft(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function j$(e){return JSON.stringify(e)}function z4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Qy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xm(e){if(Qy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Qy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function j4(e){return Xm(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function jft(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function jc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Os(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Hft(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function H4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function qft(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=zp(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Qm(this,"shape",s),s},checks:[]});return Os(e,i)}function Gft(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=zp(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Qm(this,"shape",s),s},checks:[]});return Os(e,i)}function Bft(e,t){if(!Xm(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=zp(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Qm(this,"shape",i),i}});return Os(e,o)}function Wft(e,t){if(!Xm(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Qm(this,"shape",n),n}});return Os(e,r)}function Vft(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Qm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Os(e,r)}function Kft(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=zp(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Qm(this,"shape",c),c},checks:[]});return Os(t,s)}function Zft(e,t,r){let n=zp(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Qm(this,"shape",i),i}});return Os(t,n)}function eh(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function B4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function fa(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function FR(e){return typeof e=="string"?e:e?.message}function $s(e,t,r){let n=e.message?e.message:FR(e.inst?._zod.def?.error?.(e))??FR(t?.error?.(e))??FR(r.customError?.(e))??FR(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function qR(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function GR(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function T_(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Jft(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function r_e(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function n_e(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Yft(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return r_e(t+r)}function Qft(e){return n_e(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Xft(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function emt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var t_e,U$,F4,Uft,HR,U4,q4,G4,N4,ot=p(()=>{Yy();t_e=Symbol("evaluating");U$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};F4=R_(()=>{if(Jy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});Uft=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},HR=new Set(["string","number","symbol"]),U4=new Set(["string","number","bigint","boolean","symbol","undefined"]);q4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},G4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};N4=class{constructor(...t){}}});function WR(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function VR(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function W4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function i_e(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function V4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${i_e(n.path)}`);return t.join(`
|
|
3
|
+
var kft=Object.create;var C4=Object.defineProperty;var wft=Object.getOwnPropertyDescriptor;var vft=Object.getOwnPropertyNames;var Eft=Object.getPrototypeOf,Rft=Object.prototype.hasOwnProperty;var $n=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var p=(e,t)=>()=>(e&&(t=e(e=0)),t);var ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Kn=(e,t)=>{for(var r in t)C4(e,r,{get:t[r],enumerable:!0})},Tft=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of vft(t))!Rft.call(e,o)&&o!==r&&C4(e,o,{get:()=>t[o],enumerable:!(n=wft(t,o))||n.enumerable});return e};var Lp=(e,t,r)=>(r=e!=null?kft(Eft(e)):{},Tft(t||!e||!e.__esModule?C4(r,"default",{value:e,enumerable:!0}):r,e));function P4(e){let t={app:e,version:Cft(v_("__RED_BUILD_VERSION__",()=>"4.6.1")??"0.0.0-dev"),gitSha:v_("__RED_BUILD_GIT_SHA__",()=>"59db3526253fd90ae249844241f1489031e5eade")??"unknown",buildTime:v_("__RED_BUILD_TIME__",()=>"2026-09-21T00:46:50-03:00")??"unknown",bundleAsset:v_("__RED_BUNDLE_ASSET__",()=>"redskilled-mcp.bundle.min.mjs")??"unknown"},r=v_("__REDDB_SDK_VERSION__",()=>""),n=v_("__REDDB_BINARY_TAG__",()=>"");return r&&(t.reddbSdkVersion=r),n&&(t.reddbBinaryTag=n),t}function Cft(e){return e.startsWith("v")?e.slice(1):e}function XSe(e){return`${e.app} ${e.version} ${e.gitSha}`}function v_(e,t){try{let r=t();return typeof r=="string"&&r.length>0?r:void 0}catch{return process.env[e.replace(/^__|__$/g,"")]}}var I4=p(()=>{});var Me,sr,A4,O4=p(()=>{Me={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},sr={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_connect:"mcp/connect",mcp_message:"mcp/message",mcp_disconnect:"mcp/disconnect",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},A4={cancel_request:"$/cancel_request"}});function K(e,t,r){function n(a,c){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:c,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(e))return;a._zod.traits.add(e),t(a,c);let l=s.prototype,u=Object.keys(l);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=l[f].bind(a))}}let o=r?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:e});function s(a){var c;let l=r?.Parent?new i:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(s,"init",{value:n}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}function So(e){return e&&Object.assign(Jy,e),Jy}var e_e,$4,M4,Yl,Jm,Jy,Yy=p(()=>{$4=Object.freeze({status:"aborted"});M4=Symbol("zod_brand"),Yl=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Jm=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(e_e=globalThis).__zod_globalConfig??(e_e.__zod_globalConfig={});Jy=globalThis.__zod_globalConfig});var Re={};Kn(Re,{BIGINT_FORMAT_RANGES:()=>G4,Class:()=>N4,NUMBER_FORMAT_RANGES:()=>q4,aborted:()=>eh,allowsEval:()=>F4,assert:()=>Mft,assertEqual:()=>Ift,assertIs:()=>Oft,assertNever:()=>$ft,assertNotEqual:()=>Aft,assignProp:()=>Qm,base64ToUint8Array:()=>r_e,base64urlToUint8Array:()=>Yft,cached:()=>R_,captureStackTrace:()=>U$,cleanEnum:()=>Jft,cleanRegex:()=>UR,clone:()=>Os,cloneDef:()=>Nft,createTransparentProxy:()=>Hft,defineLazy:()=>Qt,esc:()=>j$,escapeRegex:()=>jc,explicitlyAborted:()=>B4,extend:()=>Bft,finalizeIssue:()=>$s,floatSafeRemainder:()=>L4,getElementAtPath:()=>Lft,getEnumValues:()=>jR,getLengthableOrigin:()=>GR,getParsedType:()=>Uft,getSizableOrigin:()=>qR,hexToUint8Array:()=>Xft,isObject:()=>Qy,isPlainObject:()=>Xm,issue:()=>T_,joinValues:()=>ne,jsonStringifyReplacer:()=>E_,merge:()=>Vft,mergeDefs:()=>zp,normalizeParams:()=>Ie,nullish:()=>Ym,numKeys:()=>jft,objectClone:()=>Dft,omit:()=>Gft,optionalKeys:()=>H4,parsedType:()=>Ee,partial:()=>Kft,pick:()=>qft,prefixIssues:()=>fa,primitiveTypes:()=>U4,promiseAllObject:()=>zft,propertyKeyTypes:()=>HR,randomString:()=>Fft,required:()=>Zft,safeExtend:()=>Wft,shallowClone:()=>j4,slugify:()=>z4,stringifyPrimitive:()=>ve,uint8ArrayToBase64:()=>n_e,uint8ArrayToBase64url:()=>Qft,uint8ArrayToHex:()=>emt,unwrapMessage:()=>FR});function Ift(e){return e}function Aft(e){return e}function Oft(e){}function $ft(e){throw new Error("Unexpected value in exhaustive check")}function Mft(e){}function jR(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function ne(e,t="|"){return e.map(r=>ve(r)).join(t)}function E_(e,t){return typeof t=="bigint"?t.toString():t}function R_(e){return{get value(){{let r=e();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ym(e){return e==null}function UR(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function L4(e,t){let r=e/t,n=Math.round(r),o=Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<o?0:r-n}function Qt(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==t_e)return n===void 0&&(n=t_e,n=r()),n},set(o){Object.defineProperty(e,t,{value:o})},configurable:!0})}function Dft(e){return Object.create(Object.getPrototypeOf(e),Object.getOwnPropertyDescriptors(e))}function Qm(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function zp(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function Nft(e){return zp(e._zod.def)}function Lft(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function zft(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i<t.length;i++)o[t[i]]=n[i];return o})}function Fft(e=10){let t="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];return r}function j$(e){return JSON.stringify(e)}function z4(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function Qy(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xm(e){if(Qy(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(Qy(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function j4(e){return Xm(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function jft(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function jc(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Os(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function Ie(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Hft(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function ve(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function H4(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}function qft(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i=zp(e._zod.def,{get shape(){let s={};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&(s[a]=r.shape[a])}return Qm(this,"shape",s),s},checks:[]});return Os(e,i)}function Gft(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=zp(e._zod.def,{get shape(){let s={...e._zod.def.shape};for(let a in t){if(!(a in r.shape))throw new Error(`Unrecognized key: "${a}"`);t[a]&&delete s[a]}return Qm(this,"shape",s),s},checks:[]});return Os(e,i)}function Bft(e,t){if(!Xm(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let i=e._zod.def.shape;for(let s in t)if(Object.getOwnPropertyDescriptor(i,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let o=zp(e._zod.def,{get shape(){let i={...e._zod.def.shape,...t};return Qm(this,"shape",i),i}});return Os(e,o)}function Wft(e,t){if(!Xm(t))throw new Error("Invalid input to safeExtend: expected a plain object");let r=zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Qm(this,"shape",n),n}});return Os(e,r)}function Vft(e,t){if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r=zp(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Qm(this,"shape",n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Os(e,r)}function Kft(e,t,r){let o=t._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=zp(t._zod.def,{get shape(){let a=t._zod.def.shape,c={...a};if(r)for(let l in r){if(!(l in a))throw new Error(`Unrecognized key: "${l}"`);r[l]&&(c[l]=e?new e({type:"optional",innerType:a[l]}):a[l])}else for(let l in a)c[l]=e?new e({type:"optional",innerType:a[l]}):a[l];return Qm(this,"shape",c),c},checks:[]});return Os(t,s)}function Zft(e,t,r){let n=zp(t._zod.def,{get shape(){let o=t._zod.def.shape,i={...o};if(r)for(let s in r){if(!(s in i))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(i[s]=new e({type:"nonoptional",innerType:o[s]}))}else for(let s in o)i[s]=new e({type:"nonoptional",innerType:o[s]});return Qm(this,"shape",i),i}});return Os(t,n)}function eh(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function B4(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function fa(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function FR(e){return typeof e=="string"?e:e?.message}function $s(e,t,r){let n=e.message?e.message:FR(e.inst?._zod.def?.error?.(e))??FR(t?.error?.(e))??FR(r.customError?.(e))??FR(r.localeError?.(e))??"Invalid input",{inst:o,continue:i,input:s,...a}=e;return a.path??(a.path=[]),a.message=n,t?.reportInput&&(a.input=s),a}function qR(e){return e instanceof Set?"set":e instanceof Map?"map":e instanceof File?"file":"unknown"}function GR(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function Ee(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function T_(...e){let[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function Jft(e){return Object.entries(e).filter(([t,r])=>Number.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function r_e(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function n_e(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Yft(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r="=".repeat((4-t.length%4)%4);return r_e(t+r)}function Qft(e){return n_e(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Xft(e){let t=e.replace(/^0x/,"");if(t.length%2!==0)throw new Error("Invalid hex string length");let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=Number.parseInt(t.slice(n,n+2),16);return r}function emt(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}var t_e,U$,F4,Uft,HR,U4,q4,G4,N4,ot=p(()=>{Yy();t_e=Symbol("evaluating");U$="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};F4=R_(()=>{if(Jy.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});Uft=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},HR=new Set(["string","number","symbol"]),U4=new Set(["string","number","bigint","boolean","symbol","undefined"]);q4={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},G4={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};N4=class{constructor(...t){}}});function WR(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(t(o))):n.push(t(o));return{formErrors:n,fieldErrors:r}}function VR(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,l=0;for(;l<a.length;){let u=a[l];l===a.length-1?(c[u]=c[u]||{_errors:[]},c[u]._errors.push(t(s))):c[u]=c[u]||{_errors:[]},c=c[u],l++}}}};return n(e),r}function W4(e,t=r=>r.message){let r={errors:[]},n=(o,i=[])=>{var s,a;for(let c of o.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(l=>n({issues:l},[...i,...c.path]));else if(c.code==="invalid_key")n({issues:c.issues},[...i,...c.path]);else if(c.code==="invalid_element")n({issues:c.issues},[...i,...c.path]);else{let l=[...i,...c.path];if(l.length===0){r.errors.push(t(c));continue}let u=r,d=0;for(;d<l.length;){let f=l[d],m=d===l.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),m&&u.errors.push(t(c)),d++}}};return n(e),r}function i_e(e){let t=[],r=e.map(n=>typeof n=="object"?n.key:n);for(let n of r)typeof n=="number"?t.push(`[${n}]`):typeof n=="symbol"?t.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?t.push(`[${JSON.stringify(n)}]`):(t.length&&t.push("."),t.push(n));return t.join("")}function V4(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)t.push(`\u2716 ${n.message}`),n.path?.length&&t.push(` \u2192 at ${i_e(n.path)}`);return t.join(`
|
|
4
4
|
`)}var o_e,BR,ma,K4=p(()=>{Yy();ot();o_e=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,E_,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},BR=K("$ZodError",o_e),ma=K("$ZodError",o_e,{Parent:Error})});var C_,H$,P_,q$,I_,Z4,A_,J4,G$,rmt,B$,nmt,W$,omt,V$,imt,K$,smt,Z$,amt,J$,cmt,Y$,lmt,Y4=p(()=>{Yy();K4();ot();C_=e=>(t,r,n,o)=>{let i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new Yl;if(s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>$s(c,i,So())));throw U$(a,o?.callee),a}return s.value},H$=C_(ma),P_=e=>async(t,r,n,o)=>{let i=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??e)(s.issues.map(c=>$s(c,i,So())));throw U$(a,o?.callee),a}return s.value},q$=P_(ma),I_=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new Yl;return i.issues.length?{success:!1,error:new(e??BR)(i.issues.map(s=>$s(s,o,So())))}:{success:!0,data:i.value}},Z4=I_(ma),A_=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(s=>$s(s,o,So())))}:{success:!0,data:i.value}},J4=A_(ma),G$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return C_(e)(t,r,o)},rmt=G$(ma),B$=e=>(t,r,n)=>C_(e)(t,r,n),nmt=B$(ma),W$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return P_(e)(t,r,o)},omt=W$(ma),V$=e=>async(t,r,n)=>P_(e)(t,r,n),imt=V$(ma),K$=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return I_(e)(t,r,o)},smt=K$(ma),Z$=e=>(t,r,n)=>I_(e)(t,r,n),amt=Z$(ma),J$=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return A_(e)(t,r,o)},cmt=J$(ma),Y$=e=>async(t,r,n)=>A_(e)(t,r,n),lmt=Y$(ma)});var Xa={};Kn(Xa,{base64:()=>fV,base64url:()=>Q$,bigint:()=>SV,boolean:()=>kV,browserEmail:()=>ymt,cidrv4:()=>dV,cidrv6:()=>pV,cuid:()=>Q4,cuid2:()=>X4,date:()=>gV,datetime:()=>bV,domain:()=>Smt,duration:()=>oV,e164:()=>hV,email:()=>sV,emoji:()=>aV,extendedDuration:()=>umt,guid:()=>iV,hex:()=>_mt,hostname:()=>xmt,html5Email:()=>mmt,httpProtocol:()=>mV,idnEmail:()=>gmt,integer:()=>_V,ipv4:()=>cV,ipv6:()=>lV,ksuid:()=>rV,lowercase:()=>EV,mac:()=>uV,md5_base64:()=>wmt,md5_base64url:()=>vmt,md5_hex:()=>kmt,nanoid:()=>nV,null:()=>wV,number:()=>X$,rfc5322Email:()=>hmt,sha1_base64:()=>Rmt,sha1_base64url:()=>Tmt,sha1_hex:()=>Emt,sha256_base64:()=>Pmt,sha256_base64url:()=>Imt,sha256_hex:()=>Cmt,sha384_base64:()=>Omt,sha384_base64url:()=>$mt,sha384_hex:()=>Amt,sha512_base64:()=>Dmt,sha512_base64url:()=>Nmt,sha512_hex:()=>Mmt,string:()=>xV,time:()=>yV,ulid:()=>eV,undefined:()=>vV,unicodeEmail:()=>s_e,uppercase:()=>RV,uuid:()=>Xy,uuid4:()=>dmt,uuid6:()=>pmt,uuid7:()=>fmt,xid:()=>tV});function aV(){return new RegExp(bmt,"u")}function c_e(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function yV(e){return new RegExp(`^${c_e(e)}$`)}function bV(e){let t=c_e({precision:e.precision}),r=["Z"];e.local&&r.push(""),e.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${t}(?:${r.join("|")})`;return new RegExp(`^${a_e}T(?:${n})$`)}function KR(e,t){return new RegExp(`^[A-Za-z0-9+/]{${e}}${t}$`)}function ZR(e){return new RegExp(`^[A-Za-z0-9_-]{${e}}$`)}var Q4,X4,eV,tV,rV,nV,oV,umt,iV,Xy,dmt,pmt,fmt,sV,mmt,hmt,s_e,gmt,ymt,bmt,cV,lV,uV,dV,pV,fV,Q$,xmt,Smt,mV,hV,a_e,gV,xV,SV,_V,X$,kV,wV,vV,EV,RV,_mt,kmt,wmt,vmt,Emt,Rmt,Tmt,Cmt,Pmt,Imt,Amt,Omt,$mt,Mmt,Dmt,Nmt,eM=p(()=>{ot();Q4=/^[cC][0-9a-z]{6,}$/,X4=/^[0-9a-z]+$/,eV=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,tV=/^[0-9a-vA-V]{20}$/,rV=/^[A-Za-z0-9]{27}$/,nV=/^[a-zA-Z0-9_-]{21}$/,oV=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,umt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,iV=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xy=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,dmt=Xy(4),pmt=Xy(6),fmt=Xy(7),sV=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,mmt=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,hmt=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,s_e=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,gmt=s_e,ymt=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,bmt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";cV=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lV=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,uV=e=>{let t=jc(e??":");return new RegExp(`^(?:[0-9A-F]{2}${t}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${t}){5}[0-9a-f]{2}$`)},dV=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,pV=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,fV=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Q$=/^[A-Za-z0-9_-]*$/,xmt=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,Smt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,mV=/^https?$/,hV=/^\+[1-9]\d{6,14}$/,a_e="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",gV=new RegExp(`^${a_e}$`);xV=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},SV=/^-?\d+n?$/,_V=/^-?\d+$/,X$=/^-?\d+(?:\.\d+)?$/,kV=/^(?:true|false)$/i,wV=/^null$/i,vV=/^undefined$/i,EV=/^[^A-Z]*$/,RV=/^[^a-z]*$/,_mt=/^[0-9a-fA-F]*$/;kmt=/^[0-9a-fA-F]{32}$/,wmt=KR(22,"=="),vmt=ZR(22),Emt=/^[0-9a-fA-F]{40}$/,Rmt=KR(27,"="),Tmt=ZR(27),Cmt=/^[0-9a-fA-F]{64}$/,Pmt=KR(43,"="),Imt=ZR(43),Amt=/^[0-9a-fA-F]{96}$/,Omt=KR(64,""),$mt=ZR(64),Mmt=/^[0-9a-fA-F]{128}$/,Dmt=KR(86,"=="),Nmt=ZR(86)});function l_e(e,t,r){e.issues.length&&t.issues.push(...fa(r,e.issues))}var dn,u_e,tM,rM,TV,CV,PV,IV,AV,OV,$V,MV,DV,O_,NV,LV,zV,FV,jV,UV,HV,qV,GV,nM=p(()=>{Yy();eM();ot();dn=K("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),u_e={number:"number",bigint:"bigint",object:"date"},tM=K("$ZodCheckLessThan",(e,t)=>{dn.init(e,t);let r=u_e[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?o.maximum=t.value:o.exclusiveMaximum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),rM=K("$ZodCheckGreaterThan",(e,t)=>{dn.init(e,t);let r=u_e[typeof t.value];e._zod.onattach.push(n=>{let o=n._zod.bag,i=(t.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?o.minimum=t.value:o.exclusiveMinimum=t.value)}),e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),TV=K("$ZodCheckMultipleOf",(e,t)=>{dn.init(e,t),e._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%t.value===BigInt(0):L4(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),CV=K("$ZodCheckNumberFormat",(e,t)=>{dn.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=q4[t.format];e._zod.onattach.push(s=>{let a=s._zod.bag;a.format=t.format,a.minimum=o,a.maximum=i,r&&(a.pattern=_V)}),e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),PV=K("$ZodCheckBigIntFormat",(e,t)=>{dn.init(e,t);let[r,n]=G4[t.format];e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,i.minimum=r,i.maximum=n}),e._zod.check=o=>{let i=o.value;i<r&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:r,inclusive:!0,inst:e,continue:!t.abort}),i>n&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:n,inclusive:!0,inst:e,continue:!t.abort})}}),IV=K("$ZodCheckMaxSize",(e,t)=>{var r;dn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ym(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;o.size<=t.maximum||n.issues.push({origin:qR(o),code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),AV=K("$ZodCheckMinSize",(e,t)=>{var r;dn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ym(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;o.size>=t.minimum||n.issues.push({origin:qR(o),code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),OV=K("$ZodCheckSizeEquals",(e,t)=>{var r;dn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ym(o)&&o.size!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.size,o.maximum=t.size,o.size=t.size}),e._zod.check=n=>{let o=n.value,i=o.size;if(i===t.size)return;let s=i>t.size;n.issues.push({origin:qR(o),...s?{code:"too_big",maximum:t.size}:{code:"too_small",minimum:t.size},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),$V=K("$ZodCheckMaxLength",(e,t)=>{var r;dn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ym(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<o&&(n._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let o=n.value;if(o.length<=t.maximum)return;let s=GR(o);n.issues.push({origin:s,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),MV=K("$ZodCheckMinLength",(e,t)=>{var r;dn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ym(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>o&&(n._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let o=n.value;if(o.length>=t.minimum)return;let s=GR(o);n.issues.push({origin:s,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),DV=K("$ZodCheckLengthEquals",(e,t)=>{var r;dn.init(e,t),(r=e._zod.def).when??(r.when=n=>{let o=n.value;return!Ym(o)&&o.length!==void 0}),e._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=t.length,o.maximum=t.length,o.length=t.length}),e._zod.check=n=>{let o=n.value,i=o.length;if(i===t.length)return;let s=GR(o),a=i>t.length;n.issues.push({origin:s,...a?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),O_=K("$ZodCheckStringFormat",(e,t)=>{var r,n;dn.init(e,t),e._zod.onattach.push(o=>{let i=o._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),NV=K("$ZodCheckRegex",(e,t)=>{O_.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),LV=K("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=EV),O_.init(e,t)}),zV=K("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=RV),O_.init(e,t)}),FV=K("$ZodCheckIncludes",(e,t)=>{dn.init(e,t);let r=jc(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position}}${r}`:r);t.pattern=n,e._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),jV=K("$ZodCheckStartsWith",(e,t)=>{dn.init(e,t);let r=new RegExp(`^${jc(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),UV=K("$ZodCheckEndsWith",(e,t)=>{dn.init(e,t);let r=new RegExp(`.*${jc(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});HV=K("$ZodCheckProperty",(e,t)=>{dn.init(e,t),e._zod.check=r=>{let n=t.schema._zod.run({value:r.value[t.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>l_e(o,r,t.property));l_e(n,r,t.property)}}),qV=K("$ZodCheckMimeType",(e,t)=>{dn.init(e,t);let r=new Set(t.mime);e._zod.onattach.push(n=>{n._zod.bag.mime=t.mime}),e._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:t.mime,input:n.value.type,inst:e,continue:!t.abort})}}),GV=K("$ZodCheckOverwrite",(e,t)=>{dn.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}})});var JR,BV=p(()=>{JR=class{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(`
|
|
5
5
|
`).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.args,o=[...(this?.content??[""]).map(i=>` ${i}`)];return new t(...r,o.join(`
|
|
6
6
|
`))}}});var WV,VV=p(()=>{WV={major:4,minor:4,patch:3}});function h6(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function R_e(e){if(!Q$.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return h6(r)}function T_e(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}function p_e(e,t,r){e.issues.length&&t.issues.push(...fa(r,e.issues)),t.value[r]=e.value}function aM(e,t,r,n,o,i){let s=r in n;if(e.issues.length){if(o&&i&&!s)return;t.issues.push(...fa(r,e.issues))}if(!s&&!o){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?s&&(t.value[r]=void 0):t.value[r]=e.value}function C_e(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);let r=H4(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(r)}}function P_e(e,t,r,n,o,i){let s=[],a=o.keySet,c=o.catchall._zod,l=c.def.type,u=c.optin==="optional",d=c.optout==="optional";for(let f in t){if(f==="__proto__"||a.has(f))continue;if(l==="never"){s.push(f);continue}let m=c.run({value:t[f],issues:[]},n);m instanceof Promise?e.push(m.then(y=>aM(y,r,f,t,u,d))):aM(m,r,f,t,u,d)}return s.length&&r.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:i}),e.length?Promise.all(e).then(()=>r):r}function f_e(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!eh(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>$s(s,n,So())))}),t)}function m_e(e,t,r,n){let o=e.filter(i=>i.issues.length===0);return o.length===1?(t.value=o[0].value,t):(o.length===0?t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>$s(s,n,So())))}):t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:[],inclusive:!1}),t)}function KV(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xm(e)&&Xm(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};for(let i of n){let s=KV(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],i=t[n],s=KV(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[n,...s.mergeErrorPath]};r.push(s.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function h_e(e,t,r){let n=new Map,o;for(let a of t.issues)if(a.code==="unrecognized_keys"){o??(o=a);for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(a);for(let a of r.issues)if(a.code==="unrecognized_keys")for(let c of a.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(a);let i=[...n].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(i.length&&o&&e.issues.push({...o,keys:i}),eh(e))return e;let s=KV(t.value,r.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}function g_e(e,t){for(let r=e.length-1;r>=0;r--)if(e[r]._zod[t]!=="optional")return r+1;return 0}function y_e(e,t,r){e.issues.length&&t.issues.push(...fa(r,e.issues)),t.value[r]=e.value}function b_e(e,t,r,n,o){for(let i=0;i<r.length;i++){let s=e[i],a=i<n.length;if(s.issues.length){if(!a&&i>=o){t.value.length=i;break}t.issues.push(...fa(i,s.issues))}t.value[i]=s.value}for(let i=t.value.length-1;i>=n.length&&(r[i]._zod.optout==="optional"&&t.value[i]===void 0);i--)t.value.length=i;return t}function x_e(e,t,r,n,o,i,s){e.issues.length&&(HR.has(typeof n)?r.issues.push(...fa(n,e.issues)):r.issues.push({code:"invalid_key",origin:"map",input:o,inst:i,issues:e.issues.map(a=>$s(a,s,So()))})),t.issues.length&&(HR.has(typeof n)?r.issues.push(...fa(n,t.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:n,issues:t.issues.map(a=>$s(a,s,So()))})),r.value.set(e.value,t.value)}function S_e(e,t){e.issues.length&&t.issues.push(...e.issues),t.value.add(e.value)}function __e(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}function k_e(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function w_e(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function oM(e,t,r){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},r)}function iM(e,t,r){if(e.issues.length)return e.aborted=!0,e;if((r.direction||"forward")==="forward"){let o=t.transform(e.value,e);return o instanceof Promise?o.then(i=>sM(e,i,t.out,r)):sM(e,o,t.out,r)}else{let o=t.reverseTransform(e.value,e);return o instanceof Promise?o.then(i=>sM(e,i,t.in,r)):sM(e,o,t.in,r)}}function sM(e,t,r,n){return e.issues.length?(e.aborted=!0,e):r._zod.run({value:t,issues:e.issues},n)}function v_e(e){return e.value=Object.freeze(e.value),e}function E_e(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(T_(o))}}var Ot,eb,en,ZV,JV,YV,QV,XV,e6,t6,r6,n6,o6,i6,s6,a6,c6,l6,u6,d6,p6,f6,m6,g6,y6,b6,x6,S6,cM,_6,YR,lM,k6,w6,v6,E6,R6,T6,C6,P6,I6,A6,I_e,O6,QR,$6,M6,D6,uM,N6,L6,z6,F6,j6,U6,H6,dM,q6,G6,B6,W6,V6,K6,Z6,J6,pM,XR,Y6,Q6,X6,eK,tK,rK,nK,oK=p(()=>{nM();Yy();BV();Y4();eM();ot();VV();ot();Ot=K("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=WV;let n=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&n.unshift(e);for(let o of n)for(let i of o._zod.onattach)i(e);if(n.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let o=(s,a,c)=>{let l=eh(s),u;for(let d of a){if(d._zod.def.when){if(B4(s)||!d._zod.def.when(s))continue}else if(l)continue;let f=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&c?.async===!1)throw new Yl;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,s.issues.length!==f&&(l||(l=eh(s,f)))});else{if(s.issues.length===f)continue;l||(l=eh(s,f))}}return u?u.then(()=>s):s},i=(s,a,c)=>{if(eh(s))return s.aborted=!0,s;let l=o(a,n,c);if(l instanceof Promise){if(c.async===!1)throw new Yl;return l.then(u=>e._zod.parse(u,c))}return e._zod.parse(l,c)};e._zod.run=(s,a)=>{if(a.skipChecks)return e._zod.parse(s,a);if(a.direction==="backward"){let l=e._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return l instanceof Promise?l.then(u=>i(u,s,a)):i(l,s,a)}let c=e._zod.parse(s,a);if(c instanceof Promise){if(a.async===!1)throw new Yl;return c.then(l=>o(l,n,a))}return o(c,n,a)}}Qt(e,"~standard",()=>({validate:o=>{try{let i=Z4(e,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return J4(e,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),eb=K("$ZodString",(e,t)=>{Ot.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??xV(e._zod.bag),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),en=K("$ZodStringFormat",(e,t)=>{O_.init(e,t),eb.init(e,t)}),ZV=K("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=iV),en.init(e,t)}),JV=K("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Xy(n))}else t.pattern??(t.pattern=Xy());en.init(e,t)}),YV=K("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=sV),en.init(e,t)}),QV=K("$ZodURL",(e,t)=>{en.init(e,t),e._zod.check=r=>{try{let n=r.value.trim();if(!t.normalize&&t.protocol?.source===mV.source&&!/^https?:\/\//i.test(n)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}let o=new URL(n);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort})),t.normalize?r.value=o.href:r.value=n;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),XV=K("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=aV()),en.init(e,t)}),e6=K("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=nV),en.init(e,t)}),t6=K("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Q4),en.init(e,t)}),r6=K("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=X4),en.init(e,t)}),n6=K("$ZodULID",(e,t)=>{t.pattern??(t.pattern=eV),en.init(e,t)}),o6=K("$ZodXID",(e,t)=>{t.pattern??(t.pattern=tV),en.init(e,t)}),i6=K("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=rV),en.init(e,t)}),s6=K("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=bV(t)),en.init(e,t)}),a6=K("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=gV),en.init(e,t)}),c6=K("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=yV(t)),en.init(e,t)}),l6=K("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=oV),en.init(e,t)}),u6=K("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=cV),en.init(e,t),e._zod.bag.format="ipv4"}),d6=K("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=lV),en.init(e,t),e._zod.bag.format="ipv6",e._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}}),p6=K("$ZodMAC",(e,t)=>{t.pattern??(t.pattern=uV(t.delimiter)),en.init(e,t),e._zod.bag.format="mac"}),f6=K("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=dV),en.init(e,t)}),m6=K("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pV),en.init(e,t),e._zod.check=r=>{let n=r.value.split("/");try{if(n.length!==2)throw new Error;let[o,i]=n;if(!i)throw new Error;let s=Number(i);if(`${s}`!==i)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${o}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}}});g6=K("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=fV),en.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=r=>{h6(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}});y6=K("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Q$),en.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=r=>{R_e(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),b6=K("$ZodE164",(e,t)=>{t.pattern??(t.pattern=hV),en.init(e,t)});x6=K("$ZodJWT",(e,t)=>{en.init(e,t),e._zod.check=r=>{T_e(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),S6=K("$ZodCustomStringFormat",(e,t)=>{en.init(e,t),e._zod.check=r=>{t.fn(r.value)||r.issues.push({code:"invalid_format",format:t.format,input:r.value,inst:e,continue:!t.abort})}}),cM=K("$ZodNumber",(e,t)=>{Ot.init(e,t),e._zod.pattern=e._zod.bag.pattern??X$,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),_6=K("$ZodNumberFormat",(e,t)=>{CV.init(e,t),cM.init(e,t)}),YR=K("$ZodBoolean",(e,t)=>{Ot.init(e,t),e._zod.pattern=kV,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}}),lM=K("$ZodBigInt",(e,t)=>{Ot.init(e,t),e._zod.pattern=SV,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=BigInt(r.value)}catch{}return typeof r.value=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:r.value,inst:e}),r}}),k6=K("$ZodBigIntFormat",(e,t)=>{PV.init(e,t),lM.init(e,t)}),w6=K("$ZodSymbol",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:e}),r}}),v6=K("$ZodUndefined",(e,t)=>{Ot.init(e,t),e._zod.pattern=vV,e._zod.values=new Set([void 0]),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:e}),r}}),E6=K("$ZodNull",(e,t)=>{Ot.init(e,t),e._zod.pattern=wV,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}}),R6=K("$ZodAny",(e,t)=>{Ot.init(e,t),e._zod.parse=r=>r}),T6=K("$ZodUnknown",(e,t)=>{Ot.init(e,t),e._zod.parse=r=>r}),C6=K("$ZodNever",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)}),P6=K("$ZodVoid",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:e}),r}}),I6=K("$ZodDate",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:e}),r}});A6=K("$ZodArray",(e,t)=>{Ot.init(e,t),e._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:e}),r;r.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],c=t.element._zod.run({value:a,issues:[]},n);c instanceof Promise?i.push(c.then(l=>p_e(l,r,s))):p_e(c,r,s)}return i.length?Promise.all(i).then(()=>r):r}});I_e=K("$ZodObject",(e,t)=>{if(Ot.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){let a=t.shape;Object.defineProperty(t,"shape",{get:()=>{let c={...a};return Object.defineProperty(t,"shape",{value:c}),c}})}let n=R_(()=>C_e(t));Qt(e._zod,"propValues",()=>{let a=t.shape,c={};for(let l in a){let u=a[l]._zod;if(u.values){c[l]??(c[l]=new Set);for(let d of u.values)c[l].add(d)}}return c});let o=Qy,i=t.catchall,s;e._zod.parse=(a,c)=>{s??(s=n.value);let l=a.value;if(!o(l))return a.issues.push({expected:"object",code:"invalid_type",input:l,inst:e}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let m=d[f],y=m._zod.optin==="optional",S=m._zod.optout==="optional",_=m._zod.run({value:l[f],issues:[]},c);_ instanceof Promise?u.push(_.then(v=>aM(v,a,f,l,y,S))):aM(_,a,f,l,y,S)}return i?P_e(u,l,a,c,n.value,e):u.length?Promise.all(u).then(()=>a):a}}),O6=K("$ZodObjectJIT",(e,t)=>{I_e.init(e,t);let r=e._zod.parse,n=R_(()=>C_e(t)),o=f=>{let m=new JR(["shape","payload","ctx"]),y=n.value,S=C=>{let O=j$(C);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};m.write("const input = payload.value;");let _=Object.create(null),v=0;for(let C of y.keys)_[C]=`key_${v++}`;m.write("const newResult = {};");for(let C of y.keys){let O=_[C],D=j$(C),L=f[C],F=L?._zod?.optin==="optional",U=L?._zod?.optout==="optional";m.write(`const ${O} = ${S(C)};`),F&&U?m.write(`
|
|
@@ -441,7 +441,7 @@ naming the step that went inert.
|
|
|
441
441
|
--teardown-deadline-ms <n> how long project_stop may take (default: 20000)
|
|
442
442
|
--demand-deadline-ms <n> how long the probe waits for the daemon's poll and
|
|
443
443
|
the Worker it justifies (default: 60000)
|
|
444
|
-
`});I4();sd();gb();cY();eY();gb();Mk();import{connect as YTt}from"node:net";var QTt={drain:lo.projectDrain,stop:lo.projectStop,status:lo.projectStatus},XTt=512;function eCt(e){let t=e.length-XTt;return t<=0?0:(e.splice(0,t),t)}async function dY(e={}){let t=e.cwd??process.cwd(),r=e.name??"RedSkills Project client",n=e.version??"1",o=e.paths??bT(),s=await tCt(async()=>{await yT(o);let l=(await _b(o)).paths,u=await iCt(l.acpSocketPath),d=[],f=0,m="",y=!1;u.once("close",()=>{y=!0}),u.once("error",()=>{y=!0});let S=BEe({name:r}).onNotification(lh.client.session.update,async({params:v})=>{v.sessionId===m&&(d.push(v.update),f+=eCt(d),await e.onUpdate?.(v.update))});e.requestPermission!=null&&(S=S.onRequest(lh.client.session.requestPermission,({params:v})=>e.requestPermission(v)));let _=S.connect(tTe(u));return await _.agent.request(lh.agent.initialize,{protocolVersion:1,clientCapabilities:{},clientInfo:{name:r,version:n},_meta:{redskills:{wireMajor:IRe}}}),m=(await _.agent.request(lh.agent.session.new,{cwd:t,mcpServers:[]})).sessionId,{connection:_,socket:u,sessionId:m,pendingUpdates:d,droppedUpdates:()=>f,dead:()=>y,close(){y=!0,_.close(),u.destroy()}}}),a=s.ensure;return{control:async(l,u={})=>{let f=await(await a()).connection.agent.request(QTt[l],{...u.target==null?{}:{target:u.target},...u.runner==null?{}:{runner:u.runner},...u.registration==null?{}:{registration:u.registration}});if(!pAe(f))throw new Error("redskilled returned an invalid Project control outcome");if(l==="status"&&!nCt(f))throw new Error("redskilled returned Project status without a valid RedSkills context");return f},async github(l){return await(await a()).connection.agent.request(lo.githubRequest,{request:l})},async goDispatch(l){return await(await a()).connection.agent.request(lo.goDispatch,{demand:l})},async hostState(){return await(await a()).connection.agent.request(lo.hostState,{})},async brain(l){return await(await a()).connection.agent.request(lo.brainCall,{tool:l.tool,arguments:l.arguments})},async memory(l){return await(await a()).connection.agent.request(lo.memoryCall,{tool:l.tool,arguments:l.arguments,...l.mode==null?{}:{mode:l.mode}})},async prompt(l){let u=await a(),d=u.droppedUpdates()+u.pendingUpdates.length,f=await u.connection.agent.request(lh.agent.session.prompt,{sessionId:u.sessionId,prompt:[{type:"text",text:l}]});return{stopReason:f.stopReason,...rCt(f._meta),updates:u.pendingUpdates.slice(Math.max(0,d-u.droppedUpdates()))}},async cancel(){let l=await a();return await l.connection.agent.notify(lh.agent.session.cancel,{sessionId:l.sessionId})},async permission(l){return e.requestPermission==null?{outcome:{outcome:"cancelled"},_meta:{redskills:{permissionResolution:"hitl-required"}}}:await e.requestPermission(l)},close(){s.close()}}}async function tCt(e){let t=await e(),r=!1,n=null;return{async ensure(){if(r)throw new Error("this RedSkills Project ACP client is closed");return t.dead()?(n??=e().then(o=>(t=o,n=null,o),o=>{throw n=null,o}),await n):t},close(){r=!0,t.close()}}}function rCt(e){let r=rf(rf(e)?.redskills)?.projectControl;return pAe(r)?{projectControl:r}:{}}function pAe(e){let t=rf(e);return t?.version===1&&typeof t.project_id=="string"&&typeof t.revision=="number"&&Array.isArray(t.updates)}function nCt(e){let t=rf(rf(e)?.context),r=rf(t?.queue),n=rf(t?.workers),o=rf(t?.adapter_health);return t?.version===1&&typeof t.observed_at=="string"&&typeof r?.posture=="string"&&(r.depth===null||typeof r.depth=="number")&&(r.target===null||typeof r.target=="number")&&typeof r.live=="number"&&(r.wanted===null||typeof r.wanted=="number")&&(r.observed_at===null||typeof r.observed_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&(r.freshness==="fresh"||r.freshness==="stale"||r.freshness==="unknown")&&typeof r.detail=="string"&&n?.freshness==="fresh"&&typeof n.observed_at=="string"&&typeof n.total=="number"&&Array.isArray(n.items)&&n.items.every(oCt)&&(o?.status==="healthy"||o?.status==="degraded"||o?.status==="unknown")&&(o.checked_at===null||typeof o.checked_at=="string")&&(o.last_success_at===null||typeof o.last_success_at=="string")&&(o.last_failure_at===null||typeof o.last_failure_at=="string")&&typeof o.detail=="string"}function oCt(e){let t=rf(e);return typeof t?.worker_id=="string"&&t.state==="running"&&typeof t.started_at=="string"&&typeof t.isolated=="boolean"&&Array.isArray(t.warnings)&&t.warnings.every(r=>typeof r=="string")&&(t.base_commits_ahead===null||typeof t.base_commits_ahead=="number")}function rf(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async function iCt(e){return await new Promise((t,r)=>{let n=YTt(e);n.once("connect",()=>t(n)),n.once("error",r)})}Zee();wd();qre();Kk();wd();var Sz=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(s){if(i.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Bb,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},Ch,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};Gre();var wz=class extends ew{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(VT.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new xw,this.setRequestHandler(UX,n=>this._oninitialize(n)),this.setNotificationHandler(qX,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(aee,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=VT.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Sz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=FL(this._capabilities,t)}setRequestHandler(t,r){let o=_d(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(va(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,l)=>{let u=js(Xk,c);if(!u.success){let y=u.error instanceof Error?u.error.message:String(u.error);throw new Le(qe.InvalidParams,`Invalid tools/call request: ${y}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let y=js(uf,f);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new Le(qe.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let m=js(kd,f);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new Le(qe.InvalidParams,`Invalid tools/call result: ${y}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){kz(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&_z(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:pL.includes(r)?r:zT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},lf)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},KT,r):this.request({method:"sampling/createMessage",params:t},Bb,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},Ch,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ch,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Le(qe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Le?s:new Le(qe.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},dee,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};Kk();Kee();wd();var w1e=Symbol.for("mcp.completable");function Bre(e){return!!e&&typeof e=="object"&&w1e in e}function v1e(e){return e[w1e]?.complete}var k1e;(function(e){e.Completable="McpCompletable"})(k1e||(k1e={}));var YLt=/^[A-Za-z0-9._-]{1,128}$/;function QLt(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!YLt.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function XLt(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Wre(e){let t=QLt(e);return XLt(e,t.warnings),t.isValid}var vz=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};EC();var Sw=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new wz(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new vz(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Fh(TL)),this.server.assertCanSetRequestHandler(Fh(Xk)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(TL,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=Vk(r.inputSchema);return o?Bee(o,{strictUnions:!0,pipeStrategy:"input"}):ezt})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Vk(r.outputSchema);o&&(n.outputSchema=Bee(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Xk,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Le(qe.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Le(qe.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Le(qe.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Le(qe.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof Le&&n.code===qe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=Vk(t.inputSchema)??t.inputSchema,s=await sL(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=aL(a);throw new Le(qe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Le(qe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Vk(t.outputSchema),i=await sL(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=aL(s);throw new Le(qe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(c);if(!d)throw new Le(qe.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Fh(CL)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CL,async t=>{switch(t.params.ref.type){case"ref/prompt":return W$e(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return V$e(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Le(qe.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Le(qe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Le(qe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return RC;let i=_d(n.argsSchema)?.[t.params.argument.name];if(!Bre(i))return RC;let s=v1e(i);if(!s)return RC;let a=await s(t.params.argument.value,t.params.context);return R1e(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return RC;throw new Le(qe.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return RC;let i=await o(t.params.argument.value,t.params.context);return R1e(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Fh(Yk)),this.server.assertCanSetRequestHandler(Fh(vL)),this.server.assertCanSetRequestHandler(Fh(Qk)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Yk,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(vL,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Qk,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Le(qe.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new Le(qe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Fh(EL)),this.server.assertCanSetRequestHandler(Fh(RL)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(EL,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?tzt(r.argsSchema):void 0}))})),this.server.setRequestHandler(RL,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Le(qe.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Le(qe.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=Vk(n.argsSchema),i=await sL(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=aL(c);throw new Le(qe.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${l}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==t&&(delete this._registeredResourceTemplates[t],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Gb(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Gb(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let l=c instanceof ka?c._def?.innerType:c;return Bre(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,l){Wre(t);let u={title:r,description:n,inputSchema:E1e(o),outputSchema:E1e(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&Wre(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Gb(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Gb(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Vre(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Vre(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var ezt={type:"object",properties:{}};function T1e(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function C1e(e){return"_def"in e||"_zod"in e||T1e(e)}function Vre(e){return typeof e!="object"||e===null||C1e(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(T1e)}function E1e(e){if(e){if(Vre(e))return Gb(e);if(!C1e(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function tzt(e){let t=_d(e);return t?Object.entries(t).map(([r,n])=>{let o=t$e(n),i=r$e(n);return{name:r,description:o,required:!i}}):[]}function Fh(e){let r=_d(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=cL(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function R1e(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var RC={completion:{values:[],hasMore:!1}};Kre();import P1e from"node:process";var TC=class{constructor(t=P1e.stdin,r=P1e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new _w,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Ez(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{resolve as F$}from"node:path";import{fileURLToPath as xft}from"node:url";Yn();function I1e(e){return[{name:"claim_status",title:"Read AFK claim",description:"Return the parsed claim marker records and current holder for one issue (`issue`) or a batch (`issues`), keyed per issue.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimStatus(t)},{name:"claim_release",title:"Release AFK claim",description:"MUTATING: post a concede marker for every un-conceded claim holder so the issue (`issue`) or each issue in a batch (`issues`) becomes claimable again.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimRelease(t)}]}Pk();function Zre(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jre(e){return typeof e=="string"&&e.trim()!==""?e:null}function nzt(e){let t=Zre(e);if(t===null)return null;let r=Zre(t.demand);return Jre(r?.refusal)??Jre(t.latest_refusal)}function A1e(e){return{tool:"status",args:{scope:"project"},why:e}}function ozt(){return{tool:"status",args:{scope:"host"},why:"diagnose why the host daemon does not answer before changing registration"}}function izt(e,t){let r=e.registration;return r.daemon_reachable?!r.held&&r.repair!==void 0&&r.repair!=="none"?Ck():e.live_workers.length>0&&t===null?{tool:"status",args:{scope:"worker"},why:"observe the Workers already draining this project's queue"}:A1e(t!==null?"observe when the daemon's refusal clears and capacity begins draining again":"observe the next socket-local queue poll and Worker birth"):ozt()}function szt(e){let t=e.registration;if(!t.daemon_reachable)return"daemon unreachable: this project cannot read or change its host registration";if(!t.held)return"unregistered: the daemon is reachable but holds no registration for this project";let r=t.last_poll?.depth,n=r==null?"an unknown queue":`${r} queued`;return`draining: ${e.slots.busy} of ${e.slots.total} Worker slots are busy with ${n}`}function azt(e){return[{intent:"choose the capability that matches your intent",tools:e.filter(t=>!t.description.startsWith("DEPRECATED:")).map(({name:t,title:r})=>({name:t,title:r}))}]}function O1e(e,t){return[{name:"help",title:"Find the next redskilled action",description:"Read live daemon, registration, queue, Worker, and refusal state; return the pasteable next call and a generated intent map. Makes no GitHub request.",inputSchema:{},invoke:async()=>{let[r,n]=await Promise.all([e.projectStatus(),e.hostState().catch(()=>null)]),o=szt(r),i=nzt(n),s=izt(r,i),a=Sa({state:`you are ${o}`,repair:s});if(a.repair==="none")throw new Error("help produced no callable next action");return{here:o,state:{daemon:{reachable:r.registration.daemon_reachable,version:Jre(Zre(n)?.daemon_version)??""},registration:{held:r.registration.held,project:r.registration.project,renewal:r.registration.renewal,target:r.registration.target},queue:r.registration.last_poll==null?null:{at:r.registration.last_poll.at,outcome:r.registration.last_poll.outcome,depth:r.registration.last_poll.depth,detail:r.registration.last_poll.detail},workers:{busy:r.slots.busy,free:r.slots.free,live:r.live_workers.length,target:r.slots.total},validation_schedule:r.validation_schedule,last_refusal:i,warnings:r.warnings??[]},guidance:a.prose,next:a.repair,intent_map:azt(t())}}}]}Yn();function $1e(e){return[{name:"merge_arm",title:"Arm PR for the merge driver",description:"MUTATING: hand one open PR to a live project merge-driver process \u2014 it owns the PR to a terminal state (update-branch when BEHIND, merge-commit once green at head, bounded retries, needs-medic/needs-human classification) without GitHub native auto-merge. Refuses when the merge-driver process is missing so custody cannot become orphaned.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeArm({pr:t})},{name:"merge_status",title:"Read merge driver state",description:"Return whether the merge-driver process is ticking plus durable per-PR records: armed records labeled driver-ticking or orphaned, attempts, last observed state, and proof objects that name GitHub's merge assessment, blocker class, and next action.",inputSchema:{},invoke:()=>e.mergeStatus()},{name:"merge_release",title:"Release PR from the merge driver",description:"MUTATING: stop driver ownership of one PR. The record is kept as released for observability.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeRelease({pr:t})}]}Yn();var czt=["requeue","retake","park","close"];function M1e(e){return[{name:"hitl_resolve",title:"Resolve parked issue with a human decision",description:"MUTATING: encode one human decision on a parked issue atomically \u2014 requeue (concede dangling claims, strip park labels, ready-for-agent), retake (route to the no-agent landing lane), park (keep ready-for-human, record why), or close. The rationale is posted as an issue comment for the audit trail.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(czt),rationale:w.string().min(1)},invoke:t=>e.hitlResolve(t)}]}Yn();var Rz="2.0.0";function Tz(e,t){return{version:Rz,schema:e,projection:t}}var kNr=w.object({age_s:w.number(),stale:w.boolean(),stale_after_s:w.number(),reason:w.enum(["fresh","aged-out","never-observed","orphaned"])}),lzt=w.object({version:w.string(),source:w.enum(["registry","recorded","installed-plugin","bundle-cache","unresolved"]),age_ms:w.number(),stale_after_ms:w.number(),stale:w.boolean(),reason:w.enum(["fresh","aged-out","installed-only","cache-only","never-observed"])}),uzt=w.object({tool:w.string().min(1),args:w.record(w.string(),w.unknown()),why:w.string().min(1)}),dzt=w.union([uzt,w.literal("none")]),pzt=w.object({held:w.boolean(),daemon_reachable:w.boolean(),project:w.string(),socket:w.string(),selector:w.string(),target:w.number(),renewal:w.enum(["renewing","self-renewing","running-on","unknown"]),renew_by:w.string(),renewals:w.number(),lapsed_at:w.string(),reason:w.string(),repair:dzt.optional(),repair_reason:w.string().min(1).optional(),launch_revision:w.number(),bundle_version:w.string(),plugin_cache_version:w.string(),last_poll:w.object({at:w.string(),outcome:w.string(),depth:w.number().nullable(),request_count:w.number(),detail:w.string()}).optional(),published_version:lzt.optional()}).superRefine((e,t)=>{!e.held&&e.repair===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair"],message:"an absent registration must carry a repair or an argued none"}),e.repair==="none"&&e.repair_reason===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair_reason"],message:"repair none must state why no callable cure is safe"})}),fzt=w.object({name:w.literal("project-birth-breaker"),project_label:w.string(),state:w.enum(["open","half-open"]),opened_at:w.string(),reason:w.string(),closes:w.string(),probe_worker_id:w.string().nullable(),repair:w.object({tool:w.literal("project_reset"),args:w.object({latch:w.literal("project-birth-breaker")}),why:w.string()})}),mzt=w.object({narration:w.string(),moments:w.array(w.object({moment:w.enum(["iteration","post_done","landing"]),state:w.enum(["declared","skip"]),declared:w.boolean(),commands:w.array(w.string())})).length(3)}),CC=w.object({registration:pzt,validation_schedule:mzt,birth_latch:fzt.nullable(),slots:w.object({busy:w.number(),free:w.number(),parked:w.number(),total:w.number(),interactive_reservation:w.number()}),live_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),unattributed_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),warnings:w.array(w.string()).optional()}),hzt=w.object({number:w.union([w.number(),w.string()]),runner:w.string(),retries:w.number(),phase:w.string(),iteration:w.union([w.number(),w.string()]),activity:w.string(),loc_added:w.number(),loc_removed:w.number(),last_commit_at:w.string(),tools_called_count:w.number(),text_chunk_count:w.number(),reasoning_events:w.number(),reasoning_tokens:w.number(),last_event_at:w.string(),waiting_count:w.number(),input_tokens:w.number(),output_tokens:w.number(),cost_usd:w.number()}),gzt=w.object({status:w.enum(["alive","stalled","capped","unknown"]),laneFresh:w.boolean(),laneAgeMs:w.number().optional(),crossCheckArmed:w.boolean(),liveDescendants:w.boolean().optional(),reason:w.string()}),yzt=w.object({verdict:w.enum(["alive","dead","unknown"]),anchor:w.enum(["daemon","none"]),project_label:w.string().nullable(),pid:w.number().nullable(),staleness:w.object({stale:w.boolean(),age_ms:w.number().nullable(),threshold_ms:w.number().nullable(),reason:w.string()})}),N1e=w.object({worker:w.object({id:w.string(),pid:w.number(),runner:w.string(),origin:w.string(),started_at:w.string(),done:w.number(),total:w.number(),blocked:w.number(),failed:w.number(),current:hzt}),live:w.boolean(),active:w.boolean(),renderable_live:w.boolean(),liveness:w.enum(["active","quiet-but-live","dead"]),liveness_verdict:gzt,daemon_liveness:yzt.optional()}),Cz=w.array(N1e),Pz=w.array(N1e.partial()),bzt=w.object({state:w.object({worker_id:w.string(),pid:w.number(),runner:w.string(),started_at:w.string(),total:w.number(),done:w.number(),blocked:w.number(),failed:w.number(),current:w.object({number:w.union([w.number(),w.string()]),title:w.string(),activity:w.string(),started_at:w.string()})}),live:w.boolean()}),PC=w.object({workers:w.array(bzt),events:w.array(w.object({event:w.string(),epoch:w.number()})),fleet:w.object({ts:w.string(),epoch:w.number(),runner:w.string(),readyForAgent:w.number(),slotsBusy:w.number(),slotsFree:w.number(),slotsTotal:w.number(),slotsParked:w.number(),interactiveReservation:w.number(),spawnsThisTick:w.number()}).nullable(),remoteQueue:w.number().optional(),remoteHuman:w.number().optional(),remoteCacheAgeS:w.number().optional()}),D1e=w.object({number:w.number(),title:w.string(),labels:w.array(w.string())}),L1e=w.object({ready_for_agent:w.object({eligible:w.array(D1e),held_for_summon:w.array(D1e)}),ready_for_human:w.array(w.object({number:w.number(),title:w.string(),labels:w.array(w.string()),body:w.string().optional(),createdAt:w.string().nullable().optional()})),counts:w.object({ready_for_agent_eligible:w.number(),ready_for_agent_held:w.number(),ready_for_human:w.number()}),degraded:w.boolean(),errors:w.array(w.object({kind:w.literal("trust-read"),number:w.number(),message:w.string()}))}),z1e=Tz(CC),wNr=Tz(Cz,{input:"fields",schema:Pz}),vNr=Tz(PC),F1e=Tz(L1e);function xzt(e,t){let{projection:r}=e;if(!r)return e.schema;let n=t[r.input];return Array.isArray(n)&&n.length>0?r.schema:e.schema}function j1e(e){return e.map(t=>{let r=t.outputContract;if(!r)return t;let n=t.invoke.bind(t);return{...t,invoke:async o=>{let i=await n(o),s=xzt(r,o).safeParse(i);if(!s.success)throw new Error(`${t.name} output violates contract ${r.version}: ${s.error.issues.map(a=>`${a.path.join(".")||"<root>"}: ${a.message}`).join("; ")}`);return i}}})}Yn();var U1e="named fleets were removed (ADR 0130): the host daemon owns the budget and each project has exactly one demand producer, so a fleet name addresses nothing. Drop the name \u2014 the work scope, the runner and the base branch now ride with the project's producer: pass `selector` / `runner` / `base` to the rs_dev `project_start` tool (status: `project_status`, resize: `project_resize`, stop: `project_stop`).",Yre=class extends Error{constructor(t){super(t===void 0||t===""?U1e:`fleet ${JSON.stringify(t)}: ${U1e}`),this.name="FleetNamingRemovedError"}};function kw(e){if(!(e==null||e===""))throw new Yre(typeof e=="string"?e:String(e))}Yn();var Szt=w.object({tool:w.literal("status"),args:w.object({scope:w.enum(["worker","project","host"])})});function H1e(e){return w.object({deprecated:w.literal(!0),message:w.string().min(1),replacement:Szt,result:e})}function G1e(e){return{version:e.version,schema:H1e(e.schema),...e.projection===void 0?{}:{projection:{input:e.projection.input,schema:H1e(e.projection.schema)}}}}var _zt=w.object({status:w.unknown(),vitals:Cz,monitor:PC}),kzt=w.object({status:w.unknown(),vitals:Pz,monitor:PC}),q1e=w.object({state:w.unknown(),dashboard:w.unknown(),provision_check:w.unknown(),unit_status:w.unknown()}),wzt={version:Rz,schema:w.union([CC,_zt,q1e]),projection:{input:"fields",schema:w.union([CC,kzt,q1e])}};function B1e(e,t,r){return{deprecated:!0,message:`${e} is deprecated; use status { scope: ${t} }`,replacement:{tool:"status",args:{scope:t}},result:r}}async function vzt(e,t){if(t.scope==="project")return e.projectStatus();if(t.scope==="host"){let[s,a,c,l]=await Promise.all([e.hostState(),e.hostDashboard(),e.hostProvisionCheck(),e.hostUnitStatus()]);return{state:s,dashboard:a,provision_check:c,unit_status:l}}let r={worker:t.worker,live_only:t.live_only??!0,fields:t.fields},[n,o,i]=await Promise.all([e.workerStatus(r),e.workerVitals({live_only:r.live_only,fields:r.fields}),e.monitor()]);return{status:n,vitals:o,monitor:i}}function W1e(e){return[{name:"status",title:"Read redskilled status",description:"Answer the current worker, project, or host status through one intent-scoped read.",inputSchema:{scope:w.enum(["worker","project","host"]),worker:w.string().min(1).optional(),live_only:w.boolean().default(!0),fields:w.array(w.string().min(1)).optional()},outputContract:wzt,invoke:t=>vzt(e,t)}]}Iz();var Az={spec:w.number().int().positive().optional(),lane:w.string().min(1).optional(),label:w.string().min(1).optional(),issues:w.array(w.number().int().positive()).optional(),tags:w.array(w.string().min(1)).optional(),user:w.string().min(1).optional()};var Z1e=w.record(w.string(),w.union([w.string(),w.number(),w.boolean()])),IC=w.string().optional().describe("REMOVED: naming a fleet is refused; a project has one producer.");function J1e(e){return[{name:"project_activation",title:"Preview this project's redskilled activation",description:"READ-ONLY: report whether this project opted into RedSkills and the canonical runner and target a no-argument drain would register.",inputSchema:{},invoke:()=>e.projectActivation()},{name:"project_status",title:"Deprecated project status alias",description:"DEPRECATED: use status { scope: project }. Returns the project answer and names its replacement.",inputSchema:{fleet:IC},outputContract:G1e(z1e),invoke:async({fleet:t})=>(kw(t),B1e("project_status","project",await e.projectStatus()))},{name:"drain",title:"Make this project drain",description:"MUTATING: ensure the daemon is reachable and this project is registered. Omitted runner and target resolve from this project's canonical RedSkills configuration; repeated calls report what was kept. An optional budget_ms arms the harvest deadline: past 70% of it the daemon admits no new claim and spends the rest landing what is in flight. No budget_ms, no deadline.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional(),budget_ms:w.number().int().positive().optional()},invoke:async t=>e.drain(t)},{name:"project_start",title:"Start this project's workers",description:"MUTATING: register this project with the host daemon \u2014 a runner, a target width, and its work policy. Registers rather than launches: the project contributes a record, never a process of its own.",inputSchema:{runner:w.string().min(1),target:w.number().int().min(0).default(1),selector:w.object(Az).optional(),config:Z1e.optional(),base:w.string().min(1).optional(),fleet:IC},invoke:async t=>(kw(t.fleet),e.projectStart(t))},{name:"project_resize",title:"Re-aim this project's workers",description:"MUTATING: change this project's target width, runner, or work policy and send the live directive.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional(),selector:w.object(Az).optional(),config:Z1e.optional(),base:w.string().min(1).optional(),fleet:IC},invoke:async t=>(kw(t.fleet),e.projectResize(t))},{name:"project_reset",title:"Reset project execution latch",description:"MUTATING: clear a named in-memory latch for this project so autonomous demand may retry immediately.",inputSchema:{latch:w.literal("project-birth-breaker"),fleet:IC},invoke:async({latch:t,fleet:r})=>(kw(r),e.projectReset({latch:t}))},{name:"project_stop",title:"Stop this project's workers",description:"MUTATING: stop this project's work and give its registration back; force hard teardown explicitly.",inputSchema:{force:w.boolean().optional(),fleet:IC},invoke:async({force:t,fleet:r})=>(kw(r),e.projectStop({force:t}))}]}Yn();function Y1e(e){return[{name:"gate_run",title:"Run the AFK gate",description:"MUTATING: materialize the branch's feedback worktree and run the package-scoped validation gate against it.",dangerClass:"mutating",inputSchema:{branch:w.string().min(1),base:w.string().min(1).optional()},invoke:t=>e.gateRun(t)}]}function Q1e(e){return[{name:"deadend_audit",title:"Audit AFK deadends",description:"Return the read-only deadend audit: dangling claims, red PRs with dead owners, superseded PRs, executable Tickets carrying an active Current blocker, dependency blocks whose req targets all closed, human-queue age outliers, and stale worktrees \u2014 each class paired with its recommended cure. Cache-backed: repeated calls within the refresh window cost zero GitHub quota.",inputSchema:{},invoke:()=>e.deadendAudit()}]}Yn();function X1e(e){return[{name:"requeue",title:"Requeue AFK issue",description:"MUTATING: apply the complete parked-issue requeue transition and record human guidance.",inputSchema:{issue:w.number().int().positive(),guidance:w.string().min(1),repo:w.string().min(1).optional(),dryRun:w.boolean().optional(),adoptBranch:w.string().min(1).optional()},invoke:t=>e.requeue(t)},{name:"retake",title:"Recommend AFK retake",description:"Return the structured issue, PR, branch, worktree, worker-state, and recommended-next-action report.",inputSchema:{issue:w.number().int().positive(),repo:w.string().min(1).optional(),prLimit:w.number().int().positive().max(1e3).optional()},invoke:t=>e.retake(t)},{name:"reap",title:"Reap AFK branches",description:"MUTATING: classify and delete stale local and remote AFK branches.",inputSchema:{},invoke:()=>e.reap()},{name:"unblock_sweep",title:"Sweep dependency blocks",description:"MUTATING: promote dependency-blocked issues whose requirements are all closed.",inputSchema:{},invoke:()=>e.unblockSweep()}]}Yn();function eLe(e){return[{name:"land_branch",title:"Land AFK branch",description:"MUTATING: land one validated worker branch into its base through the complete landing sequence.",dangerClass:"mutating",inputSchema:{issue:w.number().int().positive(),branch:w.string().min(1),base:w.string().min(1).optional(),title:w.string().min(1).optional(),openPr:w.boolean().optional()},invoke:t=>e.landBranch(t)},{name:"cascade_status",title:"Read close cascade",description:"Return the dependents of one issue and which of them the close cascade would promote.",inputSchema:{issue:w.number().int().positive()},invoke:({issue:t})=>e.cascadeStatus({issue:t})}]}Yn();function tLe(e){return[{name:"logs",title:"Read redskilled logs",description:"Return the newest CastleLaneRecord entries from one structured lane; bounded by `limit` (default 200, max 10 000). Pass `kind` to filter before the limit.",inputSchema:{lane:w.enum(["worker","supervisor","monitor","liveness"]),id:w.string().min(1),limit:w.number().int().positive().max(1e4).default(200),kind:w.string().optional()},invoke:t=>e.logs(t)},{name:"dashboard",title:"Build AFK dashboard",description:"Build the structured operational dashboard from GitHub and local state.",inputSchema:{periodDays:w.number().int().positive().default(30)},invoke:({periodDays:t})=>e.dashboard({periodDays:t})},{name:"history",title:"Read redskilled history",description:"Return structured AFK history records, newest records last.",inputSchema:{limit:w.number().int().positive().max(1e4).optional()},invoke:({limit:t})=>e.history({limit:t})},{name:"queue_status",title:"Read AFK queues",description:"Return ready-for-agent and ready-for-human queue candidates, retaining successful candidates and naming partial trust-read failures as a degraded result. Pass `selector` to preview the producer's scoped view of the ready queue (same facets as its work selector, e.g. tags/user).",inputSchema:{selector:w.object(Az).optional()},outputContract:F1e,invoke:t=>e.queueStatus({selector:t.selector})},{name:"events_since",title:"Poll events since cursor",description:"Return AFK history events and Worker lane records after an opaque cursor, plus the next cursor. Omit cursor to get a fresh baseline cursor with no events. Unknown or expired cursors are refused with a re-baseline prompt.",inputSchema:{cursor:w.string().min(1).optional()},invoke:t=>e.eventsSince({cursor:t.cursor})}]}Yn();function rLe(e){return[{name:"manager",title:"Route work through the Manager",description:"MUTATING: take one operator intent into the Manager \u2014 intake, route an effort to a skill, attach an artifact, read effort status, or export/import the checkpoint \u2014 and return the effort record it acted on.",inputSchema:{intent:w.string().min(1).optional(),action:w.enum(["intake","route","artifact","status","checkpoint"]).optional(),effort:w.string().min(1).optional(),skill:w.string().min(1).optional(),artifact:w.string().min(1).optional(),checkpoint:w.enum(["export","import"]).optional(),path:w.string().min(1).optional()},invoke:t=>e.manager(t)},{name:"red_doctor",title:"Diagnose this repository's RedSkills setup",description:"READ-ONLY: return every doctor finding for this repository \u2014 operational probes, host toolchain, lane and process census, executable acceptance, HUMAN-ONLY type declarations and disposable-lane hygiene \u2014 each paired with the route that repairs it. Applying a repair is the `/red-doctor` skill's own fix lane, never a side effect of the read.",inputSchema:{checks:w.array(w.string().min(1)).optional()},invoke:t=>e.redDoctor(t)},{name:"audit_skills",title:"Audit the shipped skills",description:"Return the ranked skill-audit scores for this repository's skill tree. Pass `mechanical_only` to score without the judge, which makes the read deterministic and free of agent cost.",inputSchema:{mechanical_only:w.boolean().optional(),runner:w.string().min(1).optional()},invoke:t=>e.auditSkills(t)},{name:"install_type_labels",title:"Install Wayfinder type labels",description:"MUTATING: create the Wayfinder ticket type labels on the tracker AND declare the HUMAN-ONLY ones in this project's configuration, in one act \u2014 the two are one protection with two halves, and installing only the labels leaves the repository looking protected while unblocked decision Tickets enter the autonomous queue (#3013).",inputSchema:{labels:w.array(w.string().min(1)).optional(),repo:w.string().min(1).optional(),dry_run:w.boolean().optional()},invoke:t=>e.installTypeLabels(t)},{name:"codex_statusline",title:"Inspect the Codex footer preference",description:"READ-ONLY: return the active Codex configuration's status-line inspection \u2014 the file read, the current preference, and the problem that keeps the RedSkills footer from rendering.",inputSchema:{config:w.string().min(1).optional()},invoke:t=>e.codexStatusline(t)},{name:"codex_monitor_agent",title:"Build the Codex monitor agent brief",description:"Return the read-only monitor brief a Codex sub-agent is spawned with: what to poll, how often, and the conditions under which it closes itself. It spawns nothing \u2014 the host's own spawn primitive does.",inputSchema:{project_root:w.string().min(1).optional(),mode:w.string().min(1).optional(),interval_seconds:w.number().int().positive().optional()},invoke:t=>e.codexMonitorAgent(t)},{name:"reconcile_engine",title:"Reconcile this project's engine delivery",description:"MUTATING: warm the published engine bundle into the stable cache path and re-point a standing registration at it in one operation, then return the version, the bundle path, and what happened to the registration.",inputSchema:{version:w.string().min(1).optional()},invoke:t=>e.reconcileEngine(t)}]}Yn();function nLe(e){return[{name:"daily_review",title:"Build daily activity review",description:"Return the structured daily activity review report for the local window.",inputSchema:{},invoke:()=>e.dailyReview({})},{name:"weekly_review",title:"Build weekly activity review",description:"Return the structured weekly activity review report for the local window.",inputSchema:{},invoke:()=>e.weeklyReview({})},{name:"triage",title:"Apply triage decision",description:"MUTATING: apply the decided triage transition to one issue, gated by the per-repo trust policy.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(["ready-for-agent","needs-info","ready-for-human","wontfix"]),summon:w.boolean().optional(),repo:w.string().min(1).optional()},invoke:t=>e.triage(t)},{name:"respond",title:"Handle comment event",description:"MUTATING: parse a /dev comment summon, authorize the commenter, and route the advisory or mutation verb.",inputSchema:{body:w.string(),number:w.number().int().positive(),author:w.string().min(1).optional(),is_pr:w.boolean().optional(),runner:w.string().min(1).optional(),repo:w.string().min(1).optional()},invoke:t=>e.respond(t)}]}Yn();Yn();Pk();function Xre(e){let t=Sa({state:e instanceof Error?e.message:String(e),repair:Sb("the caller must choose one dispatch intent before retrying")});if(t.repair!=="none")throw new Error("invalid worker refusal repair");return{refused:!0,reason:t.prose,repair:t.repair,repair_reason:t.repair_reason}}var ene={issue:w.number().int().positive().optional(),demand:w.string().min(1).optional(),runner:w.string().min(1).optional(),mode:w.enum(["no-mistakes","direct-PR","local-only","scout"]).optional()};function AC(e){let t=e;if(t.issue===void 0==(t.demand===void 0))throw new Error("exactly one of issue or demand is required");if(t.mode==="scout"&&t.issue!==void 0)throw new Error("mode: scout is demand-only \u2014 combine scout with demand, not issue");if(t.issue!==void 0&&t.mode!==void 0)throw new Error("mode is only valid for demand dispatches");return t}function oLe(e){return[{name:"worker_dispatch",title:"Dispatch AFK worker",description:"MUTATING: run one tracked issue or mint and run one disposable demand through the AFK worker lifecycle.",inputSchema:ene,invoke:t=>{let r;try{r=AC(t)}catch(n){return Promise.resolve(Xre(n))}return e.workerDispatch(r)}},{name:"worker_stop",title:"Stop AFK worker",description:"MUTATING: terminate one worker process tree.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!1})},{name:"worker_recycle",title:"Recycle AFK worker",description:"MUTATING: terminate one fleet worker so its supervisor can replace the slot.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!0})}]}function iLe(e){return[{name:"runner_list",title:"List AFK runners",description:"Return the canonical runner specification registry.",inputSchema:{},invoke:()=>e.runnerList()},{name:"runner_detect",title:"Detect AFK runner",description:"Resolve the runner selected by an explicit override or the current host environment.",inputSchema:{runner:w.string().min(1).optional()},invoke:({runner:t})=>e.runnerDetect({runner:t})},{name:"runner_steer",title:"Steer live AFK worker",description:"MUTATING: write a live-steer request into a running worker's next iteration.",inputSchema:{worker:w.string().min(1),text:w.string().min(1)},invoke:t=>e.runnerSteer(t)},{name:"steer_status",title:"Read steer status",description:"Return the live-steer status for a worker: none (no steer ever written), pending (written, not yet consumed), or consumed (consumed at a specific iteration).",inputSchema:{worker:w.string().min(1)},invoke:t=>e.steerStatus(t)},{name:"worker_request",title:"Dispatch worker with request",description:"MUTATING: dispatch a new worker and inject a special request into its spawn-time handoff.",inputSchema:{...ene,text:w.string().min(1)},invoke:t=>{let r;try{r=AC(t)}catch(n){return Promise.resolve(Xre(n))}return e.workerRequest({...r,text:t.text})}}]}function sLe(e){return[{name:"statusline_aggregate",title:"Read statusline aggregate",description:"Return the project-side statusline aggregate (project, repo counters, docs drift, drain, Worker rows, aggregated AFK block, queue) as structured data, using the same collector cores and cache discipline as the command-backed statusLine. Host-side fields (session model/effort, context %, usage quotas) are out of scope.",inputSchema:{},invoke:()=>e.statuslineAggregate()}]}Yn();Pk();function aLe(e,t,r={}){let n=e==="confirm"?Sa({state:"dangerous tool requires explicit confirmation",repair:{tool:t,args:{...r,confirmation:!0},why:"retry the same operation with explicit confirmation"}}):Sa({state:"dangerous tool is denied by the configured posture",repair:Sb("the configured posture deliberately forbids this tool")});return{refused:!0,posture:e,action:t,reason:n.prose,repair:n.repair,...n.repair==="none"?{repair_reason:n.repair_reason}:{}}}function Oz(e,t){return t==="allow"?e:e.map(r=>{if(!r.dangerClass)return r;if(t==="deny")return{...r,invoke:async i=>aLe("deny",r.name)};let n={...r.inputSchema,confirmation:w.boolean().optional()},o=r.invoke.bind(r);return{...r,inputSchema:n,invoke:async i=>{if(i.confirmation!==!0)return aLe("confirm",r.name,i);let{confirmation:s,...a}=i;return o(a)}}})}Yn();function cLe(e){return[{name:"wait_start",title:"Start rsp wait",description:"MUTATING: spawn a detached rsp wait (pr | run | release | cmd) and return its registry id.",inputSchema:{kind:w.enum(["pr","run","release","cmd"]),target:w.string().min(1),timeout_ms:w.number().int().positive().optional(),reason:w.string().optional()},invoke:t=>e.waitStart(t)},{name:"wait_list",title:"List active rsp waits",description:"Return the active-wait registry from .red/tmp/waits.",inputSchema:{},invoke:()=>e.waitList()},{name:"wait_status",title:"Read rsp wait status",description:"Return the registry entry for a running wait or the sealed result envelope for a finished one.",inputSchema:{id:w.string().min(1)},invoke:({id:t})=>e.waitStatus({id:t})}]}Yn();function lLe(e){return[{name:"worktree_list",title:"List disposable worktrees",description:"Enumerate every checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{},invoke:()=>e.worktreeList()},{name:"worktree_remove",title:"Remove disposable worktree",description:"MUTATING: remove one checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{path:w.string().min(1)},invoke:({path:t})=>e.worktreeRemove({path:t})}]}Yn();function uLe(e){return[{name:"standing_orders_show",title:"Show standing orders for this project",description:"READ-ONLY: return all standing orders for this project. Standing orders are an append-only, numbered register injected verbatim into every Worker brief.",inputSchema:{project_label:w.string().min(1).optional().describe("Override the current project label")},invoke:t=>e.standingOrdersShow(t)},{name:"standing_orders_append",title:"Append a standing order",description:"MUTATING: append a new standing order to this project's register. The order is injected verbatim into every Worker brief at admission and on resume. Append is append-only \u2014 existing orders are never mutated or renumbered.",inputSchema:{text:w.string().min(1).describe("The standing order text"),project_label:w.string().min(1).optional().describe("Override the current project label")},invoke:t=>e.standingOrdersAppend(t)}]}var $z="Call the redskilled MCP's `help` tool.\nFollow its guidance and invoke the returned `next` call.",tne=[{name:"drain",title:"Drain this project's queue",description:"Find the next action for starting or continuing a project drain.",body:$z},{name:"diagnose",title:"Diagnose redskilled",description:"Find the next action for understanding a redskilled problem.",body:$z},{name:"configure",title:"Configure redskilled",description:"Find the next action for changing project execution configuration.",body:$z},{name:"stop",title:"Stop project work",description:"Find the next action for stopping project work safely.",body:$z}];var dLe="rs_dev";function pLe(e,t="allow"){let r=[],n=[...O1e(e,()=>r),...W1e(e),...J1e(e),...tLe(e),...Q1e(e),...oLe(e),...iLe(e),...X1e(e),...Y1e(e),...eLe(e),...I1e(e),...$1e(e),...M1e(e),...lLe(e),...cLe(e),...nLe(e),...sLe(e),...rLe(e),...uLe(e)];return r=Oz(j1e(n),t),r}Gt();function ww(e){return Zr(JSON.parse(JSON.stringify(e??null)),{objectArrayColumns:!0,primitiveArrayColumns:!0})}gb();var po="its engine went with ADR 0147; no _redskills/* daemon method serves it yet",Bs="the daemon owns this authority (ADR 0130/0148) but publishes no _redskills/* method for it yet",sl="it is answerable from this checkout alone, but the adapter owns no body for it since ADR 0147";function Et(e,t){return{tool:e,kind:"unserved",reason:t}}var fLe=[Et("help",sl),{tool:"status",kind:"control",operation:"status"},Et("project_activation",sl),{tool:"project_status",kind:"control",operation:"status"},{tool:"drain",kind:"control",operation:"drain"},Et("project_start",Bs),Et("project_resize",Bs),Et("project_reset",Bs),{tool:"project_stop",kind:"control",operation:"stop"},Et("logs",po),Et("dashboard",po),Et("history",po),Et("queue_status",po),Et("events_since",po),Et("deadend_audit",po),{tool:"worker_dispatch",kind:"served",method:lo.goDispatch},Et("worker_stop",Bs),Et("worker_recycle",Bs),Et("runner_list",Bs),Et("runner_detect",Bs),Et("runner_steer",Bs),Et("steer_status",Bs),Et("worker_request",Bs),Et("requeue",po),Et("retake",po),Et("reap",po),Et("unblock_sweep",po),Et("gate_run",Bs),Et("land_branch",po),Et("cascade_status",po),Et("claim_status",po),Et("claim_release",po),Et("merge_arm",po),Et("merge_status",po),Et("merge_release",po),Et("hitl_resolve",po),Et("worktree_list",sl),Et("worktree_remove",sl),Et("wait_start",sl),Et("wait_list",sl),Et("wait_status",sl),Et("daily_review",po),Et("weekly_review",po),Et("triage",po),Et("respond",po),Et("statusline_aggregate",sl),Et("manager",Bs),Et("red_doctor",sl),Et("audit_skills",sl),Et("install_type_labels",po),Et("codex_statusline",sl),Et("codex_monitor_agent",sl),Et("reconcile_engine",Bs),Et("standing_orders_show",Bs),Et("standing_orders_append",Bs)];var Ezt=new Map(fLe.map(e=>[e.tool,e]));function mLe(e){return Ezt.get(e)}function rne(){return fLe.flatMap(e=>e.kind==="control"&&e.operation!=null?[[e.tool,e.operation]]:[])}function Rzt(){return rne().map(([e])=>e).sort()}function hLe(e){return`rs_dev tool ${JSON.stringify(e.tool)} is not served: ${e.reason} (#4113). The adapter refuses rather than degrade the call to a Worker prompt, which returns an empty envelope that looks healthy. The Project control surface serves only: ${Rzt().join(", ")}.`}var Tzt=new Map([["project_drain","drain"],...rne()]),Czt=new Set(["target","runner","scope","registration","budget_ms","live_only","fields","worker"]);async function nne(e,t,r){let n=Tzt.get(t);if(n!=null){let i=Object.keys(r).filter(s=>!Czt.has(s));if(i.length>0)throw new Error(`the Project control surface cannot express ${JSON.stringify(i.sort())} for ${JSON.stringify(t)}`);if(n==="status"){if(r.scope==="host")return await e.hostState();if(r.scope==="worker")throw new Error('status { scope: "worker" } is not served: worker vitals live in no daemon method yet; read scope "host" and filter its workers, or use scope "project"');return await e.control("status")}return await e.control(n,Pzt(r))}let o=mLe(t);if(o?.kind==="served"&&t==="worker_dispatch"){let i=AC({...r});if(i.issue!==void 0||i.mode!==void 0||i.runner!==void 0)throw new Error(`rs_dev tool "worker_dispatch" serves demand dispatches through the daemon's go-dispatch method; a tracked-issue dispatch rides the registered drain (arm /afk), and mode/runner are not expressible on the go_dispatch wire`);return await e.goDispatch(i.demand)}throw o?.kind==="unserved"?new Error(hLe(o)):new Error(`unsupported ACP Project capability ${JSON.stringify(t)}`)}function Pzt(e){let t=e.target,r=e.runner,n=e.registration;return{...typeof t=="number"&&Number.isInteger(t)&&t>=0?{target:t}:{},...typeof r=="string"&&r.length>0?{runner:r}:{},...n!=null&&typeof n=="object"&&!Array.isArray(n)?{registration:n}:{}}}ane();import{execFileSync as FFt}from"node:child_process";Z0();Pd();function WLe(e){let t=KLe(e.repo).join("/"),r=e.selector??{},n=[`repo:${t}`,"is:issue","is:open",zz(e.readyLabel??fu)];r.lane!=null&&r.lane!==""&&n.push(zz(`lane:${r.lane}`)),r.label!=null&&r.label!==""&&n.push(zz(r.label));for(let o of r.tags??[])o!==""&&n.push(zz(`${lne}${o}`));return r.user!=null&&r.user!==""&&r.user!=="@me"&&n.push(`author:${r.user}`),n.join(" ")}function VLe(e){let[t,r]=KLe(e.repo),n=e.selector??{},o=e.readyLabel??fu,i=[o];n.lane!=null&&n.lane!==""&&i.push(`lane:${n.lane}`),n.label!=null&&n.label!==""&&i.push(n.label);for(let a of n.tags??[])a!==""&&i.push(`${lne}${a}`);let s=n.user!=null&&n.user!==""&&n.user!=="@me"?n.user:void 0;return{owner:t,repo:r,labels:i,...s===void 0?{}:{creator:s},counter_labels:{ready:o,human:jh}}}function zz(e){return`label:${JSON.stringify(e)}`}function KLe(e){let t=e.trim().split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error("a registration needs the repository its queue lives in: the daemon polls the string it is handed and cannot work out which tracker a checkout belongs to");return[t[0],t[1]]}var Jzt="Implement issue #{{work_item}} in this workspace. The Ticket is already claimed for you, and the daemon runs the gate, publishes your commits and lands the pull request after you finish \u2014 so never touch GitHub yourself: no label moves, no claim or status comments, no PR. Your whole job is the change and its commits, right here. You are already standing in your own dedicated worktree on the Ticket's base branch: work and commit right here, and never create another worktree \u2014 the repository's worktree lanes govern interactive sessions, not Workers. If your change touches apps/ or packages/, also write a .changeset/<slug>.md entry naming each touched package by its package.json name with a patch bump, and commit it with the change. When the change is committed, say <promise>DONE</promise>. If the work is genuinely blocked, say what blocks it and <promise>BLOCKED</promise>.";function ZLe(e){let t={repo:e.repo,...e.selector==null?{}:{selector:e.selector},...e.readyLabel==null?{}:{readyLabel:e.readyLabel}};return{selector:WLe(t),queue_poll:VLe(t),argv:Jp("red-skills-redskilled",["acp-worker",...e.runner==null?[]:["--child-agent",e.runner]],e.version).split(" "),workspace_path:e.workspacePath,trunk:{remote:"origin",branch:e.trunkBranch??"main"},prompt:Jzt,...e.validationCommands==null||e.validationCommands.length===0?{}:{validation_commands:[...e.validationCommands]},...e.budgetMs==null?{}:{budget_ms:e.budgetMs},target:e.target,...e.standing===!0?{standing:!0}:{}}}Rw();gb();Iz();Rw();One();hf();var Nne=["afk.standing.runner","afk.standing.target"];function zFt(e){let t=Ane(e);if(t!=null)return{kind:"declared",standing:t};let r=Nne.filter(n=>(e[n]??"").trim()!=="");return r.length===0?{kind:"absent"}:{kind:"incomplete",stated:r,missing:Nne.filter(n=>!r.includes(n))}}function Lne(e){try{return zFt(nx(al(e).configPath,{warn:()=>{}}))}catch{return{kind:"absent"}}}function zne(e){let t=Lne(e);return t.kind==="declared"?t.standing:null}function Fne(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:t?.target??1}function jne(e,t){return typeof e=="string"&&e.length>0?e:t?.runner}function Zze(e,t){if(t.kind!=="incomplete")return"";let r=t.missing.length>0?`leaves ${t.missing.join(" and ")} empty`:`states ${t.stated.join(" and ")} with a value it cannot use \u2014 runner must be one of ${EN.join(", ")} and target a positive integer`;return`redskilled MCP: ${e} declares plugins.dev.afk.standing but ${r}, so it stays inert and no drain was registered for it. State both ${Nne.join(" and ")} usably, or remove the block.`}hf();function jFt(e,t,r={},n=Mz){let o=HFt(e,n);if(o==null)return;let i=zne(e),s=Fne(r.target,i),a=jne(r.runner,i),c=UFt(e),l=typeof r.budget_ms=="number"&&Number.isFinite(r.budget_ms)&&r.budget_ms>0?r.budget_ms:void 0;return ZLe({repo:o,workspacePath:e,target:s,version:t,...i==null?{}:{standing:!0},...a==null?{}:{runner:a},...Jze(e)==null?{}:{trunkBranch:Jze(e)},...c.length===0?{}:{validationCommands:c},...l==null?{}:{budgetMs:l}})}function Wz(e,t,r={},n=Mz){let o=zne(e),i=jne(r.runner,o),s=jFt(e,t,r,n);return{...r,...i==null?{}:{runner:i},target:Fne(r.target,o),...s==null?{}:{registration:s}}}function UFt(e){try{let t=Kze(nx(al(e).configPath,{warn:()=>{}}));return[...t.post_done??[],...t.landing??[]]}catch{return[]}}function Jze(e){try{let r=FFt("git",["-C",e,"symbolic-ref","refs/remotes/origin/HEAD"],{encoding:"utf8",timeout:5e3}).trim().split("/").pop();return r==null||r===""?void 0:r}catch{return}}function HFt(e,t=Mz){let r;try{r=t(e).name}catch{return}return/^[^/\s]+\/[^/\s]+$/.test(r)?r:void 0}async function Yze(e){let t=e.warn??(s=>void process.stderr.write(`${s}
|
|
444
|
+
`});I4();sd();gb();cY();eY();gb();Mk();import{connect as YTt}from"node:net";var QTt={drain:lo.projectDrain,stop:lo.projectStop,status:lo.projectStatus},XTt=512;function eCt(e){let t=e.length-XTt;return t<=0?0:(e.splice(0,t),t)}async function dY(e={}){let t=e.cwd??process.cwd(),r=e.name??"RedSkills Project client",n=e.version??"1",o=e.paths??bT(),s=await tCt(async()=>{await yT(o);let l=(await _b(o)).paths,u=await iCt(l.acpSocketPath),d=[],f=0,m="",y=!1;u.once("close",()=>{y=!0}),u.once("error",()=>{y=!0});let S=BEe({name:r}).onNotification(lh.client.session.update,async({params:v})=>{v.sessionId===m&&(d.push(v.update),f+=eCt(d),await e.onUpdate?.(v.update))});e.requestPermission!=null&&(S=S.onRequest(lh.client.session.requestPermission,({params:v})=>e.requestPermission(v)));let _=S.connect(tTe(u));return await _.agent.request(lh.agent.initialize,{protocolVersion:1,clientCapabilities:{},clientInfo:{name:r,version:n},_meta:{redskills:{wireMajor:IRe}}}),m=(await _.agent.request(lh.agent.session.new,{cwd:t,mcpServers:[]})).sessionId,{connection:_,socket:u,sessionId:m,pendingUpdates:d,droppedUpdates:()=>f,dead:()=>y,close(){y=!0,_.close(),u.destroy()}}}),a=s.ensure;return{async extension(l,u){return await(await a()).connection.agent.request(l,u)},control:async(l,u={})=>{let f=await(await a()).connection.agent.request(QTt[l],{...u.target==null?{}:{target:u.target},...u.runner==null?{}:{runner:u.runner},...u.registration==null?{}:{registration:u.registration}});if(!pAe(f))throw new Error("redskilled returned an invalid Project control outcome");if(l==="status"&&!nCt(f))throw new Error("redskilled returned Project status without a valid RedSkills context");return f},async github(l){return await(await a()).connection.agent.request(lo.githubRequest,{request:l})},async goDispatch(l){return await(await a()).connection.agent.request(lo.goDispatch,{demand:l})},async hostState(){return await(await a()).connection.agent.request(lo.hostState,{})},async brain(l){return await(await a()).connection.agent.request(lo.brainCall,{tool:l.tool,arguments:l.arguments})},async memory(l){return await(await a()).connection.agent.request(lo.memoryCall,{tool:l.tool,arguments:l.arguments,...l.mode==null?{}:{mode:l.mode}})},async prompt(l){let u=await a(),d=u.droppedUpdates()+u.pendingUpdates.length,f=await u.connection.agent.request(lh.agent.session.prompt,{sessionId:u.sessionId,prompt:[{type:"text",text:l}]});return{stopReason:f.stopReason,...rCt(f._meta),updates:u.pendingUpdates.slice(Math.max(0,d-u.droppedUpdates()))}},async cancel(){let l=await a();return await l.connection.agent.notify(lh.agent.session.cancel,{sessionId:l.sessionId})},async permission(l){return e.requestPermission==null?{outcome:{outcome:"cancelled"},_meta:{redskills:{permissionResolution:"hitl-required"}}}:await e.requestPermission(l)},close(){s.close()}}}async function tCt(e){let t=await e(),r=!1,n=null;return{async ensure(){if(r)throw new Error("this RedSkills Project ACP client is closed");return t.dead()?(n??=e().then(o=>(t=o,n=null,o),o=>{throw n=null,o}),await n):t},close(){r=!0,t.close()}}}function rCt(e){let r=rf(rf(e)?.redskills)?.projectControl;return pAe(r)?{projectControl:r}:{}}function pAe(e){let t=rf(e);return t?.version===1&&typeof t.project_id=="string"&&typeof t.revision=="number"&&Array.isArray(t.updates)}function nCt(e){let t=rf(rf(e)?.context),r=rf(t?.queue),n=rf(t?.workers),o=rf(t?.adapter_health);return t?.version===1&&typeof t.observed_at=="string"&&typeof r?.posture=="string"&&(r.depth===null||typeof r.depth=="number")&&(r.target===null||typeof r.target=="number")&&typeof r.live=="number"&&(r.wanted===null||typeof r.wanted=="number")&&(r.observed_at===null||typeof r.observed_at=="string")&&(r.age_ms===null||typeof r.age_ms=="number")&&(r.freshness==="fresh"||r.freshness==="stale"||r.freshness==="unknown")&&typeof r.detail=="string"&&n?.freshness==="fresh"&&typeof n.observed_at=="string"&&typeof n.total=="number"&&Array.isArray(n.items)&&n.items.every(oCt)&&(o?.status==="healthy"||o?.status==="degraded"||o?.status==="unknown")&&(o.checked_at===null||typeof o.checked_at=="string")&&(o.last_success_at===null||typeof o.last_success_at=="string")&&(o.last_failure_at===null||typeof o.last_failure_at=="string")&&typeof o.detail=="string"}function oCt(e){let t=rf(e);return typeof t?.worker_id=="string"&&t.state==="running"&&typeof t.started_at=="string"&&typeof t.isolated=="boolean"&&Array.isArray(t.warnings)&&t.warnings.every(r=>typeof r=="string")&&(t.base_commits_ahead===null||typeof t.base_commits_ahead=="number")}function rf(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async function iCt(e){return await new Promise((t,r)=>{let n=YTt(e);n.once("connect",()=>t(n)),n.once("error",r)})}Zee();wd();qre();Kk();wd();var Sz=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(u=>u.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(s){if(i.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(i.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==d.size||![...u].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},Bb,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},Ch,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};Gre();var wz=class extends ew{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(VT.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new xw,this.setRequestHandler(UX,n=>this._oninitialize(n)),this.setNotificationHandler(qX,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(aee,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=VT.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Sz(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=FL(this._capabilities,t)}setRequestHandler(t,r){let o=_d(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i;if(va(o)){let a=o;i=a._zod?.def?.value??a.value}else{let a=o;i=a._def?.value??a.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,l)=>{let u=js(Xk,c);if(!u.success){let y=u.error instanceof Error?u.error.message:String(u.error);throw new Le(qe.InvalidParams,`Invalid tools/call request: ${y}`)}let{params:d}=u.data,f=await Promise.resolve(r(c,l));if(d.task){let y=js(uf,f);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new Le(qe.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let m=js(kd,f);if(!m.success){let y=m.error instanceof Error?m.error.message:String(m.error);throw new Le(qe.InvalidParams,`Invalid tools/call result: ${y}`)}return m.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){kz(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&_z(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:pL.includes(r)?r:zT,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},lf)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(l=>l.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(l=>l.type==="tool_use");if(i){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),u=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==u.size||![...l].every(d=>u.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},KT,r):this.request({method:"sampling/createMessage",params:t},Bb,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},Ch,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},Ch,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new Le(qe.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof Le?s:new Le(qe.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},dee,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};Kk();Kee();wd();var w1e=Symbol.for("mcp.completable");function Bre(e){return!!e&&typeof e=="object"&&w1e in e}function v1e(e){return e[w1e]?.complete}var k1e;(function(e){e.Completable="McpCompletable"})(k1e||(k1e={}));var YLt=/^[A-Za-z0-9._-]{1,128}$/;function QLt(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!YLt.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,i)=>i.indexOf(n)===o);return t.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function XLt(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Wre(e){let t=QLt(e);return XLt(e,t.warnings),t.isValid}var vz=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};EC();var Sw=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new wz(t,r)}get experimental(){return this._experimental||(this._experimental={tasks:new vz(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Fh(TL)),this.server.assertCanSetRequestHandler(Fh(Xk)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(TL,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=Vk(r.inputSchema);return o?Bee(o,{strictUnions:!0,pipeStrategy:"input"}):ezt})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Vk(r.outputSchema);o&&(n.outputSchema=Bee(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Xk,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new Le(qe.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new Le(qe.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,i=n.execution?.taskSupport,s="createTask"in n.handler;if((i==="required"||i==="optional")&&!s)throw new Le(qe.InternalError,`Tool ${t.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i==="required"&&!o)throw new Le(qe.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(i==="optional"&&!o&&s)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,t.params.name),c}catch(n){if(n instanceof Le&&n.code===qe.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(!t.inputSchema)return;let i=Vk(t.inputSchema)??t.inputSchema,s=await sL(i,r);if(!s.success){let a="error"in s?s.error:"Unknown error",c=aL(a);throw new Le(qe.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return s.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new Le(qe.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Vk(t.outputSchema),i=await sL(o,r.structuredContent);if(!i.success){let s="error"in i?i.error:"Unknown error",a=aL(s);throw new Le(qe.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let s={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,s))}else{let a=o;return await Promise.resolve(a.createTask(s))}}if(t.inputSchema){let s=o;return await Promise.resolve(s(r,n))}else{let s=o;return await Promise.resolve(s(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),i=t.handler,s={...n,taskStore:n.taskStore},a=o?await Promise.resolve(i.createTask(o,s)):await Promise.resolve(i.createTask(s)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let d=await n.taskStore.getTask(c);if(!d)throw new Le(qe.InternalError,`Task ${c} not found during polling`);l=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Fh(CL)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(CL,async t=>{switch(t.params.ref.type){case"ref/prompt":return W$e(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return V$e(t),this.handleResourceCompletion(t,t.params.ref);default:throw new Le(qe.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new Le(qe.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Le(qe.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return RC;let i=_d(n.argsSchema)?.[t.params.argument.name];if(!Bre(i))return RC;let s=v1e(i);if(!s)return RC;let a=await s(t.params.argument.value,t.params.context);return R1e(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(s=>s.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return RC;throw new Le(qe.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return RC;let i=await o(t.params.argument.value,t.params.context);return R1e(i)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Fh(Yk)),this.server.assertCanSetRequestHandler(Fh(vL)),this.server.assertCanSetRequestHandler(Fh(Qk)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Yk,async(t,r)=>{let n=Object.entries(this._registeredResources).filter(([i,s])=>s.enabled).map(([i,s])=>({uri:i,name:s.name,...s.metadata})),o=[];for(let i of Object.values(this._registeredResourceTemplates)){if(!i.resourceTemplate.listCallback)continue;let s=await i.resourceTemplate.listCallback(r);for(let a of s.resources)o.push({...i.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(vL,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Qk,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Le(qe.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let i of Object.values(this._registeredResourceTemplates)){let s=i.resourceTemplate.uriTemplate.match(n.toString());if(s)return i.readCallback(n,s,r)}throw new Le(qe.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Fh(EL)),this.server.assertCanSetRequestHandler(Fh(RL)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(EL,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?tzt(r.argsSchema):void 0}))})),this.server.setRequestHandler(RL,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new Le(qe.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new Le(qe.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=Vk(n.argsSchema),i=await sL(o,t.params.arguments);if(!i.success){let c="error"in i?i.error:"Unknown error",l=aL(c);throw new Le(qe.InvalidParams,`Invalid arguments for prompt ${t.params.name}: ${l}`)}let s=i.data,a=n.callback;return await Promise.resolve(a(s,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(t,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let i=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,void 0,r,o,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(t,r,n,o,i){let s={name:t,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=s)),typeof a.name<"u"&&(s.name=a.name),typeof a.title<"u"&&(s.title=a.title),typeof a.metadata<"u"&&(s.metadata=a.metadata),typeof a.callback<"u"&&(s.readCallback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=s,s}_createRegisteredResourceTemplate(t,r,n,o,i){let s={resourceTemplate:n,title:r,metadata:o,readCallback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==t&&(delete this._registeredResourceTemplates[t],l.name&&(this._registeredResourceTemplates[l.name]=s)),typeof l.title<"u"&&(s.title=l.title),typeof l.template<"u"&&(s.resourceTemplate=l.template),typeof l.metadata<"u"&&(s.metadata=l.metadata),typeof l.callback<"u"&&(s.readCallback=l.callback),typeof l.enabled<"u"&&(s.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[t]=s;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),s}_createRegisteredPrompt(t,r,n,o,i){let s={title:r,description:n,argsSchema:o===void 0?void 0:Gb(o),callback:i,enabled:!0,disable:()=>s.update({enabled:!1}),enable:()=>s.update({enabled:!0}),remove:()=>s.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==t&&(delete this._registeredPrompts[t],a.name&&(this._registeredPrompts[a.name]=s)),typeof a.title<"u"&&(s.title=a.title),typeof a.description<"u"&&(s.description=a.description),typeof a.argsSchema<"u"&&(s.argsSchema=Gb(a.argsSchema)),typeof a.callback<"u"&&(s.callback=a.callback),typeof a.enabled<"u"&&(s.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=s,o&&Object.values(o).some(c=>{let l=c instanceof ka?c._def?.innerType:c;return Bre(l)})&&this.setCompletionRequestHandler(),s}_createRegisteredTool(t,r,n,o,i,s,a,c,l){Wre(t);let u={title:r,description:n,inputSchema:E1e(o),outputSchema:E1e(i),annotations:s,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==t&&(typeof d.name=="string"&&Wre(d.name),delete this._registeredTools[t],d.name&&(this._registeredTools[d.name]=u)),typeof d.title<"u"&&(u.title=d.title),typeof d.description<"u"&&(u.description=d.description),typeof d.paramsSchema<"u"&&(u.inputSchema=Gb(d.paramsSchema)),typeof d.outputSchema<"u"&&(u.outputSchema=Gb(d.outputSchema)),typeof d.callback<"u"&&(u.handler=d.callback),typeof d.annotations<"u"&&(u.annotations=d.annotations),typeof d._meta<"u"&&(u._meta=d._meta),typeof d.enabled<"u"&&(u.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[t]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,i,s;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Vre(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Vre(r[0])&&(s=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);s=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,i,s,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:i,inputSchema:s,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(t,o,i,s,a,c,{taskSupport:"forbidden"},l,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let i=r[0],s=this._createRegisteredPrompt(t,void 0,n,o,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:i,argsSchema:s}=r,a=this._createRegisteredPrompt(t,o,i,s,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var ezt={type:"object",properties:{}};function T1e(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function C1e(e){return"_def"in e||"_zod"in e||T1e(e)}function Vre(e){return typeof e!="object"||e===null||C1e(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(T1e)}function E1e(e){if(e){if(Vre(e))return Gb(e);if(!C1e(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function tzt(e){let t=_d(e);return t?Object.entries(t).map(([r,n])=>{let o=t$e(n),i=r$e(n);return{name:r,description:o,required:!i}}):[]}function Fh(e){let r=_d(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=cL(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function R1e(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var RC={completion:{values:[],hasMore:!1}};Kre();import P1e from"node:process";var TC=class{constructor(t=P1e.stdin,r=P1e.stdout){this._stdin=t,this._stdout=r,this._readBuffer=new _w,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Ez(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{resolve as F$}from"node:path";import{fileURLToPath as xft}from"node:url";Yn();function I1e(e){return[{name:"claim_status",title:"Read AFK claim",description:"Return the parsed claim marker records and current holder for one issue (`issue`) or a batch (`issues`), keyed per issue.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimStatus(t)},{name:"claim_release",title:"Release AFK claim",description:"MUTATING: post a concede marker for every un-conceded claim holder so the issue (`issue`) or each issue in a batch (`issues`) becomes claimable again.",inputSchema:{issue:w.number().int().positive().optional(),issues:w.array(w.number().int().positive()).min(1).optional()},invoke:t=>e.claimRelease(t)}]}Pk();function Zre(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Jre(e){return typeof e=="string"&&e.trim()!==""?e:null}function nzt(e){let t=Zre(e);if(t===null)return null;let r=Zre(t.demand);return Jre(r?.refusal)??Jre(t.latest_refusal)}function A1e(e){return{tool:"status",args:{scope:"project"},why:e}}function ozt(){return{tool:"status",args:{scope:"host"},why:"diagnose why the host daemon does not answer before changing registration"}}function izt(e,t){let r=e.registration;return r.daemon_reachable?!r.held&&r.repair!==void 0&&r.repair!=="none"?Ck():e.live_workers.length>0&&t===null?{tool:"status",args:{scope:"worker"},why:"observe the Workers already draining this project's queue"}:A1e(t!==null?"observe when the daemon's refusal clears and capacity begins draining again":"observe the next socket-local queue poll and Worker birth"):ozt()}function szt(e){let t=e.registration;if(!t.daemon_reachable)return"daemon unreachable: this project cannot read or change its host registration";if(!t.held)return"unregistered: the daemon is reachable but holds no registration for this project";let r=t.last_poll?.depth,n=r==null?"an unknown queue":`${r} queued`;return`draining: ${e.slots.busy} of ${e.slots.total} Worker slots are busy with ${n}`}function azt(e){return[{intent:"choose the capability that matches your intent",tools:e.filter(t=>!t.description.startsWith("DEPRECATED:")).map(({name:t,title:r})=>({name:t,title:r}))}]}function O1e(e,t){return[{name:"help",title:"Find the next redskilled action",description:"Read live daemon, registration, queue, Worker, and refusal state; return the pasteable next call and a generated intent map. Makes no GitHub request.",inputSchema:{},invoke:async()=>{let[r,n]=await Promise.all([e.projectStatus(),e.hostState().catch(()=>null)]),o=szt(r),i=nzt(n),s=izt(r,i),a=Sa({state:`you are ${o}`,repair:s});if(a.repair==="none")throw new Error("help produced no callable next action");return{here:o,state:{daemon:{reachable:r.registration.daemon_reachable,version:Jre(Zre(n)?.daemon_version)??""},registration:{held:r.registration.held,project:r.registration.project,renewal:r.registration.renewal,target:r.registration.target},queue:r.registration.last_poll==null?null:{at:r.registration.last_poll.at,outcome:r.registration.last_poll.outcome,depth:r.registration.last_poll.depth,detail:r.registration.last_poll.detail},workers:{busy:r.slots.busy,free:r.slots.free,live:r.live_workers.length,target:r.slots.total},validation_schedule:r.validation_schedule,last_refusal:i,warnings:r.warnings??[]},guidance:a.prose,next:a.repair,intent_map:azt(t())}}}]}Yn();function $1e(e){return[{name:"merge_arm",title:"Arm PR for the merge driver",description:"MUTATING: hand one open PR to a live project merge-driver process \u2014 it owns the PR to a terminal state (update-branch when BEHIND, merge-commit once green at head, bounded retries, needs-medic/needs-human classification) without GitHub native auto-merge. Refuses when the merge-driver process is missing so custody cannot become orphaned.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeArm({pr:t})},{name:"merge_status",title:"Read merge driver state",description:"Return whether the merge-driver process is ticking plus durable per-PR records: armed records labeled driver-ticking or orphaned, attempts, last observed state, and proof objects that name GitHub's merge assessment, blocker class, and next action.",inputSchema:{},invoke:()=>e.mergeStatus()},{name:"merge_release",title:"Release PR from the merge driver",description:"MUTATING: stop driver ownership of one PR. The record is kept as released for observability.",inputSchema:{pr:w.number().int().positive()},invoke:({pr:t})=>e.mergeRelease({pr:t})}]}Yn();var czt=["requeue","retake","park","close"];function M1e(e){return[{name:"hitl_resolve",title:"Resolve parked issue with a human decision",description:"MUTATING: encode one human decision on a parked issue atomically \u2014 requeue (concede dangling claims, strip park labels, ready-for-agent), retake (route to the no-agent landing lane), park (keep ready-for-human, record why), or close. The rationale is posted as an issue comment for the audit trail.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(czt),rationale:w.string().min(1)},invoke:t=>e.hitlResolve(t)}]}Yn();var Rz="2.0.0";function Tz(e,t){return{version:Rz,schema:e,projection:t}}var kNr=w.object({age_s:w.number(),stale:w.boolean(),stale_after_s:w.number(),reason:w.enum(["fresh","aged-out","never-observed","orphaned"])}),lzt=w.object({version:w.string(),source:w.enum(["registry","recorded","installed-plugin","bundle-cache","unresolved"]),age_ms:w.number(),stale_after_ms:w.number(),stale:w.boolean(),reason:w.enum(["fresh","aged-out","installed-only","cache-only","never-observed"])}),uzt=w.object({tool:w.string().min(1),args:w.record(w.string(),w.unknown()),why:w.string().min(1)}),dzt=w.union([uzt,w.literal("none")]),pzt=w.object({held:w.boolean(),daemon_reachable:w.boolean(),project:w.string(),socket:w.string(),selector:w.string(),target:w.number(),renewal:w.enum(["renewing","self-renewing","running-on","unknown"]),renew_by:w.string(),renewals:w.number(),lapsed_at:w.string(),reason:w.string(),repair:dzt.optional(),repair_reason:w.string().min(1).optional(),launch_revision:w.number(),bundle_version:w.string(),plugin_cache_version:w.string(),last_poll:w.object({at:w.string(),outcome:w.string(),depth:w.number().nullable(),request_count:w.number(),detail:w.string()}).optional(),published_version:lzt.optional()}).superRefine((e,t)=>{!e.held&&e.repair===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair"],message:"an absent registration must carry a repair or an argued none"}),e.repair==="none"&&e.repair_reason===void 0&&t.addIssue({code:w.ZodIssueCode.custom,path:["repair_reason"],message:"repair none must state why no callable cure is safe"})}),fzt=w.object({name:w.literal("project-birth-breaker"),project_label:w.string(),state:w.enum(["open","half-open"]),opened_at:w.string(),reason:w.string(),closes:w.string(),probe_worker_id:w.string().nullable(),repair:w.object({tool:w.literal("project_reset"),args:w.object({latch:w.literal("project-birth-breaker")}),why:w.string()})}),mzt=w.object({narration:w.string(),moments:w.array(w.object({moment:w.enum(["iteration","post_done","landing"]),state:w.enum(["declared","skip"]),declared:w.boolean(),commands:w.array(w.string())})).length(3)}),CC=w.object({registration:pzt,validation_schedule:mzt,birth_latch:fzt.nullable(),slots:w.object({busy:w.number(),free:w.number(),parked:w.number(),total:w.number(),interactive_reservation:w.number()}),live_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),unattributed_workers:w.array(w.object({id:w.string(),pid:w.number(),issue:w.string(),activity:w.string(),origin:w.string()})),warnings:w.array(w.string()).optional()}),hzt=w.object({number:w.union([w.number(),w.string()]),runner:w.string(),retries:w.number(),phase:w.string(),iteration:w.union([w.number(),w.string()]),activity:w.string(),loc_added:w.number(),loc_removed:w.number(),last_commit_at:w.string(),tools_called_count:w.number(),text_chunk_count:w.number(),reasoning_events:w.number(),reasoning_tokens:w.number(),last_event_at:w.string(),waiting_count:w.number(),input_tokens:w.number(),output_tokens:w.number(),cost_usd:w.number()}),gzt=w.object({status:w.enum(["alive","stalled","capped","unknown"]),laneFresh:w.boolean(),laneAgeMs:w.number().optional(),crossCheckArmed:w.boolean(),liveDescendants:w.boolean().optional(),reason:w.string()}),yzt=w.object({verdict:w.enum(["alive","dead","unknown"]),anchor:w.enum(["daemon","none"]),project_label:w.string().nullable(),pid:w.number().nullable(),staleness:w.object({stale:w.boolean(),age_ms:w.number().nullable(),threshold_ms:w.number().nullable(),reason:w.string()})}),N1e=w.object({worker:w.object({id:w.string(),pid:w.number(),runner:w.string(),origin:w.string(),started_at:w.string(),done:w.number(),total:w.number(),blocked:w.number(),failed:w.number(),current:hzt}),live:w.boolean(),active:w.boolean(),renderable_live:w.boolean(),liveness:w.enum(["active","quiet-but-live","dead"]),liveness_verdict:gzt,daemon_liveness:yzt.optional()}),Cz=w.array(N1e),Pz=w.array(N1e.partial()),bzt=w.object({state:w.object({worker_id:w.string(),pid:w.number(),runner:w.string(),started_at:w.string(),total:w.number(),done:w.number(),blocked:w.number(),failed:w.number(),current:w.object({number:w.union([w.number(),w.string()]),title:w.string(),activity:w.string(),started_at:w.string()})}),live:w.boolean()}),PC=w.object({workers:w.array(bzt),events:w.array(w.object({event:w.string(),epoch:w.number()})),fleet:w.object({ts:w.string(),epoch:w.number(),runner:w.string(),readyForAgent:w.number(),slotsBusy:w.number(),slotsFree:w.number(),slotsTotal:w.number(),slotsParked:w.number(),interactiveReservation:w.number(),spawnsThisTick:w.number()}).nullable(),remoteQueue:w.number().optional(),remoteHuman:w.number().optional(),remoteCacheAgeS:w.number().optional()}),D1e=w.object({number:w.number(),title:w.string(),labels:w.array(w.string())}),L1e=w.object({ready_for_agent:w.object({eligible:w.array(D1e),held_for_summon:w.array(D1e)}),ready_for_human:w.array(w.object({number:w.number(),title:w.string(),labels:w.array(w.string()),body:w.string().optional(),createdAt:w.string().nullable().optional()})),counts:w.object({ready_for_agent_eligible:w.number(),ready_for_agent_held:w.number(),ready_for_human:w.number()}),degraded:w.boolean(),errors:w.array(w.object({kind:w.literal("trust-read"),number:w.number(),message:w.string()}))}),z1e=Tz(CC),wNr=Tz(Cz,{input:"fields",schema:Pz}),vNr=Tz(PC),F1e=Tz(L1e);function xzt(e,t){let{projection:r}=e;if(!r)return e.schema;let n=t[r.input];return Array.isArray(n)&&n.length>0?r.schema:e.schema}function j1e(e){return e.map(t=>{let r=t.outputContract;if(!r)return t;let n=t.invoke.bind(t);return{...t,invoke:async o=>{let i=await n(o),s=xzt(r,o).safeParse(i);if(!s.success)throw new Error(`${t.name} output violates contract ${r.version}: ${s.error.issues.map(a=>`${a.path.join(".")||"<root>"}: ${a.message}`).join("; ")}`);return i}}})}Yn();var U1e="named fleets were removed (ADR 0130): the host daemon owns the budget and each project has exactly one demand producer, so a fleet name addresses nothing. Drop the name \u2014 the work scope, the runner and the base branch now ride with the project's producer: pass `selector` / `runner` / `base` to the rs_dev `project_start` tool (status: `project_status`, resize: `project_resize`, stop: `project_stop`).",Yre=class extends Error{constructor(t){super(t===void 0||t===""?U1e:`fleet ${JSON.stringify(t)}: ${U1e}`),this.name="FleetNamingRemovedError"}};function kw(e){if(!(e==null||e===""))throw new Yre(typeof e=="string"?e:String(e))}Yn();var Szt=w.object({tool:w.literal("status"),args:w.object({scope:w.enum(["worker","project","host"])})});function H1e(e){return w.object({deprecated:w.literal(!0),message:w.string().min(1),replacement:Szt,result:e})}function G1e(e){return{version:e.version,schema:H1e(e.schema),...e.projection===void 0?{}:{projection:{input:e.projection.input,schema:H1e(e.projection.schema)}}}}var _zt=w.object({status:w.unknown(),vitals:Cz,monitor:PC}),kzt=w.object({status:w.unknown(),vitals:Pz,monitor:PC}),q1e=w.object({state:w.unknown(),dashboard:w.unknown(),provision_check:w.unknown(),unit_status:w.unknown()}),wzt={version:Rz,schema:w.union([CC,_zt,q1e]),projection:{input:"fields",schema:w.union([CC,kzt,q1e])}};function B1e(e,t,r){return{deprecated:!0,message:`${e} is deprecated; use status { scope: ${t} }`,replacement:{tool:"status",args:{scope:t}},result:r}}async function vzt(e,t){if(t.scope==="project")return e.projectStatus();if(t.scope==="host"){let[s,a,c,l]=await Promise.all([e.hostState(),e.hostDashboard(),e.hostProvisionCheck(),e.hostUnitStatus()]);return{state:s,dashboard:a,provision_check:c,unit_status:l}}let r={worker:t.worker,live_only:t.live_only??!0,fields:t.fields},[n,o,i]=await Promise.all([e.workerStatus(r),e.workerVitals({live_only:r.live_only,fields:r.fields}),e.monitor()]);return{status:n,vitals:o,monitor:i}}function W1e(e){return[{name:"status",title:"Read redskilled status",description:"Answer the current worker, project, or host status through one intent-scoped read.",inputSchema:{scope:w.enum(["worker","project","host"]),worker:w.string().min(1).optional(),live_only:w.boolean().default(!0),fields:w.array(w.string().min(1)).optional()},outputContract:wzt,invoke:t=>vzt(e,t)}]}Iz();var Az={spec:w.number().int().positive().optional(),lane:w.string().min(1).optional(),label:w.string().min(1).optional(),issues:w.array(w.number().int().positive()).optional(),tags:w.array(w.string().min(1)).optional(),user:w.string().min(1).optional()};var Z1e=w.record(w.string(),w.union([w.string(),w.number(),w.boolean()])),IC=w.string().optional().describe("REMOVED: naming a fleet is refused; a project has one producer.");function J1e(e){return[{name:"project_activation",title:"Preview this project's redskilled activation",description:"READ-ONLY: report whether this project opted into RedSkills and the canonical runner and target a no-argument drain would register.",inputSchema:{},invoke:()=>e.projectActivation()},{name:"project_status",title:"Deprecated project status alias",description:"DEPRECATED: use status { scope: project }. Returns the project answer and names its replacement.",inputSchema:{fleet:IC},outputContract:G1e(z1e),invoke:async({fleet:t})=>(kw(t),B1e("project_status","project",await e.projectStatus()))},{name:"drain",title:"Make this project drain",description:"MUTATING: ensure the daemon is reachable and this project is registered. Omitted runner and target resolve from this project's canonical RedSkills configuration; repeated calls report what was kept. An optional budget_ms arms the harvest deadline: past 70% of it the daemon admits no new claim and spends the rest landing what is in flight. No budget_ms, no deadline.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional(),budget_ms:w.number().int().positive().optional()},invoke:async t=>e.drain(t)},{name:"project_start",title:"Start this project's workers",description:"MUTATING: register this project with the host daemon \u2014 a runner, a target width, and its work policy. Registers rather than launches: the project contributes a record, never a process of its own.",inputSchema:{runner:w.string().min(1),target:w.number().int().min(0).default(1),selector:w.object(Az).optional(),config:Z1e.optional(),base:w.string().min(1).optional(),fleet:IC},invoke:async t=>(kw(t.fleet),e.projectStart(t))},{name:"project_resize",title:"Re-aim this project's workers",description:"MUTATING: change this project's target width, runner, or work policy and send the live directive.",inputSchema:{runner:w.string().min(1).optional(),target:w.number().int().min(0).optional(),selector:w.object(Az).optional(),config:Z1e.optional(),base:w.string().min(1).optional(),fleet:IC},invoke:async t=>(kw(t.fleet),e.projectResize(t))},{name:"project_reset",title:"Reset project execution latch",description:"MUTATING: clear a named in-memory latch for this project so autonomous demand may retry immediately.",inputSchema:{latch:w.literal("project-birth-breaker"),fleet:IC},invoke:async({latch:t,fleet:r})=>(kw(r),e.projectReset({latch:t}))},{name:"project_stop",title:"Stop this project's workers",description:"MUTATING: stop this project's work and give its registration back; force hard teardown explicitly.",inputSchema:{force:w.boolean().optional(),fleet:IC},invoke:async({force:t,fleet:r})=>(kw(r),e.projectStop({force:t}))}]}Yn();function Y1e(e){return[{name:"gate_run",title:"Run the AFK gate",description:"MUTATING: materialize the branch's feedback worktree and run the package-scoped validation gate against it.",dangerClass:"mutating",inputSchema:{branch:w.string().min(1),base:w.string().min(1).optional()},invoke:t=>e.gateRun(t)}]}function Q1e(e){return[{name:"deadend_audit",title:"Audit AFK deadends",description:"Return the read-only deadend audit: dangling claims, red PRs with dead owners, superseded PRs, executable Tickets carrying an active Current blocker, dependency blocks whose req targets all closed, human-queue age outliers, and stale worktrees \u2014 each class paired with its recommended cure. Cache-backed: repeated calls within the refresh window cost zero GitHub quota.",inputSchema:{},invoke:()=>e.deadendAudit()}]}Yn();function X1e(e){return[{name:"requeue",title:"Requeue AFK issue",description:"MUTATING: apply the complete parked-issue requeue transition and record human guidance.",inputSchema:{issue:w.number().int().positive(),guidance:w.string().min(1),repo:w.string().min(1).optional(),dryRun:w.boolean().optional(),adoptBranch:w.string().min(1).optional()},invoke:t=>e.requeue(t)},{name:"retake",title:"Recommend AFK retake",description:"Return the structured issue, PR, branch, worktree, worker-state, and recommended-next-action report.",inputSchema:{issue:w.number().int().positive(),repo:w.string().min(1).optional(),prLimit:w.number().int().positive().max(1e3).optional()},invoke:t=>e.retake(t)},{name:"reap",title:"Reap AFK branches",description:"MUTATING: classify and delete stale local and remote AFK branches.",inputSchema:{},invoke:()=>e.reap()},{name:"unblock_sweep",title:"Sweep dependency blocks",description:"MUTATING: promote dependency-blocked issues whose requirements are all closed.",inputSchema:{},invoke:()=>e.unblockSweep()}]}Yn();function eLe(e){return[{name:"land_branch",title:"Land AFK branch",description:"MUTATING: land one validated worker branch into its base through the complete landing sequence.",dangerClass:"mutating",inputSchema:{issue:w.number().int().positive(),branch:w.string().min(1),base:w.string().min(1).optional(),title:w.string().min(1).optional(),openPr:w.boolean().optional()},invoke:t=>e.landBranch(t)},{name:"cascade_status",title:"Read close cascade",description:"Return the dependents of one issue and which of them the close cascade would promote.",inputSchema:{issue:w.number().int().positive()},invoke:({issue:t})=>e.cascadeStatus({issue:t})}]}Yn();function tLe(e){return[{name:"logs",title:"Read redskilled logs",description:"Return the newest CastleLaneRecord entries from one structured lane; bounded by `limit` (default 200, max 10 000). Pass `kind` to filter before the limit.",inputSchema:{lane:w.enum(["worker","supervisor","monitor","liveness"]),id:w.string().min(1),limit:w.number().int().positive().max(1e4).default(200),kind:w.string().optional()},invoke:t=>e.logs(t)},{name:"dashboard",title:"Build AFK dashboard",description:"Build the structured operational dashboard from GitHub and local state.",inputSchema:{periodDays:w.number().int().positive().default(30)},invoke:({periodDays:t})=>e.dashboard({periodDays:t})},{name:"history",title:"Read redskilled history",description:"Return structured AFK history records, newest records last.",inputSchema:{limit:w.number().int().positive().max(1e4).optional()},invoke:({limit:t})=>e.history({limit:t})},{name:"queue_status",title:"Read AFK queues",description:"Return ready-for-agent and ready-for-human queue candidates, retaining successful candidates and naming partial trust-read failures as a degraded result. Pass `selector` to preview the producer's scoped view of the ready queue (same facets as its work selector, e.g. tags/user).",inputSchema:{selector:w.object(Az).optional()},outputContract:F1e,invoke:t=>e.queueStatus({selector:t.selector})},{name:"events_since",title:"Poll events since cursor",description:"Return AFK history events and Worker lane records after an opaque cursor, plus the next cursor. Omit cursor to get a fresh baseline cursor with no events. Unknown or expired cursors are refused with a re-baseline prompt.",inputSchema:{cursor:w.string().min(1).optional()},invoke:t=>e.eventsSince({cursor:t.cursor})}]}Yn();function rLe(e){return[{name:"manager",title:"Route work through the Manager",description:"MUTATING: take one operator intent into the Manager \u2014 intake, route an effort to a skill, attach an artifact, read effort status, or export/import the checkpoint \u2014 and return the effort record it acted on.",inputSchema:{intent:w.string().min(1).optional(),action:w.enum(["intake","route","artifact","status","checkpoint"]).optional(),effort:w.string().min(1).optional(),skill:w.string().min(1).optional(),artifact:w.string().min(1).optional(),checkpoint:w.enum(["export","import"]).optional(),path:w.string().min(1).optional()},invoke:t=>e.manager(t)},{name:"red_doctor",title:"Diagnose this repository's RedSkills setup",description:"READ-ONLY: return every doctor finding for this repository \u2014 operational probes, host toolchain, lane and process census, executable acceptance, HUMAN-ONLY type declarations and disposable-lane hygiene \u2014 each paired with the route that repairs it. Applying a repair is the `/red-doctor` skill's own fix lane, never a side effect of the read.",inputSchema:{checks:w.array(w.string().min(1)).optional()},invoke:t=>e.redDoctor(t)},{name:"audit_skills",title:"Audit the shipped skills",description:"Return the ranked skill-audit scores for this repository's skill tree. Pass `mechanical_only` to score without the judge, which makes the read deterministic and free of agent cost.",inputSchema:{mechanical_only:w.boolean().optional(),runner:w.string().min(1).optional()},invoke:t=>e.auditSkills(t)},{name:"install_type_labels",title:"Install Wayfinder type labels",description:"MUTATING: create the Wayfinder ticket type labels on the tracker AND declare the HUMAN-ONLY ones in this project's configuration, in one act \u2014 the two are one protection with two halves, and installing only the labels leaves the repository looking protected while unblocked decision Tickets enter the autonomous queue (#3013).",inputSchema:{labels:w.array(w.string().min(1)).optional(),repo:w.string().min(1).optional(),dry_run:w.boolean().optional()},invoke:t=>e.installTypeLabels(t)},{name:"codex_statusline",title:"Inspect the Codex footer preference",description:"READ-ONLY: return the active Codex configuration's status-line inspection \u2014 the file read, the current preference, and the problem that keeps the RedSkills footer from rendering.",inputSchema:{config:w.string().min(1).optional()},invoke:t=>e.codexStatusline(t)},{name:"codex_monitor_agent",title:"Build the Codex monitor agent brief",description:"Return the read-only monitor brief a Codex sub-agent is spawned with: what to poll, how often, and the conditions under which it closes itself. It spawns nothing \u2014 the host's own spawn primitive does.",inputSchema:{project_root:w.string().min(1).optional(),mode:w.string().min(1).optional(),interval_seconds:w.number().int().positive().optional()},invoke:t=>e.codexMonitorAgent(t)},{name:"reconcile_engine",title:"Reconcile this project's engine delivery",description:"MUTATING: warm the published engine bundle into the stable cache path and re-point a standing registration at it in one operation, then return the version, the bundle path, and what happened to the registration.",inputSchema:{version:w.string().min(1).optional()},invoke:t=>e.reconcileEngine(t)}]}Yn();function nLe(e){return[{name:"daily_review",title:"Build daily activity review",description:"Return the structured daily activity review report for the local window.",inputSchema:{},invoke:()=>e.dailyReview({})},{name:"weekly_review",title:"Build weekly activity review",description:"Return the structured weekly activity review report for the local window.",inputSchema:{},invoke:()=>e.weeklyReview({})},{name:"triage",title:"Apply triage decision",description:"MUTATING: apply the decided triage transition to one issue, gated by the per-repo trust policy.",inputSchema:{issue:w.number().int().positive(),decision:w.enum(["ready-for-agent","needs-info","ready-for-human","wontfix"]),summon:w.boolean().optional(),repo:w.string().min(1).optional()},invoke:t=>e.triage(t)},{name:"respond",title:"Handle comment event",description:"MUTATING: parse a /dev comment summon, authorize the commenter, and route the advisory or mutation verb.",inputSchema:{body:w.string(),number:w.number().int().positive(),author:w.string().min(1).optional(),is_pr:w.boolean().optional(),runner:w.string().min(1).optional(),repo:w.string().min(1).optional()},invoke:t=>e.respond(t)}]}Yn();Yn();Pk();function Xre(e){let t=Sa({state:e instanceof Error?e.message:String(e),repair:Sb("the caller must choose one dispatch intent before retrying")});if(t.repair!=="none")throw new Error("invalid worker refusal repair");return{refused:!0,reason:t.prose,repair:t.repair,repair_reason:t.repair_reason}}var ene={issue:w.number().int().positive().optional(),demand:w.string().min(1).optional(),runner:w.string().min(1).optional(),mode:w.enum(["no-mistakes","direct-PR","local-only","scout"]).optional()};function AC(e){let t=e;if(t.issue===void 0==(t.demand===void 0))throw new Error("exactly one of issue or demand is required");if(t.mode==="scout"&&t.issue!==void 0)throw new Error("mode: scout is demand-only \u2014 combine scout with demand, not issue");if(t.issue!==void 0&&t.mode!==void 0)throw new Error("mode is only valid for demand dispatches");return t}function oLe(e){return[{name:"worker_dispatch",title:"Dispatch AFK worker",description:"MUTATING: run one tracked issue or mint and run one disposable demand through the AFK worker lifecycle.",inputSchema:ene,invoke:t=>{let r;try{r=AC(t)}catch(n){return Promise.resolve(Xre(n))}return e.workerDispatch(r)}},{name:"worker_stop",title:"Stop AFK worker",description:"MUTATING: terminate one worker process tree.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!1})},{name:"worker_recycle",title:"Recycle AFK worker",description:"MUTATING: terminate one fleet worker so its supervisor can replace the slot.",inputSchema:{worker:w.string().min(1)},invoke:({worker:t})=>e.workerStop({worker:t,recycle:!0})}]}function iLe(e){return[{name:"runner_list",title:"List AFK runners",description:"Return the canonical runner specification registry.",inputSchema:{},invoke:()=>e.runnerList()},{name:"runner_detect",title:"Detect AFK runner",description:"Resolve the runner selected by an explicit override or the current host environment.",inputSchema:{runner:w.string().min(1).optional()},invoke:({runner:t})=>e.runnerDetect({runner:t})},{name:"runner_steer",title:"Steer live AFK worker",description:"MUTATING: write a live-steer request into a running worker's next iteration.",inputSchema:{worker:w.string().min(1),text:w.string().min(1)},invoke:t=>e.runnerSteer(t)},{name:"steer_status",title:"Read steer status",description:"Return the live-steer status for a worker: none (no steer ever written), pending (written, not yet consumed), or consumed (consumed at a specific iteration).",inputSchema:{worker:w.string().min(1)},invoke:t=>e.steerStatus(t)},{name:"worker_request",title:"Dispatch worker with request",description:"MUTATING: dispatch a new worker and inject a special request into its spawn-time handoff.",inputSchema:{...ene,text:w.string().min(1)},invoke:t=>{let r;try{r=AC(t)}catch(n){return Promise.resolve(Xre(n))}return e.workerRequest({...r,text:t.text})}}]}function sLe(e){return[{name:"statusline_aggregate",title:"Read statusline aggregate",description:"Return the project-side statusline aggregate (project, repo counters, docs drift, drain, Worker rows, aggregated AFK block, queue) as structured data, using the same collector cores and cache discipline as the command-backed statusLine. Host-side fields (session model/effort, context %, usage quotas) are out of scope.",inputSchema:{},invoke:()=>e.statuslineAggregate()}]}Yn();Pk();function aLe(e,t,r={}){let n=e==="confirm"?Sa({state:"dangerous tool requires explicit confirmation",repair:{tool:t,args:{...r,confirmation:!0},why:"retry the same operation with explicit confirmation"}}):Sa({state:"dangerous tool is denied by the configured posture",repair:Sb("the configured posture deliberately forbids this tool")});return{refused:!0,posture:e,action:t,reason:n.prose,repair:n.repair,...n.repair==="none"?{repair_reason:n.repair_reason}:{}}}function Oz(e,t){return t==="allow"?e:e.map(r=>{if(!r.dangerClass)return r;if(t==="deny")return{...r,invoke:async i=>aLe("deny",r.name)};let n={...r.inputSchema,confirmation:w.boolean().optional()},o=r.invoke.bind(r);return{...r,inputSchema:n,invoke:async i=>{if(i.confirmation!==!0)return aLe("confirm",r.name,i);let{confirmation:s,...a}=i;return o(a)}}})}Yn();function cLe(e){return[{name:"wait_start",title:"Start rsp wait",description:"MUTATING: spawn a detached rsp wait (pr | run | release | cmd) and return its registry id.",inputSchema:{kind:w.enum(["pr","run","release","cmd"]),target:w.string().min(1),timeout_ms:w.number().int().positive().optional(),reason:w.string().optional()},invoke:t=>e.waitStart(t)},{name:"wait_list",title:"List active rsp waits",description:"Return the active-wait registry from .red/tmp/waits.",inputSchema:{},invoke:()=>e.waitList()},{name:"wait_status",title:"Read rsp wait status",description:"Return the registry entry for a running wait or the sealed result envelope for a finished one.",inputSchema:{id:w.string().min(1)},invoke:({id:t})=>e.waitStatus({id:t})}]}Yn();function lLe(e){return[{name:"worktree_list",title:"List disposable worktrees",description:"Enumerate every checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{},invoke:()=>e.worktreeList()},{name:"worktree_remove",title:"Remove disposable worktree",description:"MUTATING: remove one checkout under the disposable `.red/tmp/worktrees/*` lanes.",inputSchema:{path:w.string().min(1)},invoke:({path:t})=>e.worktreeRemove({path:t})}]}Yn();function uLe(e){return[{name:"standing_orders_show",title:"Show standing orders for this project",description:"READ-ONLY: return all standing orders for this project. Standing orders are an append-only, numbered register injected verbatim into every Worker brief.",inputSchema:{project_label:w.string().min(1).optional().describe("Override the current project label")},invoke:t=>e.standingOrdersShow(t)},{name:"standing_orders_append",title:"Append a standing order",description:"MUTATING: append a new standing order to this project's register. The order is injected verbatim into every Worker brief at admission and on resume. Append is append-only \u2014 existing orders are never mutated or renumbered.",inputSchema:{text:w.string().min(1).describe("The standing order text"),project_label:w.string().min(1).optional().describe("Override the current project label")},invoke:t=>e.standingOrdersAppend(t)}]}var $z="Call the redskilled MCP's `help` tool.\nFollow its guidance and invoke the returned `next` call.",tne=[{name:"drain",title:"Drain this project's queue",description:"Find the next action for starting or continuing a project drain.",body:$z},{name:"diagnose",title:"Diagnose redskilled",description:"Find the next action for understanding a redskilled problem.",body:$z},{name:"configure",title:"Configure redskilled",description:"Find the next action for changing project execution configuration.",body:$z},{name:"stop",title:"Stop project work",description:"Find the next action for stopping project work safely.",body:$z}];var dLe="rs_dev";function pLe(e,t="allow"){let r=[],n=[...O1e(e,()=>r),...W1e(e),...J1e(e),...tLe(e),...Q1e(e),...oLe(e),...iLe(e),...X1e(e),...Y1e(e),...eLe(e),...I1e(e),...$1e(e),...M1e(e),...lLe(e),...cLe(e),...nLe(e),...sLe(e),...rLe(e),...uLe(e)];return r=Oz(j1e(n),t),r}Gt();function ww(e){return Zr(JSON.parse(JSON.stringify(e??null)),{objectArrayColumns:!0,primitiveArrayColumns:!0})}gb();var po="its engine went with ADR 0147; no _redskills/* daemon method serves it yet",Bs="the daemon owns this authority (ADR 0130/0148) but publishes no _redskills/* method for it yet",sl="it is answerable from this checkout alone, but the adapter owns no body for it since ADR 0147";function Et(e,t){return{tool:e,kind:"unserved",reason:t}}var fLe=[Et("help",sl),{tool:"status",kind:"control",operation:"status"},Et("project_activation",sl),{tool:"project_status",kind:"control",operation:"status"},{tool:"drain",kind:"control",operation:"drain"},Et("project_start",Bs),Et("project_resize",Bs),Et("project_reset",Bs),{tool:"project_stop",kind:"control",operation:"stop"},Et("logs",po),Et("dashboard",po),Et("history",po),Et("queue_status",po),Et("events_since",po),Et("deadend_audit",po),{tool:"worker_dispatch",kind:"served",method:lo.goDispatch},Et("worker_stop",Bs),Et("worker_recycle",Bs),Et("runner_list",Bs),Et("runner_detect",Bs),Et("runner_steer",Bs),Et("steer_status",Bs),Et("worker_request",Bs),Et("requeue",po),Et("retake",po),Et("reap",po),Et("unblock_sweep",po),Et("gate_run",Bs),Et("land_branch",po),Et("cascade_status",po),Et("claim_status",po),Et("claim_release",po),Et("merge_arm",po),Et("merge_status",po),Et("merge_release",po),Et("hitl_resolve",po),Et("worktree_list",sl),Et("worktree_remove",sl),Et("wait_start",sl),Et("wait_list",sl),Et("wait_status",sl),Et("daily_review",po),Et("weekly_review",po),Et("triage",po),Et("respond",po),Et("statusline_aggregate",sl),Et("manager",Bs),Et("red_doctor",sl),Et("audit_skills",sl),Et("install_type_labels",po),Et("codex_statusline",sl),Et("codex_monitor_agent",sl),Et("reconcile_engine",Bs),Et("standing_orders_show",Bs),Et("standing_orders_append",Bs)];var Ezt=new Map(fLe.map(e=>[e.tool,e]));function mLe(e){return Ezt.get(e)}function rne(){return fLe.flatMap(e=>e.kind==="control"&&e.operation!=null?[[e.tool,e.operation]]:[])}function Rzt(){return rne().map(([e])=>e).sort()}function hLe(e){return`rs_dev tool ${JSON.stringify(e.tool)} is not served: ${e.reason} (#4113). The adapter refuses rather than degrade the call to a Worker prompt, which returns an empty envelope that looks healthy. The Project control surface serves only: ${Rzt().join(", ")}.`}var Tzt=new Map([["project_drain","drain"],...rne()]),Czt=new Set(["target","runner","scope","registration","budget_ms","live_only","fields","worker"]);async function nne(e,t,r){let n=Tzt.get(t);if(n!=null){let i=Object.keys(r).filter(s=>!Czt.has(s));if(i.length>0)throw new Error(`the Project control surface cannot express ${JSON.stringify(i.sort())} for ${JSON.stringify(t)}`);if(n==="status"){if(r.scope==="host")return await e.hostState();if(r.scope==="worker")throw new Error('status { scope: "worker" } is not served: worker vitals live in no daemon method yet; read scope "host" and filter its workers, or use scope "project"');return await e.control("status")}return await e.control(n,Pzt(r))}let o=mLe(t);if(o?.kind==="served"&&t==="worker_dispatch"){let i=AC({...r});if(i.issue!==void 0||i.mode!==void 0||i.runner!==void 0)throw new Error(`rs_dev tool "worker_dispatch" serves demand dispatches through the daemon's go-dispatch method; a tracked-issue dispatch rides the registered drain (arm /afk), and mode/runner are not expressible on the go_dispatch wire`);return await e.goDispatch(i.demand)}throw o?.kind==="unserved"?new Error(hLe(o)):new Error(`unsupported ACP Project capability ${JSON.stringify(t)}`)}function Pzt(e){let t=e.target,r=e.runner,n=e.registration;return{...typeof t=="number"&&Number.isInteger(t)&&t>=0?{target:t}:{},...typeof r=="string"&&r.length>0?{runner:r}:{},...n!=null&&typeof n=="object"&&!Array.isArray(n)?{registration:n}:{}}}ane();import{execFileSync as FFt}from"node:child_process";Z0();Pd();function WLe(e){let t=KLe(e.repo).join("/"),r=e.selector??{},n=[`repo:${t}`,"is:issue","is:open",zz(e.readyLabel??fu)];r.lane!=null&&r.lane!==""&&n.push(zz(`lane:${r.lane}`)),r.label!=null&&r.label!==""&&n.push(zz(r.label));for(let o of r.tags??[])o!==""&&n.push(zz(`${lne}${o}`));return r.user!=null&&r.user!==""&&r.user!=="@me"&&n.push(`author:${r.user}`),n.join(" ")}function VLe(e){let[t,r]=KLe(e.repo),n=e.selector??{},o=e.readyLabel??fu,i=[o];n.lane!=null&&n.lane!==""&&i.push(`lane:${n.lane}`),n.label!=null&&n.label!==""&&i.push(n.label);for(let a of n.tags??[])a!==""&&i.push(`${lne}${a}`);let s=n.user!=null&&n.user!==""&&n.user!=="@me"?n.user:void 0;return{owner:t,repo:r,labels:i,...s===void 0?{}:{creator:s},counter_labels:{ready:o,human:jh}}}function zz(e){return`label:${JSON.stringify(e)}`}function KLe(e){let t=e.trim().split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error("a registration needs the repository its queue lives in: the daemon polls the string it is handed and cannot work out which tracker a checkout belongs to");return[t[0],t[1]]}var Jzt="Implement issue #{{work_item}} in this workspace. The Ticket is already claimed for you, and the daemon runs the gate, publishes your commits and lands the pull request after you finish \u2014 so never touch GitHub yourself: no label moves, no claim or status comments, no PR. Your whole job is the change and its commits, right here. You are already standing in your own dedicated worktree on the Ticket's base branch: work and commit right here, and never create another worktree \u2014 the repository's worktree lanes govern interactive sessions, not Workers. If your change touches apps/ or packages/, also write a .changeset/<slug>.md entry naming each touched package by its package.json name with a patch bump, and commit it with the change. When the change is committed, say <promise>DONE</promise>. If the work is genuinely blocked, say what blocks it and <promise>BLOCKED</promise>.";function ZLe(e){let t={repo:e.repo,...e.selector==null?{}:{selector:e.selector},...e.readyLabel==null?{}:{readyLabel:e.readyLabel}};return{selector:WLe(t),queue_poll:VLe(t),argv:Jp("red-skills-redskilled",["acp-worker",...e.runner==null?[]:["--child-agent",e.runner]],e.version).split(" "),workspace_path:e.workspacePath,trunk:{remote:"origin",branch:e.trunkBranch??"main"},prompt:Jzt,...e.validationCommands==null||e.validationCommands.length===0?{}:{validation_commands:[...e.validationCommands]},...e.budgetMs==null?{}:{budget_ms:e.budgetMs},target:e.target,...e.standing===!0?{standing:!0}:{}}}Rw();gb();Iz();Rw();One();hf();var Nne=["afk.standing.runner","afk.standing.target"];function zFt(e){let t=Ane(e);if(t!=null)return{kind:"declared",standing:t};let r=Nne.filter(n=>(e[n]??"").trim()!=="");return r.length===0?{kind:"absent"}:{kind:"incomplete",stated:r,missing:Nne.filter(n=>!r.includes(n))}}function Lne(e){try{return zFt(nx(al(e).configPath,{warn:()=>{}}))}catch{return{kind:"absent"}}}function zne(e){let t=Lne(e);return t.kind==="declared"?t.standing:null}function Fne(e,t){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:t?.target??1}function jne(e,t){return typeof e=="string"&&e.length>0?e:t?.runner}function Zze(e,t){if(t.kind!=="incomplete")return"";let r=t.missing.length>0?`leaves ${t.missing.join(" and ")} empty`:`states ${t.stated.join(" and ")} with a value it cannot use \u2014 runner must be one of ${EN.join(", ")} and target a positive integer`;return`redskilled MCP: ${e} declares plugins.dev.afk.standing but ${r}, so it stays inert and no drain was registered for it. State both ${Nne.join(" and ")} usably, or remove the block.`}hf();function jFt(e,t,r={},n=Mz){let o=HFt(e,n);if(o==null)return;let i=zne(e),s=Fne(r.target,i),a=jne(r.runner,i),c=UFt(e),l=typeof r.budget_ms=="number"&&Number.isFinite(r.budget_ms)&&r.budget_ms>0?r.budget_ms:void 0;return ZLe({repo:o,workspacePath:e,target:s,version:t,...i==null?{}:{standing:!0},...a==null?{}:{runner:a},...Jze(e)==null?{}:{trunkBranch:Jze(e)},...c.length===0?{}:{validationCommands:c},...l==null?{}:{budgetMs:l}})}function Wz(e,t,r={},n=Mz){let o=zne(e),i=jne(r.runner,o),s=jFt(e,t,r,n);return{...r,...i==null?{}:{runner:i},target:Fne(r.target,o),...s==null?{}:{registration:s}}}function UFt(e){try{let t=Kze(nx(al(e).configPath,{warn:()=>{}}));return[...t.post_done??[],...t.landing??[]]}catch{return[]}}function Jze(e){try{let r=FFt("git",["-C",e,"symbolic-ref","refs/remotes/origin/HEAD"],{encoding:"utf8",timeout:5e3}).trim().split("/").pop();return r==null||r===""?void 0:r}catch{return}}function HFt(e,t=Mz){let r;try{r=t(e).name}catch{return}return/^[^/\s]+\/[^/\s]+$/.test(r)?r:void 0}async function Yze(e){let t=e.warn??(s=>void process.stderr.write(`${s}
|
|
445
445
|
`)),r;try{r=await e.root()}catch(s){return{kind:"unreachable",detail:String(s)}}let n=(e.reading??Lne)(r);if(n.kind==="absent")return{kind:"undeclared"};if(n.kind==="incomplete"){let s=Zze(r,n);return t(s),{kind:"incomplete",detail:s}}let{runner:o,target:i}=n.standing;try{let s=(e.input??Wz)(r,e.version,{runner:o,target:i});if(s.registration==null){let a=`redskilled MCP: ${r} declares a standing drain at ${o} x${i}, but this checkout names no owner/name repository, so there is no queue to register \u2014 the declaration registers nothing`;return t(a),{kind:"unregisterable",detail:a}}return await e.drain(s),{kind:"registered",runner:o,target:i}}catch(s){return t(`redskilled MCP: ${r} declares a standing drain at ${o} x${i}, and registering it failed \u2014 ${String(s)}`),{kind:"unreachable",detail:String(s)}}}wd();var Tw="redskilled://lanes/events",qFt=1e3;function Qze(e,t,r={}){let n=r.bufferLimit??qFt,o=[],i=0,s,a=c=>{o.push(c.record),o.length>n&&o.splice(0,o.length-n),e.sendResourceUpdated({uri:Tw})};return e.registerCapabilities({resources:{subscribe:!0}}),e.setRequestHandler(Yk,()=>({resources:[{uri:Tw,name:"Redskilled lane events",description:"Subscribe to receive AFK lane records (Worker landings, deaths, lost claims, supervisor halts) appended after subscription. Payloads are byte-compatible with the `logs` tool's CastleLaneRecord shape.",mimeType:"application/toon"}]})),e.setRequestHandler(Qk,c=>{let l=Une(c);if(l!==Tw)throw new Error(`unknown resource ${JSON.stringify(l)}`);let u=o.splice(0,o.length);return{contents:[{uri:Tw,mimeType:"application/toon",text:ww({events:u})}]}}),e.setRequestHandler(JX,async c=>Une(c)!==Tw?{}:(i+=1,i===1&&(s=await t.subscribe(a),t.start(r.intervalMs)),{})),e.setRequestHandler(YX,c=>Une(c)!==Tw?{}:(i>0&&(i-=1),i===0&&(s?.(),s=void 0,t.stop()),{})),{poll:()=>t.poll(),stop:()=>{s?.(),s=void 0,t.stop()}}}function Une(e){let t=e?.params;return typeof t?.uri=="string"?t.uri:""}function eFe(e){let t=new Set,r,n,o=async()=>{let s=await e("events_since",r===void 0?{}:{cursor:r});if(!Xze(s)||typeof s.cursor!="string")throw new Error("redskilled ACP returned an invalid events_since envelope");let a=Array.isArray(s.lane_records)?s.lane_records.filter(Xze):[];return{cursor:s.cursor,lane_records:a}},i={async subscribe(s){return r===void 0&&(r=(await o()).cursor),t.add(s),()=>t.delete(s)},async poll(){if(t.size===0)return 0;let s=await o();r=s.cursor;for(let a of s.lane_records)for(let c of t)c({path:"redskilled-acp",record:a});return s.lane_records.length},start(s=1e3){n===void 0&&(n=setInterval(()=>void i.poll().catch(()=>{}),s),n.unref())},stop(){n!==void 0&&clearInterval(n),n=void 0,t.clear()}};return i}function Xze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}Yn();gb();var Hne="rs_github",tFe="github_request",Vz=lo.githubRequest;function qne(){return[{name:tFe,title:"Request the Project's forge",description:"MUTATING: forward one REST request to the Project's GitHub gateway. An observing method (GET, HEAD) is served from the daemon's Project cache and carries the age of what it served; concurrent identical reads share one upstream call. A mutating method is scheduled through the daemon's durable outbox and answers with its publication receipt. Paths are repository-relative \u2014 `issues/17` \u2014 or the full `repos/<owner>/<repo>/\u2026` form of this Project's own repository; another repository is refused.",method:Vz,inputSchema:{method:w.enum(G0e),path:w.string().min(1),body:w.record(w.unknown()).optional(),headers:w.record(w.string()).optional()}}]}function rFe(e){return{request:{method:e.method,path:e.path,...e.body===void 0?{}:{body:e.body},...e.headers===void 0?{}:{headers:e.headers}}}}function Gne(e){let t=new Sw({name:Hne,version:e.version}),r=t.registerTool.bind(t);for(let n of e.tools??qne())r(n.name,{title:n.title,description:n.description,inputSchema:n.inputSchema},async o=>({content:[{type:"text",text:ww(await e.invoke(n.method,rFe(o)))}]}));return t}var Hy=P4("redskilled-mcp"),Xdr="confirm";function epr(e=process.cwd(),t){let r=new Sw({name:dLe,version:Hy.version}),n=r.registerTool.bind(r),o=t??(async()=>{throw new Error("REDSKILLED_ACP_UNAVAILABLE: the stdio adapter has no ACP client")}),i={},s=async()=>typeof e=="string"?e:await e(),a=async(l,u)=>{if(l!=="drain"||u.registration!=null)return u;let d;try{d=await s()}catch(f){throw new Error(`rs_dev drain cannot build its registration: the session's project root did not resolve (${f instanceof Error?f.message:String(f)}); a drain without a registration would record intent nothing acts on, so it is refused instead`)}return Wz(d,Hy.version,u)},c=pLe(i).map(l=>({...l,invoke:async u=>o(l.name,await a(l.name,u))}));for(let l of Oz(c,Xdr))n(l.name,{title:l.title,description:l.description,inputSchema:l.inputSchema},async u=>({content:[{type:"text",text:ww(await l.invoke(u))}]}));for(let l of tne)r.registerPrompt(l.name,{title:l.title,description:l.description},async()=>({messages:[{role:"user",content:{type:"text",text:l.body}}]}));return Qze(r.server,eFe(o)),r}async function Sft(e,t=process.env,r=process.cwd()){let n=(t.RED_SKILLS_PROJECT_ROOT??t.CLAUDE_PROJECT_DIR??t.CODEX_PROJECT_DIR??t.OPENCODE_PROJECT_DIR??"").trim();if(n!=="")return F$(n);if(e.getClientCapabilities()?.roots!==void 0)try{let o=await e.listRoots();for(let i of o.roots)if(i.uri.startsWith("file:"))return F$(xft(i.uri))}catch{}return F$(r)}async function _ft(e){let t,r=new Promise(n=>{t=n});e.server.server.onclose=t,await e.server.connect(e.transport),e.afterConnect?.(),await r}async function tpr(){let e=process.cwd(),t,r,n=()=>(t??=Sft(r.server,process.env,e).then(i=>dY({cwd:i,name:"RedSkills GitHub MCP adapter",version:Hy.version})),t);r=Gne({version:Hy.version,invoke:async(i,s)=>{if(i!==Vz)throw new Error(`rs_github: no daemon method ${JSON.stringify(i)}`);return(await n()).github(s.request)}});let o=()=>{r.close()};process.once("SIGINT",o),process.once("SIGTERM",o);try{await _ft({server:r,transport:new TC})}finally{if(t!==void 0)try{(await t).close()}catch{}process.removeListener("SIGINT",o),process.removeListener("SIGTERM",o)}}async function rpr(){let e=process.cwd(),t,r,n,o=()=>r??=Sft(n.server,process.env,e),i=()=>(t??=o().then(a=>dY({cwd:a,name:"RedSkills MCP adapter",version:Hy.version})),t);n=epr(o,async(a,c)=>nne(await i(),a,c));let s=()=>{n.close()};process.once("SIGINT",s),process.once("SIGTERM",s);try{await _ft({server:n,transport:new TC,afterConnect:()=>{Yze({version:Hy.version,root:o,drain:async a=>nne(await i(),"drain",a)})}})}finally{if(t!==void 0)try{(await t).close()}catch{}process.removeListener("SIGINT",s),process.removeListener("SIGTERM",s)}}var npr=`Usage: red-skills-redskilled-mcp [command]
|
|
446
446
|
|
|
447
447
|
Commands:
|