@cerebriline/core 4.100.269 → 4.100.271

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.
@@ -1000,21 +1000,21 @@ To see a version: \`read_files\` with \`revision: "#${d}"\`. To apply it to your
1000
1000
  `,{encoding:"utf8",mode:384}),FAe(r,this.filePath)}catch(o){throw UAe(r,{force:!0}),o}this.cache=void 0;try{dG(this.filePath,384)}catch{}yb(t)}saveProviderSettings(e,t={}){let n=KAe(Sp.parse(e)),r=this.read(),o=n.provider,i=t.setLastUsed!==!1,s=r.providers[o],a=t.tokenSource??s?.tokenSource??"manual",d={...r,providers:{...r.providers,[o]:{settings:n,updatedAt:jAe(),tokenSource:a}},lastUsedProvider:i?o:r.lastUsedProvider};this.write(d);let l=r.providers.cline?.settings?.auth,c=n.provider==="cline"?n.auth:d.providers.cline?.settings?.auth,u=!!l?.accessToken&&!c?.accessToken;return ct(`providers.save providerId=${o} tokenSource=${a} clineAuthWasPresent=${!!l?.accessToken} clineAuthIsPresent=${!!c?.accessToken} authDropped=${u}`),d}resolveProviderSettings(e,t){let n=e.providers[t]?.settings,o=Yr(t)?.storageProviderId;if(!o||o===t)return n;let i=e.providers[o]?.settings;if(!i)return n;return Sp.parse({...i.auth?{auth:i.auth}:{},...i.apiKey?{apiKey:i.apiKey}:{},...i.baseUrl?{baseUrl:i.baseUrl}:{},...n??{},provider:t})}getProviderSettings(e){let t=this.read();return this.resolveProviderSettings(t,e)}getVoiceInputSettings(){return this.read().modes.voiceInput}setVoiceInputSettings(e){let t=this.read();if(e)t.modes.voiceInput=zR.parse(e);else delete t.modes.voiceInput;return this.write(t),t}resolveLastUsedProviderId(e,t){let n=e.lastUsedProvider;if(n===zAe&&t.isClinePassEnabled===!1)return qAe;return n}getLastUsedProviderSettings(e={}){let t=this.read(),n=this.resolveLastUsedProviderId(t,e);if(!n)return;return this.resolveProviderSettings(t,n)}getProviderConfig(e,t){let n=this.getProviderSettings(e);if(!n)return;return La(n,t)}getLastUsedProviderConfig(e={}){let t=this.getLastUsedProviderSettings(e);if(!t)return;return La(t,e)}async refreshCatalog(){try{await gb({})}catch{}}}import{createHash as VAe}from"node:crypto";import{resolve as YAe}from"node:path";import{setTimeout as XAe}from"node:timers/promises";import{loadSqliteDb as JAe}from"@cerebriline/shared/db";async function hG(e,t,n){let r=VAe("sha256").update(t).digest("hex"),o=JAe(`${YAe(e)}.oauth-${r}.lock`),i=!1,s=Date.now()+60000;try{o.exec("PRAGMA busy_timeout = 0;");while(!i)try{o.exec("BEGIN EXCLUSIVE;"),i=!0}catch(a){let d=a instanceof Error?a.message:String(a),l=a?.code;if(!(l==="SQLITE_BUSY"||l==="SQLITE_LOCKED"||/SQLITE_BUSY|SQLITE_LOCKED|database is locked/.test(d)))throw a;if(Date.now()>=s)throw Error("Timed out waiting for another process to refresh OAuth credentials.");await XAe(25)}return await n()}finally{try{if(i)o.exec("ROLLBACK;")}finally{o.close?.()}}}function ZR(e,t){let n=e?.expiresAt,r=t?.expiresAt;return e?.accessToken===t?.accessToken&&e?.refreshToken===t?.refreshToken&&e?.accountId===t?.accountId&&n===r}class fc extends Error{providerId;constructor(e){super(`OAuth credentials for provider "${e}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=e}}class Ap{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor(e){this.providerSettingsManager=e?.providerSettingsManager??new Vn,this.telemetry=e?.telemetry}async resolveProviderApiKey(e){let t=Yr(e.providerId);if(!t)return null;return this.resolveWithSingleFlight(t.providerId,t.storageProviderId,e.forceRefresh)}async resolveWithSingleFlight(e,t,n=!1){let r=this.refreshInFlight.get(t);if(r)return r;let o=this.providerSettingsManager.getProviderSettings(t);if(!o||!Ck(e,o))return null;let i=o.auth,s=hG(this.providerSettingsManager.getFilePath(),t,()=>this.resolveProviderApiKeyInternal(e,t,n&&ZR(i,this.providerSettingsManager.getProviderSettings(t)?.auth))).finally(()=>{this.refreshInFlight.delete(t)});return this.refreshInFlight.set(t,s),s}async resolveProviderApiKeyInternal(e,t,n){let r=Yr(e);if(!r)return null;let o=this.providerSettingsManager.getProviderSettings(t);if(!o)return ct(`oauth.resolve providerId=${e} storageProviderId=${t} outcome=no_settings`),null;let i=Ck(e,o);if(!i)return ct(`oauth.resolve providerId=${e} storageProviderId=${t} outcome=no_credentials`),null;ct(`oauth.resolve.start providerId=${e} storageProviderId=${t} forceRefresh=${n} accessTokenHash=${$n(i.access)} refreshTokenHash=${$n(i.refresh)}`);let s=await r.refresh({settings:o,credentials:i,forceRefresh:n,telemetry:this.telemetry}),a=this.providerSettingsManager.getProviderSettings(t);if(!ZR(o.auth,a?.auth))return null;if(!s)throw ct(`oauth.resolve providerId=${e} outcome=refresh_returned_null`),new fc(e);let d=Pk({manager:this.providerSettingsManager,providerId:e,settings:{...o,...a},credentials:s,setLastUsed:!1,save:!1}),l=!ZR(o.auth,d.auth);if(l)ct(`oauth.resolve.refreshed providerId=${e} newAccessTokenHash=${$n(s.access)} newRefreshTokenHash=${$n(s.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(d,{setLastUsed:!1,tokenSource:"oauth"});else ct(`oauth.resolve providerId=${e} outcome=not_refreshed`);return{apiKey:r.getApiKey(d)??s.access,accountId:s.accountId,refreshed:l}}}import{existsSync as QAe,mkdirSync as ZAe,readFileSync as eRe,writeFileSync as tRe}from"node:fs";import{dirname as nRe}from"node:path";import{FEATURE_FLAGS as pG,FeatureFlagDefaultValue as eI}from"@cerebriline/shared";var rRe=3600000,oRe=604800000,mG=2;class tI{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};pendingPoll;constructor(e){this.provider=e.provider,this.telemetry=e.telemetry,this.logger=e.logger,this.cacheTtlMs=e.cacheTtlMs??rRe,this.cacheFilePath=e.cacheFilePath,this.persistentCacheMaxAgeMs=e.persistentCacheMaxAgeMs??oRe,this.context={...e.context??{}},this.hydrateFromPersistentCache()}setContext(e){let t=this.cacheInfo.userId!==(e.userId??null);if(this.context={...e},t)this.pendingPoll=void 0,this.cache.clear(),this.cacheInfo={updateTime:0,userId:e.userId??null}}hydrateCache(e){this.cacheInfo={updateTime:e.updateTime,userId:e.userId,flagsPayload:e.flagsPayload},this.rebuildCacheFromSnapshot(e.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll(e){let t=e??this.context.userId??null;if(this.pendingPoll?.userId===t)return this.pendingPoll.promise;let n={userId:t,promise:this.pollFlags(t)};this.pendingPoll=n;try{await n.promise}finally{if(this.pendingPoll===n)this.pendingPoll=void 0}}async pollFlags(e){let t=Date.now();if(t-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===e)return}let n=this.cacheInfo;this.cacheInfo={updateTime:t,userId:e||null};try{let r=await this.provider.getAllFlagsAndPayloads({flagKeys:pG.length>0?pG:void 0,context:{...this.context,userId:e}});if(this.cacheInfo.userId!==e)return;this.cacheInfo.flagsPayload=r,this.rebuildCacheFromSnapshot(r),this.writePersistentCache()}catch(r){if(this.cacheInfo.userId!==e)return;throw this.cacheInfo=n.updateTime?n:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:r}),r}}hydrateFromPersistentCache(){let e=this.readPersistentCache();if(!e)return;if(e.userId&&this.context.userId&&e.userId!==this.context.userId)return;this.hydrateCache(e)}isFeatureFlagPayload(e){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean")return!0;if(Array.isArray(e))return e.every((t)=>this.isFeatureFlagPayload(t));if(typeof e==="object")return Object.values(e).every((t)=>this.isFeatureFlagPayload(t));return!1}readPayloadRecord(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=Object.entries(e).filter(([,r])=>this.isFeatureFlagPayload(r));if(t.length===0)return;let n={};for(let[r,o]of t)n[r]=o;return n}readPersistentCache(){try{if(!this.cacheFilePath||!QAe(this.cacheFilePath))return;let e=JSON.parse(eRe(this.cacheFilePath,"utf8"));if(!e||typeof e!=="object")return;let t=e;if(t.version!==mG||typeof t.updatedAt!=="number"||!Number.isFinite(t.updatedAt)||Date.now()-t.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:t.updatedAt,userId:t.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(t.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(t.flagsPayload?.featureFlagPayloads)}}}catch(e){this.logger?.error?.("Error reading SDK feature flags cache",{error:e});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;ZAe(nRe(this.cacheFilePath),{recursive:!0,mode:448});let e=this.getCacheSnapshot(),t={version:mG,updatedAt:e.updateTime,userId:e.userId,flagsPayload:e.flagsPayload};tRe(this.cacheFilePath,`${JSON.stringify(t,null,2)}
1001
1001
  `,"utf8")}catch(e){this.logger?.error?.("Error writing SDK feature flags cache",{error:e})}}getReturnedFlagKeys(e){return[...new Set([...Object.keys(e?.featureFlags??{}),...Object.keys(e?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot(e){let t=new Map;for(let n of this.getReturnedFlagKeys(e)){let r=this.getFeatureFlag(n);t.set(n,r??!1)}this.cache=t}getFeatureFlag(e){try{let t=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[e],n=this.cacheInfo.flagsPayload?.featureFlags?.[e],r=t??n??eI[e]??void 0;if(!this.cache.has(e)||this.cache.get(e)!==r)this.telemetry?.capture({event:Ae.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:e,$feature_flag_response:n}});return r}catch(t){return this.logger?.error?.(`Error checking SDK feature flag ${e}`,{error:t}),eI[e]??!1}}getBooleanFlagEnabled(e){return this.cache.get(e)===!0}getFlagPayload(e){return this.cache.get(e)??eI[e]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test(e,t){if(process.env.IS_TEST==="true")this.cache.set(e,t)}async dispose(){await this.provider.dispose()}}var gc;function fG(){return new Vn().getProviderSettings("cline")?.auth?.accountId?.trim()||void 0}async function nI(e){let t=fG(),n=process.env.TELEMETRY_SERVICE_API_KEY;if(!t||!n)return gc=void 0,!1;if(gc?.accountId!==t||gc.apiKey!==n)gc={accountId:t,apiKey:n,service:new tI({context:{distinctId:t,userId:t},cacheTtlMs:60000,provider:{enabled:!0,getSettings:()=>({enabled:!0}),dispose:async()=>{},async getAllFlagsAndPayloads(o){let{buildClinePostHogClient:i,PostHogFeatureFlagsProvider:s}=await import("@cerebriline/core/services/feature-flags/posthog"),a=new s({client:i(n),config:{}});try{return await a.getAllFlagsAndPayloads(o)}finally{await a.dispose()}}}})};let r=gc;try{return r.pending??=r.service.poll().finally(()=>{r.pending=void 0}),await r.pending,gc===r&&fG()===t&&r.service.getCacheSnapshot().flagsPayload?.featureFlags?.[e]===!0}catch{return!1}}import*as Mn from"@cerebriline/llms";import{isTranscriptionModel as IQe,MODEL_TOOL_NAMES as CQe,resolveProviderApiKeyOptional as PQe,resolveProviderLocalCli as MQe}from"@cerebriline/shared";import{buildClineClientHeaders as rQe,GENERATED_CLINE_RECOMMENDED_MODELS as iRe,getGeneratedProviderModels as sRe,VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES as aRe}from"@cerebriline/llms";import{getClineEnvironmentConfig as iQe}from"@cerebriline/shared";var dQe=uRe(dRe(iRe)??{recommended:[],free:[],clinePass:[]},sRe());function rI(e){if(!e||typeof e!=="object")return null;let t=e;if(typeof t.id!=="string"||t.id.length===0)return null;return{id:t.id,name:typeof t.name==="string"&&t.name.length>0?t.name:t.id,description:typeof t.description==="string"?t.description:"",tags:Array.isArray(t.tags)?t.tags.filter((n)=>typeof n==="string"):[]}}function dRe(e){if(!e||typeof e!=="object")return null;let t=e,n=Array.isArray(t.recommended)?t.recommended:[],r=Array.isArray(t.free)?t.free:[],o=Array.isArray(t.clinePass)?t.clinePass:[],i=n.map(rI).filter((d)=>d!==null),s=r.map(rI).filter((d)=>d!==null),a=o.map(rI).filter((d)=>d!==null);if(i.length===0&&s.length===0&&a.length===0)return null;return{recommended:i,free:s,clinePass:a}}function oI(e){return e.replace(/\s*\(free\)\s*$/i,"").replace(/:free$/i,"").trim()}function lRe(e){let t=[e];for(let n of aRe)if(e.startsWith(n.canonicalPrefix))t.push(`${n.aliasPrefix}${e.slice(n.canonicalPrefix.length)}`);else if(e.startsWith(n.aliasPrefix))t.push(`${n.canonicalPrefix}${e.slice(n.aliasPrefix.length)}`);return t}function cRe(e,t){for(let o of t)for(let i of lRe(e.id)){let s=o?.[i]?.name?.trim();if(s)return oI(s)}let n=e.name?.trim();if(n&&n!==e.id)return oI(n);let r=e.id.split("/").at(-1)??e.id;return oI(r)}function uRe(e,t){let n=(r,o)=>r.map((i)=>({...i,name:cRe(i,o)}));return{recommended:n(e.recommended,[t?.openrouter]),free:n(e.free,[t?.cline,t?.openrouter]),clinePass:n(e.clinePass,[t?.["cline-pass"]])}}import*as hRe from"@cerebriline/llms";import*as gG from"@cerebriline/llms";function yG(e){let t=e?.auth?.accessToken?.trim()||e?.apiKey?.trim();return t&&t.length>0?t:void 0}var wG="/api/v1/connectors";var pRe=["COMPOSIO_SEARCH_TOOLS","COMPOSIO_MANAGE_CONNECTIONS","COMPOSIO_WAIT_FOR_CONNECTIONS","COMPOSIO_MULTI_EXECUTE_TOOL"];async function bG(e,t){let n;try{n=await fetch(`${e.baseUrl}/api/v1/connectors/meta-tools/sessions`,{method:"POST",headers:{authorization:`Bearer ${e.token}`},signal:AbortSignal.timeout(5000)})}catch(r){t?.log?.(`composio-tools: meta-tool session request failed: ${r instanceof Error?r.message:String(r)}`);return}if(!n.ok){if(n.status!==404)t?.log?.(`composio-tools: meta-tool session returned HTTP ${n.status}`);return}try{let r=await n.json(),o=r?.data?.sessionId,i=r?.data?.tools;if(typeof o!=="string"||!o||!Array.isArray(i))return;let s=i.filter((l)=>typeof l?.slug==="string"&&l.slug.length>0),a=new Set(s.map((l)=>l.slug)),d=pRe.filter((l)=>!a.has(l));if(d.length>0){t?.log?.(`composio-tools: meta-tool session missing required tools: ${d.join(", ")}`);return}return{sessionId:o,tools:s}}catch{return}}async function vG(e,t,n,r){let o=`${e.baseUrl}/api/v1/connectors/meta-tools/${encodeURIComponent(n)}/execute`,i;try{i=await fetch(o,{method:"POST",headers:{authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify({sessionId:t,arguments:r&&typeof r==="object"?r:{}})})}catch(d){return{successful:!1,error:`Cline connectors request failed: ${d instanceof Error?d.message:String(d)}`}}let s=await i.text(),a;try{a=s?JSON.parse(s):void 0}catch{a=void 0}if(!i.ok){let d=a!==void 0?JSON.stringify(a).slice(0,600):s.slice(0,600);return{successful:!1,error:`Cline connectors proxy returned HTTP ${i.status} for ${n}${d?`: ${d}`:""}`}}return a??{successful:!0}}var TG=120000;function vRe(e){let t=mRe("sha256").update(e).digest("hex");return yRe(bRe(),"settings","composio",`${t}.json`)}function Rp(){return new Vn().getProviderSettings("cline")?.auth?.accountId?.trim()||void 0}function kRe(e){try{let t=vRe(e);if(!fRe(t))return;let n=JSON.parse(gRe(t,"utf8"));return typeof n==="object"&&n!==null?n:void 0}catch{return}}var SG;async function _G(e){let t=new Vn,n;try{SG??=new Ap,n=(await SG.resolveProviderApiKey({providerId:"cline"}))?.apiKey??void 0}catch(i){if(i instanceof fc)return}if(n??=yG(t.getProviderSettings("cline")),!n||Rp()!==e)return;return{baseUrl:(t.getProviderSettings("cline")?.baseUrl?.trim()||wRe().apiBaseUrl).replace(/\/+$/,""),token:n}}async function EG(e){if(Rp()!==e)return{error:{successful:!1,error:"The Cline account changed. Start a new session to use connector tools."}};if(!await nI(xG.CLINE_COMPOSIO_BETA))return{error:{successful:!1,error:"Composio connectors are not enabled for this account."}};let t=await _G(e);if(!t)return{error:{successful:!1,error:"Sign in to your Cline account to use connector tools (no account token available)."}};return{auth:t}}async function TRe(e,t,n){let r=await EG(e);if("error"in r)return r.error;let{auth:o}=r,i=`${o.baseUrl}${wG}/tools/${encodeURIComponent(t.slug)}/execute`,s={arguments:n&&typeof n==="object"?n:{}};if(t.version)s.version=t.version;let a;try{a=await fetch(i,{method:"POST",headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},body:JSON.stringify(s)})}catch(c){return{successful:!1,error:`Cline connectors request failed: ${c instanceof Error?c.message:String(c)}`}}let d=await a.text(),l;try{l=d?JSON.parse(d):void 0}catch{l=void 0}if(!a.ok){let c=l!==void 0?JSON.stringify(l).slice(0,600):d.slice(0,600);return{successful:!1,error:`Cline connectors proxy returned HTTP ${a.status} for ${t.slug}${c?`: ${c}`:""}`}}return l??{successful:!0}}async function AG(e){let t=Rp();if(!t)return;if(!await nI(xG.CLINE_COMPOSIO_BETA))return;if(Rp()!==t)return;let n=kRe(t),r=Object.entries(n?.toolkits??{}).filter(([,s])=>s?.connectedAccountId&&(s.tools?.length??0)>0),o=await _G(t),i=o?await bG(o,{log:(s)=>e?.logger?.log?.(s)}):void 0;if(r.length===0&&!i?.tools.length)return;return{name:"composio-tools",manifest:{capabilities:["tools"]},setup(s){if(Rp()!==t)return;let a=new Set;for(let[l,c]of r)for(let u of c?.tools??[]){if(!u?.slug)continue;let h=u.slug.toLowerCase().replace(/[^a-z0-9_]/g,"_");if(a.has(h))continue;a.add(h);try{s.registerTool(kG({name:h,resultPolicy:"cache-oversized",description:`${u.description||u.name||u.slug} (${l} account connected via Composio)`,inputSchema:u.input_parameters??{type:"object",properties:{}},timeoutMs:TG,retryable:!1,execute:(p)=>TRe(t,u,p)}))}catch(p){a.delete(h),e?.logger?.log?.(`composio-tools: skipping ${u.slug}: ${p instanceof Error?p.message:String(p)}`)}}let d=i?.sessionId??"";for(let l of i?.tools??[]){let c=l.slug.toLowerCase().replace(/[^a-z0-9_]/g,"_");if(a.has(c))continue;a.add(c);try{s.registerTool(kG({name:c,resultPolicy:"cache-oversized",description:l.description||l.name||l.slug,inputSchema:l.input_parameters??{type:"object",properties:{}},timeoutMs:TG,retryable:!1,execute:async(u)=>{let h=await EG(t);if("error"in h)return h.error;return vG(h.auth,d,l.slug,u)}}))}catch(u){a.delete(c),e?.logger?.log?.(`composio-tools: skipping ${l.slug}: ${u instanceof Error?u.message:String(u)}`)}}e?.logger?.log?.(`composio-tools: registered ${a.size} connector tool(s) for this session`)}}}import{existsSync as Eb,readFileSync as cIe,statSync as uIe}from"node:fs";import{basename as hIe,dirname as xb,join as Ab,resolve as _b}from"node:path";import{discoverPluginModulePaths as pIe,resolveConfiguredPluginModulePaths as GG,resolvePluginConfigSearchPaths as mIe,SKILLS_CONFIG_DIRECTORY_NAME as fIe}from"@cerebriline/shared/storage";import{resolve as WRe}from"node:path";import{normalizePluginManifest as jRe}from"@cerebriline/shared";import{existsSync as ln,readFileSync as wc}from"node:fs";import{builtinModules as SRe,createRequire as dI}from"node:module";import{dirname as os,extname as Cp,isAbsolute as xRe,resolve as Xe}from"node:path";import{fileURLToPath as IG}from"node:url";import{PLUGIN_FILE_EXTENSIONS as _Re}from"@cerebriline/shared";var CG=os(IG(import.meta.url)),ERe=dI(import.meta.url),ARe=Xe(CG,"..","..","..","..",".."),iI=CRe(ARe),RRe=["@cerebriline/sdk","@cerebriline/agents","@cerebriline/core","@cerebriline/core/hub","@cerebriline/core/hub/daemon-entry","@cerebriline/core/telemetry","@cerebriline/llms","@cerebriline/llms/browser","@cerebriline/shared","@cerebriline/shared/automation","@cerebriline/shared/browser","@cerebriline/shared/storage","@cerebriline/shared/db","@cerebriline/shared/types"],lI=new Set(SRe.flatMap((e)=>[e,e.replace(/^node:/,"")])),Ip=new Set(_Re),IRe=["development","node","import","require","default"];function CRe(e){let t={},n={"@cerebriline/sdk":Xe(e,"packages/sdk/src/index.ts"),"@cerebriline/agents":Xe(e,"packages/agents/src/index.ts"),"@cerebriline/core":Xe(e,"packages/core/src/index.ts"),"@cerebriline/llms":Xe(e,"packages/llms/src/index.ts"),"@cerebriline/shared":Xe(e,"packages/shared/src/index.ts"),"@cerebriline/shared/storage":Xe(e,"packages/shared/src/storage/index.ts"),"@cerebriline/shared/db":Xe(e,"packages/shared/src/db/index.ts")};for(let[r,o]of Object.entries(n))if(ln(o))t[r]=o;for(let r of["agents","core","llms","shared"]){let o=Xe(e,"packages",r),i=Xe(o,"package.json");if(!ln(i))continue;try{let s=JSON.parse(wc(i,"utf8"));if(typeof s.name!=="string"||!s.exports)continue;if(typeof s.exports==="string"){let a=Xe(o,s.exports);if(ln(a))t[s.name]=a;continue}if(typeof s.exports!=="object")continue;for(let[a,d]of Object.entries(s.exports)){let l=PRe(o,d);if(!l)continue;let c=a==="."?s.name:`${s.name}/${a.replace(/^\.\//,"")}`;t[c]=l}}catch{}}return t}function PRe(e,t){let n=cI(t);if(!n)return null;let r=PG(e,n);for(let o of r)if(ln(o))return o;return null}function cI(e,t=new Set){if(typeof e==="string")return e;if(!e||typeof e!=="object")return null;if(t.has(e))return null;t.add(e);let n=e;for(let r of IRe){let o=cI(n[r],t);if(o)return o}return null}function PG(e,t){let n=t.replace(/^\.\//,""),r=[Xe(e,t)];if(n.startsWith("dist/")){let o=n.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[Xe(e,`${o}.ts`),Xe(e,`${o}.tsx`),Xe(e,`${o}.mts`),Xe(e,`${o}.cts`),...r]}return r}function MRe(e){return Object.fromEntries(Object.entries(e).sort(([t],[n])=>n.length-t.length))}function vb(e){return!(e.startsWith(".")||e.startsWith("/")||e.startsWith("file:")||e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))}function yc(e){if(e.startsWith("@")){let[t,n]=e.split("/",3);return n?`${t}/${n}`:e}return e.split("/",1)[0]??e}function ORe(e){let t=yc(e);if(e===t)return".";return`.${e.slice(t.length)}`}function MG(e){return yc(e).startsWith("@cline/")}function sI(e,t){let n=yc(t),r=os(e);while(!0){let o=Xe(r,"node_modules",n);if(ln(o)||ln(Xe(o,"package.json")))return!0;let i=Xe(r,"..");if(i===r)return!1;r=i}}function RG(e){return aI(e)!==null}function aI(e){try{return ERe.resolve(e)}catch{}return LRe(e)}function LRe(e){let t=yc(e),n=OG(t);if(!n)return null;let r=Xe(n,"package.json");try{let o=JSON.parse(wc(r,"utf8")),i=ORe(e),s=i==="."&&typeof o.exports==="string"?o.exports:o.exports&&typeof o.exports==="object"&&Object.hasOwn(o.exports,i)?o.exports[i]:void 0,a=cI(s)??(i==="."&&typeof o.main==="string"?o.main:null);if(!a)return null;let d=Xe(n,a),l=[d,...PG(n,a).filter((c)=>c!==d)];for(let c of l)if(ln(c))return c;return null}catch{return null}}function NRe(){let e=[CG],t=process.env.CLINE_WRAPPER_PATH?.trim();if(t)e.push(os(os(t)));let n=process.execPath?.trim();if(n)e.push(os(n));return[...new Set(e.map((r)=>Xe(r)))]}function DRe(e,t){let n=e;while(!0){let r=Xe(n,"package.json");if(ln(r))try{if(JSON.parse(wc(r,"utf8")).name===t)return n}catch{}let o=Xe(n,"node_modules",t,"package.json");if(ln(o))return os(o);let i=Xe(n,"..");if(i===n)return null;n=i}}function OG(e){for(let t of NRe()){let n=DRe(t,e);if(n)return n}return null}function $Re(e){let n=os(e);for(let r=0;r<4;r++){let o=Xe(n,"package.json");if(ln(o))try{let s=JSON.parse(wc(o,"utf8"));return s!=null&&typeof s==="object"&&"cline"in s}catch{return!1}let i=Xe(n,"..");if(i===n)return!1;n=i}return!1}function LG(e,t){let n=t.startsWith("file:")?IG(t):xRe(t)?t:Xe(os(e),t);if(ln(n)&&Ip.has(Cp(n)))return n;for(let r of Ip){let o=`${n}${r}`;if(ln(o))return o}for(let r of Ip){let o=Xe(n,`index${r}`);if(ln(o))return o}return null}function NG(e){let t=new Set,n=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let r of n)for(let o of e.matchAll(r)){let i=o[1];if(i)t.add(i)}return[...t]}function FRe(e){return Cp(e)!==".ts"}function DG(e,t,n=new Set){if(n.has(e)||!ln(e))return;if(n.add(e),!Ip.has(Cp(e)))return;let r=wc(e,"utf8"),o=FRe(e);for(let i of NG(r)){if(i.startsWith("node:")||lI.has(i))continue;if(vb(i)){if(!o)continue;if(Object.hasOwn(iI,i)||Object.hasOwn(iI,yc(i))||sI(e,i)||MG(i)&&RG(i)||t&&RG(i))continue;throw Error(`Cannot find module '${yc(i)}'`)}let s=LG(e,i);if(s)DG(s,t,n)}}function $G(e,t=new Set,n=new Set){if(t.has(e)||!ln(e))return n;if(t.add(e),!Ip.has(Cp(e)))return n;let r=wc(e,"utf8");for(let o of NG(r)){if(n.add(o),vb(o))continue;let i=LG(e,o);if(i)$G(i,t,n)}return n}function URe(e,t){let n=dI(e),r={},o=$G(e),i=new Set(RRe);for(let[s,a]of Object.entries(iI)){try{n.resolve(s);continue}catch{}r[s]=a}for(let s of o)if(vb(s)&&(MG(s)||t))i.add(s);for(let s of i){if(Object.hasOwn(r,s)||sI(e,s))continue;let a=aI(s);if(a)r[s]=a}if(!t)return r;for(let s of o){if(!vb(s)||Object.hasOwn(r,s)||sI(e,s)||s.startsWith("node:")||lI.has(s))continue;let a=aI(s);if(a)r[s]=a}return r}function BRe(e){let t=Cp(e);return t===".ts"||t===".tsx"||t===".mts"||t===".cts"}var Na;function HRe(){if(Na!==void 0)return Na;let e=OG("jiti");if(!e)return Na=null,null;let t=Xe(e,"dist","babel.cjs");if(!ln(t))return Na=null,null;try{let r=dI(t)(t);Na=typeof r==="function"?r:null}catch{Na=null}return Na}async function FG(e,t={}){let n=!$Re(e);DG(e,n);let r=URe(e,n),o=MRe(r),i=await import("jiti"),s=typeof i==="function"?i:typeof i.default==="function"?i.default:void 0;if(!s)throw Error("Unable to load jiti");let a=Object.entries(o).filter(([,u])=>BRe(u)).map(([u])=>u),d=HRe(),l=d?(u)=>d({...u,interopDefault:!0}):void 0;return await s(e,{alias:o,cache:t.useCache,requireCache:t.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...lI],transformModules:a,tryNative:!1,...l?{transform:l}:{}}).import(e,{})}function UG(e,t){if(!e)return!0;if(e.providerIds?.length){if(!t?.providerId||!e.providerIds.includes(t.providerId))return!1}if(e.modelIds?.length){if(!t?.modelId||!e.modelIds.includes(t.modelId))return!1}return!0}function BG(e){return typeof e==="object"&&e!==null}function uI(e){return Array.isArray(e)&&e.every((t)=>typeof t==="string")}function qRe(e,t){if(!BG(e.manifest))throw Error(`Invalid plugin module at ${t}: missing required "manifest"`);if(!uI(e.manifest.capabilities))throw Error(`Invalid plugin module at ${t}: manifest.capabilities must be a string array`);if(e.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${t}: manifest.capabilities cannot be empty`);if(Object.hasOwn(e.manifest,"providerIds")&&!uI(e.manifest.providerIds))throw Error(`Invalid plugin module at ${t}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn(e.manifest,"modelIds")&&!uI(e.manifest.modelIds))throw Error(`Invalid plugin module at ${t}: manifest.modelIds must be a string array when provided`)}function zRe(e,t){if(!BG(e))throw Error(`Invalid plugin module at ${t}: expected object export`);if(typeof e.name!=="string"||e.name.length===0)throw Error(`Invalid plugin module at ${t}: expected non-empty "name"`);if(!Object.hasOwn(e,"manifest"))throw Error(`Invalid plugin module at ${t}: missing required "manifest"`);qRe(e,t)}async function KRe(e,t={}){let n=WRe(t.cwd??process.cwd(),e),r=await FG(n,{useCache:t.useCache}),o=t.exportName??"plugin",i=r.default??r[o];zRe(i,n);let s=i,a=s.setup,d=a?(l,c)=>{let u={...t.session,...c.session},h={...c,session:Object.keys(u).length>0?u:void 0,client:t.client??c.client,user:t.user??c.user,workspaceInfo:t.workspaceInfo??c.workspaceInfo,automation:t.automation??c.automation,logger:t.logger??c.logger,telemetry:t.telemetry??c.telemetry};return a(l,h)}:void 0;return{...s,manifest:jRe(s.manifest),setup:d}}async function HG(e,t={}){let n=[],r=[],o=new Map,i=0;for(let a of e)try{let d=await KRe(a,t);if(!UG(d.manifest,t))continue;let l=o.get(d.name);if(l)r.push({type:"duplicate_plugin_override",pluginName:d.name,pluginPath:a,overriddenPluginPath:l.pluginPath,message:`Plugin "${d.name}" from ${a} overrides ${l.pluginPath}`});o.set(d.name,{plugin:d,pluginPath:a,order:i++})}catch(d){let l=d instanceof Error?d.message:String(d);n.push({pluginPath:a,phase:"load",message:l,stack:d instanceof Error?d.stack:void 0})}let s=[...o.values()].sort((a,d)=>a.order-d.order);return{plugins:s.map((a)=>a.plugin),pluginPaths:s.map((a)=>a.pluginPath),failures:n,warnings:r}}import{existsSync as mI}from"node:fs";import{createRequire as qG}from"node:module";import{dirname as Tb,join as bc}from"node:path";import{fileURLToPath as GRe}from"node:url";var VRe="CLINE_PLUGIN_IDLE_TIMEOUT_MS",YRe=1800000;function XRe(e){return{...e,contributions:{tools:e.contributions?.tools??[],commands:e.contributions?.commands??[],rules:e.contributions?.rules??[],messageBuilders:e.contributions?.messageBuilders??[],providers:e.contributions?.providers??[],automationEventTypes:e.contributions?.automationEventTypes??[],mcpServers:e.contributions?.mcpServers??[],shortcuts:e.contributions?.shortcuts??[],flags:e.contributions?.flags??[]}}}function Pp(e){return(e instanceof Error?e.message:String(e)).includes("Unknown sandbox plugin id:")}function JRe(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function QRe(){let e=process.env.CLINE_WRAPPER_PATH?.trim();if(!e)return;try{let n=qG(e).resolve(`${JRe()}/package.json`),r=bc(Tb(n),"extensions","plugin-sandbox-bootstrap.js");return mI(r)?r:void 0}catch{return}}function ZRe(){let e=process.execPath?.trim();if(!e)return;let t=bc(Tb(Tb(e)),"extensions","plugin-sandbox-bootstrap.js");return mI(t)?t:void 0}function eIe(e){let t=e.exists??mI;for(let n of e.siblingCandidates)if(t(n))return{file:n};if(t(e.sourceBootstrapPath))return{sourcePath:e.sourceBootstrapPath};for(let n of e.installedCandidates)if(n&&t(n))return{file:n};return{sourcePath:e.sourceBootstrapPath}}function tIe(){let e=Tb(GRe(import.meta.url)),t=qG(import.meta.url),n=eIe({siblingCandidates:[bc(e,"plugin-sandbox-bootstrap.js"),bc(e,"extensions","plugin-sandbox-bootstrap.js"),bc(e,"agents","plugin-sandbox-bootstrap.js")],sourceBootstrapPath:bc(e,"plugin-sandbox-bootstrap.ts"),installedCandidates:[QRe(),ZRe()]});if("file"in n)return n;let r=n.sourcePath,o="jiti";try{o=t.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(o)});`,`const jiti = createJiti(${JSON.stringify(r)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(r)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
1002
1002
  `)}}var hI=tIe();function kb(e,t,n){if(typeof e==="number"&&Number.isInteger(e)&&e>0&&e<=Fu)return e;if(n){let r=process.env[n];if(r){let o=Number(r);if(Number.isInteger(o)&&o>0&&o<=Fu)return o}}return t}async function Sb(e){let t=kb(e.idleTimeoutMs,YRe,VRe),n=new MS({name:"plugin-sandbox",..."file"in hI?{bootstrapFile:hI.file}:{bootstrapScript:hI.script},idleTimeoutMs:t,onEvent:e.onEvent}),r=kb(e.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),o=kb(e.hookTimeoutMs,3000),i=kb(e.contributionTimeoutMs,60000),s={pluginPaths:e.pluginPaths,exportName:e.exportName,providerId:e.providerId,modelId:e.modelId,cwd:e.cwd,session:e.session,client:e.client,user:e.user,workspaceInfo:e.workspaceInfo,loggerEnabled:Boolean(e.logger),telemetryEnabled:e.telemetryAvailable===!0},a,d=()=>(a??=n.call("initialize",s,{timeoutMs:r}).finally(()=>{a=void 0}),a),l;try{l=await n.call("initialize",s,{timeoutMs:r})}catch(h){throw await n.shutdown().catch(()=>{}),h}let c=l.plugins.map(XRe);return{extensions:c.map((h)=>{let p={name:h.name,__clinePluginPath:h.pluginPath,manifest:h.manifest,setup:(f)=>{rIe(f,n,h,i,d),oIe(f,n,h,i,d),iIe(f,n,h,i,d),aIe(f,n,h,i,d),sIe(f,h)}};return p.hooks=lIe(n,h,o,d),p}),failures:l.failures,pluginPaths:c.map((h)=>h.pluginPath),shutdown:async()=>{await n.shutdown()},warnings:l.warnings}}function nIe(e){let t=e instanceof Error?e.message:String(e);return/cyclic|circular|bigint/i.test(t)}function pI(e,t=new WeakSet){if(e===null||typeof e!=="object")return typeof e==="function"||typeof e==="symbol"||typeof e==="bigint"?void 0:e;if(t.has(e))return;let n=e;if(typeof n.toJSON==="function")try{return n.toJSON()}catch{return}t.add(e);try{if(Array.isArray(e))return e.map((o)=>pI(o,t)??null);let r={};for(let[o,i]of Object.entries(e)){let s=pI(i,t);if(s!==void 0)r[o]=s}return r}finally{t.delete(e)}}var WG=new Set;function zG(e,t,n){let r=`${e}:${t}`;if(WG.has(r))return;WG.add(r);let o=n instanceof Error?n.message:String(n);console.warn(`[plugin-sandbox] ${e} "${t}" received a payload that is not JSON-serializable (${o}); retrying with non-serializable values dropped. Host-only objects must not be placed on tool contexts or hook payloads.`)}async function KG(e,t,n){try{return await e(t)}catch(r){if(!nIe(r))throw r;return n(r),await e(pI(t))}}function rIe(e,t,n,r,o){for(let i of n.contributions?.tools??[]){let s={name:i.name,description:i.description??"",inputSchema:i.inputSchema??{type:"object",properties:{}},timeoutMs:i.timeoutMs,retryable:i.retryable,execute:async(a,d)=>await KG(async(c)=>{let{input:u,context:h}=c;try{return await t.call("executeTool",{pluginId:n.pluginId,contributionId:i.id,input:u,context:h},{timeoutMs:r})}catch(p){if(!Pp(p))throw p;return await o(),await t.call("executeTool",{pluginId:n.pluginId,contributionId:i.id,input:u,context:h},{timeoutMs:r})}},{input:a,context:d},(c)=>zG("tool",i.name,c))};e.registerTool(s)}}function oIe(e,t,n,r,o){for(let i of n.contributions?.commands??[])e.registerCommand({name:i.name,description:i.description,handler:async(s)=>{try{return await t.call("executeCommand",{pluginId:n.pluginId,contributionId:i.id,input:s},{timeoutMs:r})}catch(a){if(!Pp(a))throw a;return await o(),await t.call("executeCommand",{pluginId:n.pluginId,contributionId:i.id,input:s},{timeoutMs:r})}}})}function iIe(e,t,n,r,o){for(let i of n.contributions?.rules??[])e.registerRule({id:i.ruleId,source:i.source,content:i.hasContentHandler===!0?async()=>{try{return await t.call("resolveRuleContent",{pluginId:n.pluginId,contributionId:i.id},{timeoutMs:r})}catch(s){if(!Pp(s))throw s;return await o(),await t.call("resolveRuleContent",{pluginId:n.pluginId,contributionId:i.id},{timeoutMs:r})}}:i.content??""})}function sIe(e,t){for(let n of t.contributions?.providers??[])e.registerProvider({name:n.name,description:n.description,metadata:n.metadata});for(let n of t.contributions?.automationEventTypes??[])e.registerAutomationEventType({eventType:n.eventType,source:n.source,description:n.description,attributesSchema:n.attributesSchema,payloadSchema:n.payloadSchema,examples:n.examples,metadata:n.metadata});for(let n of t.contributions?.mcpServers??[])e.registerMcpServer(n)}function aIe(e,t,n,r,o){for(let i of n.contributions?.messageBuilders??[])e.registerMessageBuilder({name:i.name,async build(s){try{let a=await t.call("buildMessages",{pluginId:n.pluginId,contributionId:i.id,messages:s},{timeoutMs:r});return jG(a)?a:s}catch(a){if(!Pp(a))throw a;await o();let d=await t.call("buildMessages",{pluginId:n.pluginId,contributionId:i.id,messages:s},{timeoutMs:r});return jG(d)?d:s}}})}function jG(e){return Array.isArray(e)&&e.every((t)=>typeof t==="object"&&t!==null&&("role"in t)&&("content"in t))}function dIe(e,t,n,r,o){return async(i)=>await KG(async(a)=>{try{return await e.call("invokeHook",{pluginId:t,hookName:n,payload:a},{timeoutMs:r})}catch(d){if(!Pp(d))throw d;return await o(),await e.call("invokeHook",{pluginId:t,hookName:n,payload:a},{timeoutMs:r})}},i,(a)=>zG("hook",n,a))}function lIe(e,t,n,r){let o={};for(let i of t.hooks??[])o[i]=dIe(e,t.pluginId,i,n,r);return Object.keys(o).length>0?o:void 0}import{getPluginDisplayName as RZe}from"@cerebriline/shared/storage";var gI="package.json",gIe="package";function yI(e){return mIe(e)}function wI(e){return pIe(e)}function yIe(e){try{return Eb(e)&&uIe(e).isDirectory()}catch{return!1}}function Rb(e){let t=[],n=new Set;for(let r of e){let o=_b(r);if(n.has(o))continue;n.add(o),t.push(o)}return t}function VG(e){let t=Rb(e);return Lj(t)}function YG(e){return yI(e).flatMap((t)=>wI(t)).filter((t)=>Eb(t))}function wIe(e,t){let n=[];for(let r of e)try{n.push(...GG([r],t))}catch{}return n}function fI(e){return typeof e==="object"&&e!==null}function bIe(e){try{let t=JSON.parse(cIe(Ab(e,gI),"utf8"));if(!fI(t)||!fI(t.cline))return[];let n=t.cline.plugins;if(!Array.isArray(n))return[];let r=[];for(let o of n){if(typeof o==="string"){r.push(o);continue}if(!fI(o)||!Array.isArray(o.paths))continue;for(let i of o.paths)if(typeof i==="string")r.push(i)}return r}catch{return[]}}function XG(e,t){let n=_b(t);return bIe(e).some((r)=>_b(e,r)===n)}function vIe(e,t){return hIe(e)===gIe&&Eb(Ab(xb(e),gI))&&XG(xb(e),t)}function kIe(e){let t=_b(e),n=[],r=xb(t);while(!0){if(vIe(r,t)){n.push(r);break}if(Eb(Ab(r,gI))){if(XG(r,t))n.push(r);break}let o=xb(r);if(o===r)break;r=o}return Rb(n)}function Mp(e={}){let t=e.cwd??process.cwd(),n=YG(e.workspacePath),o=[...GG(e.pluginPaths??[],t),...n];return e.includeDisabled?Rb(o):VG(o)}function TIe(e={}){let t=e.cwd??process.cwd(),n=YG(e.workspacePath),r=wIe(e.pluginPaths??[],t);return VG([...r,...n])}function vc(e){let t=[];for(let n of e)for(let r of kIe(n)){let o=Ab(r,fIe);if(yIe(o))t.push(o)}return Rb(t)}function JG(e={}){return vc(TIe(e))}async function QG(e={}){let t=Mp(e);if(t.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if(e.mode==="in_process"){let r=await HG(t,{cwd:e.cwd,exportName:e.exportName,providerId:e.providerId,modelId:e.modelId,session:e.session,client:e.client,user:e.user,workspaceInfo:e.workspaceInfo,automation:e.automation,logger:e.logger,telemetry:e.telemetry});return{extensions:r.plugins,failures:r.failures,pluginPaths:r.pluginPaths,warnings:r.warnings}}let n=await Sb({pluginPaths:t,exportName:e.exportName,importTimeoutMs:e.importTimeoutMs,hookTimeoutMs:e.hookTimeoutMs,contributionTimeoutMs:e.contributionTimeoutMs,onEvent:e.onEvent,telemetryAvailable:Boolean(e.telemetry),providerId:e.providerId,modelId:e.modelId,cwd:e.cwd,session:e.session,client:e.client,user:e.user,workspaceInfo:e.workspaceInfo,logger:e.logger});return{extensions:n.extensions??[],shutdown:n.shutdown,failures:n.failures,pluginPaths:n.pluginPaths,warnings:n.warnings}}import{execFile as SIe,spawn as xIe}from"node:child_process";import{createHash as _Ie}from"node:crypto";import{mkdir as EIe,readdir as AIe,rm as Cb,stat as RIe,writeFile as IIe}from"node:fs/promises";import{join as Op}from"node:path";import{promisify as CIe}from"node:util";import{resolveClineDataDir as PIe}from"@cerebriline/shared/storage";var Pb=CIe(SIe),ZG="cline checkpoint session=",vI=67108864,MIe=1209600000;function e3(e){return e.includes(ZG)}function t3(){return Op(PIe(),"checkpoint-scratch")}function n3(e,t){let n=_Ie("sha256").update(`${e}\x00${t}`).digest("hex").slice(0,32);return Op(t3(),n)}async function OIe(){try{let e=t3(),t=Date.now()-MIe,n=await AIe(e,{withFileTypes:!0});await Promise.all(n.map(async(r)=>{if(!r.isDirectory())return;let o=Op(e,r.name);try{if((await RIe(o)).mtimeMs<t)await Cb(o,{recursive:!0,force:!0})}catch{}}))}catch{}}function bI(e,t){e?.log(t,{severity:"warn"})}function LIe(e){let t=e?.checkpoint;if(!t||typeof t!=="object"||Array.isArray(t))return;let n=t;if(!n.latest||!Array.isArray(n.history))return;let r=n.latest,o=n.history.filter((i)=>!!i&&typeof i==="object"&&typeof i.ref==="string"&&typeof i.createdAt==="number"&&typeof i.runCount==="number");if(typeof r.ref!=="string"||typeof r.createdAt!=="number"||typeof r.runCount!=="number")return;return{latest:r,history:o}}async function bn(e,t){let n=await Pb("git",["-C",e,...t],{windowsHide:!0});return{stdout:n.stdout.trim(),stderr:n.stderr.trim()}}var kI=["-c","core.ignorestat=false","-c","core.splitIndex=false"];async function Ib(e,t,n){return(await Pb("git",["-C",e,...kI,...n],{windowsHide:!0,maxBuffer:vI,env:{...process.env,GIT_INDEX_FILE:t}})).stdout.trim()}function NIe(e,t,n,r){return new Promise((o,i)=>{let s=xIe("git",["-C",e,...kI,...n],{windowsHide:!0,env:{...process.env,GIT_INDEX_FILE:t},stdio:["pipe","ignore","pipe"]}),a="";s.stderr.on("data",(d)=>{a+=d}),s.on("error",i),s.on("close",(d)=>{if(d===0)o();else i(Error(`git ${n[0]} exited with ${d}: ${a.trim()}`))}),s.stdin.on("error",()=>{}),s.stdin.end(r)})}async function DIe(e,t){let r=(await Pb("git",["-C",e,"ls-files","--others","--exclude-standard","-z"],{windowsHide:!0,maxBuffer:vI})).stdout.split("\x00").filter(Boolean);if(r.length===0)return;await EIe(t,{recursive:!0,mode:448});let o=Op(t,"index"),i=Op(t,"pathspec");await IIe(i,`${r.join("\x00")}\x00`);let s=["add","--force","--pathspec-from-file",i,"--pathspec-file-nul"];try{await Ib(e,o,s)}catch(h){if(String(h.stderr??"").includes("did not match any files"))throw h;await Cb(o,{force:!0}),await Cb(`${o}.lock`,{force:!0}),await Ib(e,o,s)}let a=await Pb("git",["-C",e,...kI,"ls-files","-z"],{windowsHide:!0,maxBuffer:vI,env:{...process.env,GIT_INDEX_FILE:o}}),d=new Set(r.map((h)=>h.endsWith("/")?h.slice(0,-1):h)),l=a.stdout.split("\x00").filter(Boolean).filter((h)=>!d.has(h));if(l.length>0)await NIe(e,o,["update-index","-z","--force-remove","--stdin"],`${l.join("\x00")}\x00`);let c=await Ib(e,o,["write-tree"]);if(!c)return;return await Ib(e,o,["commit-tree",c,"-m","untracked files on cline checkpoint"])||void 0}async function $Ie(e,t,n){let r=(await bn(e,["stash","create",n])).stdout,o=await DIe(e,t);if(r){if(!o)return r;let d=(await bn(e,["rev-parse",`${r}^{tree}`])).stdout,l=(await bn(e,["rev-parse",`${r}^1`])).stdout,c=(await bn(e,["rev-parse",`${r}^2`])).stdout;if(!d||!l||!c)return r;return(await bn(e,["commit-tree",d,"-p",l,"-p",c,"-p",o,"-m",n])).stdout||r}if(!o)return;let i=(await bn(e,["rev-parse","HEAD"])).stdout,s=(await bn(e,["rev-parse","HEAD^{tree}"])).stdout;if(!i||!s)return;let a=(await bn(e,["commit-tree",s,"-p",i,"-m","index on cline checkpoint"])).stdout;if(!a)return;return(await bn(e,["commit-tree",s,"-p",i,"-p",a,"-p",o,"-m",n])).stdout||void 0}async function TI(e,t){if(!e)return;await Cb(n3(e,t),{recursive:!0,force:!0}).catch(()=>{return});let n=`refs/cline/checkpoints/${t}/`;try{let{stdout:r}=await bn(e,["for-each-ref","--format=%(refname)",n]),o=r.trim().split(`
1003
- `).filter(Boolean);await Promise.allSettled(o.map((i)=>bn(e,["update-ref","-d",i])))}catch{}}async function r3(e,t,n){if(!e||n.length===0)return;await Promise.allSettled(n.map((r)=>bn(e,["update-ref",`refs/cline/checkpoints/${t}/${r.runCount}`,r.ref])))}function FIe(e,t){let n=e.findIndex((r)=>r.runCount===t.runCount);if(n<0)return[...e,t];return e.map((r,o)=>o===n?t:r)}function o3(e){OIe();let t,n,r=async()=>{if(t===!0)return!0;try{t=(await bn(e.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{t=!1}return t},o=async(i)=>{if(e.createCheckpoint)return await e.createCheckpoint({cwd:e.cwd,sessionId:e.sessionId,runCount:i});if(!await r())return;let s=Date.now(),a=(h)=>{e.telemetry?.capture({event:"checkpoint.snapshot",properties:{sessionId:e.sessionId,runCount:i,outcome:h,durationMs:Date.now()-s}})},d=async(h)=>{try{let f=(await bn(e.cwd,["rev-parse","HEAD"])).stdout.trim();if(!f)return;return{ref:f,createdAt:Date.now(),runCount:i,kind:"commit"}}catch(p){bI(e.logger,`${h}: ${p instanceof Error?p.message:String(p)}`);return}},l=`${ZG}${e.sessionId} run=${i}`,c="";try{c=await $Ie(e.cwd,n3(e.cwd,e.sessionId),l)??""}catch(h){bI(e.logger,`Checkpoint snapshot failed after ${Date.now()-s}ms: ${h instanceof Error?h.message:String(h)}`);let p=await d("Checkpoint HEAD fallback failed");return a(p?"head_fallback":"skipped"),p}if(!c){let h=await d("Checkpoint HEAD fallback failed");return a(h?"head_clean":"skipped"),h}let u=`refs/cline/checkpoints/${e.sessionId}/${i}`;try{await bn(e.cwd,["update-ref",u,c])}catch(h){bI(e.logger,`Checkpoint store failed: ${h instanceof Error?h.message:String(h)}`),a("skipped");return}return a("stash"),{ref:c,createdAt:Date.now(),runCount:i,kind:"stash"}};return{beforeRun:async({snapshot:i})=>{if(i.parentAgentId==null)n=i.messages.length;return},beforeModel:async({snapshot:i})=>{if(i.parentAgentId!=null||i.iteration!==1)return;let s=i.messages.slice(n??Math.max(0,i.messages.length-1));n=void 0;let a=bu(i.messages);if(a<1)return;let d=await e.readSessionMetadata(),l=LIe(d),c=bu(s)>=1,u=l?.history.some((f)=>f.runCount===a)??!1;if(!c&&u)return;let h=await o(a);if(!h)return;if(l?.latest.ref===h.ref)return;let p=FIe(l?.history??[],h);await e.writeSessionMetadata({...d??{},checkpoint:{latest:h,history:p}});return}}}function kc(...e){let t,n,r;for(let i of e){if(!i)continue;if(i.toolExecutors)t={...t??{},...i.toolExecutors};if(i.requestToolApproval)n=i.requestToolApproval;if(i.readReceipts)r=i.readReceipts}let o=t&&Object.keys(t).length>0;if(!o&&!n&&!r)return;return{...o?{toolExecutors:t}:{},...n?{requestToolApproval:n}:{},...r?{readReceipts:r}:{}}}import*as fr from"@cerebriline/llms";import{isOllamaNativeProvider as i3,resolveOutputBudgetTokens as UIe}from"@cerebriline/shared";function BIe(e){if(i3(e))return"ollama";return e==="opencoti"||e==="openai-compatible"?"llamacpp":void 0}var Da=(e)=>typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0;function s3(e){let t=Da(e.configuredNumPredict)??Da(e.maxTokensPerTurn)??(e.outputBudget?.mode==="manual"?Da(e.outputBudget.maxTokens):void 0);if(t!==void 0)return Math.floor(t);return UIe({mode:e.outputBudget?.mode??"auto",maxTokens:e.outputBudget?.maxTokens,contextWindow:e.contextWindow,modelMaxOutputTokens:Da(e.modelMaxOutputTokens)})??fr.resolveDefaultMaxOutputTokens({contextWindow:Da(e.contextWindow),maxOutputTokens:Da(e.modelMaxOutputTokens)})}async function a3(e){let t=BIe(e.providerId);if(!t||e.thinking===!1||!e.modelId)return;let n=Da(e.configuredNumPredict)??e.outputCap;if(t==="llamacpp"){let i=e.configuredThinkBudget?.trim()||e.reasoningEffort?.trim();if(!i)return;let s=fr.resolveLlamaCppThinkBudgetTokens(i,fr.resolveLlamaCppThinkBudgetWindow(e.contextWindow,n));return s===void 0?void 0:{level:i,budgetTokens:s}}let r=fr.resolveOllamaThinking({effort:e.reasoningEffort,sampling:{thinkBudget:e.configuredThinkBudget,reasoningLevel:e.configuredReasoningLevel}}),o={...typeof r.think==="string"?{think:r.think}:{},...r.thinkBudget?{thinkBudget:r.thinkBudget}:{},numPredict:n,numCtx:e.contextWindow};return e.probeOllama?e.probeOllama(e.baseUrl,e.modelId,o):fr.probeOllamaThinkBudget(e.baseUrl,e.modelId,o,e.fetchImpl)}function d3(e){let t=e.configuredMessage?.trim();if(t)return t;return i3(e.providerId)?fr.readDeclaredThinkBudgetMessage(e.baseUrl,e.modelId):void 0}var HIe=/(api[-_]?key|token|secret|password|authorization|credential|cookie)/i,WIe=new Set(["knownModels","extensionContext","logger","telemetry","hooks","extensions","tools","systemPrompt","providerConfig","workspaceMetadata"]);function Tc(e,t="",n=0){if(e===null||e===void 0)return;if(typeof e==="function"||typeof e==="symbol")return;if(typeof e==="string")return t&&HIe.test(t)&&e?"[set]":e;if(typeof e!=="object")return e;if(n>=6)return;if(Array.isArray(e))return e.map((i)=>Tc(i,t,n+1)).filter((i)=>i!==void 0);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return;let o={};for(let[i,s]of Object.entries(e)){if(WIe.has(i))continue;let a=t==="headers"&&typeof s==="string"&&s?"[set]":Tc(s,i,n+1);if(a!==void 0)o[i]=a}return o}var jIe=new Set(["fetch","headers","knownModels","extensionContext","providerId","modelId"]);function l3(e,t){let n=e,r=t,o=[];for(let i of new Set([...Object.keys(n),...Object.keys(r)])){if(jIe.has(i)||typeof n[i]==="function")continue;if(JSON.stringify(n[i]??null)!==JSON.stringify(r[i]??null))o.push(i)}return o.sort()}function Eo(e){let t=e?.trim();return t?t:void 0}function qIe(e){let t=e.client,n=_K(t)??Eo(e.source),r=Eo(t.version),o=Eo(t.platform)??Eo(t.name),i=Eo(t.platformVersion)??r,s={cline_type:n,extension_version:r,platform:o,platform_version:i};if(e.user?.accountId===void 0)return s;let a=typeof e.user.accountId==="string"?Eo(e.user.accountId):void 0;return{...s,distinct_id:a??Eo(e.user.distinctId),user_id:a,account_id:a,account_email:a?Eo(e.user.email):void 0,organization_id:a?Eo(e.user.organizationId):void 0}}function SI(e,t){let n={},r={},o,i=(s)=>({...t,...r,...n,...s,...o?{distinct_id:o}:{}});return{setDistinctId(s){o=Eo(s)},setMetadata(s){n={...s}},updateMetadata(s){n={...n,...s}},setCommonProperties(s){r={...s}},updateCommonProperties(s){r={...r,...s}},isEnabled:()=>e.isEnabled(),capture:(s)=>e.capture({event:s.event,properties:i(s.properties)}),captureRequired:(s,a)=>e.captureRequired(s,i(a)),recordCounter:(s,a,d,l,c)=>e.recordCounter(s,a,i(d),l,c),recordHistogram:(s,a,d,l,c)=>e.recordHistogram(s,a,i(d),l,c),recordGauge:(s,a,d,l,c)=>e.recordGauge(s,a,i(d),l,c),flush:()=>e.flush(),dispose:async()=>{}}}function c3(e,t){return SI(e,qIe(t))}import{upsertWorkspaceInfo as eCe,WorkspaceManifestSchema as EI}from"@cerebriline/shared";import{execFile as zIe}from"node:child_process";import{basename as KIe,resolve as GIe}from"node:path";import{performance as u3}from"node:perf_hooks";import{promisify as VIe}from"node:util";import{processWorkspaceInfo as m3}from"@cerebriline/shared";import h3 from"simple-git";var YIe=VIe(zIe);function XIe(e,t){return YIe("git",e,{cwd:t.cwd,encoding:"utf8",windowsHide:!0,signal:t.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function JIe(e){if(!e||typeof e!=="object"||!("stderr"in e))return"";return typeof e.stderr==="string"?e.stderr.trim():""}function QIe(e){if(!e||typeof e!=="object"||!("code"in e))return;return typeof e.code==="number"?e.code:void 0}function f3(e){let t=Sc(e.cwd),n=e.git??XIe,r=async(i)=>(await n(i,{cwd:t,signal:e.signal})).stdout,o=async(i)=>(await r(i)).trim();return{async isInsideWorkTree(){try{return await o(["rev-parse","--is-inside-work-tree"])==="true"}catch(i){if(QIe(i)===128&&/not a git repository|Kein Git-Repository/i.test(JIe(i)))return!1;throw i}},remotes:()=>h3({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await h3({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>o(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>o(["rev-parse","HEAD"]),workspacePrefix:async()=>(await r(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>o(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(i)=>o(["config","--get",`branch.${i}.remote`]),branchMergeRef:(i)=>o(["config","--get",`branch.${i}.merge`]),remoteUrl:(i)=>o(["remote","get-url",i]),remoteRefs:(i,s)=>o(["ls-remote","--exit-code",i,s])}}function ZIe(e){let t=e?.git;if(!t||typeof t!=="object"||Array.isArray(t))return{};let n=t;return{...typeof n.url==="string"&&n.url.trim()?{url:n.url.trim()}:{},...typeof n.branch==="string"&&n.branch.trim()?{branch:n.branch.trim()}:{}}}function xI(e,t){let n={...e??{}};if(!t.url&&!t.branch)return delete n.git,Object.keys(n).length>0?n:void 0;let o={...n.git&&typeof n.git==="object"&&!Array.isArray(n.git)?n.git:{}};if(t.url)o.url=t.url;else delete o.url;if(t.branch)o.branch=t.branch;else delete o.branch;return n.git=o,n}function g3(e,t){let n=ZIe(e);return n.url===t.url&&n.branch===t.branch}function y3(e){let t=e.find(({name:n})=>n==="origin")??e[0];return(t?.refs.fetch||t?.refs.push)?.trim()||void 0}function Sc(e){return GIe(e)}async function _I(e){return(await w3(e)).info}function p3(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(t)}function Mb(e){if(e instanceof Error)return{errorType:e.name?.trim()||e.constructor.name||"Error",message:e.message};return{errorType:"Error",message:String(e)}}async function w3(e){let t=Sc(e),n={rootPath:t,hint:KIe(t)||void 0},r={},o;try{let i=f3({cwd:t});if(!await i.isInsideWorkTree())return{info:n,vcsType:"none",gitState:r};try{let a=await i.remotes();if(a.length>0){let d=a.map((c)=>{let u=c.refs.fetch||c.refs.push;return`${c.name}: ${u}`});n.associatedRemoteUrls=d;let l=y3(a);if(l)r.url=l}}catch(a){o??=Mb(a)}try{let a=await i.headSha();if(a.length>0)n.latestGitCommitHash=a}catch(a){if(!p3(a))o??=Mb(a)}try{let a=await i.displayBranch();if(a.length>0)n.latestGitBranchName=a,r.branch=a}catch(a){if(!p3(a))o??=Mb(a)}return{info:n,vcsType:"git",gitState:r,error:o}}catch(i){return{info:n,vcsType:"none",gitState:r,error:Mb(i)}}}async function b3(e){try{let t=f3({cwd:e});if(!await t.isInsideWorkTree())return{};let[n,r]=await Promise.all([t.remotes(),t.displayBranch()]),o=y3(n);return{...o?{url:o}:{},...r?{branch:r}:{}}}catch{return}}async function v3(e){let t=await _I(e);return m3(t)}async function k3(e){let t=u3.now(),n=await w3(e),r=u3.now()-t,o=n.info;return{workspaceInfo:o,workspaceMetadata:m3(o),durationMs:r,vcsType:n.vcsType,gitState:n.gitState,initError:n.error}}class AI{manifest;listeners=new Set;constructor(e){this.manifest=EI.parse(e??{workspaces:{}})}async addWorkspacePath(e){let t=await _I(e);return this.manifest=eCe(this.manifest,t),this.emit({type:"workspace_added",workspace:t}),t}async switchWorkspace(e){let t=Sc(e),n=this.manifest.workspaces[t];if(n)return this.manifest=EI.parse({...this.manifest,currentWorkspacePath:t}),this.emit({type:"workspace_switched",workspace:n}),n;let r=await this.addWorkspacePath(t);return this.manifest=EI.parse({...this.manifest,currentWorkspacePath:r.rootPath}),this.emit({type:"workspace_switched",workspace:r}),r}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getCurrentWorkspace(){let e=this.manifest.currentWorkspacePath;if(!e)return;return this.manifest.workspaces[e]}getWorkspace(e){let t=Sc(e);return this.manifest.workspaces[t]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(e){for(let t of this.listeners)t(e)}}import{createHash as tCe}from"node:crypto";var T3=new Set,S3=new Set;function nCe(e,t){return tCe("sha256").update(e).update("\x00").update(t?.trim()??"").digest("hex")}function rCe(e){if(e.vcsTypes&&e.vcsTypes.length>0)return e.vcsTypes;return[e.vcsType==="git"?"git":"none"]}function x3(e){if(!e.telemetry)return;let t=nCe(e.rootPath,e.dedupeScope),n=e.rootCount??1;if(!T3.has(t))T3.add(t),uM(e.telemetry,{root_count:n,vcs_types:rCe(e),init_duration_ms:e.durationMs,feature_flag_enabled:e.featureFlagEnabled??!0,is_remote_workspace:e.isRemoteWorkspace});if(e.initError&&!S3.has(t)){S3.add(t);let r=Error(e.initError.message);r.name=e.initError.errorType||"Error",hM(e.telemetry,r,{fallback_to_single_root:!0,workspace_count:n})}}function wCe(e){return`${e.pluginName??e.pluginPath}: ${e.message}`}function bCe(e,t,n){if(t.length>0)for(let i of t)n?.log(i.message,{severity:"warn"});if(e.length===0)return;let r=e.slice(0,3).map(wCe).join("; "),o=e.length>3?`; and ${e.length-3} more`:"";n?.log(`Some plugins failed to initialize. ${r}${o}. Use --verbose for more details.`,{severity:"warn"});for(let i of e)n?.log(`Plugin initialization failed (${i.phase}) for ${i.pluginPath}`,{severity:"warn",stack:i.stack,pluginPath:i.pluginPath,pluginName:i.pluginName})}function vCe(e,t){for(let n of e){let r=n.componentName?` (${n.componentName})`:"";t?.log(`[agent-plugins] ${n.pluginName??n.pluginPath}${r}: ${n.message}`,{severity:n.level==="warning"?"warn":"error"})}}function kCe(e){let t=e?.["X-CLIENT-TYPE"]?.trim();if(!t)return;let n=e?.["X-CLIENT-VERSION"]?.trim();return{name:t,...n?{version:n}:{}}}function TCe(e,t){let n=typeof e.thinking==="boolean",r=typeof e.reasoningEffort==="string";if(!n&&!r)return t;return{...t??{},...n?{enabled:e.thinking}:{},...r?{effort:e.reasoningEffort}:{}}}function Ob(e,t){return pCe(e,t)}function SCe(e,t,n){if(e.systemPrompt?.trim())return e.systemPrompt;return hCe({ide:"Terminal Shell",workspaceRoot:t.rootPath,workspaceName:t.hint,metadata:n,rules:e.rules,mode:e.mode,providerId:e.providerId,platform:process.platform||"unknown"})}function xCe(e,t){return e.storedProviderSettings==="ignore"?void 0:t.getProviderSettings(e.providerId)}function E3(e,t,n,r,o,i){let s=o||r?.modelCatalog?{...o??{},...r?.modelCatalog??{}}:void 0,a=e.providerConfig?.providerId===e.providerId?e.providerConfig:void 0,d=St(e.contextWindow),l=uCe({providerId:e.providerId,sessionId:t,source:n,defaultSource:Gt.CLI,client:{name:e.extensionContext?.client?.name,version:e.extensionContext?.client?.version,versionHeaderFallback:e.headers?.["X-CLIENT-VERSION"],platform:e.extensionContext?.client?.platform,platformVersion:e.extensionContext?.client?.platformVersion,isMultiRoot:e.extensionContext?.client?.isMultiRoot},coreVersion:tc,openAiCodex:{accountId:a?.accountId??r?.auth?.accountId,accessToken:a?.accessToken??e.apiKey??r?.auth?.accessToken??r?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:r?.headers,config:e.headers,session:a?.headers}}),c={...r??{},provider:e.providerId,model:e.modelId,apiKey:e.apiKey??r?.apiKey,baseUrl:e.baseUrl??r?.baseUrl,headers:void 0,reasoning:TCe(e,r?.reasoning),modelCatalog:s,...d!==void 0?{contextWindow:d}:{}},u={...La(c),...a??{}};if(l)u.headers=l;if(e.knownModels)u.knownModels=e.knownModels;if(d!==void 0)u.knownModels={...u.knownModels??{},[e.modelId]:{...u.knownModels?.[e.modelId]??{},id:e.modelId,contextWindow:d,maxInputTokens:void 0}};if(e.extensionContext)u.extensionContext=e.extensionContext;let p=e.fetch??u.fetch??i;if(p)u.fetch=p;return u}var St=(e)=>typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0;function _Ce(e){return{...e,compaction:{...e.compaction??{},enabled:e.compaction?.enabled??!0},checkpoint:{...e.checkpoint??{},enabled:e.checkpoint?.enabled??!0},taskProgress:{...e.taskProgress??{},enabled:e.taskProgress?.enabled??!0}}}async function ECe(e,t){let n=t.modelId??e.modelId,r=t.fetch??globalThis.fetch;if(e.providerConfig?.providerId===e.providerId&&St(e.providerConfig?.defaultMaxOutputTokens)!==void 0||!n||!Lb(e.providerId))return{council:!1};if(await iCe(t.baseUrl,n,r,e.logger).catch(()=>{return}),ACe(t,n,aCe(t.baseUrl,n),e.knownModels?.[n]),e.providerId!=="xollama")return{council:!1};return{council:(await dCe(cCe(e.providerId,t.baseUrl),n,r).catch(()=>{return}))?.council===!0}}function ACe(e,t,n,r){if(!n||n.images===void 0&&n.tools===void 0||Array.isArray(r?.capabilities))return;let o=e.knownModels?.[t],i=new Set(o?.capabilities??[]),s=(a,d)=>{if(d===!0)i.add(a);else if(d===!1)i.delete(a)};if(s("images",n.images),s("tools",n.tools),n.tools===void 0&&i.size>0)i.add("tools");e.knownModels={...e.knownModels??{},[t]:{...o??{},id:t,capabilities:[...i]}}}function RCe(e){return e.logger?.log(`${e.modelId} is an xOllama council: it compacts server-side; client compaction is off`,{severity:"info"}),{...e,compaction:{...e.compaction??{},enabled:!1,cappedThinkingEnabled:!1},staleReadRewrites:!1}}function ICe(e,t,n,r,o){let i=t.modelId,s=e.knownModels?.[i];if(r===void 0||!o&&!s)return;let d=St(n?.sampling?.numPredict)??St(t.maxTokensPerTurn)??(n?.outputBudget?.mode==="manual"?St(n.outputBudget.maxTokens):void 0)??St(s?.maxTokens)??(Lb(t.providerId)?St(e.defaultMaxOutputTokens):void 0);e.knownModels={...e.knownModels??{},[i]:{...s??{},id:i,contextWindow:r,maxInputTokens:St(t.contextWindow)!==void 0?s?.maxInputTokens:Math.min(s?.maxInputTokens??r,r),...d!==void 0?{maxTokens:d}:{}}}}function CCe(e){let{config:t,hostConfig:n,providerConfig:r,stored:o}=e,i=r.knownModels?.[t.modelId],s=o?l3(r,(()=>{let l=E3(n,e.sessionId,e.source,void 0,e.modelCatalogDefaults,e.defaultFetch);return l.defaultMaxOutputTokens=r.defaultMaxOutputTokens,l.thinkingBudgetTokens=r.thinkingBudgetTokens,l})()):[],a=n.providerConfig?.providerId===n.providerId&&St(n.providerConfig?.defaultMaxOutputTokens)!==void 0;if(o&&!a){let l=[["budget.contextWindow",St(t.contextWindow)===void 0?o.contextWindow:void 0],["budget.numPredict",o.sampling?.numPredict],["budget.thinkBudget",o.sampling?.thinkBudget],["budget.outputBudget",o.outputBudget],["budget.reasoningBudgetTokens",o.reasoning?.budgetTokens]];for(let[c,u]of l)if(u!==void 0&&u!==null)s.push(c)}let d=gCe();return{sessionId:e.sessionId,providerId:t.providerId,modelId:t.modelId,...r.baseUrl?{baseUrl:r.baseUrl}:{},contextWindow:St(t.contextWindow)??e.contextWindow??St(i?.contextWindow)??St(r.maxInputTokens),maxOutputTokens:St(r.defaultMaxOutputTokens),thinking:{...typeof r.thinking==="boolean"?{enabled:r.thinking}:{},...r.reasoningEffort?{effort:String(r.reasoningEffort)}:{},...St(r.thinkingBudgetTokens)!==void 0?{budgetTokens:r.thinkingBudgetTokens}:{}},...r.sampling?{sampling:Tc(r.sampling)}:{},reasoningHistory:lCe(t.providerId,{modelId:r.modelId??t.modelId,baseUrl:r.baseUrl,reasoningHistory:r.reasoningHistory,reasoningInline:r.reasoningInline}),provider:Tc(r),session:Tc(t),...t.systemPrompt?{systemPrompt:t.systemPrompt}:{},sources:{storedProviderSettings:t.storedProviderSettings==="ignore"?"ignored":o?"merged":"absent",inheritedFromStoredProfile:s.sort(),dataDir:fCe(),providerSettingsPath:yCe(),globalSettingsPath:d,globalSettingsPresent:oCe(d)}}}async function PCe(e,t,n){if(t.providerConfig?.providerId===t.providerId&&St(t.providerConfig?.defaultMaxOutputTokens)!==void 0)return;let o=t.modelId,i=e.baseUrl,s=e.knownModels?.[o],a=St(t.contextWindow)??St(n?.contextWindow)??(Lb(t.providerId)?_3(i,o):void 0)??St(s?.contextWindow),d=n?.sampling,l=s3({configuredNumPredict:d?.numPredict,maxTokensPerTurn:t.maxTokensPerTurn,outputBudget:n?.outputBudget,contextWindow:a,modelMaxOutputTokens:s?.maxTokens});e.defaultMaxOutputTokens=l;let c;try{c=await a3({providerId:t.providerId,modelId:o,baseUrl:i,thinking:e.thinking,reasoningEffort:e.reasoningEffort,configuredThinkBudget:d?.thinkBudget,configuredReasoningLevel:d?.reasoningLevel,configuredNumPredict:d?.numPredict,outputCap:l,contextWindow:a,fetchImpl:e.fetch??fetch})}catch{c=void 0}if(c&&St(n?.reasoning?.budgetTokens)===void 0)e.thinkingBudgetTokens=c.budgetTokens;return t.logger?.log(`Output budget: cap=${l} contextWindow=${a??"unknown"}`+(c?` thinking=${c.budgetTokens} (${c.level})`:""),{severity:"info"}),{contextWindow:a,thinking:c,budgetMessage:d3({providerId:t.providerId,modelId:o,baseUrl:i,configuredMessage:d?.thinkBudgetMessage})}}async function A3(e){let{input:t,sessionId:n,sessionOrigin:r,providerSettingsManager:o,defaultTelemetry:i,defaultLogger:s,defaultCapabilities:a,defaultToolPolicies:d,defaultFetch:l,onPluginEvent:c,onTeamEvent:u,createSubAgentLifecycleCallbacks:h,createSpawnTool:p,createSwarmTool:f,delegatedSandboxes:m,localRuntime:g,readSessionMetadata:y,writeSessionMetadata:w}=e,k=hi(t.config),{modelCatalogDefaults:b,userInstructionService:v,configExtensions:E,onTeamRestored:S,...x}=g??{},T=Object.keys(x).length>0?x:void 0,{workspaceInfo:A,workspaceMetadata:R,gitState:C,durationMs:L,vcsType:N,initError:W}=await k3(k),D=T?.extensionContext,K=D?.client?void 0:kCe(t.config.headers),V=D?.client??K,j=D?.telemetry??T?.telemetry??(i&&V?c3(i,{client:V,source:t.source,user:D?.user}):i),G=j&&r?SI(j,{session_origin:r.mode,session_origin_trigger:r.trigger}):j,z={...D??{},...K?{client:K}:{},workspace:{...A,...D?.workspace??{}},session:{...D?.session??{},sessionId:n},logger:D?.logger??T?.logger??s,telemetry:G};x3({telemetry:z.telemetry,rootPath:A.rootPath,dedupeScope:z.client?.name??t.source,workspaceInfo:A,rootCount:1,vcsType:N,durationMs:L,initError:W,featureFlagEnabled:!0});let M=Ob(E,"hooks")?vA({cwd:t.config.cwd,workspacePath:k,rootSessionId:n,logger:T?.logger,workspaceInfo:A,onHookRuntime:(Ze)=>IM(z.telemetry,Ze)}):void 0,X=RK(T?.hooks)?void 0:bA({rootSessionId:n,workspacePath:k,workspaceInfo:A}),oe=ec([T?.hooks,X]),H;if(Ob(E,"plugins"))try{H=await QG({pluginPaths:T?.pluginPaths,workspacePath:k,cwd:t.config.cwd,onEvent:c,providerId:t.config.providerId,modelId:t.config.modelId,workspaceInfo:A,session:z.session,client:z.client,user:z.user,logger:z.logger,telemetry:z.telemetry,automation:z.automation}),bCe(H.failures,H.warnings,T?.logger)}catch(Ze){let un=Ze instanceof Error?Ze.message:String(Ze);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${un})`)}let J;if(Ob(E,"plugins"))try{J=await Tp({pluginPaths:t.config.agentPluginPaths,cwd:t.config.cwd,disabledPluginNames:[...Xh()]}),vCe(J.diagnostics,z.logger)}catch(Ze){let un=Ze instanceof Error?Ze.message:String(Ze);z.logger?.log(`[agent-plugins] Package discovery failed; continuing without Agent Plugins: ${un}`,{severity:"error"})}let he=await AG({logger:T?.logger}),se=[...M?[M]:[],...he?[he]:[]],re=se.length>0?se:void 0,Ge=_R(re,_R(T?.extensions,Nj(H?.extensions))),I=Ob(E,"plugins")?vc(H?.pluginPaths??[]):void 0,_=_Ce({...t.config,...T??{},sessionId:n,hooks:oe,extensions:Ge,extensionContext:z,telemetry:z.telemetry,logger:z.logger}),F=xCe(_,o),O=E3(_,n,t.source,F,b,l),ne=(await ECe(_,O)).council?RCe(_):_,fe=await PCe(O,ne,F);if(fe)ICe(O,ne,F,fe.contextWindow,(St(ne.contextWindow)??St(F?.contextWindow)??(Lb(ne.providerId)?_3(O.baseUrl,ne.modelId):void 0))!==void 0);let Ce=ec([ne.hooks,ne.checkpoint?.enabled===!0?o3({cwd:ne.cwd,sessionId:n,logger:ne.logger,createCheckpoint:ne.checkpoint?.createCheckpoint,telemetry:ne.telemetry,readSessionMetadata:y,writeSessionMetadata:w}):void 0]),We=SCe(ne,A,R),Se={...ne,providerConfig:O,workspaceMetadata:R,systemPrompt:We,hooks:Ce,...fe?.budgetMessage&&!ne.compaction?.cappedThinkingBudgetMessage?{compaction:{...ne.compaction??{},cappedThinkingBudgetMessage:fe.budgetMessage}}:{},...We?{systemPrompt:mCe(We,{outputCap:O.defaultMaxOutputTokens,contextWindow:fe?.contextWindow??O.maxInputTokens,...fe?.thinking?{thinking:fe.thinking}:O.thinkingBudgetTokens&&O.reasoningEffort?{thinking:{level:O.reasoningEffort,budgetTokens:O.thinkingBudgetTokens}}:{}})}:{}};await sCe(Se.providerId,O.baseUrl,O.modelId??Se.modelId,O.fetch??globalThis.fetch).catch(()=>{return});let Le=CCe({config:Se,hostConfig:ne,providerConfig:O,sessionId:n,source:t.source,stored:F,modelCatalogDefaults:b,defaultFetch:l,contextWindow:fe?.contextWindow});await ne.onConfigResolved?.(Le);let it=t.toolPolicies??ne.toolPolicies??d,dt=kc(a,t.capabilities),_e=dt?.requestToolApproval,Ue=dt?.toolExecutors,xt=dt?.readReceipts,Jt=h?.(Se),Zn=new AI({currentWorkspacePath:A.rootPath,workspaces:{[A.rootPath]:A}});return{effectiveInput:t,config:Se,providerConfig:O,resolvedConfig:Le,workspaceMetadata:R,workspaceInfo:A,gitState:C,extensions:Ge,hooks:Ce,toolPolicies:it,requestToolApproval:_e,pluginSandboxShutdown:H?.shutdown,runtimeBuilderInput:{config:Se,hooks:Ce,extensions:Ge,onTeamEvent:u,createSpawnTool:p,createSwarmTool:f,...m?{delegatedSandboxes:m}:{},onTeamRestored:S,onSubAgentEvent:Jt?.onSubAgentEvent,onSubAgentStart:Jt?.onSubAgentStart,onSubAgentEnd:Jt?.onSubAgentEnd,userInstructionService:v,pluginSkillDirectories:I,agentPluginSkills:J?.skills,agentPluginMcpServers:J?.mcpServers,configExtensions:E,toolExecutors:Ue,readReceipts:xt,toolPolicies:it,workspaceManager:Zn,logger:Se.logger,telemetry:Se.telemetry,requestToolApproval:_e}}}import{RECALLED_MEMORY_TAG as FCe}from"@cerebriline/shared";import{createTool as Ktt,MAIN_MEMORY as Gtt,memorySelectionFor as Vtt}from"@cerebriline/shared";import{DEFAULT_LIBRARY_SETTINGS as NCe,DEFAULT_MEMORY_SETTINGS as Ntt,MAIN_MEMORY as Dtt,memoryWorkspaceKey as $tt}from"@cerebriline/shared";import{resolveClineDataDir as Utt}from"@cerebriline/shared/storage";import{DEFAULT_LIBRARY_SETTINGS as btt}from"@cerebriline/shared";import{resolveClineDataDir as ktt}from"@cerebriline/shared/storage";import{DEFAULT_LIBRARY_SETTINGS as Het}from"@cerebriline/shared";var Cet=Array.from({length:64},(e,t)=>(Math.imul(t+1,2654435761)|1)>>>0);import{loadSqliteDb as ttt}from"@cerebriline/shared/db";var R3=4000;var Wtt={...NCe,enabled:!0,chunkSize:R3*2,chunkOverlap:0,markdownHeaders:!1};var int=new Set("a about above after again all also am an and any are as at be because been before being below between both but by can could did do does doing down during each few for from further had has have having he her here hers him his how i if in into is it its just me more most my no nor not now of off on once only or other our ours out over own same she should so some such than that the their theirs them then there these they this those through to too under until up very was we were what when where which while who whom why will with would you your yours please thanks every always never use using used want wants need needs like get got make made new one two project projects code file files thing things".split(" "));function I3(e){let t=new Set;for(let n of e){if(!n.includes(`<${FCe}>`))continue;for(let r of n.matchAll(/^\[(m\d+)\] \d{4}-\d{2}-\d{2}, /gm))t.add(r[1])}return[...t]}import{existsSync as Nb,mkdirSync as UCe,readdirSync as BCe,rmdirSync as HCe,rmSync as WCe,unlinkSync as jCe}from"node:fs";import{dirname as C3,join as Lp}from"node:path";function ft(){return new Date().toISOString()}function Np(e){if(!e||!Nb(e))return;try{jCe(e)}catch{}}function qCe(e){let t=Ca(e);if(t)return{rootSessionId:t.rootSessionId,fileStem:`${t.agentId}__${t.teamTaskId}`};let n=mc(e);if(n)return{rootSessionId:n.rootSessionId,fileStem:n.agentId};return{rootSessionId:e,fileStem:e}}class RI{ensureSessionsDir;constructor(e){this.ensureSessionsDir=e}sessionArtifactsDir(e){return Lp(this.ensureSessionsDir(),e)}ensureSessionArtifactsDir(e){let t=this.sessionArtifactsDir(e);if(!Nb(t))UCe(t,{recursive:!0});return t}sessionMessagesPath(e){return Lp(this.sessionArtifactsDir(e),`${e}.messages.json`)}sessionCompactionPath(e){return Lp(this.sessionArtifactsDir(e),`${e}.compaction.json`)}sessionManifestPath(e,t=!1){let n=t?this.ensureSessionArtifactsDir(e):this.sessionArtifactsDir(e);return Lp(n,`${e}.json`)}removeSessionDirIfEmpty(e){let t=this.sessionArtifactsDir(e),n=this.ensureSessionsDir();while(t.startsWith(n)&&t!==n){if(!Nb(t)){t=C3(t);continue}try{if(BCe(t).length>0)break;HCe(t)}catch{break}t=C3(t)}}removeSessionDir(e){this.removeDir(this.sessionArtifactsDir(e))}removeDir(e){if(!Nb(e))return;try{WCe(e,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(e,t,n){let{rootSessionId:r,fileStem:o}=qCe(e),i=this.sessionArtifactsDir(r);return{messagesPath:Lp(i,`${o}.messages.json`)}}}import{nanoid as $nt}from"nanoid";import{nanoid as bnt}from"nanoid";import{loadSqliteDb as _nt}from"@cerebriline/shared/db";import{nanoid as Ant}from"nanoid";function M3(e){let t=e?.importedFrom;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t;if(typeof n.tool!=="string"||typeof n.sourceSessionId!=="string")return;return{tool:n.tool,sourceSessionId:n.sourceSessionId,sourcePath:typeof n.sourcePath==="string"?n.sourcePath:"",importedAt:typeof n.importedAt==="string"?n.importedAt:""}}import{resolveDocumentsExtensionPath as zCe}from"@cerebriline/shared/storage";function O3(e,t,n,r,o){if(n)yM(e.telemetry,{ulid:t,provider:e.providerId,model:e.modelId,...o});else gM(e.telemetry,{ulid:t,provider:e.providerId,model:e.modelId,...o});KCe(e.telemetry,{workspacePath:r})}function KCe(e,t){let n=zCe("Hooks"),r=Gh(t.workspacePath),o=new Map,i=n.replace(/\\/g,"/");for(let s of r){let a=s.hookEventName??"unknown",d=o.get(a)??{global:0,workspace:0},l=s.path.replace(/\\/g,"/");if(l===i||l.startsWith(`${i}/`))d.global+=1;else d.workspace+=1;o.set(a,d)}for(let[s,a]of o.entries())CM(e,s,a.global,a.workspace)}function L3(e,t){for(let n of t.mentions)AM(e,n,t.matchedFiles.includes(n)?1:0,"file",!t.matchedFiles.includes(n));for(let n of t.matchedFiles)_M(e,"file",n.length);for(let n of t.ignoredMentions)EM(e,"file","not_found",n)}import{existsSync as GCe,mkdirSync as VCe,readFileSync as YCe,writeFileSync as XCe}from"node:fs";import{resolve as JCe}from"node:path";import{resolveSessionDataDir as QCe}from"@cerebriline/shared/storage";import{nanoid as ZCe}from"nanoid";import*as ePe from"node-machine-id";var tPe="machine-id",N3,D3=!1;function $3(){if(!D3)N3=F3(),D3=!0;return N3??U3()}function $a(e){let t=e?.trim();if(t)return t;let n=F3();if(n)return n;return U3()}function nPe(){let e=ePe;return e.machineIdSync??e.default?.machineIdSync}function F3(){try{let e=nPe();if(!e)return;return e().trim()||void 0}catch{return}}function U3(){let e=QCe(),t=JCe(e,tPe);try{if(GCe(t)){let r=YCe(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${ZCe()}`;try{VCe(e,{recursive:!0}),XCe(t,n,"utf8")}catch{}return n}function rPe(e){return e?JSON.parse(JSON.stringify(e)):void 0}function oPe(e){return e?JSON.parse(JSON.stringify(e)):void 0}function iPe(e){let t=e?.checkpoint&&typeof e.checkpoint==="object"&&!Array.isArray(e.checkpoint)?e.checkpoint:void 0,r=(Array.isArray(t?.history)?t.history:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)).flatMap((s)=>{let a=typeof s.ref==="string"?s.ref.trim():"",d=Number(s.createdAt),l=Number(s.runCount);if(!a||!Number.isFinite(d)||!Number.isInteger(l))return[];return[{ref:a,createdAt:d,runCount:l,...s.kind==="stash"||s.kind==="commit"?{kind:s.kind}:{}}]}),o=r.at(-1),i=e?.checkpointEnabled===!0?!0:void 0;if(!i&&r.length===0)return;return{...i?{enabled:i}:{},...o?{latest:o}:{},history:r}}function Fa(e){let{session:t}=e,n=rPe(t.metadata);return{version:1,sessionId:t.sessionId,source:t.source,status:t.status,createdAt:t.startedAt,updatedAt:t.updatedAt,endedAt:t.endedAt??null,exitCode:t.exitCode??null,interactive:t.interactive,workspace:{cwd:t.cwd,root:t.workspaceRoot},model:{providerId:t.provider,modelId:t.model},capabilities:{enableTools:t.enableTools,enableSpawn:t.enableSpawn,enableTeams:t.enableTeams},lineage:{...t.parentSessionId?{parentSessionId:t.parentSessionId}:{},...t.parentAgentId?{parentAgentId:t.parentAgentId}:{},...t.agentId?{agentId:t.agentId}:{},...t.conversationId?{conversationId:t.conversationId}:{},isSubagent:t.isSubagent},...t.teamName?{team:{name:t.teamName}}:{},...t.prompt?{prompt:t.prompt}:{},...n?{metadata:n}:{},...t.messagesPath?{artifacts:{messagesPath:t.messagesPath}}:{},...e.messages?{messages:oPe(e.messages)}:{},...e.usage?{usage:{...e.usage}}:{},...e.aggregateUsage?{aggregateUsage:{...e.aggregateUsage}}:{},...(()=>{let r=iPe(n);return r?{checkpoint:r}:{}})()}}import{execFile as sPe}from"node:child_process";import{randomUUID as aPe}from"node:crypto";import{promisify as dPe}from"node:util";var ot=dPe(sPe);async function B3(e,t){try{return(await ot("git",["-C",e,"rev-parse","--verify","--quiet",t],{windowsHide:!0})).stdout.trim()||void 0}catch{return}}async function H3(e){if((await ot("git",["-C",e,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${e} is not a git repository`);let n=(await ot("git",["-C",e,"rev-parse","--verify","HEAD"],{windowsHide:!0})).stdout.trim(),r=await B3(e,"refs/stash"),o=aPe(),i=`refs/cline/restore-transactions/${o}`;await ot("git",["-C",e,"stash","push","--include-untracked","--message",`cline restore transaction ${o}`],{windowsHide:!0});let s=await B3(e,"refs/stash"),a=s!==void 0&&s!==r;if(a)try{await ot("git",["-C",e,"update-ref",i,s],{windowsHide:!0}),await ot("git",["-C",e,"stash","drop","stash@{0}"],{windowsHide:!0})}catch(l){try{await ot("git",["-C",e,"reset","--hard",n],{windowsHide:!0}),await ot("git",["-C",e,"clean","-fd"],{windowsHide:!0}),await ot("git",["-C",e,"stash","apply","--index",s],{windowsHide:!0})}catch(c){throw AggregateError([l,c],"Workspace snapshot and rollback both failed")}throw l}let d=!1;return{async commit(){if(d)return;if(d=!0,!a)return;await ot("git",["-C",e,"update-ref","-d",i],{windowsHide:!0}).catch(()=>{return})},async rollback(){if(d)return;if(await ot("git",["-C",e,"reset","--hard",n],{windowsHide:!0}),await ot("git",["-C",e,"clean","-fd"],{windowsHide:!0}),a)await ot("git",["-C",e,"stash","apply","--index",i],{windowsHide:!0}),await ot("git",["-C",e,"update-ref","-d",i],{windowsHide:!0});d=!0}}}function W3(e){let t=e?.metadata?.checkpoint&&typeof e.metadata.checkpoint==="object"&&!Array.isArray(e.metadata.checkpoint)?e.metadata.checkpoint:void 0;return(Array.isArray(t?.history)?t.history:[]).filter((r)=>!!r&&typeof r==="object"&&!Array.isArray(r)).flatMap((r)=>{let o=String(r.ref??"").trim(),i=Number(r.createdAt??0),s=Number(r.runCount??0);if(o.length===0||!Number.isFinite(i)||!Number.isInteger(s)||s<1)return[];let a=r.kind==="stash"||r.kind==="commit"?r.kind:void 0;return[{ref:o,createdAt:i,runCount:s,...a?{kind:a}:{}}]})}function j3(e,t){let n=W3(e).filter((o)=>o.runCount<=t),r=n.at(-1);return r?{latest:r,history:n}:void 0}function lPe(e,t){return e.reduce((n,r)=>{if(r.runCount>t)return n;if(!n||r.runCount>n.runCount)return r;return n},void 0)}function q3(e,t){let n=0;for(let r=0;r<e.length;r+=1){let o=e[r];if(!o)continue;let i=Ad(o);if(i<1)continue;let s=n+1;if(n+=i,n===t)return{index:r,span:i};if(n>t)throw Error(`Run ${t} is folded into a compacted message spanning runs ${s}-${n}`)}throw Error(`Could not find user message for run ${t}`)}function cPe(e,t){let{index:n}=q3(e,t);return e.slice(0,n+1)}function z3(e,t){let{index:n,span:r}=q3(e,t);if(r!==1)throw Error(`Cannot fork before run ${t} because it is folded into a compacted message`);return e.slice(0,n)}function K3(e){let t=e.checkpointRunCount;if(!Number.isInteger(t)||t<1)throw Error("checkpointRunCount must be a positive integer");let n=lPe(W3(e.session),t);if(!n)throw Error(`No checkpoint found at or before run ${t} in session ${e.session.sessionId}`);let r=(e.cwd?.trim()||e.session.cwd||e.session.workspaceRoot).trim();if(!r)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:n,cwd:r,...e.restoreMessages!==!1?{messages:cPe(e.messages??[],t)}:{}}}async function uPe(e,t){if(t.kind)return t.kind;let n=await ot("git",["-C",e,"show","-s","--format=%P%x00%B",t.ref],{windowsHide:!0}),r=n.stdout.indexOf("\x00"),o=r<0?[]:n.stdout.slice(0,r).trim().split(/\s+/).filter(Boolean),i=r<0?"":n.stdout.slice(r+1);return o.length>=2&&e3(i)?"stash":"commit"}async function hPe(e,t){try{return await ot("git",["-C",e,"cat-file","-e",`${t}^3^{commit}`],{windowsHide:!0}),!0}catch{return!1}}async function pPe(e,t,n){try{let r=await ot("git",["-C",e,"rev-list","--count",`${t}..${n}`],{windowsHide:!0}),o=Number(r.stdout.trim());return Number.isFinite(o)?o:void 0}catch{return}}async function G3(e,t){if((await ot("git",["-C",e,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${e} is not a git repository`);await ot("git",["-C",e,"cat-file","-e",`${t.ref}^{commit}`],{windowsHide:!0});let r=await uPe(e,t),o=r==="commit"?t.ref:`${t.ref}^1`,i=(await ot("git",["-C",e,"rev-parse","--verify",`${o}^{commit}`],{windowsHide:!0})).stdout.trim(),s=(await ot("git",["-C",e,"rev-parse","--verify","HEAD"],{windowsHide:!0})).stdout.trim();if(s!==i){let d=await pPe(e,i,s),l=d&&d>0?`${d} commit${d===1?" was":"s were"} added to the current branch after this checkpoint and would be removed by the restore`:"the current branch is no longer on the commit this checkpoint was created from (e.g. after a rebase or branch switch)";throw Error(`Cannot restore the workspace: ${l}. Restore the chat only, or move the branch back to ${i.slice(0,12)} manually (e.g. with git reset) before restoring the workspace.`)}if(r==="stash")await ot("git",["-C",e,"cat-file","-e",`${t.ref}^2^{commit}`],{windowsHide:!0});let a=await hPe(e,t.ref);if(await ot("git",["-C",e,"update-ref","-m","cline: checkpoint restore","HEAD",i,s],{windowsHide:!0}),await ot("git",["-C",e,"reset","--hard"],{windowsHide:!0}),a)await ot("git",["-C",e,"clean","-fd"],{windowsHide:!0});if(r==="commit")return;await ot("git",["-C",e,"stash","apply",t.ref],{windowsHide:!0})}class Fr extends Error{code;constructor(e,t){super(t);this.code=e;this.name="SessionVersioningError"}}function mPe(e){let t=e.sessionId.trim();if(!t)throw new Fr("invalid_restore","sessionId is required");if(!e.restoreMessages&&!e.restoreWorkspace)throw new Fr("invalid_restore","restore.messages or restore.workspace must be true");if(e.restoreMessages&&e.requiresStart)throw new Fr("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(e.checkpointRunCount)||e.checkpointRunCount<1)throw new Fr("invalid_restore","checkpointRunCount must be a positive integer");return t}class Dp{async restoreCheckpoint(e){let t=e.restore?.messages!==!1,n=e.restore?.workspace!==!1,r=Date.now(),o,i=(k,b)=>{e.telemetry?.capture({event:"checkpoint.restore",properties:{sessionId:e.sessionId,checkpointRunCount:e.checkpointRunCount,restoreWorkspace:n,restoreMessages:t,checkpointKind:o?.kind??"unknown",outcome:k,durationMs:Date.now()-r,...b}})},s,a,d;try{let k=mPe({sessionId:e.sessionId,restoreMessages:t,restoreWorkspace:n,requiresStart:e.start===void 0,checkpointRunCount:e.checkpointRunCount}),b=await e.getSession(k);if(!b)throw new Fr("session_not_found",`Session ${k} not found`);if(s=b,a=t?await e.readMessages(k):void 0,t&&a?.length===0)throw new Fr("session_messages_not_found",`No messages found for session ${k}`);d=K3({session:s,messages:a,checkpointRunCount:e.checkpointRunCount,cwd:e.cwd,restoreMessages:t}),o=d.checkpoint}catch(k){throw i("failed",{phase:"plan"}),k}let l=Fa({session:s,messages:a}),c,u=[],h,p;if(t){let{startSession:k,getStartedSessionId:b,cleanupStartedSession:v}=e;if(!e.start||!k||!b||!v)throw new Fr("invalid_restore","startSession, getStartedSessionId, and cleanupStartedSession are required when restore.messages is true");p={startSession:k,getStartedSessionId:b,cleanupStartedSession:v},c=j3(s,e.checkpointRunCount),u=e.restore?.omitCheckpointMessageFromSession?z3(a??[],e.checkpointRunCount):d.messages??[];let E={sourceSession:s,sourceMessages:a,sourceSnapshot:l,plan:d,restoredCheckpointMetadata:c,initialMessages:u,restoreMessages:t,restoreWorkspace:n,checkpointRunCount:e.checkpointRunCount};h=e.buildStartInput?await e.buildStartInput(E,e.start):e.start}let f=e.applyWorkspaceCheckpoint??G3,m=e.beginWorkspaceRestoreTransaction??(e.applyWorkspaceCheckpoint?void 0:H3),g=n&&m?await m(d.cwd):void 0,y=!1,w;try{if(n)await f(d.cwd,d.checkpoint);if(!p)return await g?.commit(),y=!0,i("success"),{checkpoint:d.checkpoint,sourceSnapshot:l};let k=await p.startSession(h);w={result:k,cleanup:p.cleanupStartedSession};let b=p.getStartedSessionId(k);if(!b)throw new Fr("invalid_restore","Restored session did not return a session id");await(e.retainCheckpointRefs??r3)(d.cwd,b,c?.history??[]);let v=e.readRestoredSession?await e.readRestoredSession(b):void 0,E=v?Fa({session:v,messages:u}):void 0;return await g?.commit(),y=!0,i("success"),{sessionId:b,startResult:k,messages:d.messages,checkpoint:d.checkpoint,sourceSnapshot:l,...E?{restoredSnapshot:E}:{}}}catch(k){let b=[];if(w)try{await w.cleanup(w.result)}catch(v){b.push(v)}if(g&&!y)try{await g.rollback()}catch(v){b.push(v)}if(i("failed",{workspaceRolledBack:!!g&&!y,recovered:b.length===0}),b.length>0)throw AggregateError([k,...b],"Checkpoint restore failed and recovery did not complete");throw k}}}import{appendFileSync as fPe}from"node:fs";import{join as gPe}from"node:path";import{resolveRootSessionId as V3}from"@cerebriline/shared";import{ensureHookLogDir as yPe}from"@cerebriline/shared/storage";import{z as II}from"zod";var wPe=II.looseObject({task:II.string().optional(),systemPrompt:II.string().optional()});class Db{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(e,t,n,r){this.adapter=e;this.manifestStore=t;this.toPersistedMessages=n;this.heartbeatLogIntervalMs=r}teamTaskQueueKey(e,t){return`${e}::${t}`}activeTeamTaskSessionId(e,t){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(e,t))?.at(-1)}buildSubsessionRow(e,t){let n=di(e.metadata);return{sessionId:t.sessionId,source:e.source,pid:e.pid,startedAt:t.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:e.provider,model:e.model,cwd:e.cwd,workspaceRoot:e.workspaceRoot,teamName:e.teamName??null,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,parentSessionId:t.parentSessionId,parentAgentId:t.parentAgentId,agentId:t.agentId,conversationId:t.conversationId??null,isSubagent:!0,prompt:t.prompt,metadata:fp({metadata:Gn(void 0,{mode:t.mode,version:n?.version}),prompt:t.prompt}),hookPath:"",messagesPath:t.messagesPath,updatedAt:t.startedAt}}async queueSpawnRequest(e){if(e.hookName!=="tool_call"||e.parent_agent_id!==null)return;if(e.tool_call?.name!=="spawn_agent")return;let t=V3(e.sessionContext);if(!t)return;let n=wPe.safeParse(e.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:t,parentAgentId:e.agent_id,task:n.success?n.data.task:void 0,systemPrompt:n.success?n.data.systemPrompt:void 0})}async upsertSubagentSession(e){let t=e.rootSessionId;if(!t)return;let n=await this.adapter.getSession(t);if(!n)return;let r=SR(t,e.agentId),o=await this.adapter.getSession(r),i=ft(),s=this.manifestStore.artifacts.subagentArtifactPaths(r,e.agentId,this.activeTeamTaskSessionId(t,e.parentAgentId)),a=e.prompt??o?.prompt??void 0;if(!a)a=await this.adapter.claimSpawnRequest(t,e.parentAgentId)??`Subagent run by ${e.parentAgentId}`;if(!o){let d=this.buildSubsessionRow(n,{sessionId:r,mode:"subagent",parentSessionId:t,parentAgentId:e.parentAgentId,agentId:e.agentId,conversationId:e.conversationId,prompt:a,startedAt:i,...s});return await this.adapter.upsertSession(d),this.manifestStore.initializeMessagesFile(d,s.messagesPath,i),r}return await this.adapter.updateSession({sessionId:r,setRunning:!0,parentSessionId:t,parentAgentId:e.parentAgentId,agentId:e.agentId,conversationId:e.conversationId,prompt:o.prompt??a??null,metadata:fp({metadata:Gn(o.metadata,{mode:"subagent",version:di(n.metadata)?.version}),prompt:o.prompt??a??null}),expectedStatusLock:o.statusLock}),r}async upsertSubagentSessionFromHook(e){if(!e.parent_agent_id)return;let t=V3(e.sessionContext);if(!t)return;if(e.hookName==="session_shutdown"){let n=SR(t,e.agent_id);return await this.adapter.getSession(n)?n:void 0}return await this.upsertSubagentSession({agentId:e.agent_id,parentAgentId:e.parent_agent_id,conversationId:e.taskId,rootSessionId:t})}async applySubagentStatus(e,t){await this.applySubagentStatusBySessionId(e,AK(t))}async applySubagentStatusBySessionId(e,t){let n=await this.adapter.getSession(e);if(!n)return;let r=Kt(t)?null:ft(),o=Kt(t)?null:t==="failed"?1:0;await this.adapter.updateSession({sessionId:e,status:t,endedAt:r,exitCode:o,expectedStatusLock:n.statusLock})}async applyStatusToRunningChildSessions(e,t){if(!e)return;let n=await this.adapter.listSessions({limit:2000,parentSessionId:e,status:"running"});for(let r of n)await this.applySubagentStatusBySessionId(r.sessionId,t)}async onTeamTaskStart(e,t,n){let r=await this.adapter.getSession(e);if(!r)return;let o=EK(e,t),i=ft(),{messagesPath:s}=this.manifestStore.artifacts.subagentArtifactPaths(o,t),a=this.buildSubsessionRow(r,{sessionId:o,mode:"team",parentSessionId:e,parentAgentId:"lead",agentId:t,prompt:n||`Team task for ${t}`,startedAt:i,messagesPath:s});await this.adapter.upsertSession(a),this.manifestStore.initializeMessagesFile(a,s,i);let d=this.teamTaskQueueKey(e,t),l=this.teamTaskSessionsByAgent.get(d)??[];l.push(o),this.teamTaskSessionsByAgent.set(d,l)}async onTeamTaskEnd(e,t,n,r,o,i){let s=this.teamTaskQueueKey(e,t),a=this.teamTaskSessionsByAgent.get(s);if(!a||a.length===0)return;let d=a.shift();if(a.length===0)this.teamTaskSessionsByAgent.delete(s);if(!d)return;let l=o?.messages??i,c=this.toPersistedMessages(l,o,i);if(c)await this.manifestStore.persistSessionMessages(d,c);await this.applySubagentStatusBySessionId(d,n),this.teamTaskLastHeartbeatBySession.delete(d),this.teamTaskLastProgressLineBySession.delete(d)}async onTeamTaskProgress(e,t,n,r){let o=this.teamTaskQueueKey(e,t),i=this.teamTaskSessionsByAgent.get(o)?.[0];if(!i)return;let s=n.trim();if(!s)return;let a=r?.kind??"progress";if(a==="heartbeat"){let l=Date.now(),c=this.teamTaskLastHeartbeatBySession.get(i)??0;if(l-c<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(i,l)}let d=a==="heartbeat"?"[progress] heartbeat":a==="text"?`[progress] text: ${s}`:`[progress] ${s}`;if(this.teamTaskLastProgressLineBySession.get(i)===d)return;this.teamTaskLastProgressLineBySession.set(i,d)}async handleSubAgentStart(e,t){let n=await this.upsertSubagentSession({agentId:t.subAgentId,parentAgentId:t.parentAgentId,conversationId:t.conversationId,prompt:t.input.task,rootSessionId:e});if(!n)return;await this.applySubagentStatusBySessionId(n,"running")}async handleSubAgentEnd(e,t){let n=await this.upsertSubagentSession({agentId:t.subAgentId,parentAgentId:t.parentAgentId,conversationId:t.conversationId,prompt:t.input.task,rootSessionId:e});if(!n)return;let r=this.toPersistedMessages(t.agentResult?.messages,t.agentResult?.usage?t.agentResult:void 0);if(r)await this.manifestStore.persistSessionMessages(n,r);if(t.error||t.agentResult?.finishReason==="error"){await this.applySubagentStatusBySessionId(n,"failed");return}let o=t.result?.finishReason??t.agentResult?.finishReason??"completed";await this.applySubagentStatusBySessionId(n,o==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(e){let n=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??gPe(yPe(),"hooks.jsonl");fPe(n,`${JSON.stringify({ts:ft(),...e})}
1004
- `,"utf8")}}import{formatUserInputBlock as zPe}from"@cerebriline/shared";import{probeServerHealth as bPe,serverRoot as vPe}from"@cerebriline/llms";function kPe(e,t,n){if(typeof n!=="number"||!Number.isFinite(n))return e;let r=e.providerConfig??t;return{...e,providerConfig:{...r??{},agentWindow:{sharePercent:n}}}}var Y3="polykv-lead",X3="Model (PolyKV)",J3="primary",TPe=new Set(["opencoti","xollama"]);function CI(e){let t=(e.agentNodes??[]).filter((r)=>!r.polykvLead);if(e.polykvAgentsPriorityZero!==!0||!TPe.has(e.providerId.trim().toLowerCase()))return[...t];let n=t.length>0?t:[{id:J3,priority:Ml+1,capacity:typeof e.overflowCapacity==="number"&&e.overflowCapacity>0?e.overflowCapacity:Number.POSITIVE_INFINITY,pacedAdmission:!0,label:"Node1",connection:{}}];return[{id:Y3,priority:Ml,capacity:sE,label:X3,connection:{thinking:void 0,reasoningEffort:void 0,thinkingBudgetTokens:void 0,maxTokensPerTurn:void 0,temperature:void 0,...e.lead,providerId:e.providerId,modelId:e.modelId},polykvLead:!0},...n]}function PI(e){if(e.nodes.length===0)return;let t=cE(e.nodes.map((i)=>$h({id:i.id,priority:i.polykvLead?Ml:Math.max(i.priority,Ml+1),capacity:i.capacity,...i.pacedAdmission?{pacedAdmission:!0}:{}})),{probe:async(i)=>{let s=(n.get(i)??e.base).getConnectionConfig(),a=vPe(s.baseUrl);return a?await bPe(a,{...s.headers?{headers:s.headers}:{}}):!1}}),n=new Map;for(let i of e.nodes){let s=e.base.getRuntimeConfig(),a=kPe(i.connection,s.providerConfig,i.windowShare);n.set(i.id,oi({...s,...a,...i.polykvLead&&s.sessionId?{polykvLeadOwner:s.sessionId}:{}},Object.keys(a)))}let r=new Map(e.nodes.flatMap((i)=>i.label?[[i.id,i.label]]:[])),o=(i)=>{let s=n.get(i.nodeId)??e.base,a=r.get(i.nodeId);return{nodeId:i.nodeId,...a?{nodeLabel:a}:{},configProvider:s,run:async(d)=>await d(),release:()=>i.release(),admitted:()=>i.admitted(),refused:(d)=>i.refused(d),markUnreachable:(d)=>t.markUnreachable(i.nodeId,d)}};return{place:async(i,s)=>o(await t.acquire(i,s)),base:e.base,occupancy:()=>t.occupancy(),hasRoomElsewhere:(i)=>t.hasRoomElsewhere(i),get waiting(){return t.waiting},describe:()=>{let i=new Map(t.nodeStates().map((s)=>[s.nodeId,s]));return e.nodes.map((s)=>{let a=(n.get(s.id)??e.base).getConnectionConfig(),d=i.get(s.id);return{nodeId:s.id,...s.label?{label:s.label}:{},priority:s.priority,providerId:a.providerId,modelId:a.modelId,...a.baseUrl?{baseUrl:a.baseUrl}:{},...a.providerConfig?{providerConfig:a.providerConfig}:{},capacity:d?.capacity??s.capacity,running:d?.running??0,...d?.downUntil?{downUntil:d.downUntil}:{},...d?.heldUntil?{heldUntil:d.heldUntil}:{}}})}}}import{existsSync as SPe,readdirSync as xPe,readFileSync as _Pe}from"node:fs";import{basename as Q3,extname as EPe,join as APe}from"node:path";import{stripUtf8Bom as RPe}from"@cerebriline/shared";import{resolveAgentConfigSearchPaths as IPe}from"@cerebriline/shared/storage";import e6 from"yaml";import{z as vn}from"zod";var t6=vn.object({name:vn.string().trim().min(1),description:vn.string().trim().min(1),tools:vn.union([vn.string(),vn.array(vn.string())]).optional(),skills:vn.union([vn.string(),vn.array(vn.string())]).optional(),providerId:vn.string().trim().min(1).optional(),modelId:vn.string().trim().min(1).optional(),profile:vn.string().trim().min(1).optional(),maxIterations:vn.number().int().positive().optional()});function CPe(e){e=RPe(e);let t=e.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!t)throw Error("Missing YAML frontmatter block in agent config file.");let n=t[0].length,r=/^---[^\S\r\n]*(?:\r?\n|$)/gm;r.lastIndex=n;let o,i=Array.from(e.matchAll(r)).filter((s)=>s.index>=n);for(let s of i){let a=s.index,d=e.slice(n,a);try{let l=e6.parse(d);if(!l||typeof l!=="object"||Array.isArray(l))continue;t6.parse(l);let c=e.slice(a+s[0].length);o={frontmatter:d,body:c}}catch{}}if(o)return o;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function Z3(e){if(e===void 0)return;let t=Array.isArray(e)?e:e.split(",");return Array.from(new Set(t.map((n)=>n.trim()).filter((n)=>n.length>0)))}function PPe(e){return e.trim().toLowerCase()}function MPe(e){let t=EPe(e).toLowerCase();return t===".md"||t===".markdown"||t===".yml"||t===".yaml"}function n6(e,t={}){let{frontmatter:n,body:r}=CPe(e),o=e6.parse(n);if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Agent config frontmatter must be a YAML mapping.");let i=t6.parse(o),s=r.trim();if(!s)throw Error("Missing system prompt body in agent config file.");return{name:i.name,description:i.description,tools:Z3(i.tools),skills:Z3(i.skills),providerId:i.providerId,modelId:i.modelId,profile:i.profile,maxIterations:i.maxIterations,systemPrompt:s,path:t.path}}function MI(e){let t=e.searchPaths??IPe(e.workspaceRoot),n=new Map,r=[];for(let i of t.filter(Boolean)){if(!SPe(i))continue;let s;try{s=xPe(i,{withFileTypes:!0})}catch(a){r.push({path:i,error:a instanceof Error?a:Error(String(a))});continue}for(let a of s){if(!a.isFile()||!MPe(a.name))continue;let d=APe(i,a.name);try{let l=_Pe(d,"utf8"),c=n6(l,{path:d}),u=PPe(c.name);if(!n.has(u))n.set(u,c)}catch(l){r.push({path:d,error:l instanceof Error?l:Error(String(l))})}}}return{configs:Array.from(n.values()).sort((i,s)=>(i.path?Q3(i.path):i.name).localeCompare(s.path?Q3(s.path):s.name)),errors:r,searchPaths:t.filter(Boolean)}}import{TeamMessageType as Me}from"@cerebriline/shared";function pi(e){let t=e.type;switch(t){case Me.AgentEvent:return!1;case Me.RunProgress:return o6(e);case Me.TaskStart:case Me.TaskEnd:case Me.TeammateSpawned:case Me.TeammateShutdown:case Me.TeamTaskUpdated:case Me.TeamMessage:case Me.TeamMissionLog:case Me.RunQueued:case Me.RunStarted:case Me.RunCompleted:case Me.RunFailed:case Me.RunCancelled:case Me.RunInterrupted:case Me.OutcomeCreated:case Me.OutcomeFragmentAttached:case Me.OutcomeFragmentReviewed:case Me.OutcomeFinalized:case Me.TeamCleaned:return!0;default:return Boolean(t)}}function NI(e){switch(e.type){case Me.TeammateSpawned:case Me.TeammateShutdown:case Me.RunCompleted:case Me.RunFailed:case Me.RunCancelled:case Me.RunInterrupted:case Me.TeamCleaned:return!0;case Me.RunProgress:return o6(e);default:return!1}}function o6(e){return e.type===Me.RunProgress&&e.run.status==="queued"}var LI=Number.POSITIVE_INFINITY;function r6(e){return typeof e==="object"&&e!==null}function $b(e,t=0){return typeof e==="number"&&Number.isFinite(e)?e:t}function OI(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function OPe(e){return e.length>LI?`${e.slice(0,LI-3)}...`:e}function Ao(e){if(!r6(e))return;let t=r6(e.usage)?e.usage:{},n=e.finishReason;return{text:OPe(typeof e.text==="string"?e.text:""),iterations:$b(e.iterations),finishReason:typeof n==="string"?n:"completed",durationMs:$b(e.durationMs),usage:{inputTokens:$b(t.inputTokens),outputTokens:$b(t.outputTokens),cacheReadTokens:OI(t.cacheReadTokens),cacheWriteTokens:OI(t.cacheWriteTokens),totalCost:OI(t.totalCost)}}}function LPe(e){if(e.result===void 0)return e;return{...e,result:Ao(e.result)}}function is(e){switch(e.type){case Me.TaskEnd:{let{messages:t,result:n,error:r,...o}=e;return{...o,result:Ao(n),error:r?{message:r.message}:void 0}}case Me.RunQueued:case Me.RunStarted:case Me.RunCompleted:case Me.RunFailed:case Me.RunCancelled:case Me.RunInterrupted:return{...e,run:LPe(e.run)};default:return e}}function Ro(){return new Date().toISOString()}function i6(e,t){if(t<=0)return 0;return Math.round(e/t*100)}function NPe(e,t){let n=new Set;for(let o of t)if(o.status==="reviewed")n.add(`${o.outcomeId}:${o.section}`);let r=new Set;for(let o of e){if(o.status==="finalized")continue;for(let i of o.requiredSections)if(!n.has(`${o.id}:${i}`))r.add(`${o.id}:${i}`)}return[...r].sort((o,i)=>o.localeCompare(i))}function DI(e,t){let n={idle:0,running:0,stopped:0},r={pending:0,in_progress:0,blocked:0,completed:0},o={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},i={draft:0,in_review:0,finalized:0},s={draft:0,reviewed:0,rejected:0},a=0,d=0;for(let g of t.members)if(n[g.status]+=1,g.role==="lead")a+=1;else d+=1;let l=[],c=[],u=t.tasks.filter((g)=>g.status==="completed").length,h=new Map(t.tasks.map((g)=>[g.id,g]));for(let g of t.tasks){if(r[g.status]+=1,g.status==="blocked"){l.push(g.id);continue}if(g.status!=="pending")continue;if(g.dependsOn.every((w)=>h.get(w)?.status==="completed"))c.push(g.id)}let p=[],f,m=0;for(let g of t.runs){if(o[g.status]+=1,g.status==="queued"||g.status==="running")p.push(g.id);let y=g.startedAt.getTime();if(y>=m)m=y,f=g.id}for(let g of t.outcomes)i[g.status]+=1;for(let g of t.outcomeFragments)s[g.status]+=1;return{teamName:e,updatedAt:Ro(),members:{total:t.members.length,byStatus:n,leadCount:a,teammateCount:d},tasks:{total:t.tasks.length,byStatus:r,blockedTaskIds:l,readyTaskIds:c,completionPct:i6(u,t.tasks.length)},runs:{total:t.runs.length,byStatus:o,activeRunIds:p,latestRunId:f},outcomes:{total:t.outcomes.length,byStatus:i,finalizedPct:i6(i.finalized,t.outcomes.length),missingRequiredSections:NPe(t.outcomes,t.outcomeFragments)},fragments:{total:t.outcomeFragments.length,byStatus:s}}}function $I(e){let{event:t}=e;switch(t.type){case"team_task_updated":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),taskId:t.task.id,agentId:t.task.assignee??t.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.run.error};case"run_progress":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.message};case"outcome_created":case"outcome_finalized":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),outcomeId:t.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),outcomeId:t.fragment.outcomeId,fragmentId:t.fragment.id,agentId:t.fragment.sourceAgentId};case"team_message":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),taskId:t.message.taskId,agentId:t.message.fromAgentId,message:t.message.subject};case"team_mission_log":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),taskId:t.entry.taskId,agentId:t.entry.agentId,message:t.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),agentId:t.agentId}}return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro()}}import{clearPolykvGrantedWindow as s6,releasePolykvAgent as FI}from"@cerebriline/llms";import{sanitizeFileName as DPe,TeamMessageType as xe}from"@cerebriline/shared";import{nanoid as $Pe}from"nanoid";import{TeamMessageType as Yrt}from"@cerebriline/shared";function Fb(){return{reset:!1,tasks:new Set,mailbox:new Set,missionLog:new Set,runs:new Set,outcomes:new Set,outcomeFragments:new Set}}function Fp(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError")return!0;if(!(e instanceof Error))return!1;return e.name==="AbortError"||e.message.toLowerCase().includes("aborted")}function UI(e){let t=Error(e);return t.name="AbortError",t}function FPe(e){return`[The lead requeued you${e?` (${e})`:""}: your engine session was given back and booked again. Your work so far is above. Carry on with your task from where you stopped.]`}function BI(e){return`Teammate "${e}" was shut down and takes no more tasks. To give it work, spawn it again with team_spawn_teammate under the same agentId.`}function a6(e,t){return e?.abortRequested===!0||e?.status==="stopped"&&Fp(t)}function UPe(e){if(e.finishReason==="aborted")return"cancelled";if(e.finishReason==="error"||e.finishReason==="max_iterations")return"failed";return"completed"}var BPe=600000,d6="recovered_queued";function HPe(e){return`This is an automatic recovery of interrupted team run ${e.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
1003
+ `).filter(Boolean);await Promise.allSettled(o.map((i)=>bn(e,["update-ref","-d",i])))}catch{}}async function r3(e,t,n){if(!e||n.length===0)return;await Promise.allSettled(n.map((r)=>bn(e,["update-ref",`refs/cline/checkpoints/${t}/${r.runCount}`,r.ref])))}function FIe(e,t){let n=e.findIndex((r)=>r.runCount===t.runCount);if(n<0)return[...e,t];return e.map((r,o)=>o===n?t:r)}function o3(e){OIe();let t,n,r=async()=>{if(t===!0)return!0;try{t=(await bn(e.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{t=!1}return t},o=async(i)=>{if(e.createCheckpoint)return await e.createCheckpoint({cwd:e.cwd,sessionId:e.sessionId,runCount:i});if(!await r())return;let s=Date.now(),a=(h)=>{e.telemetry?.capture({event:"checkpoint.snapshot",properties:{sessionId:e.sessionId,runCount:i,outcome:h,durationMs:Date.now()-s}})},d=async(h)=>{try{let f=(await bn(e.cwd,["rev-parse","HEAD"])).stdout.trim();if(!f)return;return{ref:f,createdAt:Date.now(),runCount:i,kind:"commit"}}catch(p){bI(e.logger,`${h}: ${p instanceof Error?p.message:String(p)}`);return}},l=`${ZG}${e.sessionId} run=${i}`,c="";try{c=await $Ie(e.cwd,n3(e.cwd,e.sessionId),l)??""}catch(h){bI(e.logger,`Checkpoint snapshot failed after ${Date.now()-s}ms: ${h instanceof Error?h.message:String(h)}`);let p=await d("Checkpoint HEAD fallback failed");return a(p?"head_fallback":"skipped"),p}if(!c){let h=await d("Checkpoint HEAD fallback failed");return a(h?"head_clean":"skipped"),h}let u=`refs/cline/checkpoints/${e.sessionId}/${i}`;try{await bn(e.cwd,["update-ref",u,c])}catch(h){bI(e.logger,`Checkpoint store failed: ${h instanceof Error?h.message:String(h)}`),a("skipped");return}return a("stash"),{ref:c,createdAt:Date.now(),runCount:i,kind:"stash"}};return{beforeRun:async({snapshot:i})=>{if(i.parentAgentId==null)n=i.messages.length;return},beforeModel:async({snapshot:i})=>{if(i.parentAgentId!=null||i.iteration!==1)return;let s=i.messages.slice(n??Math.max(0,i.messages.length-1));n=void 0;let a=bu(i.messages);if(a<1)return;let d=await e.readSessionMetadata(),l=LIe(d),c=bu(s)>=1,u=l?.history.some((f)=>f.runCount===a)??!1;if(!c&&u)return;let h=await o(a);if(!h)return;if(l?.latest.ref===h.ref)return;let p=FIe(l?.history??[],h);await e.writeSessionMetadata({...d??{},checkpoint:{latest:h,history:p}});return}}}function kc(...e){let t,n,r;for(let i of e){if(!i)continue;if(i.toolExecutors)t={...t??{},...i.toolExecutors};if(i.requestToolApproval)n=i.requestToolApproval;if(i.readReceipts)r=i.readReceipts}let o=t&&Object.keys(t).length>0;if(!o&&!n&&!r)return;return{...o?{toolExecutors:t}:{},...n?{requestToolApproval:n}:{},...r?{readReceipts:r}:{}}}import*as fr from"@cerebriline/llms";import{isOllamaNativeProvider as i3,resolveOutputBudgetTokens as UIe}from"@cerebriline/shared";function BIe(e){if(i3(e))return"ollama";return e==="opencoti"||e==="openai-compatible"?"llamacpp":void 0}var Da=(e)=>typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0;function s3(e){let t=Da(e.configuredNumPredict)??Da(e.maxTokensPerTurn)??(e.outputBudget?.mode==="manual"?Da(e.outputBudget.maxTokens):void 0);if(t!==void 0)return Math.floor(t);return UIe({mode:e.outputBudget?.mode??"auto",maxTokens:e.outputBudget?.maxTokens,contextWindow:e.contextWindow,modelMaxOutputTokens:Da(e.modelMaxOutputTokens)})??fr.resolveDefaultMaxOutputTokens({contextWindow:Da(e.contextWindow),maxOutputTokens:Da(e.modelMaxOutputTokens)})}async function a3(e){let t=BIe(e.providerId);if(!t||e.thinking===!1||!e.modelId)return;let n=Da(e.configuredNumPredict)??e.outputCap;if(t==="llamacpp"){let i=e.configuredThinkBudget?.trim()||e.reasoningEffort?.trim();if(!i)return;let s=fr.resolveLlamaCppThinkBudgetTokens(i,fr.resolveLlamaCppThinkBudgetWindow(e.contextWindow,n));return s===void 0?void 0:{level:i,budgetTokens:s}}let r=fr.resolveOllamaThinking({effort:e.reasoningEffort,sampling:{thinkBudget:e.configuredThinkBudget,reasoningLevel:e.configuredReasoningLevel}}),o={...typeof r.think==="string"?{think:r.think}:{},...r.thinkBudget?{thinkBudget:r.thinkBudget}:{},numPredict:n,numCtx:e.contextWindow};return e.probeOllama?e.probeOllama(e.baseUrl,e.modelId,o):fr.probeOllamaThinkBudget(e.baseUrl,e.modelId,o,e.fetchImpl)}function d3(e){let t=e.configuredMessage?.trim();if(t)return t;return i3(e.providerId)?fr.readDeclaredThinkBudgetMessage(e.baseUrl,e.modelId):void 0}var HIe=/(api[-_]?key|token|secret|password|authorization|credential|cookie)/i,WIe=new Set(["knownModels","extensionContext","logger","telemetry","hooks","extensions","tools","systemPrompt","providerConfig","workspaceMetadata"]);function Tc(e,t="",n=0){if(e===null||e===void 0)return;if(typeof e==="function"||typeof e==="symbol")return;if(typeof e==="string")return t&&HIe.test(t)&&e?"[set]":e;if(typeof e!=="object")return e;if(n>=6)return;if(Array.isArray(e))return e.map((i)=>Tc(i,t,n+1)).filter((i)=>i!==void 0);let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)return;let o={};for(let[i,s]of Object.entries(e)){if(WIe.has(i))continue;let a=t==="headers"&&typeof s==="string"&&s?"[set]":Tc(s,i,n+1);if(a!==void 0)o[i]=a}return o}var jIe=new Set(["fetch","headers","knownModels","extensionContext","providerId","modelId"]);function l3(e,t){let n=e,r=t,o=[];for(let i of new Set([...Object.keys(n),...Object.keys(r)])){if(jIe.has(i)||typeof n[i]==="function")continue;if(JSON.stringify(n[i]??null)!==JSON.stringify(r[i]??null))o.push(i)}return o.sort()}function Eo(e){let t=e?.trim();return t?t:void 0}function qIe(e){let t=e.client,n=_K(t)??Eo(e.source),r=Eo(t.version),o=Eo(t.platform)??Eo(t.name),i=Eo(t.platformVersion)??r,s={cline_type:n,extension_version:r,platform:o,platform_version:i};if(e.user?.accountId===void 0)return s;let a=typeof e.user.accountId==="string"?Eo(e.user.accountId):void 0;return{...s,distinct_id:a??Eo(e.user.distinctId),user_id:a,account_id:a,account_email:a?Eo(e.user.email):void 0,organization_id:a?Eo(e.user.organizationId):void 0}}function SI(e,t){let n={},r={},o,i=(s)=>({...t,...r,...n,...s,...o?{distinct_id:o}:{}});return{setDistinctId(s){o=Eo(s)},setMetadata(s){n={...s}},updateMetadata(s){n={...n,...s}},setCommonProperties(s){r={...s}},updateCommonProperties(s){r={...r,...s}},isEnabled:()=>e.isEnabled(),capture:(s)=>e.capture({event:s.event,properties:i(s.properties)}),captureRequired:(s,a)=>e.captureRequired(s,i(a)),recordCounter:(s,a,d,l,c)=>e.recordCounter(s,a,i(d),l,c),recordHistogram:(s,a,d,l,c)=>e.recordHistogram(s,a,i(d),l,c),recordGauge:(s,a,d,l,c)=>e.recordGauge(s,a,i(d),l,c),flush:()=>e.flush(),dispose:async()=>{}}}function c3(e,t){return SI(e,qIe(t))}import{upsertWorkspaceInfo as eCe,WorkspaceManifestSchema as EI}from"@cerebriline/shared";import{execFile as zIe}from"node:child_process";import{basename as KIe,resolve as GIe}from"node:path";import{performance as u3}from"node:perf_hooks";import{promisify as VIe}from"node:util";import{processWorkspaceInfo as m3}from"@cerebriline/shared";import h3 from"simple-git";var YIe=VIe(zIe);function XIe(e,t){return YIe("git",e,{cwd:t.cwd,encoding:"utf8",windowsHide:!0,signal:t.signal,timeout:15000,maxBuffer:10485760,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||"ssh -o BatchMode=yes"}})}function JIe(e){if(!e||typeof e!=="object"||!("stderr"in e))return"";return typeof e.stderr==="string"?e.stderr.trim():""}function QIe(e){if(!e||typeof e!=="object"||!("code"in e))return;return typeof e.code==="number"?e.code:void 0}function f3(e){let t=Sc(e.cwd),n=e.git??XIe,r=async(i)=>(await n(i,{cwd:t,signal:e.signal})).stdout,o=async(i)=>(await r(i)).trim();return{async isInsideWorkTree(){try{return await o(["rev-parse","--is-inside-work-tree"])==="true"}catch(i){if(QIe(i)===128&&/not a git repository|Kein Git-Repository/i.test(JIe(i)))return!1;throw i}},remotes:()=>h3({baseDir:t}).getRemotes(!0),displayBranch:async()=>(await h3({baseDir:t}).branch()).current.trim(),symbolicBranch:()=>o(["symbolic-ref","--quiet","--short","HEAD"]),headSha:()=>o(["rev-parse","HEAD"]),workspacePrefix:async()=>(await r(["rev-parse","--show-prefix"])).replace(/[\r\n]+$/,""),worktreeStatus:()=>o(["status","--porcelain=v1","--untracked-files=all","--ignore-submodules=none"]),branchRemote:(i)=>o(["config","--get",`branch.${i}.remote`]),branchMergeRef:(i)=>o(["config","--get",`branch.${i}.merge`]),remoteUrl:(i)=>o(["remote","get-url",i]),remoteRefs:(i,s)=>o(["ls-remote","--exit-code",i,s])}}function ZIe(e){let t=e?.git;if(!t||typeof t!=="object"||Array.isArray(t))return{};let n=t;return{...typeof n.url==="string"&&n.url.trim()?{url:n.url.trim()}:{},...typeof n.branch==="string"&&n.branch.trim()?{branch:n.branch.trim()}:{}}}function xI(e,t){let n={...e??{}};if(!t.url&&!t.branch)return delete n.git,Object.keys(n).length>0?n:void 0;let o={...n.git&&typeof n.git==="object"&&!Array.isArray(n.git)?n.git:{}};if(t.url)o.url=t.url;else delete o.url;if(t.branch)o.branch=t.branch;else delete o.branch;return n.git=o,n}function g3(e,t){let n=ZIe(e);return n.url===t.url&&n.branch===t.branch}function y3(e){let t=e.find(({name:n})=>n==="origin")??e[0];return(t?.refs.fetch||t?.refs.push)?.trim()||void 0}function Sc(e){return GIe(e)}async function _I(e){return(await w3(e)).info}function p3(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(t)}function Mb(e){if(e instanceof Error)return{errorType:e.name?.trim()||e.constructor.name||"Error",message:e.message};return{errorType:"Error",message:String(e)}}async function w3(e){let t=Sc(e),n={rootPath:t,hint:KIe(t)||void 0},r={},o;try{let i=f3({cwd:t});if(!await i.isInsideWorkTree())return{info:n,vcsType:"none",gitState:r};try{let a=await i.remotes();if(a.length>0){let d=a.map((c)=>{let u=c.refs.fetch||c.refs.push;return`${c.name}: ${u}`});n.associatedRemoteUrls=d;let l=y3(a);if(l)r.url=l}}catch(a){o??=Mb(a)}try{let a=await i.headSha();if(a.length>0)n.latestGitCommitHash=a}catch(a){if(!p3(a))o??=Mb(a)}try{let a=await i.displayBranch();if(a.length>0)n.latestGitBranchName=a,r.branch=a}catch(a){if(!p3(a))o??=Mb(a)}return{info:n,vcsType:"git",gitState:r,error:o}}catch(i){return{info:n,vcsType:"none",gitState:r,error:Mb(i)}}}async function b3(e){try{let t=f3({cwd:e});if(!await t.isInsideWorkTree())return{};let[n,r]=await Promise.all([t.remotes(),t.displayBranch()]),o=y3(n);return{...o?{url:o}:{},...r?{branch:r}:{}}}catch{return}}async function v3(e){let t=await _I(e);return m3(t)}async function k3(e){let t=u3.now(),n=await w3(e),r=u3.now()-t,o=n.info;return{workspaceInfo:o,workspaceMetadata:m3(o),durationMs:r,vcsType:n.vcsType,gitState:n.gitState,initError:n.error}}class AI{manifest;listeners=new Set;constructor(e){this.manifest=EI.parse(e??{workspaces:{}})}async addWorkspacePath(e){let t=await _I(e);return this.manifest=eCe(this.manifest,t),this.emit({type:"workspace_added",workspace:t}),t}async switchWorkspace(e){let t=Sc(e),n=this.manifest.workspaces[t];if(n)return this.manifest=EI.parse({...this.manifest,currentWorkspacePath:t}),this.emit({type:"workspace_switched",workspace:n}),n;let r=await this.addWorkspacePath(t);return this.manifest=EI.parse({...this.manifest,currentWorkspacePath:r.rootPath}),this.emit({type:"workspace_switched",workspace:r}),r}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getCurrentWorkspace(){let e=this.manifest.currentWorkspacePath;if(!e)return;return this.manifest.workspaces[e]}getWorkspace(e){let t=Sc(e);return this.manifest.workspaces[t]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit(e){for(let t of this.listeners)t(e)}}import{createHash as tCe}from"node:crypto";var T3=new Set,S3=new Set;function nCe(e,t){return tCe("sha256").update(e).update("\x00").update(t?.trim()??"").digest("hex")}function rCe(e){if(e.vcsTypes&&e.vcsTypes.length>0)return e.vcsTypes;return[e.vcsType==="git"?"git":"none"]}function x3(e){if(!e.telemetry)return;let t=nCe(e.rootPath,e.dedupeScope),n=e.rootCount??1;if(!T3.has(t))T3.add(t),uM(e.telemetry,{root_count:n,vcs_types:rCe(e),init_duration_ms:e.durationMs,feature_flag_enabled:e.featureFlagEnabled??!0,is_remote_workspace:e.isRemoteWorkspace});if(e.initError&&!S3.has(t)){S3.add(t);let r=Error(e.initError.message);r.name=e.initError.errorType||"Error",hM(e.telemetry,r,{fallback_to_single_root:!0,workspace_count:n})}}function wCe(e){return`${e.pluginName??e.pluginPath}: ${e.message}`}function bCe(e,t,n){if(t.length>0)for(let i of t)n?.log(i.message,{severity:"warn"});if(e.length===0)return;let r=e.slice(0,3).map(wCe).join("; "),o=e.length>3?`; and ${e.length-3} more`:"";n?.log(`Some plugins failed to initialize. ${r}${o}. Use --verbose for more details.`,{severity:"warn"});for(let i of e)n?.log(`Plugin initialization failed (${i.phase}) for ${i.pluginPath}`,{severity:"warn",stack:i.stack,pluginPath:i.pluginPath,pluginName:i.pluginName})}function vCe(e,t){for(let n of e){let r=n.componentName?` (${n.componentName})`:"";t?.log(`[agent-plugins] ${n.pluginName??n.pluginPath}${r}: ${n.message}`,{severity:n.level==="warning"?"warn":"error"})}}function kCe(e){let t=e?.["X-CLIENT-TYPE"]?.trim();if(!t)return;let n=e?.["X-CLIENT-VERSION"]?.trim();return{name:t,...n?{version:n}:{}}}function TCe(e,t){let n=typeof e.thinking==="boolean",r=typeof e.reasoningEffort==="string";if(!n&&!r)return t;return{...t??{},...n?{enabled:e.thinking}:{},...r?{effort:e.reasoningEffort}:{}}}function Ob(e,t){return pCe(e,t)}function SCe(e,t,n){if(e.systemPrompt?.trim())return e.systemPrompt;return hCe({ide:"Terminal Shell",workspaceRoot:t.rootPath,workspaceName:t.hint,metadata:n,rules:e.rules,mode:e.mode,providerId:e.providerId,platform:process.platform||"unknown"})}function xCe(e,t){return e.storedProviderSettings==="ignore"?void 0:t.getProviderSettings(e.providerId)}function E3(e,t,n,r,o,i){let s=o||r?.modelCatalog?{...o??{},...r?.modelCatalog??{}}:void 0,a=e.providerConfig?.providerId===e.providerId?e.providerConfig:void 0,d=St(e.contextWindow),l=uCe({providerId:e.providerId,sessionId:t,source:n,defaultSource:Gt.CLI,client:{name:e.extensionContext?.client?.name,version:e.extensionContext?.client?.version,versionHeaderFallback:e.headers?.["X-CLIENT-VERSION"],platform:e.extensionContext?.client?.platform,platformVersion:e.extensionContext?.client?.platformVersion,isMultiRoot:e.extensionContext?.client?.isMultiRoot},coreVersion:tc,openAiCodex:{accountId:a?.accountId??r?.auth?.accountId,accessToken:a?.accessToken??e.apiKey??r?.auth?.accessToken??r?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:r?.headers,config:e.headers,session:a?.headers}}),c={...r??{},provider:e.providerId,model:e.modelId,apiKey:e.apiKey??r?.apiKey,baseUrl:e.baseUrl??r?.baseUrl,headers:void 0,reasoning:TCe(e,r?.reasoning),modelCatalog:s,...d!==void 0?{contextWindow:d}:{}},u={...La(c),...a??{}};if(l)u.headers=l;if(e.knownModels)u.knownModels=e.knownModels;if(d!==void 0)u.knownModels={...u.knownModels??{},[e.modelId]:{...u.knownModels?.[e.modelId]??{},id:e.modelId,contextWindow:d,maxInputTokens:void 0}};if(e.extensionContext)u.extensionContext=e.extensionContext;let p=e.fetch??u.fetch??i;if(p)u.fetch=p;return u}var St=(e)=>typeof e==="number"&&Number.isFinite(e)&&e>0?e:void 0;function _Ce(e){return{...e,compaction:{...e.compaction??{},enabled:e.compaction?.enabled??!0},checkpoint:{...e.checkpoint??{},enabled:e.checkpoint?.enabled??!0},taskProgress:{...e.taskProgress??{},enabled:e.taskProgress?.enabled??!0}}}async function ECe(e,t){let n=t.modelId??e.modelId,r=t.fetch??globalThis.fetch;if(e.providerConfig?.providerId===e.providerId&&St(e.providerConfig?.defaultMaxOutputTokens)!==void 0||!n||!Lb(e.providerId))return{council:!1};if(await iCe(t.baseUrl,n,r,e.logger).catch(()=>{return}),ACe(t,n,aCe(t.baseUrl,n),e.knownModels?.[n]),e.providerId!=="xollama")return{council:!1};return{council:(await dCe(cCe(e.providerId,t.baseUrl),n,r).catch(()=>{return}))?.council===!0}}function ACe(e,t,n,r){if(!n||n.images===void 0&&n.tools===void 0||Array.isArray(r?.capabilities))return;let o=e.knownModels?.[t],i=new Set(o?.capabilities??[]),s=(a,d)=>{if(d===!0)i.add(a);else if(d===!1)i.delete(a)};if(s("images",n.images),s("tools",n.tools),n.tools===void 0&&i.size>0)i.add("tools");e.knownModels={...e.knownModels??{},[t]:{...o??{},id:t,capabilities:[...i]}}}function RCe(e){return e.logger?.log(`${e.modelId} is an xOllama council: it compacts server-side; client compaction is off`,{severity:"info"}),{...e,compaction:{...e.compaction??{},enabled:!1,cappedThinkingEnabled:!1},staleReadRewrites:!1}}function ICe(e,t,n,r,o){let i=t.modelId,s=e.knownModels?.[i];if(r===void 0||!o&&!s)return;let d=St(n?.sampling?.numPredict)??St(t.maxTokensPerTurn)??(n?.outputBudget?.mode==="manual"?St(n.outputBudget.maxTokens):void 0)??St(s?.maxTokens)??(Lb(t.providerId)?St(e.defaultMaxOutputTokens):void 0);e.knownModels={...e.knownModels??{},[i]:{...s??{},id:i,contextWindow:r,maxInputTokens:St(t.contextWindow)!==void 0?s?.maxInputTokens:Math.min(s?.maxInputTokens??r,r),...d!==void 0?{maxTokens:d}:{}}}}function CCe(e){let{config:t,hostConfig:n,providerConfig:r,stored:o}=e,i=r.knownModels?.[t.modelId],s=o?l3(r,(()=>{let l=E3(n,e.sessionId,e.source,void 0,e.modelCatalogDefaults,e.defaultFetch);return l.defaultMaxOutputTokens=r.defaultMaxOutputTokens,l.thinkingBudgetTokens=r.thinkingBudgetTokens,l})()):[],a=n.providerConfig?.providerId===n.providerId&&St(n.providerConfig?.defaultMaxOutputTokens)!==void 0;if(o&&!a){let l=[["budget.contextWindow",St(t.contextWindow)===void 0?o.contextWindow:void 0],["budget.numPredict",o.sampling?.numPredict],["budget.thinkBudget",o.sampling?.thinkBudget],["budget.outputBudget",o.outputBudget],["budget.reasoningBudgetTokens",o.reasoning?.budgetTokens]];for(let[c,u]of l)if(u!==void 0&&u!==null)s.push(c)}let d=gCe();return{sessionId:e.sessionId,providerId:t.providerId,modelId:t.modelId,...r.baseUrl?{baseUrl:r.baseUrl}:{},contextWindow:St(t.contextWindow)??e.contextWindow??St(i?.contextWindow)??St(r.maxInputTokens),maxOutputTokens:St(r.defaultMaxOutputTokens),thinking:{...typeof r.thinking==="boolean"?{enabled:r.thinking}:{},...r.reasoningEffort?{effort:String(r.reasoningEffort)}:{},...St(r.thinkingBudgetTokens)!==void 0?{budgetTokens:r.thinkingBudgetTokens}:{}},...r.sampling?{sampling:Tc(r.sampling)}:{},reasoningHistory:lCe(t.providerId,{modelId:r.modelId??t.modelId,baseUrl:r.baseUrl,reasoningHistory:r.reasoningHistory,reasoningInline:r.reasoningInline}),provider:Tc(r),session:Tc(t),...t.systemPrompt?{systemPrompt:t.systemPrompt}:{},sources:{storedProviderSettings:t.storedProviderSettings==="ignore"?"ignored":o?"merged":"absent",inheritedFromStoredProfile:s.sort(),dataDir:fCe(),providerSettingsPath:yCe(),globalSettingsPath:d,globalSettingsPresent:oCe(d)}}}async function PCe(e,t,n){if(t.providerConfig?.providerId===t.providerId&&St(t.providerConfig?.defaultMaxOutputTokens)!==void 0)return;let o=t.modelId,i=e.baseUrl,s=e.knownModels?.[o],a=St(t.contextWindow)??St(n?.contextWindow)??(Lb(t.providerId)?_3(i,o):void 0)??St(s?.contextWindow),d=n?.sampling,l=s3({configuredNumPredict:d?.numPredict,maxTokensPerTurn:t.maxTokensPerTurn,outputBudget:n?.outputBudget,contextWindow:a,modelMaxOutputTokens:s?.maxTokens});e.defaultMaxOutputTokens=l;let c;try{c=await a3({providerId:t.providerId,modelId:o,baseUrl:i,thinking:e.thinking,reasoningEffort:e.reasoningEffort,configuredThinkBudget:d?.thinkBudget,configuredReasoningLevel:d?.reasoningLevel,configuredNumPredict:d?.numPredict,outputCap:l,contextWindow:a,fetchImpl:e.fetch??fetch})}catch{c=void 0}if(c&&St(n?.reasoning?.budgetTokens)===void 0)e.thinkingBudgetTokens=c.budgetTokens;return t.logger?.log(`Output budget: cap=${l} contextWindow=${a??"unknown"}`+(c?` thinking=${c.budgetTokens} (${c.level})`:""),{severity:"info"}),{contextWindow:a,thinking:c,budgetMessage:d3({providerId:t.providerId,modelId:o,baseUrl:i,configuredMessage:d?.thinkBudgetMessage})}}async function A3(e){let{input:t,sessionId:n,sessionOrigin:r,providerSettingsManager:o,defaultTelemetry:i,defaultLogger:s,defaultCapabilities:a,defaultToolPolicies:d,defaultFetch:l,onPluginEvent:c,onTeamEvent:u,createSubAgentLifecycleCallbacks:h,createSpawnTool:p,createSwarmTool:f,delegatedSandboxes:m,localRuntime:g,readSessionMetadata:y,writeSessionMetadata:w}=e,k=hi(t.config),{modelCatalogDefaults:b,userInstructionService:v,configExtensions:E,onTeamRestored:S,...x}=g??{},T=Object.keys(x).length>0?x:void 0,{workspaceInfo:A,workspaceMetadata:R,gitState:C,durationMs:L,vcsType:N,initError:W}=await k3(k),D=T?.extensionContext,K=D?.client?void 0:kCe(t.config.headers),V=D?.client??K,j=D?.telemetry??T?.telemetry??(i&&V?c3(i,{client:V,source:t.source,user:D?.user}):i),G=j&&r?SI(j,{session_origin:r.mode,session_origin_trigger:r.trigger}):j,z={...D??{},...K?{client:K}:{},workspace:{...A,...D?.workspace??{}},session:{...D?.session??{},sessionId:n},logger:D?.logger??T?.logger??s,telemetry:G};x3({telemetry:z.telemetry,rootPath:A.rootPath,dedupeScope:z.client?.name??t.source,workspaceInfo:A,rootCount:1,vcsType:N,durationMs:L,initError:W,featureFlagEnabled:!0});let M=Ob(E,"hooks")?vA({cwd:t.config.cwd,workspacePath:k,rootSessionId:n,logger:T?.logger,workspaceInfo:A,onHookRuntime:(Ze)=>IM(z.telemetry,Ze)}):void 0,X=RK(T?.hooks)?void 0:bA({rootSessionId:n,workspacePath:k,workspaceInfo:A}),oe=ec([T?.hooks,X]),H;if(Ob(E,"plugins"))try{H=await QG({pluginPaths:T?.pluginPaths,workspacePath:k,cwd:t.config.cwd,onEvent:c,providerId:t.config.providerId,modelId:t.config.modelId,workspaceInfo:A,session:z.session,client:z.client,user:z.user,logger:z.logger,telemetry:z.telemetry,automation:z.automation}),bCe(H.failures,H.warnings,T?.logger)}catch(Ze){let un=Ze instanceof Error?Ze.message:String(Ze);T?.logger?.log?.(`plugin loading failed; continuing without plugins (${un})`)}let J;if(Ob(E,"plugins"))try{J=await Tp({pluginPaths:t.config.agentPluginPaths,cwd:t.config.cwd,disabledPluginNames:[...Xh()]}),vCe(J.diagnostics,z.logger)}catch(Ze){let un=Ze instanceof Error?Ze.message:String(Ze);z.logger?.log(`[agent-plugins] Package discovery failed; continuing without Agent Plugins: ${un}`,{severity:"error"})}let he=await AG({logger:T?.logger}),se=[...M?[M]:[],...he?[he]:[]],re=se.length>0?se:void 0,Ge=_R(re,_R(T?.extensions,Nj(H?.extensions))),I=Ob(E,"plugins")?vc(H?.pluginPaths??[]):void 0,_=_Ce({...t.config,...T??{},sessionId:n,hooks:oe,extensions:Ge,extensionContext:z,telemetry:z.telemetry,logger:z.logger}),F=xCe(_,o),O=E3(_,n,t.source,F,b,l),ne=(await ECe(_,O)).council?RCe(_):_,fe=await PCe(O,ne,F);if(fe)ICe(O,ne,F,fe.contextWindow,(St(ne.contextWindow)??St(F?.contextWindow)??(Lb(ne.providerId)?_3(O.baseUrl,ne.modelId):void 0))!==void 0);let Ce=ec([ne.hooks,ne.checkpoint?.enabled===!0?o3({cwd:ne.cwd,sessionId:n,logger:ne.logger,createCheckpoint:ne.checkpoint?.createCheckpoint,telemetry:ne.telemetry,readSessionMetadata:y,writeSessionMetadata:w}):void 0]),We=SCe(ne,A,R),Se={...ne,providerConfig:O,workspaceMetadata:R,systemPrompt:We,hooks:Ce,...fe?.budgetMessage&&!ne.compaction?.cappedThinkingBudgetMessage?{compaction:{...ne.compaction??{},cappedThinkingBudgetMessage:fe.budgetMessage}}:{},...We?{systemPrompt:mCe(We,{outputCap:O.defaultMaxOutputTokens,contextWindow:fe?.contextWindow??O.maxInputTokens,...fe?.thinking?{thinking:fe.thinking}:O.thinkingBudgetTokens&&O.reasoningEffort?{thinking:{level:O.reasoningEffort,budgetTokens:O.thinkingBudgetTokens}}:{}})}:{}};await sCe(Se.providerId,O.baseUrl,O.modelId??Se.modelId,O.fetch??globalThis.fetch).catch(()=>{return});let Le=CCe({config:Se,hostConfig:ne,providerConfig:O,sessionId:n,source:t.source,stored:F,modelCatalogDefaults:b,defaultFetch:l,contextWindow:fe?.contextWindow});await ne.onConfigResolved?.(Le);let it=t.toolPolicies??ne.toolPolicies??d,dt=kc(a,t.capabilities),_e=dt?.requestToolApproval,Ue=dt?.toolExecutors,xt=dt?.readReceipts,Jt=h?.(Se),Zn=new AI({currentWorkspacePath:A.rootPath,workspaces:{[A.rootPath]:A}});return{effectiveInput:t,config:Se,providerConfig:O,resolvedConfig:Le,workspaceMetadata:R,workspaceInfo:A,gitState:C,extensions:Ge,hooks:Ce,toolPolicies:it,requestToolApproval:_e,pluginSandboxShutdown:H?.shutdown,runtimeBuilderInput:{config:Se,hooks:Ce,extensions:Ge,onTeamEvent:u,createSpawnTool:p,createSwarmTool:f,...m?{delegatedSandboxes:m}:{},onTeamRestored:S,onSubAgentEvent:Jt?.onSubAgentEvent,onSubAgentStart:Jt?.onSubAgentStart,onSubAgentEnd:Jt?.onSubAgentEnd,userInstructionService:v,pluginSkillDirectories:I,agentPluginSkills:J?.skills,agentPluginMcpServers:J?.mcpServers,configExtensions:E,toolExecutors:Ue,readReceipts:xt,toolPolicies:it,workspaceManager:Zn,logger:Se.logger,telemetry:Se.telemetry,requestToolApproval:_e}}}import{RECALLED_MEMORY_TAG as FCe}from"@cerebriline/shared";import{createTool as Ytt,MAIN_MEMORY as Xtt,memorySelectionFor as Jtt}from"@cerebriline/shared";import{DEFAULT_LIBRARY_SETTINGS as NCe,DEFAULT_MEMORY_SETTINGS as Ftt,MAIN_MEMORY as Utt,memoryWorkspaceKey as Btt}from"@cerebriline/shared";import{resolveClineDataDir as Wtt}from"@cerebriline/shared/storage";import{DEFAULT_LIBRARY_SETTINGS as Ttt}from"@cerebriline/shared";import{resolveClineDataDir as xtt}from"@cerebriline/shared/storage";import{DEFAULT_LIBRARY_SETTINGS as Het}from"@cerebriline/shared";var Cet=Array.from({length:64},(e,t)=>(Math.imul(t+1,2654435761)|1)>>>0);import{loadSqliteDb as ott}from"@cerebriline/shared/db";var R3=4000;var ztt={...NCe,enabled:!0,chunkSize:R3*2,chunkOverlap:0,markdownHeaders:!1};var dnt=new Set("a about above after again all also am an and any are as at be because been before being below between both but by can could did do does doing down during each few for from further had has have having he her here hers him his how i if in into is it its just me more most my no nor not now of off on once only or other our ours out over own same she should so some such than that the their theirs them then there these they this those through to too under until up very was we were what when where which while who whom why will with would you your yours please thanks every always never use using used want wants need needs like get got make made new one two project projects code file files thing things".split(" "));function I3(e){let t=new Set;for(let n of e){if(!n.includes(`<${FCe}>`))continue;for(let r of n.matchAll(/^\[(m\d+)\] \d{4}-\d{2}-\d{2}, /gm))t.add(r[1])}return[...t]}import{existsSync as Nb,mkdirSync as UCe,readdirSync as BCe,rmdirSync as HCe,rmSync as WCe,unlinkSync as jCe}from"node:fs";import{dirname as C3,join as Lp}from"node:path";function ft(){return new Date().toISOString()}function Np(e){if(!e||!Nb(e))return;try{jCe(e)}catch{}}function qCe(e){let t=Ca(e);if(t)return{rootSessionId:t.rootSessionId,fileStem:`${t.agentId}__${t.teamTaskId}`};let n=mc(e);if(n)return{rootSessionId:n.rootSessionId,fileStem:n.agentId};return{rootSessionId:e,fileStem:e}}class RI{ensureSessionsDir;constructor(e){this.ensureSessionsDir=e}sessionArtifactsDir(e){return Lp(this.ensureSessionsDir(),e)}ensureSessionArtifactsDir(e){let t=this.sessionArtifactsDir(e);if(!Nb(t))UCe(t,{recursive:!0});return t}sessionMessagesPath(e){return Lp(this.sessionArtifactsDir(e),`${e}.messages.json`)}sessionCompactionPath(e){return Lp(this.sessionArtifactsDir(e),`${e}.compaction.json`)}sessionManifestPath(e,t=!1){let n=t?this.ensureSessionArtifactsDir(e):this.sessionArtifactsDir(e);return Lp(n,`${e}.json`)}removeSessionDirIfEmpty(e){let t=this.sessionArtifactsDir(e),n=this.ensureSessionsDir();while(t.startsWith(n)&&t!==n){if(!Nb(t)){t=C3(t);continue}try{if(BCe(t).length>0)break;HCe(t)}catch{break}t=C3(t)}}removeSessionDir(e){this.removeDir(this.sessionArtifactsDir(e))}removeDir(e){if(!Nb(e))return;try{WCe(e,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths(e,t,n){let{rootSessionId:r,fileStem:o}=qCe(e),i=this.sessionArtifactsDir(r);return{messagesPath:Lp(i,`${o}.messages.json`)}}}import{nanoid as Bnt}from"nanoid";import{nanoid as Tnt}from"nanoid";import{loadSqliteDb as Rnt}from"@cerebriline/shared/db";import{nanoid as Cnt}from"nanoid";function M3(e){let t=e?.importedFrom;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t;if(typeof n.tool!=="string"||typeof n.sourceSessionId!=="string")return;return{tool:n.tool,sourceSessionId:n.sourceSessionId,sourcePath:typeof n.sourcePath==="string"?n.sourcePath:"",importedAt:typeof n.importedAt==="string"?n.importedAt:""}}import{resolveDocumentsExtensionPath as zCe}from"@cerebriline/shared/storage";function O3(e,t,n,r,o){if(n)yM(e.telemetry,{ulid:t,provider:e.providerId,model:e.modelId,...o});else gM(e.telemetry,{ulid:t,provider:e.providerId,model:e.modelId,...o});KCe(e.telemetry,{workspacePath:r})}function KCe(e,t){let n=zCe("Hooks"),r=Gh(t.workspacePath),o=new Map,i=n.replace(/\\/g,"/");for(let s of r){let a=s.hookEventName??"unknown",d=o.get(a)??{global:0,workspace:0},l=s.path.replace(/\\/g,"/");if(l===i||l.startsWith(`${i}/`))d.global+=1;else d.workspace+=1;o.set(a,d)}for(let[s,a]of o.entries())CM(e,s,a.global,a.workspace)}function L3(e,t){for(let n of t.mentions)AM(e,n,t.matchedFiles.includes(n)?1:0,"file",!t.matchedFiles.includes(n));for(let n of t.matchedFiles)_M(e,"file",n.length);for(let n of t.ignoredMentions)EM(e,"file","not_found",n)}import{existsSync as GCe,mkdirSync as VCe,readFileSync as YCe,writeFileSync as XCe}from"node:fs";import{resolve as JCe}from"node:path";import{resolveSessionDataDir as QCe}from"@cerebriline/shared/storage";import{nanoid as ZCe}from"nanoid";import*as ePe from"node-machine-id";var tPe="machine-id",N3,D3=!1;function $3(){if(!D3)N3=F3(),D3=!0;return N3??U3()}function $a(e){let t=e?.trim();if(t)return t;let n=F3();if(n)return n;return U3()}function nPe(){let e=ePe;return e.machineIdSync??e.default?.machineIdSync}function F3(){try{let e=nPe();if(!e)return;return e().trim()||void 0}catch{return}}function U3(){let e=QCe(),t=JCe(e,tPe);try{if(GCe(t)){let r=YCe(t,"utf8").trim();if(r.length>0)return r}}catch{}let n=`cl-${ZCe()}`;try{VCe(e,{recursive:!0}),XCe(t,n,"utf8")}catch{}return n}function rPe(e){return e?JSON.parse(JSON.stringify(e)):void 0}function oPe(e){return e?JSON.parse(JSON.stringify(e)):void 0}function iPe(e){let t=e?.checkpoint&&typeof e.checkpoint==="object"&&!Array.isArray(e.checkpoint)?e.checkpoint:void 0,r=(Array.isArray(t?.history)?t.history:[]).filter((s)=>!!s&&typeof s==="object"&&!Array.isArray(s)).flatMap((s)=>{let a=typeof s.ref==="string"?s.ref.trim():"",d=Number(s.createdAt),l=Number(s.runCount);if(!a||!Number.isFinite(d)||!Number.isInteger(l))return[];return[{ref:a,createdAt:d,runCount:l,...s.kind==="stash"||s.kind==="commit"?{kind:s.kind}:{}}]}),o=r.at(-1),i=e?.checkpointEnabled===!0?!0:void 0;if(!i&&r.length===0)return;return{...i?{enabled:i}:{},...o?{latest:o}:{},history:r}}function Fa(e){let{session:t}=e,n=rPe(t.metadata);return{version:1,sessionId:t.sessionId,source:t.source,status:t.status,createdAt:t.startedAt,updatedAt:t.updatedAt,endedAt:t.endedAt??null,exitCode:t.exitCode??null,interactive:t.interactive,workspace:{cwd:t.cwd,root:t.workspaceRoot},model:{providerId:t.provider,modelId:t.model},capabilities:{enableTools:t.enableTools,enableSpawn:t.enableSpawn,enableTeams:t.enableTeams},lineage:{...t.parentSessionId?{parentSessionId:t.parentSessionId}:{},...t.parentAgentId?{parentAgentId:t.parentAgentId}:{},...t.agentId?{agentId:t.agentId}:{},...t.conversationId?{conversationId:t.conversationId}:{},isSubagent:t.isSubagent},...t.teamName?{team:{name:t.teamName}}:{},...t.prompt?{prompt:t.prompt}:{},...n?{metadata:n}:{},...t.messagesPath?{artifacts:{messagesPath:t.messagesPath}}:{},...e.messages?{messages:oPe(e.messages)}:{},...e.usage?{usage:{...e.usage}}:{},...e.aggregateUsage?{aggregateUsage:{...e.aggregateUsage}}:{},...(()=>{let r=iPe(n);return r?{checkpoint:r}:{}})()}}import{execFile as sPe}from"node:child_process";import{randomUUID as aPe}from"node:crypto";import{promisify as dPe}from"node:util";var ot=dPe(sPe);async function B3(e,t){try{return(await ot("git",["-C",e,"rev-parse","--verify","--quiet",t],{windowsHide:!0})).stdout.trim()||void 0}catch{return}}async function H3(e){if((await ot("git",["-C",e,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${e} is not a git repository`);let n=(await ot("git",["-C",e,"rev-parse","--verify","HEAD"],{windowsHide:!0})).stdout.trim(),r=await B3(e,"refs/stash"),o=aPe(),i=`refs/cline/restore-transactions/${o}`;await ot("git",["-C",e,"stash","push","--include-untracked","--message",`cline restore transaction ${o}`],{windowsHide:!0});let s=await B3(e,"refs/stash"),a=s!==void 0&&s!==r;if(a)try{await ot("git",["-C",e,"update-ref",i,s],{windowsHide:!0}),await ot("git",["-C",e,"stash","drop","stash@{0}"],{windowsHide:!0})}catch(l){try{await ot("git",["-C",e,"reset","--hard",n],{windowsHide:!0}),await ot("git",["-C",e,"clean","-fd"],{windowsHide:!0}),await ot("git",["-C",e,"stash","apply","--index",s],{windowsHide:!0})}catch(c){throw AggregateError([l,c],"Workspace snapshot and rollback both failed")}throw l}let d=!1;return{async commit(){if(d)return;if(d=!0,!a)return;await ot("git",["-C",e,"update-ref","-d",i],{windowsHide:!0}).catch(()=>{return})},async rollback(){if(d)return;if(await ot("git",["-C",e,"reset","--hard",n],{windowsHide:!0}),await ot("git",["-C",e,"clean","-fd"],{windowsHide:!0}),a)await ot("git",["-C",e,"stash","apply","--index",i],{windowsHide:!0}),await ot("git",["-C",e,"update-ref","-d",i],{windowsHide:!0});d=!0}}}function W3(e){let t=e?.metadata?.checkpoint&&typeof e.metadata.checkpoint==="object"&&!Array.isArray(e.metadata.checkpoint)?e.metadata.checkpoint:void 0;return(Array.isArray(t?.history)?t.history:[]).filter((r)=>!!r&&typeof r==="object"&&!Array.isArray(r)).flatMap((r)=>{let o=String(r.ref??"").trim(),i=Number(r.createdAt??0),s=Number(r.runCount??0);if(o.length===0||!Number.isFinite(i)||!Number.isInteger(s)||s<1)return[];let a=r.kind==="stash"||r.kind==="commit"?r.kind:void 0;return[{ref:o,createdAt:i,runCount:s,...a?{kind:a}:{}}]})}function j3(e,t){let n=W3(e).filter((o)=>o.runCount<=t),r=n.at(-1);return r?{latest:r,history:n}:void 0}function lPe(e,t){return e.reduce((n,r)=>{if(r.runCount>t)return n;if(!n||r.runCount>n.runCount)return r;return n},void 0)}function q3(e,t){let n=0;for(let r=0;r<e.length;r+=1){let o=e[r];if(!o)continue;let i=Ad(o);if(i<1)continue;let s=n+1;if(n+=i,n===t)return{index:r,span:i};if(n>t)throw Error(`Run ${t} is folded into a compacted message spanning runs ${s}-${n}`)}throw Error(`Could not find user message for run ${t}`)}function cPe(e,t){let{index:n}=q3(e,t);return e.slice(0,n+1)}function z3(e,t){let{index:n,span:r}=q3(e,t);if(r!==1)throw Error(`Cannot fork before run ${t} because it is folded into a compacted message`);return e.slice(0,n)}function K3(e){let t=e.checkpointRunCount;if(!Number.isInteger(t)||t<1)throw Error("checkpointRunCount must be a positive integer");let n=lPe(W3(e.session),t);if(!n)throw Error(`No checkpoint found at or before run ${t} in session ${e.session.sessionId}`);let r=(e.cwd?.trim()||e.session.cwd||e.session.workspaceRoot).trim();if(!r)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:n,cwd:r,...e.restoreMessages!==!1?{messages:cPe(e.messages??[],t)}:{}}}async function uPe(e,t){if(t.kind)return t.kind;let n=await ot("git",["-C",e,"show","-s","--format=%P%x00%B",t.ref],{windowsHide:!0}),r=n.stdout.indexOf("\x00"),o=r<0?[]:n.stdout.slice(0,r).trim().split(/\s+/).filter(Boolean),i=r<0?"":n.stdout.slice(r+1);return o.length>=2&&e3(i)?"stash":"commit"}async function hPe(e,t){try{return await ot("git",["-C",e,"cat-file","-e",`${t}^3^{commit}`],{windowsHide:!0}),!0}catch{return!1}}async function pPe(e,t,n){try{let r=await ot("git",["-C",e,"rev-list","--count",`${t}..${n}`],{windowsHide:!0}),o=Number(r.stdout.trim());return Number.isFinite(o)?o:void 0}catch{return}}async function G3(e,t){if((await ot("git",["-C",e,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${e} is not a git repository`);await ot("git",["-C",e,"cat-file","-e",`${t.ref}^{commit}`],{windowsHide:!0});let r=await uPe(e,t),o=r==="commit"?t.ref:`${t.ref}^1`,i=(await ot("git",["-C",e,"rev-parse","--verify",`${o}^{commit}`],{windowsHide:!0})).stdout.trim(),s=(await ot("git",["-C",e,"rev-parse","--verify","HEAD"],{windowsHide:!0})).stdout.trim();if(s!==i){let d=await pPe(e,i,s),l=d&&d>0?`${d} commit${d===1?" was":"s were"} added to the current branch after this checkpoint and would be removed by the restore`:"the current branch is no longer on the commit this checkpoint was created from (e.g. after a rebase or branch switch)";throw Error(`Cannot restore the workspace: ${l}. Restore the chat only, or move the branch back to ${i.slice(0,12)} manually (e.g. with git reset) before restoring the workspace.`)}if(r==="stash")await ot("git",["-C",e,"cat-file","-e",`${t.ref}^2^{commit}`],{windowsHide:!0});let a=await hPe(e,t.ref);if(await ot("git",["-C",e,"update-ref","-m","cline: checkpoint restore","HEAD",i,s],{windowsHide:!0}),await ot("git",["-C",e,"reset","--hard"],{windowsHide:!0}),a)await ot("git",["-C",e,"clean","-fd"],{windowsHide:!0});if(r==="commit")return;await ot("git",["-C",e,"stash","apply",t.ref],{windowsHide:!0})}class Fr extends Error{code;constructor(e,t){super(t);this.code=e;this.name="SessionVersioningError"}}function mPe(e){let t=e.sessionId.trim();if(!t)throw new Fr("invalid_restore","sessionId is required");if(!e.restoreMessages&&!e.restoreWorkspace)throw new Fr("invalid_restore","restore.messages or restore.workspace must be true");if(e.restoreMessages&&e.requiresStart)throw new Fr("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger(e.checkpointRunCount)||e.checkpointRunCount<1)throw new Fr("invalid_restore","checkpointRunCount must be a positive integer");return t}class Dp{async restoreCheckpoint(e){let t=e.restore?.messages!==!1,n=e.restore?.workspace!==!1,r=Date.now(),o,i=(k,b)=>{e.telemetry?.capture({event:"checkpoint.restore",properties:{sessionId:e.sessionId,checkpointRunCount:e.checkpointRunCount,restoreWorkspace:n,restoreMessages:t,checkpointKind:o?.kind??"unknown",outcome:k,durationMs:Date.now()-r,...b}})},s,a,d;try{let k=mPe({sessionId:e.sessionId,restoreMessages:t,restoreWorkspace:n,requiresStart:e.start===void 0,checkpointRunCount:e.checkpointRunCount}),b=await e.getSession(k);if(!b)throw new Fr("session_not_found",`Session ${k} not found`);if(s=b,a=t?await e.readMessages(k):void 0,t&&a?.length===0)throw new Fr("session_messages_not_found",`No messages found for session ${k}`);d=K3({session:s,messages:a,checkpointRunCount:e.checkpointRunCount,cwd:e.cwd,restoreMessages:t}),o=d.checkpoint}catch(k){throw i("failed",{phase:"plan"}),k}let l=Fa({session:s,messages:a}),c,u=[],h,p;if(t){let{startSession:k,getStartedSessionId:b,cleanupStartedSession:v}=e;if(!e.start||!k||!b||!v)throw new Fr("invalid_restore","startSession, getStartedSessionId, and cleanupStartedSession are required when restore.messages is true");p={startSession:k,getStartedSessionId:b,cleanupStartedSession:v},c=j3(s,e.checkpointRunCount),u=e.restore?.omitCheckpointMessageFromSession?z3(a??[],e.checkpointRunCount):d.messages??[];let E={sourceSession:s,sourceMessages:a,sourceSnapshot:l,plan:d,restoredCheckpointMetadata:c,initialMessages:u,restoreMessages:t,restoreWorkspace:n,checkpointRunCount:e.checkpointRunCount};h=e.buildStartInput?await e.buildStartInput(E,e.start):e.start}let f=e.applyWorkspaceCheckpoint??G3,m=e.beginWorkspaceRestoreTransaction??(e.applyWorkspaceCheckpoint?void 0:H3),g=n&&m?await m(d.cwd):void 0,y=!1,w;try{if(n)await f(d.cwd,d.checkpoint);if(!p)return await g?.commit(),y=!0,i("success"),{checkpoint:d.checkpoint,sourceSnapshot:l};let k=await p.startSession(h);w={result:k,cleanup:p.cleanupStartedSession};let b=p.getStartedSessionId(k);if(!b)throw new Fr("invalid_restore","Restored session did not return a session id");await(e.retainCheckpointRefs??r3)(d.cwd,b,c?.history??[]);let v=e.readRestoredSession?await e.readRestoredSession(b):void 0,E=v?Fa({session:v,messages:u}):void 0;return await g?.commit(),y=!0,i("success"),{sessionId:b,startResult:k,messages:d.messages,checkpoint:d.checkpoint,sourceSnapshot:l,...E?{restoredSnapshot:E}:{}}}catch(k){let b=[];if(w)try{await w.cleanup(w.result)}catch(v){b.push(v)}if(g&&!y)try{await g.rollback()}catch(v){b.push(v)}if(i("failed",{workspaceRolledBack:!!g&&!y,recovered:b.length===0}),b.length>0)throw AggregateError([k,...b],"Checkpoint restore failed and recovery did not complete");throw k}}}import{appendFileSync as fPe}from"node:fs";import{join as gPe}from"node:path";import{resolveRootSessionId as V3}from"@cerebriline/shared";import{ensureHookLogDir as yPe}from"@cerebriline/shared/storage";import{z as II}from"zod";var wPe=II.looseObject({task:II.string().optional(),systemPrompt:II.string().optional()});class Db{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor(e,t,n,r){this.adapter=e;this.manifestStore=t;this.toPersistedMessages=n;this.heartbeatLogIntervalMs=r}teamTaskQueueKey(e,t){return`${e}::${t}`}activeTeamTaskSessionId(e,t){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey(e,t))?.at(-1)}buildSubsessionRow(e,t){let n=di(e.metadata);return{sessionId:t.sessionId,source:e.source,pid:e.pid,startedAt:t.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:e.provider,model:e.model,cwd:e.cwd,workspaceRoot:e.workspaceRoot,teamName:e.teamName??null,enableTools:e.enableTools,enableSpawn:e.enableSpawn,enableTeams:e.enableTeams,parentSessionId:t.parentSessionId,parentAgentId:t.parentAgentId,agentId:t.agentId,conversationId:t.conversationId??null,isSubagent:!0,prompt:t.prompt,metadata:fp({metadata:Gn(void 0,{mode:t.mode,version:n?.version}),prompt:t.prompt}),hookPath:"",messagesPath:t.messagesPath,updatedAt:t.startedAt}}async queueSpawnRequest(e){if(e.hookName!=="tool_call"||e.parent_agent_id!==null)return;if(e.tool_call?.name!=="spawn_agent")return;let t=V3(e.sessionContext);if(!t)return;let n=wPe.safeParse(e.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:t,parentAgentId:e.agent_id,task:n.success?n.data.task:void 0,systemPrompt:n.success?n.data.systemPrompt:void 0})}async upsertSubagentSession(e){let t=e.rootSessionId;if(!t)return;let n=await this.adapter.getSession(t);if(!n)return;let r=SR(t,e.agentId),o=await this.adapter.getSession(r),i=ft(),s=this.manifestStore.artifacts.subagentArtifactPaths(r,e.agentId,this.activeTeamTaskSessionId(t,e.parentAgentId)),a=e.prompt??o?.prompt??void 0;if(!a)a=await this.adapter.claimSpawnRequest(t,e.parentAgentId)??`Subagent run by ${e.parentAgentId}`;if(!o){let d=this.buildSubsessionRow(n,{sessionId:r,mode:"subagent",parentSessionId:t,parentAgentId:e.parentAgentId,agentId:e.agentId,conversationId:e.conversationId,prompt:a,startedAt:i,...s});return await this.adapter.upsertSession(d),this.manifestStore.initializeMessagesFile(d,s.messagesPath,i),r}return await this.adapter.updateSession({sessionId:r,setRunning:!0,parentSessionId:t,parentAgentId:e.parentAgentId,agentId:e.agentId,conversationId:e.conversationId,prompt:o.prompt??a??null,metadata:fp({metadata:Gn(o.metadata,{mode:"subagent",version:di(n.metadata)?.version}),prompt:o.prompt??a??null}),expectedStatusLock:o.statusLock}),r}async upsertSubagentSessionFromHook(e){if(!e.parent_agent_id)return;let t=V3(e.sessionContext);if(!t)return;if(e.hookName==="session_shutdown"){let n=SR(t,e.agent_id);return await this.adapter.getSession(n)?n:void 0}return await this.upsertSubagentSession({agentId:e.agent_id,parentAgentId:e.parent_agent_id,conversationId:e.taskId,rootSessionId:t})}async applySubagentStatus(e,t){await this.applySubagentStatusBySessionId(e,AK(t))}async applySubagentStatusBySessionId(e,t){let n=await this.adapter.getSession(e);if(!n)return;let r=Kt(t)?null:ft(),o=Kt(t)?null:t==="failed"?1:0;await this.adapter.updateSession({sessionId:e,status:t,endedAt:r,exitCode:o,expectedStatusLock:n.statusLock})}async applyStatusToRunningChildSessions(e,t){if(!e)return;let n=await this.adapter.listSessions({limit:2000,parentSessionId:e,status:"running"});for(let r of n)await this.applySubagentStatusBySessionId(r.sessionId,t)}async onTeamTaskStart(e,t,n){let r=await this.adapter.getSession(e);if(!r)return;let o=EK(e,t),i=ft(),{messagesPath:s}=this.manifestStore.artifacts.subagentArtifactPaths(o,t),a=this.buildSubsessionRow(r,{sessionId:o,mode:"team",parentSessionId:e,parentAgentId:"lead",agentId:t,prompt:n||`Team task for ${t}`,startedAt:i,messagesPath:s});await this.adapter.upsertSession(a),this.manifestStore.initializeMessagesFile(a,s,i);let d=this.teamTaskQueueKey(e,t),l=this.teamTaskSessionsByAgent.get(d)??[];l.push(o),this.teamTaskSessionsByAgent.set(d,l)}async onTeamTaskEnd(e,t,n,r,o,i){let s=this.teamTaskQueueKey(e,t),a=this.teamTaskSessionsByAgent.get(s);if(!a||a.length===0)return;let d=a.shift();if(a.length===0)this.teamTaskSessionsByAgent.delete(s);if(!d)return;let l=o?.messages??i,c=this.toPersistedMessages(l,o,i);if(c)await this.manifestStore.persistSessionMessages(d,c);await this.applySubagentStatusBySessionId(d,n),this.teamTaskLastHeartbeatBySession.delete(d),this.teamTaskLastProgressLineBySession.delete(d)}async onTeamTaskProgress(e,t,n,r){let o=this.teamTaskQueueKey(e,t),i=this.teamTaskSessionsByAgent.get(o)?.[0];if(!i)return;let s=n.trim();if(!s)return;let a=r?.kind??"progress";if(a==="heartbeat"){let l=Date.now(),c=this.teamTaskLastHeartbeatBySession.get(i)??0;if(l-c<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(i,l)}let d=a==="heartbeat"?"[progress] heartbeat":a==="text"?`[progress] text: ${s}`:`[progress] ${s}`;if(this.teamTaskLastProgressLineBySession.get(i)===d)return;this.teamTaskLastProgressLineBySession.set(i,d)}async handleSubAgentStart(e,t){let n=await this.upsertSubagentSession({agentId:t.subAgentId,parentAgentId:t.parentAgentId,conversationId:t.conversationId,prompt:t.input.task,rootSessionId:e});if(!n)return;await this.applySubagentStatusBySessionId(n,"running")}async handleSubAgentEnd(e,t){let n=await this.upsertSubagentSession({agentId:t.subAgentId,parentAgentId:t.parentAgentId,conversationId:t.conversationId,prompt:t.input.task,rootSessionId:e});if(!n)return;let r=this.toPersistedMessages(t.agentResult?.messages,t.agentResult?.usage?t.agentResult:void 0);if(r)await this.manifestStore.persistSessionMessages(n,r);if(t.error||t.agentResult?.finishReason==="error"){await this.applySubagentStatusBySessionId(n,"failed");return}let o=t.result?.finishReason??t.agentResult?.finishReason??"completed";await this.applySubagentStatusBySessionId(n,o==="aborted"?"cancelled":"completed")}appendSubagentHookAudit(e){let n=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??gPe(yPe(),"hooks.jsonl");fPe(n,`${JSON.stringify({ts:ft(),...e})}
1004
+ `,"utf8")}}import{formatUserInputBlock as zPe}from"@cerebriline/shared";import{probeServerHealth as bPe,serverRoot as vPe}from"@cerebriline/llms";function kPe(e,t,n){if(typeof n!=="number"||!Number.isFinite(n))return e;let r=e.providerConfig??t;return{...e,providerConfig:{...r??{},agentWindow:{sharePercent:n}}}}var Y3="polykv-lead",X3="Model (PolyKV)",J3="primary",TPe=new Set(["opencoti","xollama"]);function CI(e){let t=(e.agentNodes??[]).filter((r)=>!r.polykvLead);if(e.polykvAgentsPriorityZero!==!0||!TPe.has(e.providerId.trim().toLowerCase()))return[...t];let n=t.length>0?t:[{id:J3,priority:Ml+1,capacity:typeof e.overflowCapacity==="number"&&e.overflowCapacity>0?e.overflowCapacity:Number.POSITIVE_INFINITY,pacedAdmission:!0,label:"Node1",connection:{}}];return[{id:Y3,priority:Ml,capacity:sE,label:X3,connection:{thinking:void 0,reasoningEffort:void 0,thinkingBudgetTokens:void 0,maxTokensPerTurn:void 0,temperature:void 0,...e.lead,providerId:e.providerId,modelId:e.modelId},polykvLead:!0},...n]}function PI(e){if(e.nodes.length===0)return;let t=cE(e.nodes.map((i)=>$h({id:i.id,priority:i.polykvLead?Ml:Math.max(i.priority,Ml+1),capacity:i.capacity,...i.pacedAdmission?{pacedAdmission:!0}:{}})),{probe:async(i)=>{let s=(n.get(i)??e.base).getConnectionConfig(),a=vPe(s.baseUrl);return a?await bPe(a,{...s.headers?{headers:s.headers}:{}}):!1}}),n=new Map;for(let i of e.nodes){let s=e.base.getRuntimeConfig(),a=kPe(i.connection,s.providerConfig,i.windowShare);n.set(i.id,oi({...s,...a,...i.polykvLead&&s.sessionId?{polykvLeadOwner:s.sessionId}:{}},Object.keys(a)))}let r=new Map(e.nodes.flatMap((i)=>i.label?[[i.id,i.label]]:[])),o=(i)=>{let s=n.get(i.nodeId)??e.base,a=r.get(i.nodeId);return{nodeId:i.nodeId,...a?{nodeLabel:a}:{},configProvider:s,run:async(d)=>await d(),release:()=>i.release(),admitted:()=>i.admitted(),refused:(d)=>i.refused(d),markUnreachable:(d)=>t.markUnreachable(i.nodeId,d)}};return{place:async(i,s)=>o(await t.acquire(i,s)),base:e.base,occupancy:()=>t.occupancy(),hasRoomElsewhere:(i)=>t.hasRoomElsewhere(i),get waiting(){return t.waiting},describe:()=>{let i=new Map(t.nodeStates().map((s)=>[s.nodeId,s]));return e.nodes.map((s)=>{let a=(n.get(s.id)??e.base).getConnectionConfig(),d=i.get(s.id);return{nodeId:s.id,...s.label?{label:s.label}:{},priority:s.priority,providerId:a.providerId,modelId:a.modelId,...a.baseUrl?{baseUrl:a.baseUrl}:{},...a.providerConfig?{providerConfig:a.providerConfig}:{},capacity:d?.capacity??s.capacity,running:d?.running??0,...d?.downUntil?{downUntil:d.downUntil}:{},...d?.heldUntil?{heldUntil:d.heldUntil}:{}}})}}}import{existsSync as SPe,readdirSync as xPe,readFileSync as _Pe}from"node:fs";import{basename as Q3,extname as EPe,join as APe}from"node:path";import{stripUtf8Bom as RPe}from"@cerebriline/shared";import{resolveAgentConfigSearchPaths as IPe}from"@cerebriline/shared/storage";import e4 from"yaml";import{z as vn}from"zod";var t4=vn.object({name:vn.string().trim().min(1),description:vn.string().trim().min(1),tools:vn.union([vn.string(),vn.array(vn.string())]).optional(),skills:vn.union([vn.string(),vn.array(vn.string())]).optional(),providerId:vn.string().trim().min(1).optional(),modelId:vn.string().trim().min(1).optional(),profile:vn.string().trim().min(1).optional(),maxIterations:vn.number().int().positive().optional()});function CPe(e){e=RPe(e);let t=e.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!t)throw Error("Missing YAML frontmatter block in agent config file.");let n=t[0].length,r=/^---[^\S\r\n]*(?:\r?\n|$)/gm;r.lastIndex=n;let o,i=Array.from(e.matchAll(r)).filter((s)=>s.index>=n);for(let s of i){let a=s.index,d=e.slice(n,a);try{let l=e4.parse(d);if(!l||typeof l!=="object"||Array.isArray(l))continue;t4.parse(l);let c=e.slice(a+s[0].length);o={frontmatter:d,body:c}}catch{}}if(o)return o;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function Z3(e){if(e===void 0)return;let t=Array.isArray(e)?e:e.split(",");return Array.from(new Set(t.map((n)=>n.trim()).filter((n)=>n.length>0)))}function PPe(e){return e.trim().toLowerCase()}function MPe(e){let t=EPe(e).toLowerCase();return t===".md"||t===".markdown"||t===".yml"||t===".yaml"}function n4(e,t={}){let{frontmatter:n,body:r}=CPe(e),o=e4.parse(n);if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Agent config frontmatter must be a YAML mapping.");let i=t4.parse(o),s=r.trim();if(!s)throw Error("Missing system prompt body in agent config file.");return{name:i.name,description:i.description,tools:Z3(i.tools),skills:Z3(i.skills),providerId:i.providerId,modelId:i.modelId,profile:i.profile,maxIterations:i.maxIterations,systemPrompt:s,path:t.path}}function MI(e){let t=e.searchPaths??IPe(e.workspaceRoot),n=new Map,r=[];for(let i of t.filter(Boolean)){if(!SPe(i))continue;let s;try{s=xPe(i,{withFileTypes:!0})}catch(a){r.push({path:i,error:a instanceof Error?a:Error(String(a))});continue}for(let a of s){if(!a.isFile()||!MPe(a.name))continue;let d=APe(i,a.name);try{let l=_Pe(d,"utf8"),c=n4(l,{path:d}),u=PPe(c.name);if(!n.has(u))n.set(u,c)}catch(l){r.push({path:d,error:l instanceof Error?l:Error(String(l))})}}}return{configs:Array.from(n.values()).sort((i,s)=>(i.path?Q3(i.path):i.name).localeCompare(s.path?Q3(s.path):s.name)),errors:r,searchPaths:t.filter(Boolean)}}import{TeamMessageType as Me}from"@cerebriline/shared";function pi(e){let t=e.type;switch(t){case Me.AgentEvent:return!1;case Me.RunProgress:return o4(e);case Me.TaskStart:case Me.TaskEnd:case Me.TeammateSpawned:case Me.TeammateShutdown:case Me.TeamTaskUpdated:case Me.TeamMessage:case Me.TeamMissionLog:case Me.RunQueued:case Me.RunStarted:case Me.RunCompleted:case Me.RunFailed:case Me.RunCancelled:case Me.RunInterrupted:case Me.OutcomeCreated:case Me.OutcomeFragmentAttached:case Me.OutcomeFragmentReviewed:case Me.OutcomeFinalized:case Me.TeamCleaned:return!0;default:return Boolean(t)}}function NI(e){switch(e.type){case Me.TeammateSpawned:case Me.TeammateShutdown:case Me.RunCompleted:case Me.RunFailed:case Me.RunCancelled:case Me.RunInterrupted:case Me.TeamCleaned:return!0;case Me.RunProgress:return o4(e);default:return!1}}function o4(e){return e.type===Me.RunProgress&&e.run.status==="queued"}var LI=Number.POSITIVE_INFINITY;function r4(e){return typeof e==="object"&&e!==null}function $b(e,t=0){return typeof e==="number"&&Number.isFinite(e)?e:t}function OI(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function OPe(e){return e.length>LI?`${e.slice(0,LI-3)}...`:e}function Ao(e){if(!r4(e))return;let t=r4(e.usage)?e.usage:{},n=e.finishReason;return{text:OPe(typeof e.text==="string"?e.text:""),iterations:$b(e.iterations),finishReason:typeof n==="string"?n:"completed",durationMs:$b(e.durationMs),usage:{inputTokens:$b(t.inputTokens),outputTokens:$b(t.outputTokens),cacheReadTokens:OI(t.cacheReadTokens),cacheWriteTokens:OI(t.cacheWriteTokens),totalCost:OI(t.totalCost)}}}function LPe(e){if(e.result===void 0)return e;return{...e,result:Ao(e.result)}}function is(e){switch(e.type){case Me.TaskEnd:{let{messages:t,result:n,error:r,...o}=e;return{...o,result:Ao(n),error:r?{message:r.message}:void 0}}case Me.RunQueued:case Me.RunStarted:case Me.RunCompleted:case Me.RunFailed:case Me.RunCancelled:case Me.RunInterrupted:return{...e,run:LPe(e.run)};default:return e}}function Ro(){return new Date().toISOString()}function i4(e,t){if(t<=0)return 0;return Math.round(e/t*100)}function NPe(e,t){let n=new Set;for(let o of t)if(o.status==="reviewed")n.add(`${o.outcomeId}:${o.section}`);let r=new Set;for(let o of e){if(o.status==="finalized")continue;for(let i of o.requiredSections)if(!n.has(`${o.id}:${i}`))r.add(`${o.id}:${i}`)}return[...r].sort((o,i)=>o.localeCompare(i))}function DI(e,t){let n={idle:0,running:0,stopped:0},r={pending:0,in_progress:0,blocked:0,completed:0},o={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},i={draft:0,in_review:0,finalized:0},s={draft:0,reviewed:0,rejected:0},a=0,d=0;for(let g of t.members)if(n[g.status]+=1,g.role==="lead")a+=1;else d+=1;let l=[],c=[],u=t.tasks.filter((g)=>g.status==="completed").length,h=new Map(t.tasks.map((g)=>[g.id,g]));for(let g of t.tasks){if(r[g.status]+=1,g.status==="blocked"){l.push(g.id);continue}if(g.status!=="pending")continue;if(g.dependsOn.every((w)=>h.get(w)?.status==="completed"))c.push(g.id)}let p=[],f,m=0;for(let g of t.runs){if(o[g.status]+=1,g.status==="queued"||g.status==="running")p.push(g.id);let y=g.startedAt.getTime();if(y>=m)m=y,f=g.id}for(let g of t.outcomes)i[g.status]+=1;for(let g of t.outcomeFragments)s[g.status]+=1;return{teamName:e,updatedAt:Ro(),members:{total:t.members.length,byStatus:n,leadCount:a,teammateCount:d},tasks:{total:t.tasks.length,byStatus:r,blockedTaskIds:l,readyTaskIds:c,completionPct:i4(u,t.tasks.length)},runs:{total:t.runs.length,byStatus:o,activeRunIds:p,latestRunId:f},outcomes:{total:t.outcomes.length,byStatus:i,finalizedPct:i4(i.finalized,t.outcomes.length),missingRequiredSections:NPe(t.outcomes,t.outcomeFragments)},fragments:{total:t.outcomeFragments.length,byStatus:s}}}function $I(e){let{event:t}=e;switch(t.type){case"team_task_updated":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),taskId:t.task.id,agentId:t.task.assignee??t.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.run.error};case"run_progress":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),runId:t.run.id,taskId:t.run.taskId,agentId:t.run.agentId,message:t.message};case"outcome_created":case"outcome_finalized":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),outcomeId:t.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),outcomeId:t.fragment.outcomeId,fragmentId:t.fragment.id,agentId:t.fragment.sourceAgentId};case"team_message":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),taskId:t.message.taskId,agentId:t.message.fromAgentId,message:t.message.subject};case"team_mission_log":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),taskId:t.entry.taskId,agentId:t.entry.agentId,message:t.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro(),agentId:t.agentId}}return{teamName:e.teamName,sessionId:e.sessionId,eventType:t.type,ts:Ro()}}import{clearPolykvGrantedWindow as s4,releasePolykvAgent as FI}from"@cerebriline/llms";import{sanitizeFileName as DPe,TeamMessageType as xe}from"@cerebriline/shared";import{nanoid as $Pe}from"nanoid";import{TeamMessageType as Qrt}from"@cerebriline/shared";function Fb(){return{reset:!1,tasks:new Set,mailbox:new Set,missionLog:new Set,runs:new Set,outcomes:new Set,outcomeFragments:new Set}}function Fp(e){if(typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError")return!0;if(!(e instanceof Error))return!1;return e.name==="AbortError"||e.message.toLowerCase().includes("aborted")}function UI(e){let t=Error(e);return t.name="AbortError",t}function FPe(e){return`[The lead requeued you${e?` (${e})`:""}: your engine session was given back and booked again. Your work so far is above. Carry on with your task from where you stopped.]`}function BI(e){return`Teammate "${e}" was shut down and takes no more tasks. To give it work, spawn it again with team_spawn_teammate under the same agentId.`}function a4(e,t){return e?.abortRequested===!0||e?.status==="stopped"&&Fp(t)}function UPe(e){if(e.finishReason==="aborted")return"cancelled";if(e.finishReason==="error"||e.finishReason==="max_iterations")return"failed";return"completed"}var BPe=600000,d4="recovered_queued";function HPe(e){return`This is an automatic recovery of interrupted team run ${e.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
1005
1005
 
1006
- ${e.message}`}class Ub{teamId;teamName;sessionId;onTeamEvent;onStateDirty;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;dirty=Fb();runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;teammateWorkspaces;acceptTeammateConnectionUpdates;constructor(e){this.teamName=e.teamName,this.sessionId=e.sessionId?.trim()||void 0,this.teammateWorkspaces=e.teammateWorkspaces,this.acceptTeammateConnectionUpdates=e.acceptTeammateConnectionUpdates,this.teamId=`t_${DPe($Pe(10))}`,this.onTeamEvent=e.onTeamEvent,this.onStateDirty=e.onStateDirty,this.missionLogIntervalSteps=Math.max(1,e.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,e.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,e.maxConcurrentRuns??2);let t=e.leadAgentId??"lead";this.members.set(t,{agentId:t,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(e){return this.members.get(e)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((e)=>e.role==="teammate").map((e)=>e.agentId)}getTask(e){return this.tasks.get(e)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(e){return Array.from(this.tasks.values()).map((t)=>{let n=this.getUnresolvedDependencies(t);return{...t,blockedBy:n,isReady:t.status==="pending"&&!t.assignee&&n.length===0}}).filter((t)=>{if(e?.status&&t.status!==e.status)return!1;if(e?.assignee&&t.assignee!==e.assignee)return!1;return!0})}listMissionLog(e){if(!e||e<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-e))}listMailbox(e,t){let n=t?.unreadOnly??!0,r=t?.markRead??!0,o=t?.limit,i=this.mailbox.filter((a)=>a.toAgentId===e&&(!n||!a.readAt)),s=typeof o==="number"&&o>0?i.slice(Math.max(0,i.length-o)):i;if(r){let a=new Date,d=!1;for(let l of s)if(!l.readAt)l.readAt=a,this.dirty.mailbox.add(l.id),d=!0;if(d)this.notifyStateDirty()}return s.map((a)=>({...a}))}getSnapshot(){let e={pending:0,in_progress:0,blocked:0,completed:0};for(let n of this.tasks.values())e[n.status]++;let t={draft:0,in_review:0,finalized:0};for(let n of this.outcomes.values())t[n.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((n)=>({agentId:n.agentId,role:n.role,description:n.description,status:n.status})),taskCounts:e,unreadMessages:this.mailbox.filter((n)=>!n.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((n)=>n.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((n)=>n.status==="queued").length,outcomeCounts:t}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((e)=>({agentId:e.agentId,role:e.role,description:e.description,status:e.status,...WPe(e),...e.role==="teammate"&&e.sampling?{sampling:e.sampling}:{},...e.control?.id?{cancelId:e.control.id}:{}})),tasks:Array.from(this.tasks.values()).map((e)=>({...e})),mailbox:this.mailbox.map((e)=>({...e})),missionLog:this.missionLog.map((e)=>({...e})),runs:Array.from(this.runs.values()).map((e)=>({...e,...e.result?{result:{...e.result,messages:[],toolCalls:[]}}:{},...e.status==="running"?$p(this.members.get(e.agentId)):{}})),outcomes:Array.from(this.outcomes.values()).map((e)=>({...e})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((e)=>({...e}))}}hydrateState(e){this.clearQueuedRunDispatchTimer(),this.dirty=Fb(),this.tasks.clear();for(let n of e.tasks)this.tasks.set(n.id,{...n});this.mailbox.length=0,this.mailbox.push(...e.mailbox.map((n)=>({...n}))),this.missionLog.length=0,this.missionLog.push(...e.missionLog.map((n)=>({...n}))),this.runs.clear();for(let n of e.runs??[])this.runs.set(n.id,{...n,result:Ao(n.result)});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((n)=>n.status==="queued").map((n)=>n.id)),this.outcomes.clear();for(let n of e.outcomes??[])this.outcomes.set(n.id,{...n});this.outcomeFragments.clear();for(let n of e.outcomeFragments??[])this.outcomeFragments.set(n.id,{...n});let t=Array.from(this.members.values()).filter((n)=>n.role==="lead");this.members.clear();for(let n of t)this.members.set(n.agentId,{...n,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let n of e.members){if(n.role!=="teammate")continue;this.members.set(n.agentId,{agentId:n.agentId,role:"teammate",description:n.description,status:"stopped",...n.activity?{activity:n.activity}:{},...n.taskActivity?{taskActivity:n.taskActivity}:{},...n.sampling?{sampling:n.sampling}:{},agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,xc(e.tasks.map((n)=>n.id),"task_")),this.messageCounter=Math.max(this.messageCounter,xc(e.mailbox.map((n)=>n.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,xc(e.missionLog.map((n)=>n.id),"log_")),this.runCounter=Math.max(this.runCounter,xc((e.runs??[]).map((n)=>n.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,xc((e.outcomes??[]).map((n)=>n.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,xc((e.outcomeFragments??[]).map((n)=>n.id),"frag_"))}isTeammateActive(e){let t=this.members.get(e);return!!t&&t.role==="teammate"&&!!t.agent&&t.status!=="stopped"}requireTaskableTeammate(e){let t=this.members.get(e);if(!t||t.role!=="teammate"||!t.agent)throw Error(`Teammate "${e}" was not found`);if(t.status==="stopped")throw Error(BI(e));return t}assertCanSpawnTeammate(e){let t=this.members.get(e);if(t&&t.role!=="teammate")throw Error(`Team member "${e}" already exists and is not a teammate`);if(t&&t.runningCount>0)throw Error(`Teammate "${e}" is currently running and cannot be respawned`)}spawnTeammate({agentId:e,config:t,sampling:n}){this.assertCanSpawnTeammate(e);let r=this.members.get(e);if(r&&r.engineSessionId!==t.engineSessionId)this.releaseEngineSession(r);let o={...t,apiTimeoutMs:BPe,consumePendingUserMessage:()=>{let a=this.members.get(e),d=a?.control?.takeMessage();if(d!==void 0)return d;if(!a||!a.pendingSteerMessage)return;let l=a.pendingSteerMessage;return a.pendingSteerMessage=void 0,l},onEvent:(a)=>{t.onEvent?.(a);let d=this.members.get(e),l=d?.activityCounter?.observe(a)===!0,c=d?.currentTaskCounter?.observe(a)===!0;this.emitEvent({type:xe.AgentEvent,agentId:e,event:a,...l||c?{activityChanged:!0}:{}}),this.trackMeaningfulEvent(e,a)}},i=new Sa(o);if(o.onEvent)i.subscribeEvents(o.onEvent);let s={agentId:e,role:"teammate",description:t.role,status:"idle",agent:i,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now(),...t.engineSessionId?{engineSessionId:t.engineSessionId}:{},...n?{sampling:n}:{},activityCounter:bw(r?.activityCounter?.snapshot()??r?.activity),...r?.taskActivity||r?.currentTaskCounter?{taskActivity:r.currentTaskCounter?.snapshot()??r.taskActivity}:{}};return this.members.set(e,s),this.emitEvent({type:xe.TeammateSpawned,agentId:e,role:t.role,teammate:{rolePrompt:t.systemPrompt,modelId:t.modelId,maxIterations:t.maxIterations,...n?.temperature!==void 0?{temperature:n.temperature}:{},...n?.seed!==void 0?{seed:n.seed}:{},...n?.seedRandom?{seedRandom:!0}:{},...n?.temperatureBase!==void 0?{temperatureBase:n.temperatureBase}:{},...n?.temperatureRange!==void 0?{temperatureRange:n.temperatureRange}:{},runtimeAgentId:i.getAgentId(),conversationId:i.getConversationId(),parentAgentId:null}}),{agentId:s.agentId,role:s.role,description:s.description,status:s.status}}shutdownTeammate(e,t){let n=this.members.get(e);if(!n||n.role!=="teammate")throw Error(`Teammate "${e}" was not found`);let r=`Teammate "${e}" was shut down${t?` (${t})`:""}`;for(let o of this.runs.values())if(o.agentId===e&&(o.status==="queued"||o.status==="running"))this.cancelRun(o.id,r);if(this.abortTeammateRun(e,r),n.status="stopped",n.runningCount<=0)this.releaseWorkspace(e),this.releaseEngineSession(n);this.emitEvent({type:xe.TeammateShutdown,agentId:e,reason:t})}releaseWorkspace(e){this.teammateWorkspaces?.release(e).catch(()=>{})}releaseEngineSession(e){let t=e.engineSessionId;if(!t)return;e.engineSessionId=void 0,FI(t).catch(()=>{return})}releaseEngineSessionBetweenTasks(e){let t=e.engineSessionId;if(!t)return;e.pendingEngineRelease=FI(t).catch(()=>{return})}async rebookEngineSession(e,t){let n=e.engineSessionId;if(n){if(await FI(n).catch(()=>{return}),t)s6(n)}if(e.status==="stopped")throw UI(BI(e.agentId))}async runTeammateSegment(e,t,n,r){let o=n.signal,i=()=>{let s=n.id?pt.stoppedBy(n.id):void 0,a=n.id!==void 0&&pt.wrappingUp(n.id);if(s&&!e.abortRequested&&!a)e.abortRequested=!0,e.abortReason=s==="lead"?"Stopped by the lead.":"Stopped by the user.";try{t.abort(o?.reason)}catch(d){if(!Fp(d))throw d}};if(o?.aborted)throw i(),UI(e.abortReason??"The teammate's task was stopped.");o?.addEventListener("abort",i,{once:!0});try{if(n.track(t),"carry"in r){if(r.carry.wrapUp){e.wrappedUpBy=r.carry.wrapUp;let s=t.getMaxIterations();t.setMaxIterations(1);try{let a=await t.continue(IE(r.carry.wrapUp)),d=a.text?.trim();return d?{...a,text:`${CE(r.carry.wrapUp)}
1006
+ ${e.message}`}class Ub{teamId;teamName;sessionId;onTeamEvent;onStateDirty;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;dirty=Fb();runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;teammateWorkspaces;acceptTeammateConnectionUpdates;constructor(e){this.teamName=e.teamName,this.sessionId=e.sessionId?.trim()||void 0,this.teammateWorkspaces=e.teammateWorkspaces,this.acceptTeammateConnectionUpdates=e.acceptTeammateConnectionUpdates,this.teamId=`t_${DPe($Pe(10))}`,this.onTeamEvent=e.onTeamEvent,this.onStateDirty=e.onStateDirty,this.missionLogIntervalSteps=Math.max(1,e.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,e.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,e.maxConcurrentRuns??2);let t=e.leadAgentId??"lead";this.members.set(t,{agentId:t,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole(e){return this.members.get(e)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter((e)=>e.role==="teammate").map((e)=>e.agentId)}getTask(e){return this.tasks.get(e)}listTasks(){return Array.from(this.tasks.values())}listTaskItems(e){return Array.from(this.tasks.values()).map((t)=>{let n=this.getUnresolvedDependencies(t);return{...t,blockedBy:n,isReady:t.status==="pending"&&!t.assignee&&n.length===0}}).filter((t)=>{if(e?.status&&t.status!==e.status)return!1;if(e?.assignee&&t.assignee!==e.assignee)return!1;return!0})}listMissionLog(e){if(!e||e<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-e))}listMailbox(e,t){let n=t?.unreadOnly??!0,r=t?.markRead??!0,o=t?.limit,i=this.mailbox.filter((a)=>a.toAgentId===e&&(!n||!a.readAt)),s=typeof o==="number"&&o>0?i.slice(Math.max(0,i.length-o)):i;if(r){let a=new Date,d=!1;for(let l of s)if(!l.readAt)l.readAt=a,this.dirty.mailbox.add(l.id),d=!0;if(d)this.notifyStateDirty()}return s.map((a)=>({...a}))}getSnapshot(){let e={pending:0,in_progress:0,blocked:0,completed:0};for(let n of this.tasks.values())e[n.status]++;let t={draft:0,in_review:0,finalized:0};for(let n of this.outcomes.values())t[n.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((n)=>({agentId:n.agentId,role:n.role,description:n.description,status:n.status})),taskCounts:e,unreadMessages:this.mailbox.filter((n)=>!n.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((n)=>n.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((n)=>n.status==="queued").length,outcomeCounts:t}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((e)=>({agentId:e.agentId,role:e.role,description:e.description,status:e.status,...WPe(e),...e.role==="teammate"&&e.sampling?{sampling:e.sampling}:{},...e.control?.id?{cancelId:e.control.id}:{}})),tasks:Array.from(this.tasks.values()).map((e)=>({...e})),mailbox:this.mailbox.map((e)=>({...e})),missionLog:this.missionLog.map((e)=>({...e})),runs:Array.from(this.runs.values()).map((e)=>({...e,...e.result?{result:{...e.result,messages:[],toolCalls:[]}}:{},...e.status==="running"?$p(this.members.get(e.agentId)):{}})),outcomes:Array.from(this.outcomes.values()).map((e)=>({...e})),outcomeFragments:Array.from(this.outcomeFragments.values()).map((e)=>({...e}))}}hydrateState(e){this.clearQueuedRunDispatchTimer(),this.dirty=Fb(),this.tasks.clear();for(let n of e.tasks)this.tasks.set(n.id,{...n});this.mailbox.length=0,this.mailbox.push(...e.mailbox.map((n)=>({...n}))),this.missionLog.length=0,this.missionLog.push(...e.missionLog.map((n)=>({...n}))),this.runs.clear();for(let n of e.runs??[])this.runs.set(n.id,{...n,result:Ao(n.result)});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((n)=>n.status==="queued").map((n)=>n.id)),this.outcomes.clear();for(let n of e.outcomes??[])this.outcomes.set(n.id,{...n});this.outcomeFragments.clear();for(let n of e.outcomeFragments??[])this.outcomeFragments.set(n.id,{...n});let t=Array.from(this.members.values()).filter((n)=>n.role==="lead");this.members.clear();for(let n of t)this.members.set(n.agentId,{...n,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let n of e.members){if(n.role!=="teammate")continue;this.members.set(n.agentId,{agentId:n.agentId,role:"teammate",description:n.description,status:"stopped",...n.activity?{activity:n.activity}:{},...n.taskActivity?{taskActivity:n.taskActivity}:{},...n.sampling?{sampling:n.sampling}:{},agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,xc(e.tasks.map((n)=>n.id),"task_")),this.messageCounter=Math.max(this.messageCounter,xc(e.mailbox.map((n)=>n.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,xc(e.missionLog.map((n)=>n.id),"log_")),this.runCounter=Math.max(this.runCounter,xc((e.runs??[]).map((n)=>n.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,xc((e.outcomes??[]).map((n)=>n.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,xc((e.outcomeFragments??[]).map((n)=>n.id),"frag_"))}isTeammateActive(e){let t=this.members.get(e);return!!t&&t.role==="teammate"&&!!t.agent&&t.status!=="stopped"}requireTaskableTeammate(e){let t=this.members.get(e);if(!t||t.role!=="teammate"||!t.agent)throw Error(`Teammate "${e}" was not found`);if(t.status==="stopped")throw Error(BI(e));return t}assertCanSpawnTeammate(e){let t=this.members.get(e);if(t&&t.role!=="teammate")throw Error(`Team member "${e}" already exists and is not a teammate`);if(t&&t.runningCount>0)throw Error(`Teammate "${e}" is currently running and cannot be respawned`)}spawnTeammate({agentId:e,config:t,sampling:n}){this.assertCanSpawnTeammate(e);let r=this.members.get(e);if(r&&r.engineSessionId!==t.engineSessionId)this.releaseEngineSession(r);let o={...t,apiTimeoutMs:BPe,consumePendingUserMessage:()=>{let a=this.members.get(e),d=a?.control?.takeMessage();if(d!==void 0)return d;if(!a||!a.pendingSteerMessage)return;let l=a.pendingSteerMessage;return a.pendingSteerMessage=void 0,l},onEvent:(a)=>{t.onEvent?.(a);let d=this.members.get(e),l=d?.activityCounter?.observe(a)===!0,c=d?.currentTaskCounter?.observe(a)===!0;this.emitEvent({type:xe.AgentEvent,agentId:e,event:a,...l||c?{activityChanged:!0}:{}}),this.trackMeaningfulEvent(e,a)}},i=new Sa(o);if(o.onEvent)i.subscribeEvents(o.onEvent);let s={agentId:e,role:"teammate",description:t.role,status:"idle",agent:i,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now(),...t.engineSessionId?{engineSessionId:t.engineSessionId}:{},...n?{sampling:n}:{},activityCounter:bw(r?.activityCounter?.snapshot()??r?.activity),...r?.taskActivity||r?.currentTaskCounter?{taskActivity:r.currentTaskCounter?.snapshot()??r.taskActivity}:{}};return this.members.set(e,s),this.emitEvent({type:xe.TeammateSpawned,agentId:e,role:t.role,teammate:{rolePrompt:t.systemPrompt,modelId:t.modelId,maxIterations:t.maxIterations,...n?.temperature!==void 0?{temperature:n.temperature}:{},...n?.seed!==void 0?{seed:n.seed}:{},...n?.seedRandom?{seedRandom:!0}:{},...n?.temperatureBase!==void 0?{temperatureBase:n.temperatureBase}:{},...n?.temperatureRange!==void 0?{temperatureRange:n.temperatureRange}:{},runtimeAgentId:i.getAgentId(),conversationId:i.getConversationId(),parentAgentId:null}}),{agentId:s.agentId,role:s.role,description:s.description,status:s.status}}shutdownTeammate(e,t){let n=this.members.get(e);if(!n||n.role!=="teammate")throw Error(`Teammate "${e}" was not found`);let r=`Teammate "${e}" was shut down${t?` (${t})`:""}`;for(let o of this.runs.values())if(o.agentId===e&&(o.status==="queued"||o.status==="running"))this.cancelRun(o.id,r);if(this.abortTeammateRun(e,r),n.status="stopped",n.runningCount<=0)this.releaseWorkspace(e),this.releaseEngineSession(n);this.emitEvent({type:xe.TeammateShutdown,agentId:e,reason:t})}releaseWorkspace(e){this.teammateWorkspaces?.release(e).catch(()=>{})}releaseEngineSession(e){let t=e.engineSessionId;if(!t)return;e.engineSessionId=void 0,FI(t).catch(()=>{return})}releaseEngineSessionBetweenTasks(e){let t=e.engineSessionId;if(!t)return;e.pendingEngineRelease=FI(t).catch(()=>{return})}async rebookEngineSession(e,t){let n=e.engineSessionId;if(n){if(await FI(n).catch(()=>{return}),t)s4(n)}if(e.status==="stopped")throw UI(BI(e.agentId))}async runTeammateSegment(e,t,n,r){let o=n.signal,i=()=>{let s=n.id?pt.stoppedBy(n.id):void 0,a=n.id!==void 0&&pt.wrappingUp(n.id);if(s&&!e.abortRequested&&!a)e.abortRequested=!0,e.abortReason=s==="lead"?"Stopped by the lead.":"Stopped by the user.";try{t.abort(o?.reason)}catch(d){if(!Fp(d))throw d}};if(o?.aborted)throw i(),UI(e.abortReason??"The teammate's task was stopped.");o?.addEventListener("abort",i,{once:!0});try{if(n.track(t),"carry"in r){if(r.carry.wrapUp){e.wrappedUpBy=r.carry.wrapUp;let s=t.getMaxIterations();t.setMaxIterations(1);try{let a=await t.continue(IE(r.carry.wrapUp)),d=a.text?.trim();return d?{...a,text:`${CE(r.carry.wrapUp)}
1007
1007
 
1008
- ${d}`,finishReason:"completed"}:a}finally{t.setMaxIterations(s)}}return await t.continue(FPe(r.carry.reason))}return r.continueConversation?await t.continue(r.message):await t.run(r.message)}finally{o?.removeEventListener("abort",i)}}async handBackWorkspace(e){if(!this.teammateWorkspaces)return;try{return await this.teammateWorkspaces.handBack(e)}catch{return}}updateTeammateConnections(e){let t=this.acceptTeammateConnectionUpdates?.(e)??e;if(Object.keys(t).length===0)return;for(let n of this.members.values()){if(n.role!=="teammate"||!n.agent)continue;n.agent.updateConnection(t)}}createTask(e){let t=`task_${String(++this.taskCounter).padStart(4,"0")}`,n=new Date,r={id:t,title:e.title,description:e.description,status:e.assignee?"in_progress":"pending",createdAt:n,updatedAt:n,createdBy:e.createdBy,assignee:e.assignee,dependsOn:e.dependsOn??[]};return this.tasks.set(t,r),this.emitEvent({type:xe.TeamTaskUpdated,task:{...r}}),{...r}}claimTask(e,t){let n=this.requireTask(e);return this.assertDependenciesResolved(n),n.status="in_progress",n.assignee=t,n.updatedAt=new Date,this.emitEvent({type:xe.TeamTaskUpdated,task:{...n}}),this.appendMissionLog({agentId:t,taskId:e,kind:"progress",summary:`Claimed task "${n.title}"`}),{...n}}blockTask(e,t,n){let r=this.requireTask(e);return r.status="blocked",r.updatedAt=new Date,r.summary=n,this.emitEvent({type:xe.TeamTaskUpdated,task:{...r}}),this.appendMissionLog({agentId:t,taskId:e,kind:"blocked",summary:n}),{...r}}completeTask(e,t,n){let r=this.requireTask(e);if(r.status="completed",r.updatedAt=new Date,r.summary=n,!r.assignee)r.assignee=t;return this.emitEvent({type:xe.TeamTaskUpdated,task:{...r}}),this.appendMissionLog({agentId:t,taskId:e,kind:"done",summary:n}),{...r}}async routeToTeammate(e,t,n){let r=this.requireTaskableTeammate(e);if(r.runningCount>0||!r.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");r.abortRequested=!1,r.abortReason=void 0,r.wrappedUpBy=void 0,r.runningCount++,r.status="running",r.currentTaskCounter=bw();let o=bo(this.sessionId?hr(this.sessionId,`teammate:${e}`):void 0,void 0,e);r.control=o,this.emitEvent({type:xe.TaskStart,agentId:e,message:t});try{let i=r.pendingEngineRelease;if(i)r.pendingEngineRelease=void 0,await i;if(r.status==="stopped")throw UI(BI(e));if(!n?.continueConversation&&r.engineSessionId)s6(r.engineSessionId);let s=this.listMailbox(e,{unreadOnly:!0,markRead:!0}),a=s.length>0?`${this.buildMailboxNotification(s)}
1008
+ ${d}`,finishReason:"completed"}:a}finally{t.setMaxIterations(s)}}return await t.continue(FPe(r.carry.reason))}return r.continueConversation?await t.continue(r.message):await t.run(r.message)}finally{o?.removeEventListener("abort",i)}}async handBackWorkspace(e){if(!this.teammateWorkspaces)return;try{return await this.teammateWorkspaces.handBack(e)}catch{return}}updateTeammateConnections(e){let t=this.acceptTeammateConnectionUpdates?.(e)??e;if(Object.keys(t).length===0)return;for(let n of this.members.values()){if(n.role!=="teammate"||!n.agent)continue;n.agent.updateConnection(t)}}createTask(e){let t=`task_${String(++this.taskCounter).padStart(4,"0")}`,n=new Date,r={id:t,title:e.title,description:e.description,status:e.assignee?"in_progress":"pending",createdAt:n,updatedAt:n,createdBy:e.createdBy,assignee:e.assignee,dependsOn:e.dependsOn??[]};return this.tasks.set(t,r),this.emitEvent({type:xe.TeamTaskUpdated,task:{...r}}),{...r}}claimTask(e,t){let n=this.requireTask(e);return this.assertDependenciesResolved(n),n.status="in_progress",n.assignee=t,n.updatedAt=new Date,this.emitEvent({type:xe.TeamTaskUpdated,task:{...n}}),this.appendMissionLog({agentId:t,taskId:e,kind:"progress",summary:`Claimed task "${n.title}"`}),{...n}}blockTask(e,t,n){let r=this.requireTask(e);return r.status="blocked",r.updatedAt=new Date,r.summary=n,this.emitEvent({type:xe.TeamTaskUpdated,task:{...r}}),this.appendMissionLog({agentId:t,taskId:e,kind:"blocked",summary:n}),{...r}}completeTask(e,t,n){let r=this.requireTask(e);if(r.status="completed",r.updatedAt=new Date,r.summary=n,!r.assignee)r.assignee=t;return this.emitEvent({type:xe.TeamTaskUpdated,task:{...r}}),this.appendMissionLog({agentId:t,taskId:e,kind:"done",summary:n}),{...r}}async routeToTeammate(e,t,n){let r=this.requireTaskableTeammate(e);if(r.runningCount>0||!r.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");r.abortRequested=!1,r.abortReason=void 0,r.wrappedUpBy=void 0,r.runningCount++,r.status="running",r.currentTaskCounter=bw();let o=bo(this.sessionId?hr(this.sessionId,`teammate:${e}`):void 0,void 0,e);r.control=o,this.emitEvent({type:xe.TaskStart,agentId:e,message:t});try{let i=r.pendingEngineRelease;if(i)r.pendingEngineRelease=void 0,await i;if(r.status==="stopped")throw UI(BI(e));if(!n?.continueConversation&&r.engineSessionId)s4(r.engineSessionId);let s=this.listMailbox(e,{unreadOnly:!0,markRead:!0}),a=s.length>0?`${this.buildMailboxNotification(s)}
1009
1009
 
1010
- ${t}`:t,d=r.agent,l=d.getMaxIterations?.();if(n?.maxIterations!==void 0)d.setMaxIterations?.(n.maxIterations);let c=n?.continueConversation?d.getMessages():void 0,u;try{u=await o.restartable(()=>o.continuable((g)=>this.runTeammateSegment(r,d,o,g?{carry:g}:{message:qi(a,o.instructions),continueConversation:c!==void 0}),()=>this.rebookEngineSession(r,!1)),async()=>{if(c)d.restore(c);await this.rebookEngineSession(r,c===void 0)})}finally{if(n?.maxIterations!==void 0)d.setMaxIterations?.(l)}let h=await this.handBackWorkspace(e),f=u.finishReason==="aborted"&&!u.text.trim()?vK(d.getMessages()):"";if(h)u.text+=Ia(u.text,u.finishReason,e,h);if(f)u.text=`${f}${u.text}`;let m=UPe(u);if(this.emitEvent({type:xe.TaskEnd,agentId:e,status:m,result:u}),m==="completed")this.recordProgressStep(e,`Completed a delegated run (${u.iterations} iterations)`,n?.taskId,!0);else if(m==="failed")this.appendMissionLog({agentId:e,taskId:n?.taskId,kind:"error",summary:u.text||"Teammate run failed"});return u}catch(i){let s=i instanceof Error?i:Error(String(i)),a=await this.handBackWorkspace(e);if(a&&a.length>0)s.message+=Ia("","error",e,a);let d=a6(r,s);if(this.emitEvent({type:xe.TaskEnd,agentId:e,status:d?"cancelled":"failed",error:s,messages:r.agent.getMessages()}),!d)this.appendMissionLog({agentId:e,taskId:n?.taskId,kind:"error",summary:s.message});throw s}finally{if(o.release(),r.control===o)r.control=void 0;if(r.runningCount--,r.runningCount<=0&&this.members.get(e)?.status!=="stopped")r.status="idle",this.releaseEngineSessionBetweenTasks(r),this.dispatchQueuedRuns();else if(r.runningCount<=0&&r.status==="stopped")this.releaseWorkspace(e),this.releaseEngineSession(r)}}startTeammateRun(e,t,n){this.requireTaskableTeammate(e);let r=`run_${String(++this.runCounter).padStart(5,"0")}`,o={id:r,agentId:e,taskId:n?.taskId,status:"queued",message:t,priority:n?.priority??0,retryCount:0,maxRetries:Math.max(0,n?.maxRetries??0),continueConversation:n?.continueConversation,...n?.maxIterations!==void 0?{maxIterations:n.maxIterations}:{},startedAt:new Date(0),leaseOwner:n?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(r,o),this.runQueue.push(r),this.emitEvent({type:xe.RunQueued,run:{...o}}),this.dispatchQueuedRuns(),{...o}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let e;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let t=this.selectNextDispatchableQueuedRun();e=t.nextDelayedAttemptAt;let n=t.index;if(n<0){this.scheduleQueuedRunDispatch(e);return}let[r]=this.runQueue.splice(n,1),o=r?this.runs.get(r):void 0;if(!o||o.status!=="queued")continue;this.executeQueuedRun(o)}this.scheduleQueuedRunDispatch(e)}selectNextDispatchableQueuedRun(){let e=-1,t=Number.NEGATIVE_INFINITY,n,r=Date.now();for(let o=0;o<this.runQueue.length;o++){let i=this.runs.get(this.runQueue[o]);if(!i||i.status!=="queued")continue;if(!this.canTakeQueuedRun(i.agentId))continue;if(i.nextAttemptAt&&i.nextAttemptAt.getTime()>r){if(!n||i.nextAttemptAt<n)n=i.nextAttemptAt;continue}if(i.priority>t)t=i.priority,e=o}return{index:e,nextDelayedAttemptAt:n}}canTakeQueuedRun(e){let t=this.members.get(e);if(!t||t.role!=="teammate"||!t.agent||t.status==="stopped"||t.runningCount>0)return!1;for(let n of this.runs.values())if(n.agentId===e&&n.status==="running")return!1;return!0}scheduleQueuedRunDispatch(e){if(!e)return;let t=Math.max(0,e.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},t)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let e=0;for(let t of this.runs.values())if(t.status==="running")e++;return e}async executeQueuedRun(e){let t=e.currentActivity===d6;e.nextAttemptAt=void 0,e.status="running",e.startedAt=new Date,e.heartbeatAt=new Date,e.currentActivity="run_started",this.emitEvent({type:xe.RunStarted,run:{...e}});let n=()=>JSON.stringify($p(this.members.get(e.agentId))),r=JSON.stringify($p({currentTaskCounter:bw()})),o=setInterval(()=>{if(e.status!=="running")return;let i=n();if(i===r){e.heartbeatAt=new Date;return}r=i,this.recordRunProgress(e,"heartbeat")},2000);try{let i=t?HPe(e):e.message,s=await this.routeToTeammate(e.agentId,i,{taskId:e.taskId,continueConversation:e.continueConversation,...e.maxIterations!==void 0?{maxIterations:e.maxIterations}:{}});if(this.runs.get(e.id)?.status!=="running")return;let a=this.members.get(e.agentId)?.wrappedUpBy;if(a&&s.finishReason!=="aborted"){this.cancelRun(e.id,`Stopped gracefully by the ${a}; its result is its report of where it stopped.`),e.result=s;return}let d=this.members.get(e.agentId)?.abortReason;if(d!==void 0||s.finishReason==="aborted"){this.cancelRun(e.id,d??"aborted");return}if(s.finishReason==="error"||s.finishReason==="max_iterations")throw Error(s.finishReason==="max_iterations"?`Teammate run stopped at its iteration cap (${s.iterations} iterations); its conversation is kept -- run the task again with continueConversation to go on.`:s.text||"Teammate run failed");e.status="completed",e.result=Ao(s),e.endedAt=new Date,Object.assign(e,$p(this.members.get(e.agentId))),e.currentActivity="completed",this.emitEvent({type:xe.RunCompleted,run:{...e}})}catch(i){let s=i instanceof Error?i.message:String(i??"Unknown error");if(this.runs.get(e.id)?.status!=="running")return;e.error=s,e.endedAt=new Date;let a=this.members.get(e.agentId);if(Object.assign(e,$p(a)),Fp(i)&&a6(a,i))this.cancelRun(e.id,a?.abortReason??s);else if(e.retryCount<e.maxRetries)e.retryCount++,e.status="queued",e.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**e.retryCount)),this.runQueue.push(e.id),this.recordRunProgress(e,`retry_scheduled_${e.retryCount}`);else e.status="failed",e.currentActivity="failed",this.emitEvent({type:xe.RunFailed,run:{...e}})}finally{clearInterval(o),this.dispatchQueuedRuns()}}listRuns(e){let t=e?.includeCompleted??!0;return Array.from(this.runs.values()).filter((n)=>{if(!t&&!["running","queued"].includes(n.status))return!1;if(e?.status&&n.status!==e.status)return!1;if(e?.agentId&&n.agentId!==e.agentId)return!1;return!0}).map((n)=>({...n}))}getRun(e){let t=this.runs.get(e);return t?{...t}:void 0}async awaitRun(e,t=250,n){let r=this.runs.get(e);if(!r)throw Error(`Run "${e}" was not found`);if(n!==void 0&&r.agentId===n&&(r.status==="queued"||r.status==="running"))throw Error(`Run "${e}" is your own run: it ends when you finish this task, so waiting for it would never return.`);while(r.status==="queued"||r.status==="running")await l6(t);return{...r}}async awaitAllRuns(e=250,t){let n=(r)=>t===void 0||r.agentId!==t;while(Array.from(this.runs.values()).some((r)=>n(r)&&["queued","running"].includes(r.status)))await l6(e);return this.listRuns().filter(n)}cancelOutstandingWork(e){let t=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"parent_session_abort":String(e);this.clearQueuedRunDispatchTimer();let n;for(let r of this.runs.values())if(r.status==="queued"||r.status==="running")try{this.cancelRun(r.id,t)}catch(o){n??=o}for(let r of this.members.values())try{this.abortTeammateRun(r.agentId,t)}catch(o){n??=o}if(n!==void 0)throw n}cancelRun(e,t){let n=this.runs.get(e);if(!n)throw Error(`Run "${e}" was not found`);if(n.status==="completed"||n.status==="failed"||n.status==="cancelled"||n.status==="interrupted")return{...n};let r=n.status==="running";n.status="cancelled",n.error=t,n.endedAt=new Date,n.currentActivity="cancelled";let o=this.runQueue.indexOf(e);if(o>=0)this.runQueue.splice(o,1);if(this.emitEvent({type:xe.RunCancelled,run:{...n},reason:t}),r)this.abortTeammateRun(n.agentId,t??"cancelled");return{...n}}abortTeammateRun(e,t){let n=this.members.get(e);if(!n||n.role!=="teammate"||!n.agent||n.runningCount<=0||n.abortRequested)return;n.abortRequested=!0,n.abortReason=t;try{n.agent.abort(Error(t))}catch(r){if(!Fp(r))throw r}}recoverActiveRuns(e="runtime_recovered"){let t=[];for(let n of this.runs.values()){if(!["queued","running"].includes(n.status))continue;let r=this.members.get(n.agentId);if(!r||r.role!=="teammate"||!r.agent){n.status="interrupted",n.error="teammate_unavailable_after_recovery",n.endedAt=new Date,n.currentActivity="interrupted",this.emitEvent({type:xe.RunInterrupted,run:{...n},reason:n.error});continue}let o=new Date;if(n.status="queued",n.error=void 0,n.endedAt=void 0,n.heartbeatAt=o,n.lastProgressAt=o,n.lastProgressMessage=e,n.currentActivity=d6,!this.runQueue.includes(n.id))this.runQueue.push(n.id);t.push({...n}),this.emitEvent({type:xe.RunQueued,run:{...n}})}return this.dispatchQueuedRuns(),t}markStaleRunsInterrupted(e="runtime_recovered"){let t=[];for(let n of this.runs.values()){if(!["queued","running"].includes(n.status))continue;n.status="interrupted",n.error=e,n.endedAt=new Date,n.currentActivity="interrupted",t.push({...n}),this.emitEvent({type:xe.RunInterrupted,run:{...n},reason:e})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),t}sendMessage(e,t,n,r,o){if(!this.members.has(e))throw Error(`Unknown sender "${e}"`);let i=this.members.get(t)??(t==="lead"?Array.from(this.members.values()).find((a)=>a.role==="lead"):void 0);if(!i)throw Error(`Unknown recipient "${t}"`);let s={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:e,toAgentId:i.agentId,subject:n,body:r,taskId:o,sentAt:new Date};if(this.mailbox.push(s),this.emitEvent({type:xe.TeamMessage,message:{...s}}),i.role==="teammate"&&i.runningCount>0&&i.agent)i.pendingSteerMessage=`[MAILBOX] You got a message from ${e}. Subject: "${n}". Use the team_read_mailbox tool to read it at your convenience.`;return{...s}}broadcast(e,t,n,r){let o=[];for(let i of this.members.values()){if(i.agentId===e)continue;if(i.role==="lead")continue;o.push(this.sendMessage(e,i.agentId,t,n,r?.taskId))}return o}appendMissionLog(e){if(!this.members.has(e.agentId))throw Error(`Unknown team member "${e.agentId}"`);let t={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:e.agentId,taskId:e.taskId,kind:e.kind,summary:e.summary,evidence:e.evidence,nextAction:e.nextAction};this.missionLog.push(t);let n=this.members.get(e.agentId);if(n)n.lastMissionAt=Date.now(),n.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:xe.TeamMissionLog,entry:{...t}}),{...t}}createOutcome(e){let t={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:e.title,status:"draft",requiredSections:[...new Set(e.requiredSections)],createdBy:e.createdBy,createdAt:new Date};return this.outcomes.set(t.id,t),this.emitEvent({type:xe.OutcomeCreated,outcome:{...t}}),{...t}}listOutcomes(){return Array.from(this.outcomes.values()).map((e)=>({...e}))}attachOutcomeFragment(e){let t=this.outcomes.get(e.outcomeId);if(!t)throw Error(`Outcome "${e.outcomeId}" was not found`);if(!t.requiredSections.includes(e.section))throw Error(`Section "${e.section}" is not part of outcome "${e.outcomeId}"`);let n={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:e.outcomeId,section:e.section,sourceAgentId:e.sourceAgentId,sourceRunId:e.sourceRunId,content:e.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(n.id,n),t.status==="draft")t.status="in_review",this.dirty.outcomes.add(t.id);return this.emitEvent({type:xe.OutcomeFragmentAttached,fragment:{...n}}),{...n}}reviewOutcomeFragment(e){let t=this.outcomeFragments.get(e.fragmentId);if(!t)throw Error(`Fragment "${e.fragmentId}" was not found`);return t.status=e.approved?"reviewed":"rejected",t.reviewedBy=e.reviewedBy,t.reviewedAt=new Date,this.emitEvent({type:xe.OutcomeFragmentReviewed,fragment:{...t}}),{...t}}listOutcomeFragments(e){return Array.from(this.outcomeFragments.values()).filter((t)=>t.outcomeId===e).map((t)=>({...t}))}finalizeOutcome(e){let t=this.outcomes.get(e);if(!t)throw Error(`Outcome "${e}" was not found`);let n=this.listOutcomeFragments(e);for(let r of t.requiredSections)if(!n.some((i)=>i.section===r&&i.status==="reviewed"))throw Error(`Outcome "${e}" cannot be finalized. Section "${r}" is missing a reviewed fragment.`);return t.status="finalized",t.finalizedAt=new Date,this.emitEvent({type:xe.OutcomeFinalized,outcome:{...t}}),{...t}}cleanup(){for(let e of this.members.values())if(e.role==="teammate"&&e.runningCount>0)throw Error(`Cannot cleanup team while teammate "${e.agentId}" is still running`);if(Array.from(this.runs.values()).some((e)=>["queued","running"].includes(e.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let e of this.members.values())if(e.role==="teammate")try{e.agent?.abort()}catch(t){if(!Fp(t))throw t}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[e,t]of this.members.entries())if(t.role==="teammate")this.members.delete(e),this.releaseWorkspace(e),this.releaseEngineSession(t),this.emitEvent({type:xe.TeammateShutdown,agentId:e,reason:"team_cleanup"});this.emitEvent({type:xe.TeamCleaned}),this.dirty=Fb(),this.dirty.reset=!0,this.notifyStateDirty()}requireTask(e){let t=this.tasks.get(e);if(!t)throw Error(`Task "${e}" was not found`);return t}assertDependenciesResolved(e){let t=this.getUnresolvedDependencies(e);if(t.length>0)throw Error(`Task "${e.id}" is blocked by "${t[0]}"`)}getUnresolvedDependencies(e){return e.dependsOn.filter((t)=>{let n=this.tasks.get(t);return!n||n.status!=="completed"})}trackMeaningfulEvent(e,t){if(this.recordRunActivityFromAgentEvent(e,t),t.type==="iteration_end"&&t.hadToolCalls){this.recordProgressStep(e,`Completed iteration ${t.iteration} with ${t.toolCallCount} tool call(s)`);return}if(t.type==="content_end"&&t.contentType==="tool"&&!t.error){this.recordProgressStep(e,`Finished tool "${t.toolName??"unknown"}"`);return}if(t.type==="done"){this.appendMissionLog({agentId:e,kind:"done",summary:`Completed a delegated run (${t.iterations} iterations)`});return}if(t.type==="error")this.appendMissionLog({agentId:e,kind:"error",summary:t.error.message})}recordRunActivityFromAgentEvent(e,t){let n;switch(t.type){case"iteration_start":n=`iteration_${t.iteration}_started`;break;case"content_start":if(t.contentType==="tool")n=`running_tool_${t.toolName??"unknown"}`;break;case"content_end":if(t.contentType==="tool")n=t.error?this.formatProgressErrorActivity(`tool_${t.toolName??"unknown"}_error`,t.error):`finished_tool_${t.toolName??"unknown"}`;break;case"done":n="finalizing_response";break;case"error":n=this.formatProgressErrorActivity("run_error",t.error.message);break;default:break}if(!n)return;for(let r of this.runs.values()){if(r.agentId!==e||r.status!=="running")continue;this.recordRunProgress(r,n)}}recordRunProgress(e,t){let n=new Date;e.heartbeatAt=n,e.lastProgressAt=n,e.lastProgressMessage=t,e.currentActivity=t,this.emitEvent({type:xe.RunProgress,run:{...e},message:t})}formatProgressErrorActivity(e,t){let n=t.replace(/\s+/g," ").trim();if(n.length===0)return e;let r=n.length>240?`${n.slice(0,237).trimEnd()}...`:n;return`${e}: ${r}`}recordProgressStep(e,t,n,r=!1){this.missionStepCounter++;let o=this.members.get(e);if(!o)return;let i=this.missionStepCounter-o.lastMissionStep,s=Date.now()-o.lastMissionAt;if(!r&&i<this.missionLogIntervalSteps&&s<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:e,taskId:n,kind:"progress",summary:t})}buildMailboxNotification(e){if(e.length===0)return"";let t=[`[MAILBOX] You have ${e.length} unread message(s):`];for(let n of e)t.push(`--- Message from ${n.fromAgentId} | subject: ${n.subject} ---`),t.push(n.body);return t.push("---"),t.join(`
1011
- `)}markDirtyFromEvent(e){switch(e.type){case xe.TeamTaskUpdated:this.dirty.tasks.add(e.task.id);break;case xe.TeamMessage:this.dirty.mailbox.add(e.message.id);break;case xe.TeamMissionLog:this.dirty.missionLog.add(e.entry.id);break;case xe.RunQueued:case xe.RunStarted:case xe.RunCompleted:case xe.RunFailed:case xe.RunCancelled:case xe.RunInterrupted:case xe.RunProgress:this.dirty.runs.add(e.run.id);break;case xe.OutcomeCreated:case xe.OutcomeFinalized:this.dirty.outcomes.add(e.outcome.id);break;case xe.OutcomeFragmentAttached:case xe.OutcomeFragmentReviewed:this.dirty.outcomeFragments.add(e.fragment.id);break;default:break}}hasPendingStateDelta(){let e=this.dirty;return e.reset||e.tasks.size>0||e.mailbox.size>0||e.missionLog.size>0||e.runs.size>0||e.outcomes.size>0||e.outcomeFragments.size>0}drainStateDelta(){let e=this.dirty;this.dirty=Fb();let t=(o,i)=>{let s=[];for(let a of o){let d=i(a);if(d!==void 0)s.push({...d})}return s},n=e.mailbox.size>0?new Map(this.mailbox.map((o)=>[o.id,o])):void 0,r=e.missionLog.size>0?new Map(this.missionLog.map((o)=>[o.id,o])):void 0;return{teamId:this.teamId,teamName:this.teamName,reset:e.reset,members:this.exportMembers(),tasks:t(e.tasks,(o)=>this.tasks.get(o)),mailbox:t(e.mailbox,(o)=>n?.get(o)),missionLog:t(e.missionLog,(o)=>r?.get(o)),runs:t(e.runs,(o)=>this.runs.get(o)),outcomes:t(e.outcomes,(o)=>this.outcomes.get(o)),outcomeFragments:t(e.outcomeFragments,(o)=>this.outcomeFragments.get(o))}}requeueStateDelta(e){this.dirty.reset=this.dirty.reset||e.reset;for(let t of e.tasks)this.dirty.tasks.add(t.id);for(let t of e.mailbox)this.dirty.mailbox.add(t.id);for(let t of e.missionLog)this.dirty.missionLog.add(t.id);for(let t of e.runs)this.dirty.runs.add(t.id);for(let t of e.outcomes)this.dirty.outcomes.add(t.id);for(let t of e.outcomeFragments)this.dirty.outcomeFragments.add(t.id)}notifyStateDirty(){try{this.onStateDirty?.()}catch{}}markAllStateDirty(e=!0){this.dirty.reset=this.dirty.reset||e;for(let t of this.tasks.keys())this.dirty.tasks.add(t);for(let t of this.mailbox)this.dirty.mailbox.add(t.id);for(let t of this.missionLog)this.dirty.missionLog.add(t.id);for(let t of this.runs.keys())this.dirty.runs.add(t);for(let t of this.outcomes.keys())this.dirty.outcomes.add(t);for(let t of this.outcomeFragments.keys())this.dirty.outcomeFragments.add(t)}exportMembers(){return Array.from(this.members.values()).map((e)=>({agentId:e.agentId,role:e.role,description:e.description,status:e.status}))}emitEvent(e){this.markDirtyFromEvent(e);try{this.onTeamEvent?.(e)}catch{}}}function l6(e){return new Promise((t)=>setTimeout(t,e))}function xc(e,t){let n=0;for(let r of e){if(!r.startsWith(t))continue;let o=Number.parseInt(r.slice(t.length),10);if(Number.isFinite(o))n=Math.max(n,o)}return n}function WPe(e){if(e.role!=="teammate")return{};let t=e.activityCounter?.snapshot()??e.activity,n=e.currentTaskCounter?.snapshot()??e.taskActivity;return{...t?{activity:t}:{},...n?{taskActivity:n}:{}}}function $p(e){let t=e?.currentTaskCounter?.snapshot();return t?{activity:t}:{}}var jPe=/session allocation full/i;function c6(e){if(!e)return!1;let t=e instanceof Error?e.message:typeof e==="string"?e:"";return jPe.test(t)}var qPe=(e)=>new Promise((t)=>setTimeout(t,e));async function HI(e,t={}){let n=Math.max(1,t.attempts??3),r=t.sleep??qPe;for(let o=1;;o+=1)try{return await e()}catch(i){if(!c6(i)||o>=n)throw i;let s=2000*2**(o-1);t.onRetry?.(o,s),await r(s)}}function WI(e,t){switch(t.type){case"run_queued":case"run_started":e.activeTeamRunIds.add(t.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let n;if(t.type==="run_failed")n=t.run.error;else if(t.type==="run_cancelled"||t.type==="run_interrupted")n=t.run.error??t.reason;e.activeTeamRunIds.delete(t.run.id),e.pendingTeamRunUpdates.push({runId:t.run.id,agentId:t.run.agentId,taskId:t.run.taskId,status:t.type.replace("run_",""),error:n,iterations:t.run.result?.iterations}),Bp(e);break}default:break}}async function jI(e,t,n){switch(t.type){case"run_progress":await n("onTeamTaskProgress",e,t.run.agentId,t.message,{kind:t.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(t.event.type==="content_start"&&t.event.contentType==="text"&&typeof t.event.text==="string"){let r=t.event.text.replace(/\s+/g," ").trim().slice(0,120);if(r)await n("onTeamTaskProgress",e,t.agentId,r,{kind:"text"})}break;case"task_start":await n("onTeamTaskStart",e,t.agentId,t.message);break;case"task_end":{let r=t.status??(t.error?"failed":t.result?.finishReason==="aborted"?"cancelled":"completed");if(r==="cancelled")await n("onTeamTaskEnd",e,t.agentId,"cancelled","[done] aborted",t.result,t.result?.messages??t.messages);else if(r==="failed"){let o=t.error?.message||t.result?.text||"Teammate task failed";await n("onTeamTaskEnd",e,t.agentId,"failed",`[error] ${o}`,t.result,t.result?.messages??t.messages)}else await n("onTeamTaskEnd",e,t.agentId,"completed",`[done] ${t.result?.finishReason??"completed"}`,t.result,t.result?.messages);break}default:break}}var KPe=1000,u6=new WeakMap;function qI(e,t,n,r,o=Date.now){let i=e.runtime.teamRuntime;if(!i)return;let s=()=>GPe(e,t,n,r),a=u6.get(i);if(!a)a={last:0},u6.set(i,a);if(pi(n)){a.pending=void 0,s();return}let d=o(),l=KPe-(d-a.last);if(l<=0){a.last=d,a.pending=void 0,s();return}if(a.pending=s,!a.timer){let c=a;c.timer=setTimeout(()=>{c.timer=void 0;let u=c.pending;if(c.pending=void 0,u)c.last=o(),u()},l),c.timer.unref?.()}}function GPe(e,t,n,r){let o=e.runtime.teamRuntime;if(!o)return;let i=o.getTeamName(),s=o.exportState();r({type:"team_progress",payload:{sessionId:t,teamName:i,lifecycle:$I({teamName:i,sessionId:t,event:n}),summary:DI(i,s),teammates:s.members.filter((a)=>a.role==="teammate")}})}function Up(e){return e.activeTeamRunIds.size>0||e.pendingTeamRunUpdates.length>0}function zI(e,t){if(e.aborting)return!1;if(!(t==="completed"||t==="max_iterations"))return!1;return e.config.enableAgentTeams===!0&&Up(e)}function Bp(e){let t=e.teamRunWaiters.splice(0);for(let n of t)n()}async function KI(e){while(!0){if(e.aborting)return[];if(e.pendingTeamRunUpdates.length>0){let t=[...e.pendingTeamRunUpdates];return e.pendingTeamRunUpdates.length=0,t}if(e.activeTeamRunIds.size===0)return[];await new Promise((t)=>{e.teamRunWaiters.push(t)})}}function GI(e,t){let n=t.map((i)=>{let s=[`- ${i.runId} (${i.agentId}) -> ${i.status}`];if(i.taskId)s.push(` task=${i.taskId}`);if(typeof i.iterations==="number")s.push(` iterations=${i.iterations}`);if(i.error)s.push(` error=${i.error}`);return s.join("")}),r=e.activeTeamRunIds.size,o=r>0?`There are still ${r} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return _c(`System-delivered teammate async run updates:
1010
+ ${t}`:t,d=r.agent,l=d.getMaxIterations?.();if(n?.maxIterations!==void 0)d.setMaxIterations?.(n.maxIterations);let c=n?.continueConversation?d.getMessages():void 0,u;try{u=await o.restartable(()=>o.continuable((g)=>this.runTeammateSegment(r,d,o,g?{carry:g}:{message:qi(a,o.instructions),continueConversation:c!==void 0}),()=>this.rebookEngineSession(r,!1)),async()=>{if(c)d.restore(c);await this.rebookEngineSession(r,c===void 0)})}finally{if(n?.maxIterations!==void 0)d.setMaxIterations?.(l)}let h=await this.handBackWorkspace(e),f=u.finishReason==="aborted"&&!u.text.trim()?vK(d.getMessages()):"";if(h)u.text+=Ia(u.text,u.finishReason,e,h);if(f)u.text=`${f}${u.text}`;let m=UPe(u);if(this.emitEvent({type:xe.TaskEnd,agentId:e,status:m,result:u}),m==="completed")this.recordProgressStep(e,`Completed a delegated run (${u.iterations} iterations)`,n?.taskId,!0);else if(m==="failed")this.appendMissionLog({agentId:e,taskId:n?.taskId,kind:"error",summary:u.text||"Teammate run failed"});return u}catch(i){let s=i instanceof Error?i:Error(String(i)),a=await this.handBackWorkspace(e);if(a&&a.length>0)s.message+=Ia("","error",e,a);let d=a4(r,s);if(this.emitEvent({type:xe.TaskEnd,agentId:e,status:d?"cancelled":"failed",error:s,messages:r.agent.getMessages()}),!d)this.appendMissionLog({agentId:e,taskId:n?.taskId,kind:"error",summary:s.message});throw s}finally{if(o.release(),r.control===o)r.control=void 0;if(r.runningCount--,r.runningCount<=0&&this.members.get(e)?.status!=="stopped")r.status="idle",this.releaseEngineSessionBetweenTasks(r),this.dispatchQueuedRuns();else if(r.runningCount<=0&&r.status==="stopped")this.releaseWorkspace(e),this.releaseEngineSession(r)}}startTeammateRun(e,t,n){this.requireTaskableTeammate(e);let r=`run_${String(++this.runCounter).padStart(5,"0")}`,o={id:r,agentId:e,taskId:n?.taskId,status:"queued",message:t,priority:n?.priority??0,retryCount:0,maxRetries:Math.max(0,n?.maxRetries??0),continueConversation:n?.continueConversation,...n?.maxIterations!==void 0?{maxIterations:n.maxIterations}:{},startedAt:new Date(0),leaseOwner:n?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(r,o),this.runQueue.push(r),this.emitEvent({type:xe.RunQueued,run:{...o}}),this.dispatchQueuedRuns(),{...o}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let e;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let t=this.selectNextDispatchableQueuedRun();e=t.nextDelayedAttemptAt;let n=t.index;if(n<0){this.scheduleQueuedRunDispatch(e);return}let[r]=this.runQueue.splice(n,1),o=r?this.runs.get(r):void 0;if(!o||o.status!=="queued")continue;this.executeQueuedRun(o)}this.scheduleQueuedRunDispatch(e)}selectNextDispatchableQueuedRun(){let e=-1,t=Number.NEGATIVE_INFINITY,n,r=Date.now();for(let o=0;o<this.runQueue.length;o++){let i=this.runs.get(this.runQueue[o]);if(!i||i.status!=="queued")continue;if(!this.canTakeQueuedRun(i.agentId))continue;if(i.nextAttemptAt&&i.nextAttemptAt.getTime()>r){if(!n||i.nextAttemptAt<n)n=i.nextAttemptAt;continue}if(i.priority>t)t=i.priority,e=o}return{index:e,nextDelayedAttemptAt:n}}canTakeQueuedRun(e){let t=this.members.get(e);if(!t||t.role!=="teammate"||!t.agent||t.status==="stopped"||t.runningCount>0)return!1;for(let n of this.runs.values())if(n.agentId===e&&n.status==="running")return!1;return!0}scheduleQueuedRunDispatch(e){if(!e)return;let t=Math.max(0,e.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},t)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let e=0;for(let t of this.runs.values())if(t.status==="running")e++;return e}async executeQueuedRun(e){let t=e.currentActivity===d4;e.nextAttemptAt=void 0,e.status="running",e.startedAt=new Date,e.heartbeatAt=new Date,e.currentActivity="run_started",this.emitEvent({type:xe.RunStarted,run:{...e}});let n=()=>JSON.stringify($p(this.members.get(e.agentId))),r=JSON.stringify($p({currentTaskCounter:bw()})),o=setInterval(()=>{if(e.status!=="running")return;let i=n();if(i===r){e.heartbeatAt=new Date;return}r=i,this.recordRunProgress(e,"heartbeat")},2000);try{let i=t?HPe(e):e.message,s=await this.routeToTeammate(e.agentId,i,{taskId:e.taskId,continueConversation:e.continueConversation,...e.maxIterations!==void 0?{maxIterations:e.maxIterations}:{}});if(this.runs.get(e.id)?.status!=="running")return;let a=this.members.get(e.agentId)?.wrappedUpBy;if(a&&s.finishReason!=="aborted"){this.cancelRun(e.id,`Stopped gracefully by the ${a}; its result is its report of where it stopped.`),e.result=s;return}let d=this.members.get(e.agentId)?.abortReason;if(d!==void 0||s.finishReason==="aborted"){this.cancelRun(e.id,d??"aborted");return}if(s.finishReason==="error"||s.finishReason==="max_iterations")throw Error(s.finishReason==="max_iterations"?`Teammate run stopped at its iteration cap (${s.iterations} iterations); its conversation is kept -- run the task again with continueConversation to go on.`:s.text||"Teammate run failed");e.status="completed",e.result=Ao(s),e.endedAt=new Date,Object.assign(e,$p(this.members.get(e.agentId))),e.currentActivity="completed",this.emitEvent({type:xe.RunCompleted,run:{...e}})}catch(i){let s=i instanceof Error?i.message:String(i??"Unknown error");if(this.runs.get(e.id)?.status!=="running")return;e.error=s,e.endedAt=new Date;let a=this.members.get(e.agentId);if(Object.assign(e,$p(a)),Fp(i)&&a4(a,i))this.cancelRun(e.id,a?.abortReason??s);else if(e.retryCount<e.maxRetries)e.retryCount++,e.status="queued",e.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**e.retryCount)),this.runQueue.push(e.id),this.recordRunProgress(e,`retry_scheduled_${e.retryCount}`);else e.status="failed",e.currentActivity="failed",this.emitEvent({type:xe.RunFailed,run:{...e}})}finally{clearInterval(o),this.dispatchQueuedRuns()}}listRuns(e){let t=e?.includeCompleted??!0;return Array.from(this.runs.values()).filter((n)=>{if(!t&&!["running","queued"].includes(n.status))return!1;if(e?.status&&n.status!==e.status)return!1;if(e?.agentId&&n.agentId!==e.agentId)return!1;return!0}).map((n)=>({...n}))}getRun(e){let t=this.runs.get(e);return t?{...t}:void 0}async awaitRun(e,t=250,n){let r=this.runs.get(e);if(!r)throw Error(`Run "${e}" was not found`);if(n!==void 0&&r.agentId===n&&(r.status==="queued"||r.status==="running"))throw Error(`Run "${e}" is your own run: it ends when you finish this task, so waiting for it would never return.`);while(r.status==="queued"||r.status==="running")await l4(t);return{...r}}async awaitAllRuns(e=250,t){let n=(r)=>t===void 0||r.agentId!==t;while(Array.from(this.runs.values()).some((r)=>n(r)&&["queued","running"].includes(r.status)))await l4(e);return this.listRuns().filter(n)}cancelOutstandingWork(e){let t=typeof e==="string"?e:e instanceof Error?e.message:e===void 0?"parent_session_abort":String(e);this.clearQueuedRunDispatchTimer();let n;for(let r of this.runs.values())if(r.status==="queued"||r.status==="running")try{this.cancelRun(r.id,t)}catch(o){n??=o}for(let r of this.members.values())try{this.abortTeammateRun(r.agentId,t)}catch(o){n??=o}if(n!==void 0)throw n}cancelRun(e,t){let n=this.runs.get(e);if(!n)throw Error(`Run "${e}" was not found`);if(n.status==="completed"||n.status==="failed"||n.status==="cancelled"||n.status==="interrupted")return{...n};let r=n.status==="running";n.status="cancelled",n.error=t,n.endedAt=new Date,n.currentActivity="cancelled";let o=this.runQueue.indexOf(e);if(o>=0)this.runQueue.splice(o,1);if(this.emitEvent({type:xe.RunCancelled,run:{...n},reason:t}),r)this.abortTeammateRun(n.agentId,t??"cancelled");return{...n}}abortTeammateRun(e,t){let n=this.members.get(e);if(!n||n.role!=="teammate"||!n.agent||n.runningCount<=0||n.abortRequested)return;n.abortRequested=!0,n.abortReason=t;try{n.agent.abort(Error(t))}catch(r){if(!Fp(r))throw r}}recoverActiveRuns(e="runtime_recovered"){let t=[];for(let n of this.runs.values()){if(!["queued","running"].includes(n.status))continue;let r=this.members.get(n.agentId);if(!r||r.role!=="teammate"||!r.agent){n.status="interrupted",n.error="teammate_unavailable_after_recovery",n.endedAt=new Date,n.currentActivity="interrupted",this.emitEvent({type:xe.RunInterrupted,run:{...n},reason:n.error});continue}let o=new Date;if(n.status="queued",n.error=void 0,n.endedAt=void 0,n.heartbeatAt=o,n.lastProgressAt=o,n.lastProgressMessage=e,n.currentActivity=d4,!this.runQueue.includes(n.id))this.runQueue.push(n.id);t.push({...n}),this.emitEvent({type:xe.RunQueued,run:{...n}})}return this.dispatchQueuedRuns(),t}markStaleRunsInterrupted(e="runtime_recovered"){let t=[];for(let n of this.runs.values()){if(!["queued","running"].includes(n.status))continue;n.status="interrupted",n.error=e,n.endedAt=new Date,n.currentActivity="interrupted",t.push({...n}),this.emitEvent({type:xe.RunInterrupted,run:{...n},reason:e})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),t}sendMessage(e,t,n,r,o){if(!this.members.has(e))throw Error(`Unknown sender "${e}"`);let i=this.members.get(t)??(t==="lead"?Array.from(this.members.values()).find((a)=>a.role==="lead"):void 0);if(!i)throw Error(`Unknown recipient "${t}"`);let s={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:e,toAgentId:i.agentId,subject:n,body:r,taskId:o,sentAt:new Date};if(this.mailbox.push(s),this.emitEvent({type:xe.TeamMessage,message:{...s}}),i.role==="teammate"&&i.runningCount>0&&i.agent)i.pendingSteerMessage=`[MAILBOX] You got a message from ${e}. Subject: "${n}". Use the team_read_mailbox tool to read it at your convenience.`;return{...s}}broadcast(e,t,n,r){let o=[];for(let i of this.members.values()){if(i.agentId===e)continue;if(i.role==="lead")continue;o.push(this.sendMessage(e,i.agentId,t,n,r?.taskId))}return o}appendMissionLog(e){if(!this.members.has(e.agentId))throw Error(`Unknown team member "${e.agentId}"`);let t={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:e.agentId,taskId:e.taskId,kind:e.kind,summary:e.summary,evidence:e.evidence,nextAction:e.nextAction};this.missionLog.push(t);let n=this.members.get(e.agentId);if(n)n.lastMissionAt=Date.now(),n.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:xe.TeamMissionLog,entry:{...t}}),{...t}}createOutcome(e){let t={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:e.title,status:"draft",requiredSections:[...new Set(e.requiredSections)],createdBy:e.createdBy,createdAt:new Date};return this.outcomes.set(t.id,t),this.emitEvent({type:xe.OutcomeCreated,outcome:{...t}}),{...t}}listOutcomes(){return Array.from(this.outcomes.values()).map((e)=>({...e}))}attachOutcomeFragment(e){let t=this.outcomes.get(e.outcomeId);if(!t)throw Error(`Outcome "${e.outcomeId}" was not found`);if(!t.requiredSections.includes(e.section))throw Error(`Section "${e.section}" is not part of outcome "${e.outcomeId}"`);let n={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:e.outcomeId,section:e.section,sourceAgentId:e.sourceAgentId,sourceRunId:e.sourceRunId,content:e.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(n.id,n),t.status==="draft")t.status="in_review",this.dirty.outcomes.add(t.id);return this.emitEvent({type:xe.OutcomeFragmentAttached,fragment:{...n}}),{...n}}reviewOutcomeFragment(e){let t=this.outcomeFragments.get(e.fragmentId);if(!t)throw Error(`Fragment "${e.fragmentId}" was not found`);return t.status=e.approved?"reviewed":"rejected",t.reviewedBy=e.reviewedBy,t.reviewedAt=new Date,this.emitEvent({type:xe.OutcomeFragmentReviewed,fragment:{...t}}),{...t}}listOutcomeFragments(e){return Array.from(this.outcomeFragments.values()).filter((t)=>t.outcomeId===e).map((t)=>({...t}))}finalizeOutcome(e){let t=this.outcomes.get(e);if(!t)throw Error(`Outcome "${e}" was not found`);let n=this.listOutcomeFragments(e);for(let r of t.requiredSections)if(!n.some((i)=>i.section===r&&i.status==="reviewed"))throw Error(`Outcome "${e}" cannot be finalized. Section "${r}" is missing a reviewed fragment.`);return t.status="finalized",t.finalizedAt=new Date,this.emitEvent({type:xe.OutcomeFinalized,outcome:{...t}}),{...t}}cleanup(){for(let e of this.members.values())if(e.role==="teammate"&&e.runningCount>0)throw Error(`Cannot cleanup team while teammate "${e.agentId}" is still running`);if(Array.from(this.runs.values()).some((e)=>["queued","running"].includes(e.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let e of this.members.values())if(e.role==="teammate")try{e.agent?.abort()}catch(t){if(!Fp(t))throw t}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[e,t]of this.members.entries())if(t.role==="teammate")this.members.delete(e),this.releaseWorkspace(e),this.releaseEngineSession(t),this.emitEvent({type:xe.TeammateShutdown,agentId:e,reason:"team_cleanup"});this.emitEvent({type:xe.TeamCleaned}),this.dirty=Fb(),this.dirty.reset=!0,this.notifyStateDirty()}requireTask(e){let t=this.tasks.get(e);if(!t)throw Error(`Task "${e}" was not found`);return t}assertDependenciesResolved(e){let t=this.getUnresolvedDependencies(e);if(t.length>0)throw Error(`Task "${e.id}" is blocked by "${t[0]}"`)}getUnresolvedDependencies(e){return e.dependsOn.filter((t)=>{let n=this.tasks.get(t);return!n||n.status!=="completed"})}trackMeaningfulEvent(e,t){if(this.recordRunActivityFromAgentEvent(e,t),t.type==="iteration_end"&&t.hadToolCalls){this.recordProgressStep(e,`Completed iteration ${t.iteration} with ${t.toolCallCount} tool call(s)`);return}if(t.type==="content_end"&&t.contentType==="tool"&&!t.error){this.recordProgressStep(e,`Finished tool "${t.toolName??"unknown"}"`);return}if(t.type==="done"){this.appendMissionLog({agentId:e,kind:"done",summary:`Completed a delegated run (${t.iterations} iterations)`});return}if(t.type==="error")this.appendMissionLog({agentId:e,kind:"error",summary:t.error.message})}recordRunActivityFromAgentEvent(e,t){let n;switch(t.type){case"iteration_start":n=`iteration_${t.iteration}_started`;break;case"content_start":if(t.contentType==="tool")n=`running_tool_${t.toolName??"unknown"}`;break;case"content_end":if(t.contentType==="tool")n=t.error?this.formatProgressErrorActivity(`tool_${t.toolName??"unknown"}_error`,t.error):`finished_tool_${t.toolName??"unknown"}`;break;case"done":n="finalizing_response";break;case"error":n=this.formatProgressErrorActivity("run_error",t.error.message);break;default:break}if(!n)return;for(let r of this.runs.values()){if(r.agentId!==e||r.status!=="running")continue;this.recordRunProgress(r,n)}}recordRunProgress(e,t){let n=new Date;e.heartbeatAt=n,e.lastProgressAt=n,e.lastProgressMessage=t,e.currentActivity=t,this.emitEvent({type:xe.RunProgress,run:{...e},message:t})}formatProgressErrorActivity(e,t){let n=t.replace(/\s+/g," ").trim();if(n.length===0)return e;let r=n.length>240?`${n.slice(0,237).trimEnd()}...`:n;return`${e}: ${r}`}recordProgressStep(e,t,n,r=!1){this.missionStepCounter++;let o=this.members.get(e);if(!o)return;let i=this.missionStepCounter-o.lastMissionStep,s=Date.now()-o.lastMissionAt;if(!r&&i<this.missionLogIntervalSteps&&s<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:e,taskId:n,kind:"progress",summary:t})}buildMailboxNotification(e){if(e.length===0)return"";let t=[`[MAILBOX] You have ${e.length} unread message(s):`];for(let n of e)t.push(`--- Message from ${n.fromAgentId} | subject: ${n.subject} ---`),t.push(n.body);return t.push("---"),t.join(`
1011
+ `)}markDirtyFromEvent(e){switch(e.type){case xe.TeamTaskUpdated:this.dirty.tasks.add(e.task.id);break;case xe.TeamMessage:this.dirty.mailbox.add(e.message.id);break;case xe.TeamMissionLog:this.dirty.missionLog.add(e.entry.id);break;case xe.RunQueued:case xe.RunStarted:case xe.RunCompleted:case xe.RunFailed:case xe.RunCancelled:case xe.RunInterrupted:case xe.RunProgress:this.dirty.runs.add(e.run.id);break;case xe.OutcomeCreated:case xe.OutcomeFinalized:this.dirty.outcomes.add(e.outcome.id);break;case xe.OutcomeFragmentAttached:case xe.OutcomeFragmentReviewed:this.dirty.outcomeFragments.add(e.fragment.id);break;default:break}}hasPendingStateDelta(){let e=this.dirty;return e.reset||e.tasks.size>0||e.mailbox.size>0||e.missionLog.size>0||e.runs.size>0||e.outcomes.size>0||e.outcomeFragments.size>0}drainStateDelta(){let e=this.dirty;this.dirty=Fb();let t=(o,i)=>{let s=[];for(let a of o){let d=i(a);if(d!==void 0)s.push({...d})}return s},n=e.mailbox.size>0?new Map(this.mailbox.map((o)=>[o.id,o])):void 0,r=e.missionLog.size>0?new Map(this.missionLog.map((o)=>[o.id,o])):void 0;return{teamId:this.teamId,teamName:this.teamName,reset:e.reset,members:this.exportMembers(),tasks:t(e.tasks,(o)=>this.tasks.get(o)),mailbox:t(e.mailbox,(o)=>n?.get(o)),missionLog:t(e.missionLog,(o)=>r?.get(o)),runs:t(e.runs,(o)=>this.runs.get(o)),outcomes:t(e.outcomes,(o)=>this.outcomes.get(o)),outcomeFragments:t(e.outcomeFragments,(o)=>this.outcomeFragments.get(o))}}requeueStateDelta(e){this.dirty.reset=this.dirty.reset||e.reset;for(let t of e.tasks)this.dirty.tasks.add(t.id);for(let t of e.mailbox)this.dirty.mailbox.add(t.id);for(let t of e.missionLog)this.dirty.missionLog.add(t.id);for(let t of e.runs)this.dirty.runs.add(t.id);for(let t of e.outcomes)this.dirty.outcomes.add(t.id);for(let t of e.outcomeFragments)this.dirty.outcomeFragments.add(t.id)}notifyStateDirty(){try{this.onStateDirty?.()}catch{}}markAllStateDirty(e=!0){this.dirty.reset=this.dirty.reset||e;for(let t of this.tasks.keys())this.dirty.tasks.add(t);for(let t of this.mailbox)this.dirty.mailbox.add(t.id);for(let t of this.missionLog)this.dirty.missionLog.add(t.id);for(let t of this.runs.keys())this.dirty.runs.add(t);for(let t of this.outcomes.keys())this.dirty.outcomes.add(t);for(let t of this.outcomeFragments.keys())this.dirty.outcomeFragments.add(t)}exportMembers(){return Array.from(this.members.values()).map((e)=>({agentId:e.agentId,role:e.role,description:e.description,status:e.status}))}emitEvent(e){this.markDirtyFromEvent(e);try{this.onTeamEvent?.(e)}catch{}}}function l4(e){return new Promise((t)=>setTimeout(t,e))}function xc(e,t){let n=0;for(let r of e){if(!r.startsWith(t))continue;let o=Number.parseInt(r.slice(t.length),10);if(Number.isFinite(o))n=Math.max(n,o)}return n}function WPe(e){if(e.role!=="teammate")return{};let t=e.activityCounter?.snapshot()??e.activity,n=e.currentTaskCounter?.snapshot()??e.taskActivity;return{...t?{activity:t}:{},...n?{taskActivity:n}:{}}}function $p(e){let t=e?.currentTaskCounter?.snapshot();return t?{activity:t}:{}}var jPe=/session allocation full/i;function c4(e){if(!e)return!1;let t=e instanceof Error?e.message:typeof e==="string"?e:"";return jPe.test(t)}var qPe=(e)=>new Promise((t)=>setTimeout(t,e));async function HI(e,t={}){let n=Math.max(1,t.attempts??3),r=t.sleep??qPe;for(let o=1;;o+=1)try{return await e()}catch(i){if(!c4(i)||o>=n)throw i;let s=2000*2**(o-1);t.onRetry?.(o,s),await r(s)}}function WI(e,t){switch(t.type){case"run_queued":case"run_started":e.activeTeamRunIds.add(t.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let n;if(t.type==="run_failed")n=t.run.error;else if(t.type==="run_cancelled"||t.type==="run_interrupted")n=t.run.error??t.reason;e.activeTeamRunIds.delete(t.run.id),e.pendingTeamRunUpdates.push({runId:t.run.id,agentId:t.run.agentId,taskId:t.run.taskId,status:t.type.replace("run_",""),error:n,iterations:t.run.result?.iterations}),Bp(e);break}default:break}}async function jI(e,t,n){switch(t.type){case"run_progress":await n("onTeamTaskProgress",e,t.run.agentId,t.message,{kind:t.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(t.event.type==="content_start"&&t.event.contentType==="text"&&typeof t.event.text==="string"){let r=t.event.text.replace(/\s+/g," ").trim().slice(0,120);if(r)await n("onTeamTaskProgress",e,t.agentId,r,{kind:"text"})}break;case"task_start":await n("onTeamTaskStart",e,t.agentId,t.message);break;case"task_end":{let r=t.status??(t.error?"failed":t.result?.finishReason==="aborted"?"cancelled":"completed");if(r==="cancelled")await n("onTeamTaskEnd",e,t.agentId,"cancelled","[done] aborted",t.result,t.result?.messages??t.messages);else if(r==="failed"){let o=t.error?.message||t.result?.text||"Teammate task failed";await n("onTeamTaskEnd",e,t.agentId,"failed",`[error] ${o}`,t.result,t.result?.messages??t.messages)}else await n("onTeamTaskEnd",e,t.agentId,"completed",`[done] ${t.result?.finishReason??"completed"}`,t.result,t.result?.messages);break}default:break}}var KPe=1000,u4=new WeakMap;function qI(e,t,n,r,o=Date.now){let i=e.runtime.teamRuntime;if(!i)return;let s=()=>GPe(e,t,n,r),a=u4.get(i);if(!a)a={last:0},u4.set(i,a);if(pi(n)){a.pending=void 0,s();return}let d=o(),l=KPe-(d-a.last);if(l<=0){a.last=d,a.pending=void 0,s();return}if(a.pending=s,!a.timer){let c=a;c.timer=setTimeout(()=>{c.timer=void 0;let u=c.pending;if(c.pending=void 0,u)c.last=o(),u()},l),c.timer.unref?.()}}function GPe(e,t,n,r){let o=e.runtime.teamRuntime;if(!o)return;let i=o.getTeamName(),s=o.exportState();r({type:"team_progress",payload:{sessionId:t,teamName:i,lifecycle:$I({teamName:i,sessionId:t,event:n}),summary:DI(i,s),teammates:s.members.filter((a)=>a.role==="teammate")}})}function Up(e){return e.activeTeamRunIds.size>0||e.pendingTeamRunUpdates.length>0}function zI(e,t){if(e.aborting)return!1;if(!(t==="completed"||t==="max_iterations"))return!1;return e.config.enableAgentTeams===!0&&Up(e)}function Bp(e){let t=e.teamRunWaiters.splice(0);for(let n of t)n()}async function KI(e){while(!0){if(e.aborting)return[];if(e.pendingTeamRunUpdates.length>0){let t=[...e.pendingTeamRunUpdates];return e.pendingTeamRunUpdates.length=0,t}if(e.activeTeamRunIds.size===0)return[];await new Promise((t)=>{e.teamRunWaiters.push(t)})}}function GI(e,t){let n=t.map((i)=>{let s=[`- ${i.runId} (${i.agentId}) -> ${i.status}`];if(i.taskId)s.push(` task=${i.taskId}`);if(typeof i.iterations==="number")s.push(` iterations=${i.iterations}`);if(i.error)s.push(` error=${i.error}`);return s.join("")}),r=e.activeTeamRunIds.size,o=r>0?`There are still ${r} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return _c(`System-delivered teammate async run updates:
1012
1012
  ${n.join(`
1013
1013
  `)}
1014
1014
 
1015
- ${o}`,e.config.mode)}function _c(e,t){return zPe(e,t==="plan"?"plan":t==="yolo"?"yolo":"act")}import{DEFAULT_TOOL_RESULT_FORMAT as VPe,isToolResultFormat as YPe,LEGACY_TOOL_RESULT_FORMAT as XPe}from"@cerebriline/shared";var VI="toolResultFormat";function h6(e){let t=e.stored?.[VI];if(YPe(t))return t;if(e.hasHistory)return XPe;return e.configured??VPe}import{readFile as y6}from"node:fs/promises";import*as Wp from"node:path";import*as cn from"node:path";function Ec(e,t){let n=cn.normalize(cn.isAbsolute(t)?t:cn.resolve(e.root,t)),r=e.files.get(n);if(r)return{kind:"held",absolutePath:n,body:r.body};if(e.skipped.includes(n))return{kind:"uncovered",absolutePath:n};let o=cn.normalize(e.root),i=cn.relative(o,n);return i!==""&&!i.startsWith("..")&&!cn.isAbsolute(i)?{kind:"created",absolutePath:n}:{kind:"outside",absolutePath:n}}function Hp(e){switch(e.kind){case"created":return"This transaction created that file — before it, the file did not exist, so there is no earlier version of it to show.";case"uncovered":return"That file is outside what this transaction can put back: it was too large to hold, or it is a symlink. Nothing was kept for it, so it has no base revision and a rollback would not restore it either.";case"outside":return"That path is outside the directory this transaction covers, so nothing was held for it."}}function Ac(e){return!e.subarray(0,8000).includes(0)}function Bb(e,t){let n=cn.normalize(cn.isAbsolute(t)?t:cn.resolve(e,t)),r=cn.relative(cn.normalize(e),n);return r!==""&&!r.startsWith("..")&&!cn.isAbsolute(r)?{kind:"created",absolutePath:n}:{kind:"outside",absolutePath:n}}import{createHash as JPe}from"node:crypto";var QPe=33554432,ZPe=134217728,e0e=5,t0e=10,Vt="original",Yt="last",n0e="absent",p6=120;function Hb(e){if(!e)return;let t=e.replace(/\s+/g," ").trim();if(!t)return;return t.length<=p6?t:`${t.slice(0,p6-1)}…`}function r0e(e,t,n,r){let o=Hb(e?.intent),i=Hb(e?.summary),s=Hb(e?.check),a=n===void 0||!r?void 0:t===n?"same length":`${t>n?"+":"−"}${Math.abs(t-n)} lines`,d=o??i??a??(r?"written":"deleted"),l=[d];if(o&&i)l.push(i);if(s)l.push(`check: ${s}`);return{note:Hb(l.join(" — "))??d,noteSource:o?"model":"derived"}}function Wb(e){return e?JPe("sha256").update(e).digest("hex"):n0e}function o0e(e){if(!e)return 0;let t=e.toString("utf8");if(t==="")return 0;let n=t.split(/\r\n|\r|\n/);if(n[n.length-1]==="")n.pop();return n.length}function f6(e){let t=e[0],n=e[e.length-1];if(!t||!n)return;return n.index>t.index?`#${t.index}–#${n.index}`:`#${n.index}`}var YI={transaction:{by:"transaction open",existed:"the file as this transaction found it",absent:"did not exist when this transaction opened"},session:{by:"first seen",existed:"the file as it stood before this session first wrote to it",absent:"did not exist when this session first wrote to it"}};function i0e(e){let t=e.trim().toLowerCase();if(t==="")return null;if(t===Vt||t==="base"||t==="first")return"original";if(t===Yt||t==="previous"||t==="undo")return"last";let n=t.match(/^(?:#|v|rev(?:ision)?\s*#?\s*)?(\d+)$/);if(!n?.[1])return null;let r=Number(n[1]);return Number.isInteger(r)&&r>0?r:null}function ss(e,t={}){let n=t.maxBytesPerFile??QPe,r=t.maxBytesTotal??ZPe,o=new Map,i=new Map,s=new Map,a=0,d=(y)=>y.dropped||!y.existed?void 0:i.get(y.hash)?.body,l=(y)=>({index:y.index,body:d(y),hash:y.hash,by:y.by,note:y.note,noteSource:y.noteSource,lines:y.lines,bytes:y.bytes,dropped:y.dropped,...y.held?{held:!0}:{},...y.sameAs===void 0?{}:{sameAs:y.sameAs}}),c=(y)=>{let w=i.get(y.hash);if(!w)return;if(w.refs-=1,w.refs<=0)i.delete(y.hash)},u=(y)=>{let w=new Set,k=0;for(let b of y){if(b.dropped||!b.existed||w.has(b.hash))continue;w.add(b.hash),k+=b.bytes}return k},h=(y)=>{let w=(k)=>k>0&&k<y.length-e0e;for(;;){if(u(y)<=n)return;let k=[];for(let E=0;E<y.length;E+=1){let S=y[E];if(!S||S.dropped||!S.existed)continue;if(!w(E))continue;if((i.get(S.hash)?.refs??0)>1)continue;k.push(E)}if(k.length===0)return;let b=k[Math.floor(k.length/2)],v=b===void 0?void 0:y[b];if(!v)return;c(v),v.dropped=!0}},p=()=>{let y=0;for(let w of i.values())y+=w.body.length;return y},f=()=>{if(p()<=r)return;let y=[...o.keys()];for(let w of[!1,!0])for(let k of y){let b=o.get(k);if(!b)continue;for(let v=b.length-1;v>=0;v-=1){if(v===0&&!w)continue;let E=b[v];if(!E||E.dropped||!E.existed)continue;if((i.get(E.hash)?.refs??0)>1)continue;if(c(E),E.dropped=!0,p()<=r)return}}},m=(y,w,k,b)=>{let v=o.get(y)??[],E=Wb(w),S=v.find((C)=>C.existed&&C.hash===E);if(w){let C=i.get(E);if(C)C.refs+=1;else i.set(E,{body:w,refs:1})}let x=o0e(w),T=v[v.length-1],A=r0e(b,x,T?.lines,w!==void 0),R={index:v.length+1,hash:E,by:k,note:A.note,noteSource:A.noteSource,lines:x,bytes:w?.byteLength??0,dropped:!1,existed:w!==void 0,...b?.held?{held:!0}:{},...S?{sameAs:S.index}:{}};return v.push(R),s.set(y,a),o.delete(y),o.set(y,v),h(v),f(),l(R)},g=(y)=>{for(let w=y.length-1;w>=0;w--)if(!y[w]?.held)return y[w];return};return{seed(y,w,k="transaction"){if(o.has(y))return;let b=YI[k];m(y,w,b.by,{summary:w===void 0?b.absent:b.existed})},record(y,w,k,b){let v=o.get(y);if(!v||v.length===0)m(y,void 0,YI.transaction.by,{summary:YI.transaction.absent});let E=o.get(y)??[],S=b?.held?E[E.length-1]:g(E);if(S&&S.hash===Wb(w))return;return m(y,w,k,b)},revisions(y){return(o.get(y)??[]).map(l)},resolve(y,w){let k=o.get(y);if(!k||k.length===0)return{kind:"untracked"};let b=k.map((x)=>x.index),v=i0e(w);if(v===null)return{kind:"unknown",requested:w,available:b};let E;if(v==="original")E=1;else if(v==="last"){let x=k.filter((T)=>!T.held);E=x[Math.max(0,x.length-2)]?.index??1}else E=v;let S=k[E-1];if(!S)return{kind:"unknown",requested:w,available:b};if(S.dropped)return{kind:"dropped",index:S.index};return{kind:"found",revision:l(S)}},tracked(){return[...o.keys()]},heldBytes(y){return u(o.get(y)??[])},reset(){o.clear(),i.clear(),s.clear()},noteCompaction(y){a+=1;let w=a-2;if(w<0)return 0;let k=new Set;for(let v of y??[])k.add(v);let b=0;for(let[v,E]of[...o.entries()]){if(k.has(v))continue;if((s.get(v)??a)>=w)continue;for(let S of E)if(!S.dropped&&S.existed)c(S);o.delete(v),s.delete(v),b+=1}return b}}}function Io(e,t,n={}){let r=n.span??"this transaction";if(t.length===0)return`No revisions of \`${e}\` have been recorded in ${r}.`;let o=n.limit??t0e,i=[...t].reverse(),s=t[0],a=t.length<=o?i:[...i.slice(0,o-1),"gap",s],d=[...t].reverse().find((c)=>!c.held)?.index,l=a.map((c)=>{if(c==="gap"){let m=t.length-o;return` … ${m+1} older revision${m===0?"":"s"} not listed — ask for one by number`}let u=c.index===d,h=c.index===1?`${Vt} (${c.by})`:c.by,f=[c.body?`${c.lines} line${c.lines===1?"":"s"}`:c.index===1?"did not exist":"deleted"];if(c.sameAs!==void 0)f.push(`identical to #${c.sameAs}`);if(c.dropped)f.push("content released to save memory — it cannot be restored");if(u)f.push("on disk now");return` #${c.index} ${h} — ${f.join(", ")}
1015
+ ${o}`,e.config.mode)}function _c(e,t){return zPe(e,t==="plan"?"plan":t==="yolo"?"yolo":"act")}import{DEFAULT_TOOL_RESULT_FORMAT as VPe,isToolResultFormat as YPe,LEGACY_TOOL_RESULT_FORMAT as XPe}from"@cerebriline/shared";var VI="toolResultFormat";function h4(e){let t=e.stored?.[VI];if(YPe(t))return t;if(e.hasHistory)return XPe;return e.configured??VPe}import{readFile as y4}from"node:fs/promises";import*as Wp from"node:path";import*as cn from"node:path";function Ec(e,t){let n=cn.normalize(cn.isAbsolute(t)?t:cn.resolve(e.root,t)),r=e.files.get(n);if(r)return{kind:"held",absolutePath:n,body:r.body};if(e.skipped.includes(n))return{kind:"uncovered",absolutePath:n};let o=cn.normalize(e.root),i=cn.relative(o,n);return i!==""&&!i.startsWith("..")&&!cn.isAbsolute(i)?{kind:"created",absolutePath:n}:{kind:"outside",absolutePath:n}}function Hp(e){switch(e.kind){case"created":return"This transaction created that file — before it, the file did not exist, so there is no earlier version of it to show.";case"uncovered":return"That file is outside what this transaction can put back: it was too large to hold, or it is a symlink. Nothing was kept for it, so it has no base revision and a rollback would not restore it either.";case"outside":return"That path is outside the directory this transaction covers, so nothing was held for it."}}function Ac(e){return!e.subarray(0,8000).includes(0)}function Bb(e,t){let n=cn.normalize(cn.isAbsolute(t)?t:cn.resolve(e,t)),r=cn.relative(cn.normalize(e),n);return r!==""&&!r.startsWith("..")&&!cn.isAbsolute(r)?{kind:"created",absolutePath:n}:{kind:"outside",absolutePath:n}}import{createHash as JPe}from"node:crypto";var QPe=33554432,ZPe=134217728,e0e=5,t0e=10,Vt="original",Yt="last",n0e="absent",p4=120;function Hb(e){if(!e)return;let t=e.replace(/\s+/g," ").trim();if(!t)return;return t.length<=p4?t:`${t.slice(0,p4-1)}…`}function r0e(e,t,n,r){let o=Hb(e?.intent),i=Hb(e?.summary),s=Hb(e?.check),a=n===void 0||!r?void 0:t===n?"same length":`${t>n?"+":"−"}${Math.abs(t-n)} lines`,d=o??i??a??(r?"written":"deleted"),l=[d];if(o&&i)l.push(i);if(s)l.push(`check: ${s}`);return{note:Hb(l.join(" — "))??d,noteSource:o?"model":"derived"}}function Wb(e){return e?JPe("sha256").update(e).digest("hex"):n0e}function o0e(e){if(!e)return 0;let t=e.toString("utf8");if(t==="")return 0;let n=t.split(/\r\n|\r|\n/);if(n[n.length-1]==="")n.pop();return n.length}function f4(e){let t=e[0],n=e[e.length-1];if(!t||!n)return;return n.index>t.index?`#${t.index}–#${n.index}`:`#${n.index}`}var YI={transaction:{by:"transaction open",existed:"the file as this transaction found it",absent:"did not exist when this transaction opened"},session:{by:"first seen",existed:"the file as it stood before this session first wrote to it",absent:"did not exist when this session first wrote to it"}};function i0e(e){let t=e.trim().toLowerCase();if(t==="")return null;if(t===Vt||t==="base"||t==="first")return"original";if(t===Yt||t==="previous"||t==="undo")return"last";let n=t.match(/^(?:#|v|rev(?:ision)?\s*#?\s*)?(\d+)$/);if(!n?.[1])return null;let r=Number(n[1]);return Number.isInteger(r)&&r>0?r:null}function ss(e,t={}){let n=t.maxBytesPerFile??QPe,r=t.maxBytesTotal??ZPe,o=new Map,i=new Map,s=new Map,a=0,d=(y)=>y.dropped||!y.existed?void 0:i.get(y.hash)?.body,l=(y)=>({index:y.index,body:d(y),hash:y.hash,by:y.by,note:y.note,noteSource:y.noteSource,lines:y.lines,bytes:y.bytes,dropped:y.dropped,...y.held?{held:!0}:{},...y.sameAs===void 0?{}:{sameAs:y.sameAs}}),c=(y)=>{let w=i.get(y.hash);if(!w)return;if(w.refs-=1,w.refs<=0)i.delete(y.hash)},u=(y)=>{let w=new Set,k=0;for(let b of y){if(b.dropped||!b.existed||w.has(b.hash))continue;w.add(b.hash),k+=b.bytes}return k},h=(y)=>{let w=(k)=>k>0&&k<y.length-e0e;for(;;){if(u(y)<=n)return;let k=[];for(let E=0;E<y.length;E+=1){let S=y[E];if(!S||S.dropped||!S.existed)continue;if(!w(E))continue;if((i.get(S.hash)?.refs??0)>1)continue;k.push(E)}if(k.length===0)return;let b=k[Math.floor(k.length/2)],v=b===void 0?void 0:y[b];if(!v)return;c(v),v.dropped=!0}},p=()=>{let y=0;for(let w of i.values())y+=w.body.length;return y},f=()=>{if(p()<=r)return;let y=[...o.keys()];for(let w of[!1,!0])for(let k of y){let b=o.get(k);if(!b)continue;for(let v=b.length-1;v>=0;v-=1){if(v===0&&!w)continue;let E=b[v];if(!E||E.dropped||!E.existed)continue;if((i.get(E.hash)?.refs??0)>1)continue;if(c(E),E.dropped=!0,p()<=r)return}}},m=(y,w,k,b)=>{let v=o.get(y)??[],E=Wb(w),S=v.find((C)=>C.existed&&C.hash===E);if(w){let C=i.get(E);if(C)C.refs+=1;else i.set(E,{body:w,refs:1})}let x=o0e(w),T=v[v.length-1],A=r0e(b,x,T?.lines,w!==void 0),R={index:v.length+1,hash:E,by:k,note:A.note,noteSource:A.noteSource,lines:x,bytes:w?.byteLength??0,dropped:!1,existed:w!==void 0,...b?.held?{held:!0}:{},...S?{sameAs:S.index}:{}};return v.push(R),s.set(y,a),o.delete(y),o.set(y,v),h(v),f(),l(R)},g=(y)=>{for(let w=y.length-1;w>=0;w--)if(!y[w]?.held)return y[w];return};return{seed(y,w,k="transaction"){if(o.has(y))return;let b=YI[k];m(y,w,b.by,{summary:w===void 0?b.absent:b.existed})},record(y,w,k,b){let v=o.get(y);if(!v||v.length===0)m(y,void 0,YI.transaction.by,{summary:YI.transaction.absent});let E=o.get(y)??[],S=b?.held?E[E.length-1]:g(E);if(S&&S.hash===Wb(w))return;return m(y,w,k,b)},revisions(y){return(o.get(y)??[]).map(l)},resolve(y,w){let k=o.get(y);if(!k||k.length===0)return{kind:"untracked"};let b=k.map((x)=>x.index),v=i0e(w);if(v===null)return{kind:"unknown",requested:w,available:b};let E;if(v==="original")E=1;else if(v==="last"){let x=k.filter((T)=>!T.held);E=x[Math.max(0,x.length-2)]?.index??1}else E=v;let S=k[E-1];if(!S)return{kind:"unknown",requested:w,available:b};if(S.dropped)return{kind:"dropped",index:S.index};return{kind:"found",revision:l(S)}},tracked(){return[...o.keys()]},heldBytes(y){return u(o.get(y)??[])},reset(){o.clear(),i.clear(),s.clear()},noteCompaction(y){a+=1;let w=a-2;if(w<0)return 0;let k=new Set;for(let v of y??[])k.add(v);let b=0;for(let[v,E]of[...o.entries()]){if(k.has(v))continue;if((s.get(v)??a)>=w)continue;for(let S of E)if(!S.dropped&&S.existed)c(S);o.delete(v),s.delete(v),b+=1}return b}}}function Io(e,t,n={}){let r=n.span??"this transaction";if(t.length===0)return`No revisions of \`${e}\` have been recorded in ${r}.`;let o=n.limit??t0e,i=[...t].reverse(),s=t[0],a=t.length<=o?i:[...i.slice(0,o-1),"gap",s],d=[...t].reverse().find((c)=>!c.held)?.index,l=a.map((c)=>{if(c==="gap"){let m=t.length-o;return` … ${m+1} older revision${m===0?"":"s"} not listed — ask for one by number`}let u=c.index===d,h=c.index===1?`${Vt} (${c.by})`:c.by,f=[c.body?`${c.lines} line${c.lines===1?"":"s"}`:c.index===1?"did not exist":"deleted"];if(c.sameAs!==void 0)f.push(`identical to #${c.sameAs}`);if(c.dropped)f.push("content released to save memory — it cannot be restored");if(u)f.push("on disk now");return` #${c.index} ${h} — ${f.join(", ")}
1016
1016
  ${c.note}`});return[`Revisions of \`${e}\` in ${r}:`,...l,"",`Restore any of them with \`restore_file\` and \`revision\`: a number, \`"${Vt}"\` for #1, or \`"${Yt}"\` to undo just the most recent change.`].join(`
1017
- `)}var s0e=8,m6=120;function g6(e,t,n){let r=n.trim();if(!r)return`Say what to look for. \`find\` takes the text you want to locate among the revisions of \`${e}\`.`;let o=r.toLowerCase(),i=[];for(let l of t){if(l.note.toLowerCase().includes(o)){i.push({revision:l,where:"in its note"});continue}if(!l.body)continue;let c=l.body.toString("utf8"),u=c.toLowerCase().indexOf(o);if(u<0)continue;let h=c.slice(0,u).split(/\r\n|\r|\n/).length,p=c.split(/\r\n|\r|\n/)[h-1]??"",f=p.trim().length>m6?`${p.trim().slice(0,m6-1)}…`:p.trim();i.push({revision:l,where:`line ${h}: ${f}`})}if(i.length===0){let l=t.filter((u)=>u.dropped).length,c=l?` ${l} revision${l===1?" has":"s have"} had its content released and could not be searched.`:"";return`No revision of \`${e}\` in this transaction contains \`${r}\`.${c} The history is below.
1017
+ `)}var s0e=8,m4=120;function g4(e,t,n){let r=n.trim();if(!r)return`Say what to look for. \`find\` takes the text you want to locate among the revisions of \`${e}\`.`;let o=r.toLowerCase(),i=[];for(let l of t){if(l.note.toLowerCase().includes(o)){i.push({revision:l,where:"in its note"});continue}if(!l.body)continue;let c=l.body.toString("utf8"),u=c.toLowerCase().indexOf(o);if(u<0)continue;let h=c.slice(0,u).split(/\r\n|\r|\n/).length,p=c.split(/\r\n|\r|\n/)[h-1]??"",f=p.trim().length>m4?`${p.trim().slice(0,m4-1)}…`:p.trim();i.push({revision:l,where:`line ${h}: ${f}`})}if(i.length===0){let l=t.filter((u)=>u.dropped).length,c=l?` ${l} revision${l===1?" has":"s have"} had its content released and could not be searched.`:"";return`No revision of \`${e}\` in this transaction contains \`${r}\`.${c} The history is below.
1018
1018
 
1019
1019
  ${Io(e,t)}`}let s=[...i].reverse().slice(0,s0e),a=s.map(({revision:l,where:c})=>` #${l.index} ${l.by} — ${l.lines} line${l.lines===1?"":"s"}
1020
1020
  ${l.note}
@@ -1047,27 +1047,27 @@ It is a read and nothing else. The file is untouched, and you are standing down
1047
1047
  - \`"${Yt}"\` — as it was before your most recent change to it.
1048
1048
  - \`"#3"\` — that numbered version. Every version a tool writes is numbered, and the result reporting the change names its number.
1049
1049
 
1050
- The file on disk is left exactly as it is. Use this to see what you had before, and \`restore_file\` when you want it back.`,parameter:`Which earlier version of the file to show, instead of the file as it stands: "${Vt}" for the file before this session first wrote to it, "${Yt}" for the version before your most recent change, or a number such as "#3".`,span:"this session",baseLabel:"the version from before this session's changes",closed:"Nothing has written that file in this session, so there is no earlier version of it held. Read the file as it stands."},w6={description:c0e,parameter:u0e,span:"this escalation",baseLabel:"the version from before the expert's changes",closed:"No escalation is open, so there is no earlier version to read. Read the file as it stands."};function h0e(e){if(!e||typeof e!=="object"||Array.isArray(e))return{revision:void 0,rest:e};let{revision:t,...n}=e;return{revision:t,rest:n}}function p0e(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let{files:t,revision:n,...r}=e;if(!Array.isArray(t))return;let o=(s)=>s&&typeof s==="object"&&!Array.isArray(s)?s.revision:void 0;if(!t.some((s)=>typeof o(s)==="string"))return;let i=[];for(let s of t){let a=typeof o(s)==="string"?o(s):n,{revision:d,...l}=s,c=typeof o(s)==="string"?l:s,u=i[i.length-1];if(u&&u.revision===a)u.files.push(c);else i.push({revision:a,files:[c]})}return i.map((s)=>({...r,files:s.files,...s.revision===void 0?{}:{revision:s.revision}}))}function m0e(e,t,n){let r=typeof e.properties==="object"&&e.properties!==null?e.properties:{};return{...e,properties:{...r,revision:{type:"string",description:n?`${t.parameter} While an expert is working this workspace, the versions are the expert's: ${n.wording.parameter}`:t.parameter}}}}function f0e(e,t,n,r,o){let i=e.revisions.revisions(t);if(i.length===0){if(!b6(n))return{kind:"error",message:`Nothing has written to that file in ${o.span}, so the only earlier version of it is the one ${o.span} opened with — there is no \`${n}\` to read. Ask for \`"${jp}"\`, or read the file as it stands.`};return r?{kind:"body",body:r,label:o.baseLabel}:{kind:"error",message:Hp({kind:"created",absolutePath:t})}}let s=e.revisions.resolve(t,n);if(s.kind==="dropped")return{kind:"error",message:`Revision #${s.index} is no longer held: its content was released to stay inside the memory ${o.span} may spend on file history.
1050
+ The file on disk is left exactly as it is. Use this to see what you had before, and \`restore_file\` when you want it back.`,parameter:`Which earlier version of the file to show, instead of the file as it stands: "${Vt}" for the file before this session first wrote to it, "${Yt}" for the version before your most recent change, or a number such as "#3".`,span:"this session",baseLabel:"the version from before this session's changes",closed:"Nothing has written that file in this session, so there is no earlier version of it held. Read the file as it stands."},w4={description:c0e,parameter:u0e,span:"this escalation",baseLabel:"the version from before the expert's changes",closed:"No escalation is open, so there is no earlier version to read. Read the file as it stands."};function h0e(e){if(!e||typeof e!=="object"||Array.isArray(e))return{revision:void 0,rest:e};let{revision:t,...n}=e;return{revision:t,rest:n}}function p0e(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let{files:t,revision:n,...r}=e;if(!Array.isArray(t))return;let o=(s)=>s&&typeof s==="object"&&!Array.isArray(s)?s.revision:void 0;if(!t.some((s)=>typeof o(s)==="string"))return;let i=[];for(let s of t){let a=typeof o(s)==="string"?o(s):n,{revision:d,...l}=s,c=typeof o(s)==="string"?l:s,u=i[i.length-1];if(u&&u.revision===a)u.files.push(c);else i.push({revision:a,files:[c]})}return i.map((s)=>({...r,files:s.files,...s.revision===void 0?{}:{revision:s.revision}}))}function m0e(e,t,n){let r=typeof e.properties==="object"&&e.properties!==null?e.properties:{};return{...e,properties:{...r,revision:{type:"string",description:n?`${t.parameter} While an expert is working this workspace, the versions are the expert's: ${n.wording.parameter}`:t.parameter}}}}function f0e(e,t,n,r,o){let i=e.revisions.revisions(t);if(i.length===0){if(!b4(n))return{kind:"error",message:`Nothing has written to that file in ${o.span}, so the only earlier version of it is the one ${o.span} opened with — there is no \`${n}\` to read. Ask for \`"${jp}"\`, or read the file as it stands.`};return r?{kind:"body",body:r,label:o.baseLabel}:{kind:"error",message:Hp({kind:"created",absolutePath:t})}}let s=e.revisions.resolve(t,n);if(s.kind==="dropped")return{kind:"error",message:`Revision #${s.index} is no longer held: its content was released to stay inside the memory ${o.span} may spend on file history.
1051
1051
 
1052
1052
  ${Io(Wp.basename(t),i)}`};if(s.kind!=="found")return{kind:"error",message:`\`${n}\` does not name a version of that file that exists.
1053
1053
 
1054
- ${Io(Wp.basename(t),i)}`};if(!s.revision.body)return{kind:"error",message:`The file did not exist at revision #${s.revision.index}, so there is nothing to show.`};return{kind:"body",body:s.revision.body,label:s.revision.index===1?o.baseLabel:`revision #${s.revision.index}`}}function b6(e){let t=e.trim().toLowerCase();return t===jp||t===Vt||t==="first"||t==="1"||t==="#1"}function v6(e){let t=e.pending;if(t)return{root:t.root,snapshotBacked:!0,resolve:(r)=>Ec(t,r)};if(e.root===void 0)return;let n=e.root;return{root:n,snapshotBacked:!1,resolve:(r)=>Bb(n,r)}}async function g0e(e,t,n,r,o,i){let s=cg(n);return Promise.all(s.map(async(a)=>{let d=`${Us(a)}@${o}`,l=Gf(a);if(l)return{query:d,result:"",error:`Invalid file range: ${l}`,success:!1};let c=t.resolve(a.path);if(c.kind==="uncovered"||c.kind==="outside")return{query:d,result:"",error:Hp(c),success:!1};if(!t.snapshotBacked&&b6(o)&&e.revisions.revisions(c.absolutePath).length===0){let p=await y6(c.absolutePath).catch(()=>{return});if(!p)return{query:d,result:"",error:`That file does not exist, and nothing has written it in ${i.span}.`,success:!1};if(!Ac(p))return{query:d,result:"",error:"That file is not text, so there is nothing to show.",success:!1};let f=await z_({text:p.toString("utf8"),includeLineNumbers:a.line_numbers??!0,startLine:a.start_line,endLine:a.end_line,signal:r.signal});return{query:d,result:`${f.text}
1054
+ ${Io(Wp.basename(t),i)}`};if(!s.revision.body)return{kind:"error",message:`The file did not exist at revision #${s.revision.index}, so there is nothing to show.`};return{kind:"body",body:s.revision.body,label:s.revision.index===1?o.baseLabel:`revision #${s.revision.index}`}}function b4(e){let t=e.trim().toLowerCase();return t===jp||t===Vt||t==="first"||t==="1"||t==="#1"}function v4(e){let t=e.pending;if(t)return{root:t.root,snapshotBacked:!0,resolve:(r)=>Ec(t,r)};if(e.root===void 0)return;let n=e.root;return{root:n,snapshotBacked:!1,resolve:(r)=>Bb(n,r)}}async function g0e(e,t,n,r,o,i){let s=cg(n);return Promise.all(s.map(async(a)=>{let d=`${Us(a)}@${o}`,l=Gf(a);if(l)return{query:d,result:"",error:`Invalid file range: ${l}`,success:!1};let c=t.resolve(a.path);if(c.kind==="uncovered"||c.kind==="outside")return{query:d,result:"",error:Hp(c),success:!1};if(!t.snapshotBacked&&b4(o)&&e.revisions.revisions(c.absolutePath).length===0){let p=await y4(c.absolutePath).catch(()=>{return});if(!p)return{query:d,result:"",error:`That file does not exist, and nothing has written it in ${i.span}.`,success:!1};if(!Ac(p))return{query:d,result:"",error:"That file is not text, so there is nothing to show.",success:!1};let f=await z_({text:p.toString("utf8"),includeLineNumbers:a.line_numbers??!0,startLine:a.start_line,endLine:a.end_line,signal:r.signal});return{query:d,result:`${f.text}
1055
1055
 
1056
1056
  [Nothing has written this file in ${i.span}, so its original is the file as it stands, shown here. Read it without \`revision\` before editing it.]`,success:!0}}let u=f0e(e,c.absolutePath,o,c.kind==="held"?c.body:void 0,i);if(u.kind==="error")return{query:d,result:"",error:u.message,success:!1};if(!Ac(u.body))return{query:d,result:"",error:"That file is not text, so there is nothing to show. A rollback would still put it back.",success:!1};let h=await z_({text:u.body.toString("utf8"),includeLineNumbers:a.line_numbers??!0,startLine:a.start_line,endLine:a.end_line,signal:r.signal});return{query:d,result:`${h.text}
1057
1057
 
1058
1058
  [This is ${u.label}, not the file as it stands.]`,success:!0}}))}function y0e(e,t,n,r){let o=new Map;for(let i of cg(n)){let s=t.resolve(i.path);if(s.kind==="uncovered"||s.kind==="outside")continue;o.set(Us(i),s.absolutePath)}if(o.size===0)return r;return r.map((i)=>{if(!i.success)return i;let s=o.get(i.query);if(!s)return i;let a=e.revisions.revisions(s);if(a.length<2)return i;return{...i,result:`${i.result}
1059
1059
 
1060
- ${Io(Wp.basename(s),a)}`}})}function w0e(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e.paths:void 0;return(typeof t==="string"?[t]:Array.isArray(t)?t:[]).filter((r)=>typeof r==="string").map((r)=>r.trim()).filter((r)=>r!=="")}async function b0e(e,t,n){let r=[],o=new Set;for(let i of w0e(n)){let s=t.resolve(i);if(s.kind==="uncovered"||s.kind==="outside")continue;let a=s.absolutePath;if(o.has(a))continue;o.add(a);let d=e.revisions.revisions(a);if(d.length<2)continue;let l;try{l=await y6(a)}catch{l=void 0}let c=Wb(l),u=d[d.length-1],h=`\`${Wp.basename(a)}\``,p=[...d].reverse().find((f)=>f.hash===c);if(!p)r.push(`Checked ${h} as it is on disk now, which is none of its ${d.length} revisions: something other than this session's file tools has written it since revision #${u?.index} (${u?.note}).`);else if(p.index===u?.index)r.push(`Checked ${h} as it is on disk now: revision #${p.index}, ${p.index===1?"the file before your first change":`the content your most recent change left (${p.note})`}. Nothing older is cached; an error reported here is in that content.`);else r.push(`Checked ${h} as it is on disk now: the same content as revision #${p.index} (${p.note}), not your most recent change, #${u?.index}.`)}return r.length>0?r.join(`
1061
- `):void 0}function qp(e,t,n=l0e,r){let o=()=>r?.live()?r:{source:t,wording:n};return e.map((i)=>{if(i.name===Lr)return v0e(i,o);if(i.name!==le.READ_FILES)return i;let s=i;return{...s,description:s.description+n.description+(r?r.wording.description:""),inputSchema:m0e(s.inputSchema,n,r),execute:async function a(d,l){let c=p0e(d);if(c){let y=[];for(let w of c){let k=await a(w,l);if(Array.isArray(k))y.push(...k);else y.push(k)}return y}let u=o(),{revision:h,rest:p}=h0e(d),f=v6(u.source),m=typeof h==="string"?h.trim():void 0;if(m===void 0||m===""||["current","now","disk","head","working"].includes(m.toLowerCase())){let y=await s.execute(p,l);return f&&Array.isArray(y)?y0e(u.source,f,p,y):y}if(!f)return[{query:m,result:"",error:u.wording.closed,success:!1}];return g0e(u.source,f,p,l,m,u.wording)}}})}function v0e(e,t){let n=e;return{...n,execute:async(r,o)=>{let i=await n.execute(r,o);if(typeof i!=="string")return i;let{source:s}=t(),a=v6(s);if(!a)return i;let d=await b0e(s,a,r).catch(()=>{return});return d?`${i}
1060
+ ${Io(Wp.basename(s),a)}`}})}function w0e(e){let t=e&&typeof e==="object"&&!Array.isArray(e)?e.paths:void 0;return(typeof t==="string"?[t]:Array.isArray(t)?t:[]).filter((r)=>typeof r==="string").map((r)=>r.trim()).filter((r)=>r!=="")}async function b0e(e,t,n){let r=[],o=new Set;for(let i of w0e(n)){let s=t.resolve(i);if(s.kind==="uncovered"||s.kind==="outside")continue;let a=s.absolutePath;if(o.has(a))continue;o.add(a);let d=e.revisions.revisions(a);if(d.length<2)continue;let l;try{l=await y4(a)}catch{l=void 0}let c=Wb(l),u=d[d.length-1],h=`\`${Wp.basename(a)}\``,p=[...d].reverse().find((f)=>f.hash===c);if(!p)r.push(`Checked ${h} as it is on disk now, which is none of its ${d.length} revisions: something other than this session's file tools has written it since revision #${u?.index} (${u?.note}).`);else if(p.index===u?.index)r.push(`Checked ${h} as it is on disk now: revision #${p.index}, ${p.index===1?"the file before your first change":`the content your most recent change left (${p.note})`}. Nothing older is cached; an error reported here is in that content.`);else r.push(`Checked ${h} as it is on disk now: the same content as revision #${p.index} (${p.note}), not your most recent change, #${u?.index}.`)}return r.length>0?r.join(`
1061
+ `):void 0}function qp(e,t,n=l0e,r){let o=()=>r?.live()?r:{source:t,wording:n};return e.map((i)=>{if(i.name===Lr)return v0e(i,o);if(i.name!==le.READ_FILES)return i;let s=i;return{...s,description:s.description+n.description+(r?r.wording.description:""),inputSchema:m0e(s.inputSchema,n,r),execute:async function a(d,l){let c=p0e(d);if(c){let y=[];for(let w of c){let k=await a(w,l);if(Array.isArray(k))y.push(...k);else y.push(k)}return y}let u=o(),{revision:h,rest:p}=h0e(d),f=v4(u.source),m=typeof h==="string"?h.trim():void 0;if(m===void 0||m===""||["current","now","disk","head","working"].includes(m.toLowerCase())){let y=await s.execute(p,l);return f&&Array.isArray(y)?y0e(u.source,f,p,y):y}if(!f)return[{query:m,result:"",error:u.wording.closed,success:!1}];return g0e(u.source,f,p,l,m,u.wording)}}})}function v0e(e,t){let n=e;return{...n,execute:async(r,o)=>{let i=await n.execute(r,o);if(typeof i!=="string")return i;let{source:s}=t(),a=v4(s);if(!a)return i;let d=await b0e(s,a,r).catch(()=>{return});return d?`${i}
1062
1062
 
1063
- ${d}`:i}}}import*as Ur from"node:path";import{editorFilePath as k0e}from"@cerebriline/shared";var T0e=[le.EDITOR,le.APPLY_PATCH,le.SED],S0e=[le.RUN_COMMANDS];function k6(e){let t=[],n=/^\*\*\*\s+(?:Update|Add|Delete)\s+File:\s*(.+?)\s*$/gim;for(;;){let r=n.exec(e);if(!r)break;if(r[1])t.push(r[1])}return t}function x0e(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return typeof t==="string"&&e===le.APPLY_PATCH?k6(t):[];let n=t;if(e===le.EDITOR){let r=k0e(n);return r?[r]:[]}if(e===le.APPLY_PATCH)return typeof n.input==="string"?k6(n.input):[];if(e===le.SED){if(n.in_place!==!0)return[];return Array.isArray(n.files)?n.files.filter((r)=>typeof r==="string"):[]}return[]}function _0e(e,t,n,r,o){let i=`\`${e}\` is now revision #${t} (${n} lines) — ${r}.`,s=`To undo just this change, \`restore_file\` with \`revision: "${Yt}"\`; #1 is the file as this transaction opened.`;if(o)return`${i} ${s}`;return`${i} ${s}
1063
+ ${d}`:i}}}import*as Ur from"node:path";import{editorFilePath as k0e}from"@cerebriline/shared";var T0e=[le.EDITOR,le.APPLY_PATCH,le.SED],S0e=[le.RUN_COMMANDS];function k4(e){let t=[],n=/^\*\*\*\s+(?:Update|Add|Delete)\s+File:\s*(.+?)\s*$/gim;for(;;){let r=n.exec(e);if(!r)break;if(r[1])t.push(r[1])}return t}function x0e(e,t){if(!t||typeof t!=="object"||Array.isArray(t))return typeof t==="string"&&e===le.APPLY_PATCH?k4(t):[];let n=t;if(e===le.EDITOR){let r=k0e(n);return r?[r]:[]}if(e===le.APPLY_PATCH)return typeof n.input==="string"?k4(n.input):[];if(e===le.SED){if(n.in_place!==!0)return[];return Array.isArray(n.files)?n.files.filter((r)=>typeof r==="string"):[]}return[]}function _0e(e,t,n,r,o){let i=`\`${e}\` is now revision #${t} (${n} lines) — ${r}.`,s=`To undo just this change, \`restore_file\` with \`revision: "${Yt}"\`; #1 is the file as this transaction opened.`;if(o)return`${i} ${s}`;return`${i} ${s}
1064
1064
 
1065
- That note was worked out from the change itself. Send \`intent\` with your next edit — one short sentence on what it is meant to do — and it will be the label for that revision.`}function E0e(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;for(let n of["intent","why","purpose"]){let r=t[n];if(typeof r==="string"&&r.trim())return r.trim()}return}function A0e(e){let t=T6(e);if(!t)return;let n=t.split(`
1066
- `).find((r)=>r.trim());if(!n)return;return n.replace(/\s+in\s+\/\S+$/,"").trim()||void 0}function T6(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t=e.length-1;t>=0;t-=1){let n=T6(e[t]);if(n)return n}return}if(e&&typeof e==="object"){let t=e.result;if(typeof t==="string")return t}return}function R0e(e){let t=typeof e.properties==="object"&&e.properties!==null?e.properties:{};return{...e,properties:{...t,intent:{type:"string",description:"One short sentence on what this change is meant to achieve. It becomes the label for the revision this write creates, and it is what you will be choosing between if you later need to go back to a particular point. Omit it and the label is worked out from the change itself, which says what moved but not why."}}}}function S6(e,t){if(typeof e==="string")return`${e}
1065
+ That note was worked out from the change itself. Send \`intent\` with your next edit — one short sentence on what it is meant to do — and it will be the label for that revision.`}function E0e(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e;for(let n of["intent","why","purpose"]){let r=t[n];if(typeof r==="string"&&r.trim())return r.trim()}return}function A0e(e){let t=T4(e);if(!t)return;let n=t.split(`
1066
+ `).find((r)=>r.trim());if(!n)return;return n.replace(/\s+in\s+\/\S+$/,"").trim()||void 0}function T4(e){if(typeof e==="string")return e;if(Array.isArray(e)){for(let t=e.length-1;t>=0;t-=1){let n=T4(e[t]);if(n)return n}return}if(e&&typeof e==="object"){let t=e.result;if(typeof t==="string")return t}return}function R0e(e){let t=typeof e.properties==="object"&&e.properties!==null?e.properties:{};return{...e,properties:{...t,intent:{type:"string",description:"One short sentence on what this change is meant to achieve. It becomes the label for the revision this write creates, and it is what you will be choosing between if you later need to go back to a particular point. Omit it and the label is worked out from the change itself, which says what moved but not why."}}}}function S4(e,t){if(typeof e==="string")return`${e}
1067
1067
 
1068
- ${t}`;if(Array.isArray(e)){if(e.length===0)return e;let n=e[e.length-1],r=S6(n,t);return r===n?e:[...e.slice(0,-1),r]}if(e&&typeof e==="object"){let n=e;if(typeof n.result==="string")return{...n,result:`${n.result}
1068
+ ${t}`;if(Array.isArray(e)){if(e.length===0)return e;let n=e[e.length-1],r=S4(n,t);return r===n?e:[...e.slice(0,-1),r]}if(e&&typeof e==="object"){let n=e;if(typeof n.result==="string")return{...n,result:`${n.result}
1069
1069
 
1070
- ${t}`}}return e}function Rc(e,t){let{source:n}=t,r=async(a,d)=>{let l=Ec(a,d);if(l.kind==="uncovered"||l.kind==="outside")return;return n.log.seed(l.absolutePath,l.kind==="held"?l.body:void 0),l.absolutePath},o=async(a,d)=>{let l=Ur.normalize(Ur.isAbsolute(d)?d:Ur.resolve(a,d)),c=Ur.relative(Ur.normalize(a),l);if(!(c!==""&&!c.startsWith("..")&&!Ur.isAbsolute(c)))return;return n.log.seed(l,await t.readFile(l),"session"),l},i=async(a,d,l)=>{let c;for(let u of d){let h=await t.readFile(u),p=n.log.record(u,h,s,l);if(!p)continue;c={display:Ur.relative(a,u)||u,index:p.index,lines:p.lines,note:p.note,fromModel:p.noteSource==="model"}}return c},s="";return e.map((a)=>{let d=T0e.includes(a.name),l=S0e.includes(a.name);if(!d&&!l)return a;let c=a;return{...c,...d?{inputSchema:R0e(c.inputSchema??{})}:{},execute:async(u,h)=>{let p=n.pending,f=p?.root??n.root;if(f===void 0)return c.execute(u,h);let m=d?(await Promise.all(x0e(a.name,u).map((w)=>p?r(p,w):o(f,w)))).filter((w)=>w!==void 0):[...n.log.tracked()];s=a.name;let g=await c.execute(u,h),y=await i(f,m,{intent:E0e(u),summary:A0e(g),check:t.lastCheck?.()});if(!y)return g;return S6(g,_0e(y.display,y.index,y.lines,y.note,y.fromModel))}}})}import{readFile as xMe}from"node:fs/promises";import{createTool as I0e}from"@cerebriline/shared";var Br="run_check",x6=10,C0e=`Run the check that decides whether this task is done, right now, against the files as they currently stand.
1070
+ ${t}`}}return e}function Rc(e,t){let{source:n}=t,r=async(a,d)=>{let l=Ec(a,d);if(l.kind==="uncovered"||l.kind==="outside")return;return n.log.seed(l.absolutePath,l.kind==="held"?l.body:void 0),l.absolutePath},o=async(a,d)=>{let l=Ur.normalize(Ur.isAbsolute(d)?d:Ur.resolve(a,d)),c=Ur.relative(Ur.normalize(a),l);if(!(c!==""&&!c.startsWith("..")&&!Ur.isAbsolute(c)))return;return n.log.seed(l,await t.readFile(l),"session"),l},i=async(a,d,l)=>{let c;for(let u of d){let h=await t.readFile(u),p=n.log.record(u,h,s,l);if(!p)continue;c={display:Ur.relative(a,u)||u,index:p.index,lines:p.lines,note:p.note,fromModel:p.noteSource==="model"}}return c},s="";return e.map((a)=>{let d=T0e.includes(a.name),l=S0e.includes(a.name);if(!d&&!l)return a;let c=a;return{...c,...d?{inputSchema:R0e(c.inputSchema??{})}:{},execute:async(u,h)=>{let p=n.pending,f=p?.root??n.root;if(f===void 0)return c.execute(u,h);let m=d?(await Promise.all(x0e(a.name,u).map((w)=>p?r(p,w):o(f,w)))).filter((w)=>w!==void 0):[...n.log.tracked()];s=a.name;let g=await c.execute(u,h),y=await i(f,m,{intent:E0e(u),summary:A0e(g),check:t.lastCheck?.()});if(!y)return g;return S4(g,_0e(y.display,y.index,y.lines,y.note,y.fromModel))}}})}import{readFile as xMe}from"node:fs/promises";import{createTool as I0e}from"@cerebriline/shared";var Br="run_check",x4=10,C0e=`Run the check that decides whether this task is done, right now, against the files as they currently stand.
1071
1071
 
1072
1072
  This is your feedback loop. Nothing is settled and nothing is rolled back: the result is information, the transaction stays open, and your changes stay in place whatever it says.
1073
1073
 
@@ -1076,16 +1076,16 @@ Run it early, on the unmodified files, so you see the failure you are fixing in
1076
1076
  Take no output as no output. If the check passes, say so and finish; the same check runs once more when you do.`,P0e={type:"object",properties:{},required:[]};function M0e(e,t){let n=e.output.trim(),r=e.passed?`The check passed: \`${t}\`.`:`The check failed: \`${t}\`.`,o=e.passed?"Nothing was settled — say so and finish, and it will be run once more when you do.":"Nothing was rolled back: the transaction is open and your changes are still there. Fix what it named and run it again.";return[r,n?`
1077
1077
  ${n}
1078
1078
  `:void 0,o].filter((i)=>i!==void 0).join(`
1079
- `)}function _6(e){let t=0,n=0;return I0e({name:Br,description:C0e,inputSchema:P0e,execute:async()=>{let r=e.controller.oracle;if(!r)return e.canProposeCheck?"There is no check yet. Propose one with `propose_check` and, once the user approves it, this runs it.":"There is no check to run in this workspace, so your own account of the work is the verdict. Say plainly whether the change worked and how you know.";let o=e.controller.transaction;if(o!==t)t=o,n=0;if(n>=x6)return`The check has been run ${x6} times in this transaction without the task closing. Running it again will not tell you anything the last result did not. Either make a different change, or say plainly that you cannot get it to pass.`;n+=1;let i;try{i=await e.controller.runCheck()}catch(a){return e.onError?.("[Atomic] the check could not be run",a),`The check could not be run: ${String(a)}. It will still be run when you finish, so this is not a reason to stop.`}let s=await e.onRun?.(i,r);return[M0e(i,r.label),s].filter((a)=>Boolean(a)).join(`
1079
+ `)}function _4(e){let t=0,n=0;return I0e({name:Br,description:C0e,inputSchema:P0e,execute:async()=>{let r=e.controller.oracle;if(!r)return e.canProposeCheck?"There is no check yet. Propose one with `propose_check` and, once the user approves it, this runs it.":"There is no check to run in this workspace, so your own account of the work is the verdict. Say plainly whether the change worked and how you know.";let o=e.controller.transaction;if(o!==t)t=o,n=0;if(n>=x4)return`The check has been run ${x4} times in this transaction without the task closing. Running it again will not tell you anything the last result did not. Either make a different change, or say plainly that you cannot get it to pass.`;n+=1;let i;try{i=await e.controller.runCheck()}catch(a){return e.onError?.("[Atomic] the check could not be run",a),`The check could not be run: ${String(a)}. It will still be run when you finish, so this is not a reason to stop.`}let s=await e.onRun?.(i,r);return[M0e(i,r.label),s].filter((a)=>Boolean(a)).join(`
1080
1080
 
1081
- `)}})}var O0e=[le.EDITOR,le.APPLY_PATCH];function E6(e,t=!1){return["That edit was not made. Nothing has changed on disk.","",...t?["You have run the check, which is the right way to open a transaction — this is not asking you to run it again. What is missing is the plan.","","State it before you edit: a numbered list, each entry naming WHERE, WHAT and WHY. Put it in your reply, so it is on the record and the user can see it, not only in your reasoning."]:[`Run \`${Br}\` first — it runs ${e} — and read what it reports. It is the failure this transaction is judged on, and reading the source is not a substitute for it: a file can look wrong in one place and fail in another, and the edit you were about to make would have been aimed at whichever one you happened to read.`,"","Then state your plan before you edit: a numbered list, each entry naming WHERE, WHAT and WHY. State it in your reply, so it is on the record and the user can see it, not only in your reasoning."],"","After that, make the edit. This is asked once per transaction and not again — the next edit goes through whatever you decide."].join(`
1082
- `)}function A6(e,t){let n=t.transaction,r=!1,o=!1,i,s=()=>{if(t.transaction!==n)n=t.transaction,r=!1,o=!1,i=void 0};return e.map((a)=>{if(a.name===Br){let l=a;return{...l,execute:async(c,u)=>(s(),r=!0,l.execute(c,u))}}if(!O0e.includes(a.name))return a;let d=a;return{...d,execute:async(l,c)=>{if(s(),o){if(i!==void 0&&c.iteration===i)return E6(t.checkLabel,r);return d.execute(l,c)}return o=!0,i=c.iteration,E6(t.checkLabel,r)}}})}var P6=/^\s{0,3}(?:#{1,6}\s*)?(?:\*\*|__)?\s*(?:TX-?\d+\s*[-:—]?\s*)?plan\b[^\n]*$/i,L0e=/^\s{0,3}#{1,6}\s+/,M6=/^\s{0,6}(?:\d{1,2}[.)]|[-*+])\s+\S/,O6=/^\s{0,6}\|.*\|\s*$/;function R6(e){return/\bwhere\b/i.test(e)&&/\bwhat\b/i.test(e)&&/\bwhy\b/i.test(e)}function N0e(e){return e.some((t)=>M6.test(t)||O6.test(t))}function zp(e){if(!e)return;let t=e.split(`
1083
- `);for(let n=0;n<t.length;n+=1){if(!P6.test(t[n]))continue;let r=I6(t,n+1);if(r.length>0&&R6(r.join(`
1084
- `)))return C6([t[n],...r])}for(let n=0;n<t.length;n+=1){if(!M6.test(t[n])&&!O6.test(t[n]))continue;let r=[t[n],...I6(t,n+1)];if(R6(r.join(`
1085
- `)))return C6(r);n+=r.length}return}function I6(e,t){let n=[],r=0;for(let o=t;o<e.length;o+=1){let i=e[o];if(L0e.test(i)&&!P6.test(i))break;if(i.trim()===""){if(r+=1,r>=2)break;n.push(i);continue}r=0,n.push(i)}while(n.length>0&&n[n.length-1].trim()==="")n.pop();return n}function C6(e){if(!N0e(e))return;let t=e.join(`
1081
+ `)}})}var O0e=[le.EDITOR,le.APPLY_PATCH];function E4(e,t=!1){return["That edit was not made. Nothing has changed on disk.","",...t?["You have run the check, which is the right way to open a transaction — this is not asking you to run it again. What is missing is the plan.","","State it before you edit: a numbered list, each entry naming WHERE, WHAT and WHY. Put it in your reply, so it is on the record and the user can see it, not only in your reasoning."]:[`Run \`${Br}\` first — it runs ${e} — and read what it reports. It is the failure this transaction is judged on, and reading the source is not a substitute for it: a file can look wrong in one place and fail in another, and the edit you were about to make would have been aimed at whichever one you happened to read.`,"","Then state your plan before you edit: a numbered list, each entry naming WHERE, WHAT and WHY. State it in your reply, so it is on the record and the user can see it, not only in your reasoning."],"","After that, make the edit. This is asked once per transaction and not again — the next edit goes through whatever you decide."].join(`
1082
+ `)}function A4(e,t){let n=t.transaction,r=!1,o=!1,i,s=()=>{if(t.transaction!==n)n=t.transaction,r=!1,o=!1,i=void 0};return e.map((a)=>{if(a.name===Br){let l=a;return{...l,execute:async(c,u)=>(s(),r=!0,l.execute(c,u))}}if(!O0e.includes(a.name))return a;let d=a;return{...d,execute:async(l,c)=>{if(s(),o){if(i!==void 0&&c.iteration===i)return E4(t.checkLabel,r);return d.execute(l,c)}return o=!0,i=c.iteration,E4(t.checkLabel,r)}}})}var P4=/^\s{0,3}(?:#{1,6}\s*)?(?:\*\*|__)?\s*(?:TX-?\d+\s*[-:—]?\s*)?plan\b[^\n]*$/i,L0e=/^\s{0,3}#{1,6}\s+/,M4=/^\s{0,6}(?:\d{1,2}[.)]|[-*+])\s+\S/,O4=/^\s{0,6}\|.*\|\s*$/;function R4(e){return/\bwhere\b/i.test(e)&&/\bwhat\b/i.test(e)&&/\bwhy\b/i.test(e)}function N0e(e){return e.some((t)=>M4.test(t)||O4.test(t))}function zp(e){if(!e)return;let t=e.split(`
1083
+ `);for(let n=0;n<t.length;n+=1){if(!P4.test(t[n]))continue;let r=I4(t,n+1);if(r.length>0&&R4(r.join(`
1084
+ `)))return C4([t[n],...r])}for(let n=0;n<t.length;n+=1){if(!M4.test(t[n])&&!O4.test(t[n]))continue;let r=[t[n],...I4(t,n+1)];if(R4(r.join(`
1085
+ `)))return C4(r);n+=r.length}return}function I4(e,t){let n=[],r=0;for(let o=t;o<e.length;o+=1){let i=e[o];if(L0e.test(i)&&!P4.test(i))break;if(i.trim()===""){if(r+=1,r>=2)break;n.push(i);continue}r=0,n.push(i)}while(n.length>0&&n[n.length-1].trim()==="")n.pop();return n}function C4(e){if(!N0e(e))return;let t=e.join(`
1086
1086
  `).trim();if(t.length===0)return;return t.length>4000?`${t.slice(0,4000).trimEnd()}
1087
- …`:t}function L6(e,t){if(!e)return"";return e.content.filter((n)=>n.type===t&&typeof n.text==="string").map((n)=>n.text).join(`
1088
- `).trim()}function D0e(e){if(!e)return;for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="assistant")return e[t];return}function N6(e,t){let n=t.transaction,r=!1,o=(i)=>{if(t.transaction!==n)n=t.transaction,r=!1;if(r)return;let s=D0e(i.snapshot?.messages),a=zp(L6(s,"text"));if(a){r=!0,t.onPlan(a,"reply");return}let d=zp(L6(s,"reasoning"));if(d)r=!0,t.onPlan(d,"reasoning")};return e.map((i)=>{let s=i;return{...s,execute:async(a,d)=>{try{o(d)}catch{}return s.execute(a,d)}}})}import{createTool as $0e}from"@cerebriline/shared";var Cc="plan",F0e=400,D6=3,U0e=`Keep the plan for this task: what you intend to change, and which of those changes have landed.
1087
+ …`:t}function L4(e,t){if(!e)return"";return e.content.filter((n)=>n.type===t&&typeof n.text==="string").map((n)=>n.text).join(`
1088
+ `).trim()}function D0e(e){if(!e)return;for(let t=e.length-1;t>=0;t-=1)if(e[t].role==="assistant")return e[t];return}function N4(e,t){let n=t.transaction,r=!1,o=(i)=>{if(t.transaction!==n)n=t.transaction,r=!1;if(r)return;let s=D0e(i.snapshot?.messages),a=zp(L4(s,"text"));if(a){r=!0,t.onPlan(a,"reply");return}let d=zp(L4(s,"reasoning"));if(d)r=!0,t.onPlan(d,"reasoning")};return e.map((i)=>{let s=i;return{...s,execute:async(a,d)=>{try{o(d)}catch{}return s.execute(a,d)}}})}import{createTool as $0e}from"@cerebriline/shared";var Cc="plan",F0e=400,D4=3,U0e=`Keep the plan for this task: what you intend to change, and which of those changes have landed.
1089
1089
 
1090
1090
  Call it three ways.
1091
1091
 
@@ -1101,15 +1101,15 @@ The plan survives a discarded transaction. An item that landed and was then roll
1101
1101
  `)}function Ic(e,t){if(e.length===0)return"No plan stated yet. Send `changes` with the list of edits you intend to make.";let n=e.map((s)=>{let a=s.note?`
1102
1102
  note: ${s.note}`:"";return[`${W0e[s.status]} ${s.id}. ${s.what}`,` where: ${s.where}`,` why: ${s.why}${a}${H0e(s)}`].join(`
1103
1103
  `)}),r=e.filter((s)=>s.status==="done").length,o=e.filter((s)=>s.status==="failed").length,i=e.length-r-o;return[`Plan for TX-${String(t).padStart(2,"0")} — ${e.length} change${e.length===1?"":"s"}: ${r} landed, ${o} failed, ${i} still to do.`,"",...n].join(`
1104
- `)}function $6(e){let t=[],n=e.controller.transaction,r=0,o;function i(l){for(let c of t){if(c.status!=="pending")c.history.push({transaction:l,status:c.status,note:c.note});c.status="pending",c.note=void 0}if(r=0,t.length>0)o=l}function s(){let l=e.controller.transaction;if(l!==n)i(n),n=l;return l}function a(l,c,u,h){if(typeof l!=="number"||!Number.isInteger(l))return`\`${c}\` needs the number of a plan item. ${Ic(t,h)}`;let p=t.find((f)=>f.id===l);if(!p)return t.length===0?"There is no plan yet, so there is no item to mark. Send `changes` first.":`There is no item ${l} in this plan.
1104
+ `)}function $4(e){let t=[],n=e.controller.transaction,r=0,o;function i(l){for(let c of t){if(c.status!=="pending")c.history.push({transaction:l,status:c.status,note:c.note});c.status="pending",c.note=void 0}if(r=0,t.length>0)o=l}function s(){let l=e.controller.transaction;if(l!==n)i(n),n=l;return l}function a(l,c,u,h){if(typeof l!=="number"||!Number.isInteger(l))return`\`${c}\` needs the number of a plan item. ${Ic(t,h)}`;let p=t.find((f)=>f.id===l);if(!p)return t.length===0?"There is no plan yet, so there is no item to mark. Send `changes` first.":`There is no item ${l} in this plan.
1105
1105
 
1106
1106
  ${Ic(t,h)}`;return p.status=c,p.note=u||void 0,e.onPlan?.(t),d(Ic(t,h),!1)}function d(l,c){if(o===void 0)return l;let u=j0e(t,o);if(c)o=void 0;return`${u}
1107
1107
 
1108
- ${l}`}return $0e({name:Cc,description:U0e,inputSchema:B0e,execute:async(l)=>{let c=s(),u=l??{},h=jb(u.note);if(u.done!==void 0)return a(u.done,"done",h,c);if(u.failed!==void 0)return a(u.failed,"failed",h,c);if(u.changes===void 0)return d(Ic(t,c),!1);if(!Array.isArray(u.changes))return"`changes` is a list of entries, each naming where, what and why.";if(r>=D6)return`You have stated a plan ${D6} times in this transaction. Restating it is not progress — the plan below is the one you have. Mark items \`done\` as they land, and make the next change.
1108
+ ${l}`}return $0e({name:Cc,description:U0e,inputSchema:B0e,execute:async(l)=>{let c=s(),u=l??{},h=jb(u.note);if(u.done!==void 0)return a(u.done,"done",h,c);if(u.failed!==void 0)return a(u.failed,"failed",h,c);if(u.changes===void 0)return d(Ic(t,c),!1);if(!Array.isArray(u.changes))return"`changes` is a list of entries, each naming where, what and why.";if(r>=D4)return`You have stated a plan ${D4} times in this transaction. Restating it is not progress — the plan below is the one you have. Mark items \`done\` as they land, and make the next change.
1109
1109
 
1110
- ${Ic(t,c)}`;let p=[];for(let g of u.changes){let y=g??{},w=jb(y.where),k=jb(y.what),b=jb(y.why);if(!w||!k||!b)return"Every entry needs all three of `where`, `what` and `why`. An entry missing one of them is not a change anyone can check.";p.push({where:w,what:k,why:b})}if(p.length===0)return"An empty list is not a plan. Send the changes you intend to make.";let f=e.maxChanges;if(p.length>f)return`That is ${p.length} changes and this transaction allows ${f}. Send the ${f} that matter most; the rest can have a transaction of their own.`;let m=t;return t=p.map((g,y)=>{let w=m.find((k)=>k.what===g.what);return{id:y+1,...g,status:w?.status??"pending",note:w?.note,history:w?[...w.history]:[]}}),r+=1,e.onPlan?.(t),d(Ic(t,c),!0)}})}import*as Pc from"node:path";var Mc="propose_check",qb=2,F6=2;function Ua(e){return typeof e==="string"&&e.trim()!==""?e.trim():void 0}function q0e(e,t){let n=Pc.resolve(e,t),r=Pc.relative(e,n);return r!==""&&!r.startsWith("..")&&!Pc.isAbsolute(r)}function U6(e,t){let n=e??{},r=Ua(n.reason);if(!r)return{problem:"`reason` is missing. Say what this check demonstrates about the task, in one sentence — the user reads it to decide."};let o=Ua(n.kind),i=Ua(n.path)!==void 0,s=Ua(n.command)!==void 0,a;if(o==="page"||o==="command")a=o;else if(o!==void 0)return{problem:`\`kind\` must be "page" (load a file and run it — needs nothing installed) or "command" (a line for the shell). \`${o}\` is neither.`};else if(i&&!s)a="page";else if(s&&!i)a="command";else if(i&&s)return{problem:'This proposal gives both `path` and `command`, so it is two different checks. Set `kind` to "page" or "command" to say which one you mean.'};else return{problem:'`kind` must be "page" (load a file and run it — needs nothing installed) or "command" (a line for the shell), and the proposal needs the matching `path` or `command` with it.'};if(a==="page"){let c=Ua(n.path);if(!c)return{problem:"`path` is missing. Name the file to load, relative to the workspace root."};if(!q0e(t,c))return{problem:`\`path\` must be inside the workspace. \`${c}\` is not.`};if(!/\.(html?|js|cjs)$/i.test(c))return{problem:`This check loads a page or a script: \`${c}\` is neither. Use \`kind: "command"\` for anything else.`};return{kind:a,path:c,reason:r}}let d=Ua(n.command);if(!d)return{problem:"`command` is missing. Give the exact line to run."};let l=Ua(n.expect);if(l)try{new RegExp(l)}catch(c){return{problem:`\`expect\` is not a valid regular expression: ${c instanceof Error?c.message:String(c)}. It is matched against the output in this process, so it is a pattern and never a command.`}}return{kind:a,command:d,reason:r,...l?{expect:l}:{}}}function B6(e){if(e.kind==="page")return["Cline runs this itself after every attempt, start to finish. You are not asked to test anything, now or later.","",`It loads \`${e.path}\` here in Cline — no browser window opens — runs its scripts, and fails if the file does not parse, throws, or never draws a frame.`,"",`Cline's reason for choosing it: ${e.reason}`].join(`
1110
+ ${Ic(t,c)}`;let p=[];for(let g of u.changes){let y=g??{},w=jb(y.where),k=jb(y.what),b=jb(y.why);if(!w||!k||!b)return"Every entry needs all three of `where`, `what` and `why`. An entry missing one of them is not a change anyone can check.";p.push({where:w,what:k,why:b})}if(p.length===0)return"An empty list is not a plan. Send the changes you intend to make.";let f=e.maxChanges;if(p.length>f)return`That is ${p.length} changes and this transaction allows ${f}. Send the ${f} that matter most; the rest can have a transaction of their own.`;let m=t;return t=p.map((g,y)=>{let w=m.find((k)=>k.what===g.what);return{id:y+1,...g,status:w?.status??"pending",note:w?.note,history:w?[...w.history]:[]}}),r+=1,e.onPlan?.(t),d(Ic(t,c),!0)}})}import*as Pc from"node:path";var Mc="propose_check",qb=2,F4=2;function Ua(e){return typeof e==="string"&&e.trim()!==""?e.trim():void 0}function q0e(e,t){let n=Pc.resolve(e,t),r=Pc.relative(e,n);return r!==""&&!r.startsWith("..")&&!Pc.isAbsolute(r)}function U4(e,t){let n=e??{},r=Ua(n.reason);if(!r)return{problem:"`reason` is missing. Say what this check demonstrates about the task, in one sentence — the user reads it to decide."};let o=Ua(n.kind),i=Ua(n.path)!==void 0,s=Ua(n.command)!==void 0,a;if(o==="page"||o==="command")a=o;else if(o!==void 0)return{problem:`\`kind\` must be "page" (load a file and run it — needs nothing installed) or "command" (a line for the shell). \`${o}\` is neither.`};else if(i&&!s)a="page";else if(s&&!i)a="command";else if(i&&s)return{problem:'This proposal gives both `path` and `command`, so it is two different checks. Set `kind` to "page" or "command" to say which one you mean.'};else return{problem:'`kind` must be "page" (load a file and run it — needs nothing installed) or "command" (a line for the shell), and the proposal needs the matching `path` or `command` with it.'};if(a==="page"){let c=Ua(n.path);if(!c)return{problem:"`path` is missing. Name the file to load, relative to the workspace root."};if(!q0e(t,c))return{problem:`\`path\` must be inside the workspace. \`${c}\` is not.`};if(!/\.(html?|js|cjs)$/i.test(c))return{problem:`This check loads a page or a script: \`${c}\` is neither. Use \`kind: "command"\` for anything else.`};return{kind:a,path:c,reason:r}}let d=Ua(n.command);if(!d)return{problem:"`command` is missing. Give the exact line to run."};let l=Ua(n.expect);if(l)try{new RegExp(l)}catch(c){return{problem:`\`expect\` is not a valid regular expression: ${c instanceof Error?c.message:String(c)}. It is matched against the output in this process, so it is a pattern and never a command.`}}return{kind:a,command:d,reason:r,...l?{expect:l}:{}}}function B4(e){if(e.kind==="page")return["Cline runs this itself after every attempt, start to finish. You are not asked to test anything, now or later.","",`It loads \`${e.path}\` here in Cline — no browser window opens — runs its scripts, and fails if the file does not parse, throws, or never draws a frame.`,"",`Cline's reason for choosing it: ${e.reason}`].join(`
1111
1111
  `);return["Cline runs this itself after every attempt, start to finish. You are not asked to test anything, now or later.","","It runs this command, unattended, and judges the change by it:",` ${e.command}`,e.expect?`It has to finish cleanly AND its output has to match /${e.expect}/.`:"It has to finish cleanly.","",`Cline's reason for choosing it: ${e.reason}`].join(`
1112
- `)}function H6(e,t){if(e.kind==="page")return{kind:"page",label:`load \`${e.path}\` and check that it runs`,path:e.path,cwd:t,reason:"proposed for this task and approved by you"};let n=e.command;return{label:n,command:process.platform==="win32"?"cmd":"sh",args:process.platform==="win32"?["/c",n]:["-c",n],cwd:t,reason:"proposed for this task and approved by you",...e.expect?{expect:e.expect}:{}}}function W6(e,t){return e.kind===t.kind&&e.path===t.path&&e.command===t.command&&e.expect===t.expect}var z0e=[{pattern:/\[(?:eval|stdin|worker eval)\]:\d+[\s\S]{0,2000}?SyntaxError/,what:"node could not parse the program given to `-e`"},{pattern:/(?:^|\n)(?:sh|bash|dash|zsh):(?: -c:)? line \d+: syntax error/,what:"the shell could not parse the line"},{pattern:/syntax error near unexpected token|unexpected EOF while looking for matching/,what:"the shell could not parse the line"},{pattern:/File "<string>"[\s\S]{0,2000}?SyntaxError/,what:"python could not parse the program given to `-c`"}];function K0e(e){if(e.exitCode===127)return{what:"the command was not found on this machine"};for(let{pattern:t,what:n}of z0e)if(t.test(e.output))return{what:n};return}function j6(e,t){if(e.passed){if(t?.kind==="command"&&!t.expect)return{usable:!1,problem:`That check exited cleanly on the files as they were before any edit, and with no \`expect\` its exit code is the whole verdict — so it would keep any change at all. It printed: ${e.output.trim()||"no output"}. Propose it again with an \`expect\` that matches only the output of a working state.`};return{usable:!1,problem:"That check already passes on the files as they were before any edit, so it cannot tell a fix from no fix at all. Propose one that fails right now and passes once the change lands."}}if(e.timedOut)return{usable:!1,problem:"That check did not finish in the time it is given, so it cannot judge an attempt. Propose something faster."};if(e.exitCode===null)return{usable:!1,problem:`That check could not be run here at all, so it would judge nothing: ${e.output.trim()||"no output"}. Propose something that exists on this machine — \`kind: "page"\` needs nothing installed.`};let n=K0e(e);if(n)return{usable:!1,problem:`That check did not run: ${n.what}, so it would fail on any files at all, fixed or not. It said: ${e.output.trim()||"no output"}. Fix the check itself, or propose a simpler one — \`kind: "page"\` needs nothing quoted or escaped.`};return{usable:!0}}import{createTool as G0e}from"@cerebriline/shared";var V0e=`Propose the check that will decide whether your change worked, and ask the user to approve it once.
1112
+ `)}function H4(e,t){if(e.kind==="page")return{kind:"page",label:`load \`${e.path}\` and check that it runs`,path:e.path,cwd:t,reason:"proposed for this task and approved by you"};let n=e.command;return{label:n,command:process.platform==="win32"?"cmd":"sh",args:process.platform==="win32"?["/c",n]:["-c",n],cwd:t,reason:"proposed for this task and approved by you",...e.expect?{expect:e.expect}:{}}}function W4(e,t){return e.kind===t.kind&&e.path===t.path&&e.command===t.command&&e.expect===t.expect}var z0e=[{pattern:/\[(?:eval|stdin|worker eval)\]:\d+[\s\S]{0,2000}?SyntaxError/,what:"node could not parse the program given to `-e`"},{pattern:/(?:^|\n)(?:sh|bash|dash|zsh):(?: -c:)? line \d+: syntax error/,what:"the shell could not parse the line"},{pattern:/syntax error near unexpected token|unexpected EOF while looking for matching/,what:"the shell could not parse the line"},{pattern:/File "<string>"[\s\S]{0,2000}?SyntaxError/,what:"python could not parse the program given to `-c`"}];function K0e(e){if(e.exitCode===127)return{what:"the command was not found on this machine"};for(let{pattern:t,what:n}of z0e)if(t.test(e.output))return{what:n};return}function j4(e,t){if(e.passed){if(t?.kind==="command"&&!t.expect)return{usable:!1,problem:`That check exited cleanly on the files as they were before any edit, and with no \`expect\` its exit code is the whole verdict — so it would keep any change at all. It printed: ${e.output.trim()||"no output"}. Propose it again with an \`expect\` that matches only the output of a working state.`};return{usable:!1,problem:"That check already passes on the files as they were before any edit, so it cannot tell a fix from no fix at all. Propose one that fails right now and passes once the change lands."}}if(e.timedOut)return{usable:!1,problem:"That check did not finish in the time it is given, so it cannot judge an attempt. Propose something faster."};if(e.exitCode===null)return{usable:!1,problem:`That check could not be run here at all, so it would judge nothing: ${e.output.trim()||"no output"}. Propose something that exists on this machine — \`kind: "page"\` needs nothing installed.`};let n=K0e(e);if(n)return{usable:!1,problem:`That check did not run: ${n.what}, so it would fail on any files at all, fixed or not. It said: ${e.output.trim()||"no output"}. Fix the check itself, or propose a simpler one — \`kind: "page"\` needs nothing quoted or escaped.`};return{usable:!0}}import{createTool as G0e}from"@cerebriline/shared";var V0e=`Propose the check that will decide whether your change worked, and ask the user to approve it once.
1113
1113
 
1114
1114
  Nothing in this workspace can be run to judge a change, so without a check your own account of the work is the verdict — and that is the weakest evidence there is. Propose one instead. You have read the code; name the thing that would show the fix.
1115
1115
 
@@ -1125,7 +1125,7 @@ Propose once, early — as soon as you know what you are fixing. What is approve
1125
1125
 
1126
1126
  Then use it. \`run_check\` runs it against the files as they stand, settles nothing and rolls nothing back. Run it before you edit, to see the failure in the check's own words, and after each change. A check you only meet when you finish is a check that can only ever throw the transaction away.
1127
1127
 
1128
- Once the user approves it, it is tried against the files as they were before your changes, and it has to FAIL there. A check that already passes on the unmodified files cannot tell a fix from no fix, and is refused.`,Y0e={type:"object",properties:{kind:{type:"string",enum:["page","command"],description:"`page` for a file Cline loads and runs itself; `command` for a shell line."},path:{type:"string",description:"For `page`: the file to load, relative to the workspace root."},command:{type:"string",description:"For `command`: the exact line to run."},expect:{type:"string",description:"For `command`: a regular expression the output must match, on top of exiting cleanly. Matched inside Cline; never a command."},reason:{type:"string",description:"One sentence: what passing this check proves."}},required:["kind","reason"]};function q6(e){let t=0,n,r=0,o=!1;return G0e({name:Mc,description:V0e,inputSchema:Y0e,execute:async(i)=>{let s=e.controller.checkIsUnderReconsideration===!0;if(s&&!o)r+=1,o=!0;if(!s)o=!1;if(!e.controller.canAdoptOracle)return"This run already has a check and it is frozen for the rest of the run. Make your change and let the check judge it.";let a=e.maxProposals??qb;if(t>=a+r)return"Every proposal this run allows has been put to the user without one being taken on, so it has no check and your own account of the work is the verdict. Do not propose again — say plainly whether the change worked and how you know.";let d=U6(i,e.workspaceRoot);if("problem"in d)return`That proposal cannot be used. ${d.problem}`;if(s&&n&&W6(n,d))return"That is the check this run already has. It is being reconsidered because it has never passed — propose a different one, or say the check is right and carry on fixing the change.";let l=B6(d),c;try{c=await e.approve(d,l)}catch(h){return e.onError?.("[Atomic] the check proposal was not answered",h),"The user could not be asked about that check, so the run continues without one. Say plainly whether your change worked and how you know."}if(!c.approved){t+=1;let h=c.feedback?.trim(),p=qb-t;return["The user did not approve that check.",h?`They said: ${h}`:void 0,p>0?"Propose one more, taking that into account. If you cannot think of a better one, carry on without a check and say so.":"That was the last round, so this run has no check and your own account of the work is the verdict."].filter((f)=>f!==void 0).join(" ")}let u=H6(d,e.workspaceRoot);try{let h=await e.controller.judgeAgainstBase(u),p=j6(h,d);if(!p.usable){t+=1;let f=qb-t;return[`The user approved that check, but it was tried against the files as they were before your changes and it does not work as a check. ${p.problem}`,f>0?"Propose one more.":"That was the last round, so this run has no check and your own account of the work is the verdict."].join(" ")}}catch(h){e.onError?.("[Atomic] the proposed check could not be tried against the base",h)}try{e.controller.adoptOracle(u)}catch(h){return e.onError?.("[Atomic] the approved check was not adopted",h),"That check was approved but could not be taken on, so the run keeps the check it already had."}return n=d,e.onAdopted?.(u,d),[`Approved. Every attempt from here is judged by: ${u.label}.`,"Run it whenever you want with `run_check` — it settles nothing and rolls nothing back — and it is run once more when you finish, where it decides rather than your account of the change.","It is fixed for the rest of the run, so make the change work rather than proposing something easier — if it turns out never to pass at all, you will be asked about it rather than getting to swap it now."].join(" ")}})}import*as Wr from"node:fs/promises";import*as zb from"node:path";import{createTool as X0e}from"@cerebriline/shared";var Hr="restore_file",JI=27,J0e=3,Q0e=`Put one file back exactly as it was when this transaction opened, discarding every change you have made to it since.
1128
+ Once the user approves it, it is tried against the files as they were before your changes, and it has to FAIL there. A check that already passes on the unmodified files cannot tell a fix from no fix, and is refused.`,Y0e={type:"object",properties:{kind:{type:"string",enum:["page","command"],description:"`page` for a file Cline loads and runs itself; `command` for a shell line."},path:{type:"string",description:"For `page`: the file to load, relative to the workspace root."},command:{type:"string",description:"For `command`: the exact line to run."},expect:{type:"string",description:"For `command`: a regular expression the output must match, on top of exiting cleanly. Matched inside Cline; never a command."},reason:{type:"string",description:"One sentence: what passing this check proves."}},required:["kind","reason"]};function q4(e){let t=0,n,r=0,o=!1;return G0e({name:Mc,description:V0e,inputSchema:Y0e,execute:async(i)=>{let s=e.controller.checkIsUnderReconsideration===!0;if(s&&!o)r+=1,o=!0;if(!s)o=!1;if(!e.controller.canAdoptOracle)return"This run already has a check and it is frozen for the rest of the run. Make your change and let the check judge it.";let a=e.maxProposals??qb;if(t>=a+r)return"Every proposal this run allows has been put to the user without one being taken on, so it has no check and your own account of the work is the verdict. Do not propose again — say plainly whether the change worked and how you know.";let d=U4(i,e.workspaceRoot);if("problem"in d)return`That proposal cannot be used. ${d.problem}`;if(s&&n&&W4(n,d))return"That is the check this run already has. It is being reconsidered because it has never passed — propose a different one, or say the check is right and carry on fixing the change.";let l=B4(d),c;try{c=await e.approve(d,l)}catch(h){return e.onError?.("[Atomic] the check proposal was not answered",h),"The user could not be asked about that check, so the run continues without one. Say plainly whether your change worked and how you know."}if(!c.approved){t+=1;let h=c.feedback?.trim(),p=qb-t;return["The user did not approve that check.",h?`They said: ${h}`:void 0,p>0?"Propose one more, taking that into account. If you cannot think of a better one, carry on without a check and say so.":"That was the last round, so this run has no check and your own account of the work is the verdict."].filter((f)=>f!==void 0).join(" ")}let u=H4(d,e.workspaceRoot);try{let h=await e.controller.judgeAgainstBase(u),p=j4(h,d);if(!p.usable){t+=1;let f=qb-t;return[`The user approved that check, but it was tried against the files as they were before your changes and it does not work as a check. ${p.problem}`,f>0?"Propose one more.":"That was the last round, so this run has no check and your own account of the work is the verdict."].join(" ")}}catch(h){e.onError?.("[Atomic] the proposed check could not be tried against the base",h)}try{e.controller.adoptOracle(u)}catch(h){return e.onError?.("[Atomic] the approved check was not adopted",h),"That check was approved but could not be taken on, so the run keeps the check it already had."}return n=d,e.onAdopted?.(u,d),[`Approved. Every attempt from here is judged by: ${u.label}.`,"Run it whenever you want with `run_check` — it settles nothing and rolls nothing back — and it is run once more when you finish, where it decides rather than your account of the change.","It is fixed for the rest of the run, so make the change work rather than proposing something easier — if it turns out never to pass at all, you will be asked about it rather than getting to swap it now."].join(" ")}})}import*as Wr from"node:fs/promises";import*as zb from"node:path";import{createTool as X0e}from"@cerebriline/shared";var Hr="restore_file",JI=27,J0e=3,Q0e=`Put one file back exactly as it was when this transaction opened, discarding every change you have made to it since.
1129
1129
 
1130
1130
  Use it the moment an edit goes wrong in a way you would otherwise have to undo by hand — you deleted more than you meant to, you merged two lines together, you have rewritten the same line four times and it is further from working than when you started. Restoring is exact. Retyping the original from memory is not, and on a long or minified line it is where runs go to die.
1131
1131
 
@@ -1155,49 +1155,49 @@ It affects one file, and only files this session has written: a file nothing has
1155
1155
 
1156
1156
  Read the file again afterwards: its line numbers are back to what they were at that revision, and any range you read earlier no longer addresses the same code.
1157
1157
 
1158
- If you only want to *see* what the file said before your changes, do not restore it — call \`read_files\` with \`revision: "${Vt}"\` (or a number) and it is shown to you with the file left alone.`,eMe={type:"object",properties:{path:{type:"string",description:"The file to put back, absolute or relative to the workspace root."},revision:{type:"string",description:`Which version to return to: "${Yt}" to undo only your most recent change to this file, a number such as "#3" for that version, or "${Vt}" for the file as this transaction opened. Defaults to "${Vt}".`},find:{type:"string",description:"Search this file's revisions instead of restoring anything: the text you are looking for, matched against each revision's note and its contents. Nothing is written and no restore is spent. Use it when you know what you want back but not which number holds it — a method you deleted, a line that used to read differently, or your own note about a change."},reason:{type:"string",description:"One sentence: what went wrong with this file that restoring it undoes."}},required:["path"]};function QI(e){let t=typeof e==="string"?e:e.toString("utf8");if(t==="")return 0;let n=t.split(/\r\n|\r|\n/);if(n[n.length-1]==="")n.pop();return n.length}function tMe(e,t){let n=e.split(/\r\n|\r|\n/),r=t.split(/\r\n|\r|\n/),o=Math.min(n.length,r.length);for(let i=0;i<o;i+=1)if(n[i]!==r[i])return i+1;return n.length===r.length?0:o+1}function nMe(e){let t=0;for(let n of e.tracked())for(let r of e.revisions(n))if(r.by!==Hr)t+=1;return t}function Kb(e){let t=0,n=0,r=-1,o=0;return X0e({name:Hr,description:e.scope==="session"?Z0e:Q0e,inputSchema:eMe,execute:async(i)=>{let s=e.controller.pending,a=e.controller.transaction,d=e.controller.root;if(a!==n)n=a,t=0,o=0;if(!s&&d===void 0)return"No transaction is open, so there is nothing to put the file back to.";if(!s){let R=nMe(e.controller.revisions);if(R!==r)t=0,o=0;r=R}let l=i&&typeof i==="object"&&!Array.isArray(i)?i.path:void 0;if(typeof l!=="string"||l.trim()==="")return"Name the file to restore, as `path`.";let c=i&&typeof i==="object"&&!Array.isArray(i)?i.find:void 0,u=typeof c==="string"&&c.trim()!==""?c.trim():void 0;if(u===void 0&&t>=JI)return`That is ${JI} restores already in this transaction, so no more will be made. Undoing the same work repeatedly is not converging on it. Read the file as it stands, decide on one change, and make that change — or say plainly that you cannot, and let the transaction be judged.`;let h=i&&typeof i==="object"&&!Array.isArray(i)?i.revision:void 0,p=typeof h==="string"&&h.trim()!==""?h.trim():typeof h==="number"&&Number.isFinite(h)?String(h):Vt,f=s?.root??d,m=s?"this transaction":"this session",g=s?Ec(s,l.trim()):Bb(f,l.trim());if(g.kind==="uncovered"||g.kind==="outside")return Hp(g);let y=zb.relative(f,g.absolutePath)||g.absolutePath,w=e.controller.revisions;if(s)w.seed(g.absolutePath,g.kind==="held"?g.body:void 0);let k=w.revisions(g.absolutePath);if(!s&&k.length===0)return`\`${y}\` has no earlier version held: nothing has written to it in this session, so there is nothing to put back. Only files this session has changed can be restored.`;if(u!==void 0)return g6(y,k,u);let b=w.resolve(g.absolutePath,p);if(b.kind==="dropped")return[`Revision #${b.index} of \`${y}\` is no longer held: its content was released to stay inside the memory this transaction may spend on file history. The revisions still held are below, and one of them is the nearest point you can return to.`,"",Io(y,k,{span:m})].join(`
1158
+ If you only want to *see* what the file said before your changes, do not restore it — call \`read_files\` with \`revision: "${Vt}"\` (or a number) and it is shown to you with the file left alone.`,eMe={type:"object",properties:{path:{type:"string",description:"The file to put back, absolute or relative to the workspace root."},revision:{type:"string",description:`Which version to return to: "${Yt}" to undo only your most recent change to this file, a number such as "#3" for that version, or "${Vt}" for the file as this transaction opened. Defaults to "${Vt}".`},find:{type:"string",description:"Search this file's revisions instead of restoring anything: the text you are looking for, matched against each revision's note and its contents. Nothing is written and no restore is spent. Use it when you know what you want back but not which number holds it — a method you deleted, a line that used to read differently, or your own note about a change."},reason:{type:"string",description:"One sentence: what went wrong with this file that restoring it undoes."}},required:["path"]};function QI(e){let t=typeof e==="string"?e:e.toString("utf8");if(t==="")return 0;let n=t.split(/\r\n|\r|\n/);if(n[n.length-1]==="")n.pop();return n.length}function tMe(e,t){let n=e.split(/\r\n|\r|\n/),r=t.split(/\r\n|\r|\n/),o=Math.min(n.length,r.length);for(let i=0;i<o;i+=1)if(n[i]!==r[i])return i+1;return n.length===r.length?0:o+1}function nMe(e){let t=0;for(let n of e.tracked())for(let r of e.revisions(n))if(r.by!==Hr)t+=1;return t}function Kb(e){let t=0,n=0,r=-1,o=0;return X0e({name:Hr,description:e.scope==="session"?Z0e:Q0e,inputSchema:eMe,execute:async(i)=>{let s=e.controller.pending,a=e.controller.transaction,d=e.controller.root;if(a!==n)n=a,t=0,o=0;if(!s&&d===void 0)return"No transaction is open, so there is nothing to put the file back to.";if(!s){let R=nMe(e.controller.revisions);if(R!==r)t=0,o=0;r=R}let l=i&&typeof i==="object"&&!Array.isArray(i)?i.path:void 0;if(typeof l!=="string"||l.trim()==="")return"Name the file to restore, as `path`.";let c=i&&typeof i==="object"&&!Array.isArray(i)?i.find:void 0,u=typeof c==="string"&&c.trim()!==""?c.trim():void 0;if(u===void 0&&t>=JI)return`That is ${JI} restores already in this transaction, so no more will be made. Undoing the same work repeatedly is not converging on it. Read the file as it stands, decide on one change, and make that change — or say plainly that you cannot, and let the transaction be judged.`;let h=i&&typeof i==="object"&&!Array.isArray(i)?i.revision:void 0,p=typeof h==="string"&&h.trim()!==""?h.trim():typeof h==="number"&&Number.isFinite(h)?String(h):Vt,f=s?.root??d,m=s?"this transaction":"this session",g=s?Ec(s,l.trim()):Bb(f,l.trim());if(g.kind==="uncovered"||g.kind==="outside")return Hp(g);let y=zb.relative(f,g.absolutePath)||g.absolutePath,w=e.controller.revisions;if(s)w.seed(g.absolutePath,g.kind==="held"?g.body:void 0);let k=w.revisions(g.absolutePath);if(!s&&k.length===0)return`\`${y}\` has no earlier version held: nothing has written to it in this session, so there is nothing to put back. Only files this session has changed can be restored.`;if(u!==void 0)return g4(y,k,u);let b=w.resolve(g.absolutePath,p);if(b.kind==="dropped")return[`Revision #${b.index} of \`${y}\` is no longer held: its content was released to stay inside the memory this transaction may spend on file history. The revisions still held are below, and one of them is the nearest point you can return to.`,"",Io(y,k,{span:m})].join(`
1159
1159
  `);if(b.kind!=="found")return[`\`${p}\` does not name a version of \`${y}\` that exists.`,"",Io(y,k,{span:m})].join(`
1160
- `);let v=b.revision.body,E=b.revision.index===1?"the original (#1)":`revision #${b.revision.index}`;if(v===void 0){try{await Wr.stat(g.absolutePath)}catch{return`\`${y}\` does not exist and did not exist at ${E}, so there is nothing to put back. Check the path.`}let R=!0;try{await Wr.rm(g.absolutePath,{force:!0})}catch(L){return e.onError?.(`[Atomic] ${y} could not be removed`,L),`\`${y}\` could not be removed: ${String(L)}`}try{await Wr.stat(g.absolutePath)}catch{R=!1}if(R)return`\`${y}\` is still there — the delete reported success and the file remains. Do not rely on it having been undone.`;t+=1,e.forgetReads?.(g.absolutePath),e.onRestored?.({path:g.absolutePath,transaction:a,deleted:!0});let C=w.record(g.absolutePath,void 0,Hr);return[`\`${y}\` did not exist at ${E}, so it has been deleted — that is what putting it back means.${C?` That is now revision #${C.index}.`:""} ${z6(t,s!==void 0)}`,"",Io(y,w.revisions(g.absolutePath),{span:m})].join(`
1160
+ `);let v=b.revision.body,E=b.revision.index===1?"the original (#1)":`revision #${b.revision.index}`;if(v===void 0){try{await Wr.stat(g.absolutePath)}catch{return`\`${y}\` does not exist and did not exist at ${E}, so there is nothing to put back. Check the path.`}let R=!0;try{await Wr.rm(g.absolutePath,{force:!0})}catch(L){return e.onError?.(`[Atomic] ${y} could not be removed`,L),`\`${y}\` could not be removed: ${String(L)}`}try{await Wr.stat(g.absolutePath)}catch{R=!1}if(R)return`\`${y}\` is still there — the delete reported success and the file remains. Do not rely on it having been undone.`;t+=1,e.forgetReads?.(g.absolutePath),e.onRestored?.({path:g.absolutePath,transaction:a,deleted:!0});let C=w.record(g.absolutePath,void 0,Hr);return[`\`${y}\` did not exist at ${E}, so it has been deleted — that is what putting it back means.${C?` That is now revision #${C.index}.`:""} ${z4(t,s!==void 0)}`,"",Io(y,w.revisions(g.absolutePath),{span:m})].join(`
1161
1161
  `)}let S;try{S=await Wr.readFile(g.absolutePath)}catch{S=void 0}if(S?.equals(v)){if(o+=1,o>J0e)return[`\`${y}\` already matches ${E}. You have now asked to restore it ${o} times without it having changed in between, and this tool will not answer again for this file in this transaction — there is nothing here to undo.`,"","That is the answer to the question you keep asking: your edits are not landing. The file on disk is exactly what it was, so nothing you have done to it has taken effect.","",`Read \`${y}\` now — the whole region you mean to change, with \`start_line\` and \`end_line\` — and send one \`editor\` call using the line numbers that read reports. If that call is refused, the refusal says why; fix what it names and send it again.`].join(`
1162
- `);let R=b.revision.index===1?"Whatever is still wrong with it was wrong before you touched it":"Whatever is still wrong with it was wrong at that revision";return`\`${y}\` is already exactly ${E}, so nothing was changed${o>1?` (that is ${o} times you have asked)`:""}. ${R} — look at the file itself rather than at your own edits.`}try{await Wr.mkdir(zb.dirname(g.absolutePath),{recursive:!0}),await Wr.writeFile(g.absolutePath,v)}catch(R){return e.onError?.(`[Atomic] ${y} could not be restored`,R),`\`${y}\` could not be restored: ${String(R)}`}t+=1,e.forgetReads?.(g.absolutePath),e.onRestored?.({path:g.absolutePath,transaction:a,deleted:!1});let x=w.record(g.absolutePath,v,Hr),T=QI(v),A=S===void 0?"it had been deleted":sMe(S,v,k[0]?.body!==void 0&&S.equals(k[0].body));return[`\`${y}\` is back to ${E}: ${T} lines, ${A}.${x?` That is now revision #${x.index}.`:""} Every line number you read before this now points somewhere else, so read the file again before you edit it. ${z6(t,s!==void 0)}`,"",Io(y,w.revisions(g.absolutePath),{span:m})].join(`
1163
- `)}})}function z6(e,t=!0){let n=JI-e,r=t?" in this transaction":" before making a change",o=n>0?`${n} more restore${n===1?"":"s"} available${r}.`:`That was the last restore available${r}.`,i=iMe(e);return i?`${o} ${i}`:o}var rMe=3,oMe=6;function iMe(e){if(e<rMe)return;if(e<oMe)return[`That is ${e} changes undone in this transaction.`,"Undoing the same kind of edit that many times means the reading behind it is wrong, not the typing.","Run the check and say what it actually reports, and what in the file produces it, before you edit again.","You do not have to restore your way back to a clean file: if this transaction ends with the check still failing, every file in it is put back in full and what you wrote about it is kept."].join(" ");return[`That is ${e} changes undone in this transaction, which is no longer recovery — it is one attempt being repeated.`,"Stop editing and end the transaction: say plainly what you tried and what the check still says.","The files are put back either way, and saying it is the only part that reaches the next transaction."].join(" ")}function sMe(e,t,n=!1){if(!Ac(e)||!Ac(t))return n?"replacing the original":"your changes to it are gone";let r=e.toString("utf8"),o=t.toString("utf8"),i=tMe(o,r),s=QI(r)-QI(o),a=s===0?"the same number of lines":`${Math.abs(s)} line${Math.abs(s)===1?"":"s"} ${s>0?"more":"fewer"}`,d=n?"replacing the original, which you had not changed":"discarding what you had made of it";return i>0?`${d}, which had ${a} and first differed at line ${i}`:d}import{createTool as aMe}from"@cerebriline/shared";var as="submit_transaction",dMe=`Submit this transaction for judging, when you have made the changes you planned and you are confident in them.
1162
+ `);let R=b.revision.index===1?"Whatever is still wrong with it was wrong before you touched it":"Whatever is still wrong with it was wrong at that revision";return`\`${y}\` is already exactly ${E}, so nothing was changed${o>1?` (that is ${o} times you have asked)`:""}. ${R} — look at the file itself rather than at your own edits.`}try{await Wr.mkdir(zb.dirname(g.absolutePath),{recursive:!0}),await Wr.writeFile(g.absolutePath,v)}catch(R){return e.onError?.(`[Atomic] ${y} could not be restored`,R),`\`${y}\` could not be restored: ${String(R)}`}t+=1,e.forgetReads?.(g.absolutePath),e.onRestored?.({path:g.absolutePath,transaction:a,deleted:!1});let x=w.record(g.absolutePath,v,Hr),T=QI(v),A=S===void 0?"it had been deleted":sMe(S,v,k[0]?.body!==void 0&&S.equals(k[0].body));return[`\`${y}\` is back to ${E}: ${T} lines, ${A}.${x?` That is now revision #${x.index}.`:""} Every line number you read before this now points somewhere else, so read the file again before you edit it. ${z4(t,s!==void 0)}`,"",Io(y,w.revisions(g.absolutePath),{span:m})].join(`
1163
+ `)}})}function z4(e,t=!0){let n=JI-e,r=t?" in this transaction":" before making a change",o=n>0?`${n} more restore${n===1?"":"s"} available${r}.`:`That was the last restore available${r}.`,i=iMe(e);return i?`${o} ${i}`:o}var rMe=3,oMe=6;function iMe(e){if(e<rMe)return;if(e<oMe)return[`That is ${e} changes undone in this transaction.`,"Undoing the same kind of edit that many times means the reading behind it is wrong, not the typing.","Run the check and say what it actually reports, and what in the file produces it, before you edit again.","You do not have to restore your way back to a clean file: if this transaction ends with the check still failing, every file in it is put back in full and what you wrote about it is kept."].join(" ");return[`That is ${e} changes undone in this transaction, which is no longer recovery — it is one attempt being repeated.`,"Stop editing and end the transaction: say plainly what you tried and what the check still says.","The files are put back either way, and saying it is the only part that reaches the next transaction."].join(" ")}function sMe(e,t,n=!1){if(!Ac(e)||!Ac(t))return n?"replacing the original":"your changes to it are gone";let r=e.toString("utf8"),o=t.toString("utf8"),i=tMe(o,r),s=QI(r)-QI(o),a=s===0?"the same number of lines":`${Math.abs(s)} line${Math.abs(s)===1?"":"s"} ${s>0?"more":"fewer"}`,d=n?"replacing the original, which you had not changed":"discarding what you had made of it";return i>0?`${d}, which had ${a} and first differed at line ${i}`:d}import{createTool as aMe}from"@cerebriline/shared";var as="submit_transaction",dMe=`Submit this transaction for judging, when you have made the changes you planned and you are confident in them.
1164
1164
 
1165
1165
  This is how a transaction ends. Nothing else submits it: finishing your turn without calling anything does not, and describing the work in your reply does not.
1166
1166
 
1167
1167
  What happens when you call it: the check runs, and the answer comes straight back to you. If it passes the transaction is kept and the task is done. If it does not, every change in this transaction is rolled back for you, and you are given the next transaction with a record of what this one tried.
1168
1168
 
1169
- So call it when you believe the work is finished — not to ask whether it is. Use \`run_check\` for that, as often as you like; it settles nothing. Submitting is the commitment.`,lMe={type:"object",properties:{account:{type:"string",description:"What you changed and why you believe it works. One or two sentences. This is recorded with the transaction and, where nothing here can run a check, it is what the verdict is based on."}},required:[]};function K6(e){return aMe({name:as,description:dMe,inputSchema:lMe,execute:async(t)=>{let n=t&&typeof t==="object"&&"account"in t?typeof t.account==="string"?t.account.trim()||void 0:void 0:void 0;try{return await e.submit(n)}catch(r){return e.onError?.("[Atomic] the transaction could not be settled",r),`The transaction could not be settled: ${String(r)}. It is still open and your changes are still in place.`}}})}function G6(e){let t=`TX-${String(e.transaction).padStart(2,"0")}`,n=["== CHANGE PROTOCOL ==","",`You are working in transactions. This one is ${t} of at most ${e.maxTransactions}.`,"","This adds to your instructions; it does not replace them. Everything you were already told still applies — which tools you have, how to call them, how to verify your work. What follows governs only how changes are grouped and judged.","","Start by finding out what is actually wrong. Read the files involved and run the check before you plan anything: a plan written before you have read the code is a guess, and the WHERE below asks for text you have to have actually seen. Reading and running cost nothing from the budget below, so there is no reason to economise on them.","",`Then state your plan as a numbered list of AT MOST ${e.maxChanges} changes. For each one give three things:`," WHERE - the function, or the exact text you will match on"," WHAT - the single concrete edit you will make there"," WHY - the specific symptom it removes","","A change is an edit to a file: after it, the file is different. Running a check, reading a file, or verifying the result is none of those, and must not take a number — you will do plenty of all three, and they cost nothing from this budget. If an item's WHAT does not name text being replaced, inserted or deleted, it is not a change and does not belong in the list.","","Then make exactly those changes, in that order, and nothing else. Do not fix anything you did not declare. Do not rewrite a whole function or a whole file: edit the smallest region that removes the symptom.","","Make them one at a time, not as a batch: after each edit, confirm it did what you intended before you start the next. Six edits that fail together leave you six things to undo and no way to tell which one was wrong. This governs edits only — reads, searches and commands change nothing and can be sent together freely, as many at a time as you find useful.","",`Each of those edits is numbered as you make it, and \`${Hr}\` takes a \`revision\`: \`"${Yt}"\` undoes only your most recent change to a file and keeps everything before it, and a number goes back to any earlier point. So a single edit that goes wrong costs one step and not the transaction, and you are never choosing between keeping a mistake and throwing away the work that came before it.`,"",`Put the same list into \`${Cc}\` as well as into your reply, and mark each item \`done\` the moment its edit applies. It numbers them for you and hands the whole list back on every call, so you never have to remember what has already landed — and it survives a discarded transaction, which your own account of it does not.`,""];if(e.oracle)n.push(Nl(e.oracle)?`Run \`${Br}\` to ${e.oracle.label} — before you edit anything, so you see the failure in its own words, and again after each change.`:`Run \`${e.oracle.label}\` and read what it says — before you edit anything, so you see the failure in its own words, and again after each change. \`${Br}\` runs the same check if you would rather not retype it.`,"",`That check is what decides. It is run again when your turn ends, and ${pMe(e.oracle)} — not your account of the change, and not the fact that the edit applied. ${mMe(e.oracle)}`,"","A program you write yourself is not that check and cannot take its place. A small helper to locate the fault is fine; running one in place of the check is not, because a program you wrote can only tell you what you already believe. If you have written more than one helper, or you are editing a helper rather than the file this task is about, stop and run the check.","",`If it passes, ${t} is kept and the task is finished.`,"",`If it does not, every change in ${t} is discarded. The files go back to exactly what they were when ${t} opened, and you get a new transaction with a record of what this one tried. You will never be asked to undo an edit yourself — that is done for you, mechanically, before the next transaction starts.`);else if(e.canProposeCheck)n.push(`Nothing in this workspace can be run to check the change, so as it stands you are the check — and your own account of your work is the weakest evidence there is. Name a better one: call \`${Mc}\` with the check that would show this task is done, and the user approves it or says what they want instead.`,"","Propose it as soon as you know what you are fixing, before you make the change. What is approved judges every attempt for the rest of the run and cannot be changed afterwards, so name the thing that would fail right now and pass once the fix lands.","",`Once it is approved, \`${Br}\` runs it against the files as they stand, as often as you want. It settles nothing and rolls nothing back. Run it before you edit and after each change: a check you only meet at the end is one that can only throw the transaction away.`,"",`Once a check is approved it is the only one that counts. Another program you write is not it and cannot take its place — approval is what makes a check the standard, and a program you wrote afterwards can only tell you what you already believe. A small helper to locate the fault is fine; if you have written more than one, or you are editing a helper rather than the file this task is about, stop and run \`${Br}\`.`,"",`If no check is agreed, say plainly when you are done whether the change achieved what was asked and how you know. Answering "yes" because the edit applied is not knowing. If you cannot tell, say that instead — ${t} is then discarded and you get another transaction rather than a change nobody verified.`);else n.push("Nothing in this workspace can be run to check the change, so you are the check.","",`When you are done, say plainly whether the change achieved what was asked, and how you know. Answering "yes" because the edit applied is not knowing. If you cannot tell, say that instead — ${t} is then discarded and you get another transaction rather than a change nobody verified.`,"",`If it worked, ${t} is kept. If it did not, every change in it is discarded and the files go back to exactly what they were when it opened.`);if(e.canReplaceCheck)n.push("","== THE CHECK HAS NEVER PASSED ==","","The check this run adopted has judged every attempt so far and has not passed once, on any files. Usually that means the change is not landing. It can also mean the check is wrong — that it asks for something no correct fix would produce, or that it never ran properly in the first place.","",`Decide which. Read what the check actually reports, with \`${Br}\`, and look at it as a program rather than as a verdict. If it is wrong, call \`${Mc}\` once more with a replacement — this is the only chance to change it, and the replacement is held to the same standard: it must fail on the unmodified files. If the check is right and the change simply has not worked yet, say so and carry on fixing.`);if(n.push("",`${e.maxChanges} is a hard limit and not a target. One change that removes one symptom is a better transaction than ${e.maxChanges} that might.`),e.lastTransactionNotice&&e.transaction>=e.maxTransactions)n.push("",e.lastTransactionNotice);if(e.history.length>0){n.push("",fMe(e.history,e.checkNeverPassed===!0));let r=e.hostSuppliedCheck?uMe(e.history):void 0;if(r)n.push("",r);n.push("",hMe(e.history.length))}return n.push("","== HOW THIS TRANSACTION ENDS ==","",`When you have made the changes you planned and you are confident in them, call \`${as}\`. That is what submits ${t}, and it is the only thing that does. The check runs and the answer comes straight back to you in the same reply.`,"","You decide when. Take the turns you need: thinking a turn through, reading another file, running the check again — none of that ends anything, and none of it costs you a transaction. There is no credit for submitting early and no penalty for taking another look first.","",`Ending your turn without calling anything does not submit and never has. If you do it repeatedly the run has to assume you have stopped, and ${t} gets submitted for you and judged exactly as it stands — which is strictly worse than submitting it yourself, because you do not get to finish first.`),n.join(`
1169
+ So call it when you believe the work is finished — not to ask whether it is. Use \`run_check\` for that, as often as you like; it settles nothing. Submitting is the commitment.`,lMe={type:"object",properties:{account:{type:"string",description:"What you changed and why you believe it works. One or two sentences. This is recorded with the transaction and, where nothing here can run a check, it is what the verdict is based on."}},required:[]};function K4(e){return aMe({name:as,description:dMe,inputSchema:lMe,execute:async(t)=>{let n=t&&typeof t==="object"&&"account"in t?typeof t.account==="string"?t.account.trim()||void 0:void 0:void 0;try{return await e.submit(n)}catch(r){return e.onError?.("[Atomic] the transaction could not be settled",r),`The transaction could not be settled: ${String(r)}. It is still open and your changes are still in place.`}}})}function G4(e){let t=`TX-${String(e.transaction).padStart(2,"0")}`,n=["== CHANGE PROTOCOL ==","",`You are working in transactions. This one is ${t} of at most ${e.maxTransactions}.`,"","This adds to your instructions; it does not replace them. Everything you were already told still applies — which tools you have, how to call them, how to verify your work. What follows governs only how changes are grouped and judged.","","Start by finding out what is actually wrong. Read the files involved and run the check before you plan anything: a plan written before you have read the code is a guess, and the WHERE below asks for text you have to have actually seen. Reading and running cost nothing from the budget below, so there is no reason to economise on them.","",`Then state your plan as a numbered list of AT MOST ${e.maxChanges} changes. For each one give three things:`," WHERE - the function, or the exact text you will match on"," WHAT - the single concrete edit you will make there"," WHY - the specific symptom it removes","","A change is an edit to a file: after it, the file is different. Running a check, reading a file, or verifying the result is none of those, and must not take a number — you will do plenty of all three, and they cost nothing from this budget. If an item's WHAT does not name text being replaced, inserted or deleted, it is not a change and does not belong in the list.","","Then make exactly those changes, in that order, and nothing else. Do not fix anything you did not declare. Do not rewrite a whole function or a whole file: edit the smallest region that removes the symptom.","","Make them one at a time, not as a batch: after each edit, confirm it did what you intended before you start the next. Six edits that fail together leave you six things to undo and no way to tell which one was wrong. This governs edits only — reads, searches and commands change nothing and can be sent together freely, as many at a time as you find useful.","",`Each of those edits is numbered as you make it, and \`${Hr}\` takes a \`revision\`: \`"${Yt}"\` undoes only your most recent change to a file and keeps everything before it, and a number goes back to any earlier point. So a single edit that goes wrong costs one step and not the transaction, and you are never choosing between keeping a mistake and throwing away the work that came before it.`,"",`Put the same list into \`${Cc}\` as well as into your reply, and mark each item \`done\` the moment its edit applies. It numbers them for you and hands the whole list back on every call, so you never have to remember what has already landed — and it survives a discarded transaction, which your own account of it does not.`,""];if(e.oracle)n.push(Nl(e.oracle)?`Run \`${Br}\` to ${e.oracle.label} — before you edit anything, so you see the failure in its own words, and again after each change.`:`Run \`${e.oracle.label}\` and read what it says — before you edit anything, so you see the failure in its own words, and again after each change. \`${Br}\` runs the same check if you would rather not retype it.`,"",`That check is what decides. It is run again when your turn ends, and ${pMe(e.oracle)} — not your account of the change, and not the fact that the edit applied. ${mMe(e.oracle)}`,"","A program you write yourself is not that check and cannot take its place. A small helper to locate the fault is fine; running one in place of the check is not, because a program you wrote can only tell you what you already believe. If you have written more than one helper, or you are editing a helper rather than the file this task is about, stop and run the check.","",`If it passes, ${t} is kept and the task is finished.`,"",`If it does not, every change in ${t} is discarded. The files go back to exactly what they were when ${t} opened, and you get a new transaction with a record of what this one tried. You will never be asked to undo an edit yourself — that is done for you, mechanically, before the next transaction starts.`);else if(e.canProposeCheck)n.push(`Nothing in this workspace can be run to check the change, so as it stands you are the check — and your own account of your work is the weakest evidence there is. Name a better one: call \`${Mc}\` with the check that would show this task is done, and the user approves it or says what they want instead.`,"","Propose it as soon as you know what you are fixing, before you make the change. What is approved judges every attempt for the rest of the run and cannot be changed afterwards, so name the thing that would fail right now and pass once the fix lands.","",`Once it is approved, \`${Br}\` runs it against the files as they stand, as often as you want. It settles nothing and rolls nothing back. Run it before you edit and after each change: a check you only meet at the end is one that can only throw the transaction away.`,"",`Once a check is approved it is the only one that counts. Another program you write is not it and cannot take its place — approval is what makes a check the standard, and a program you wrote afterwards can only tell you what you already believe. A small helper to locate the fault is fine; if you have written more than one, or you are editing a helper rather than the file this task is about, stop and run \`${Br}\`.`,"",`If no check is agreed, say plainly when you are done whether the change achieved what was asked and how you know. Answering "yes" because the edit applied is not knowing. If you cannot tell, say that instead — ${t} is then discarded and you get another transaction rather than a change nobody verified.`);else n.push("Nothing in this workspace can be run to check the change, so you are the check.","",`When you are done, say plainly whether the change achieved what was asked, and how you know. Answering "yes" because the edit applied is not knowing. If you cannot tell, say that instead — ${t} is then discarded and you get another transaction rather than a change nobody verified.`,"",`If it worked, ${t} is kept. If it did not, every change in it is discarded and the files go back to exactly what they were when it opened.`);if(e.canReplaceCheck)n.push("","== THE CHECK HAS NEVER PASSED ==","","The check this run adopted has judged every attempt so far and has not passed once, on any files. Usually that means the change is not landing. It can also mean the check is wrong — that it asks for something no correct fix would produce, or that it never ran properly in the first place.","",`Decide which. Read what the check actually reports, with \`${Br}\`, and look at it as a program rather than as a verdict. If it is wrong, call \`${Mc}\` once more with a replacement — this is the only chance to change it, and the replacement is held to the same standard: it must fail on the unmodified files. If the check is right and the change simply has not worked yet, say so and carry on fixing.`);if(n.push("",`${e.maxChanges} is a hard limit and not a target. One change that removes one symptom is a better transaction than ${e.maxChanges} that might.`),e.lastTransactionNotice&&e.transaction>=e.maxTransactions)n.push("",e.lastTransactionNotice);if(e.history.length>0){n.push("",fMe(e.history,e.checkNeverPassed===!0));let r=e.hostSuppliedCheck?uMe(e.history):void 0;if(r)n.push("",r);n.push("",hMe(e.history.length))}return n.push("","== HOW THIS TRANSACTION ENDS ==","",`When you have made the changes you planned and you are confident in them, call \`${as}\`. That is what submits ${t}, and it is the only thing that does. The check runs and the answer comes straight back to you in the same reply.`,"","You decide when. Take the turns you need: thinking a turn through, reading another file, running the check again — none of that ends anything, and none of it costs you a transaction. There is no credit for submitting early and no penalty for taking another look first.","",`Ending your turn without calling anything does not submit and never has. If you do it repeatedly the run has to assume you have stopped, and ${t} gets submitted for you and judged exactly as it stands — which is strictly worse than submitting it yourself, because you do not get to finish first.`),n.join(`
1170
1170
  `)}var cMe=3;function uMe(e){if(e.length<cMe)return;if(!e.every((i)=>!i.kept&&i.source==="oracle"))return;let t=e[e.length-1].evidence.trim();if(!t)return;let n=1;for(let i=e.length-2;i>=0;i--){if(e[i].evidence.trim()!==t)break;n+=1}if(n<2)return;let r=e[e.length-n],o=`TX-${String(r.transaction).padStart(2,"0")}`;return[`== THE CHECK HAS JUDGED ${e.length} ATTEMPTS AND PASSED NONE ==`,"","This check is the gate to mark the task completed successfully. It was named for this task by the user and it will not change, so the question is not whether it is right. The question is what it has been telling you, which is not the same as what you have been reading it as.","",`Its output has not changed since ${o} — the same text, byte for byte, across ${n} attempts:`,"",t,"","Nothing you have edited is on the path the check takes. Whatever the file looks like where you have been working, the failure it reports is raised somewhere your changes have not reached. Before editing anything else, find where that output actually comes from — read it as text, locate the thing it names, and confirm you are looking at the code that produces it.","","Say in one sentence where you now think it comes from. Then plan."].join(`
1171
1171
  `)}function hMe(e){let t=e===1?"that attempt":"those attempts";return["== BEFORE YOU PLAN, LOOK BACK ==","",`Call \`${Cc}\` first. It answers WORKED, DID NOT and RE-USE for you, from what was actually recorded rather than from what you remember, and the plan you stated last time is still in it.`,"",`Then open this transaction with a short retrospective on ${t} — four lines, before the plan, in your reply where the user can see it:`,""," WORKED - what you established that is still true. A symptom you located, a line you confirmed is fine, a reading of the file that held up. This survives the rollback even though the edits did not."," DID NOT - which edit failed to move the check, and what the check said instead of what you expected."," RE-USE - what you will carry into this attempt unchanged, so you do not spend the transaction rediscovering it.",' DIFFERENT - what you will do differently, named concretely. Not "be more careful".',"",`DIFFERENT is this transaction's plan. A retrospective on its own is not one — state the new list through \`${Cc}\` before your first edit, the way you did for the first transaction.`,"","Then read the check's last output again as text rather than as a verdict. Does it name the thing you were fixing? If it names something else, the plan that follows should be about what it names, not about what you were working on when it said so.","","The files are back to their starting state, but what you learned is not. That is the only thing this transaction begins with that the last one did not."].join(`
1172
1172
  `)}function pMe(e){if(Nl(e))return"the verdict is that the page loads, runs its frames and throws nothing";return e.expect?`the verdict is that it finishes cleanly AND its output matches /${e.expect}/`:"its exit status is the verdict"}function mMe(e){return e.reason==="named for this task"?"It was named for this task, so it is the standard the change is held to.":`It was chosen because ${e.reason}.`}function fMe(e,t){let n=["== WHAT EARLIER TRANSACTIONS TRIED =="];for(let r of e){let o=`TX-${String(r.transaction).padStart(2,"0")}`;if(n.push("",`${o} — ${r.kept?"kept":r.carried?"carried, and its changes are still in place":"discarded"}${r.source==="self-declared"?" (no check available)":r.source==="undeclared"?" (no check available, and you never said whether it worked)":""}`),r.plan?.trim())n.push("plan:",r.plan.trim());if(r.account?.trim())n.push("you said:",r.account.trim());if(r.evidence.trim())n.push("result:",r.evidence.trim())}return n.push("",t?"Those changes are gone: the files are as they were before that transaction. Do not repeat a plan that has already been discarded. The check has not passed once across any of them, so either the same reading of the symptom keeps coming back wrong, or the check itself is not asking for what a fix would produce — the second is worth considering by now.":"Those changes are gone: the files are as they were before that transaction. Do not repeat a plan that has already been discarded — if the same symptom is still there, the previous reading of it was wrong."),n.join(`
1173
- `)}function V6(e){let t=`TX-${String(e.transaction).padStart(2,"0")}`,n=Math.max(1,e.maxTransactions-e.transaction+1),r=n===1?`${t} is the last transaction you have`:`you have ${n} left, counting this one: ${t} of ${e.maxTransactions}`;return["== NOTHING WAS CHANGED ==","",`You ended ${t} without editing a single file, so there was nothing to judge. The transaction was not spent, it is still open, and ${r}.`,...e.check?["",`\`${e.check.label}\` was run for you at that boundary and it FAILED. The defect is still there, so the task is not done and this run is not over — ending your turn does not end it. What finishes this task is the check passing, not your account of the work.`,"","Take that as the state of the files, not as your diagnosis being done. It says the defect is still present; it does not tell you which line is wrong. Read the file.",...e.check.output?[`The check said:
1173
+ `)}function V4(e){let t=`TX-${String(e.transaction).padStart(2,"0")}`,n=Math.max(1,e.maxTransactions-e.transaction+1),r=n===1?`${t} is the last transaction you have`:`you have ${n} left, counting this one: ${t} of ${e.maxTransactions}`;return["== NOTHING WAS CHANGED ==","",`You ended ${t} without editing a single file, so there was nothing to judge. The transaction was not spent, it is still open, and ${r}.`,...e.check?["",`\`${e.check.label}\` was run for you at that boundary and it FAILED. The defect is still there, so the task is not done and this run is not over — ending your turn does not end it. What finishes this task is the check passing, not your account of the work.`,"","Take that as the state of the files, not as your diagnosis being done. It says the defect is still present; it does not tell you which line is wrong. Read the file.",...e.check.output?[`The check said:
1174
1174
  ${e.check.output}`]:[]]:[],"","Keep going. An empty submission is not a failed attempt — it is an attempt that has not happened yet, and nothing has been used up.",...e.neverBegan?["","Nothing has been called in this transaction yet — not a read, not the check, not an edit. That is the thing to change in this turn: read the file you mean to change, or run the check. Not a description of doing it — the call itself.","","It is true that this costs you no transaction, and that is deliberate. It is not the same as costing nothing. The run has a wall clock, the turns are being counted, and a run that reasons its way to the end of that clock without calling anything finishes with the defect exactly where it started."]:[],"",`State the plan as before — AT MOST ${e.maxChanges} changes, each with WHERE, WHAT and WHY — and then make it.`,"","If your edits are being refused, the refusal says why, and it is worth more than another read: an `old_text` that disagrees with the line range you named is the usual cause, so send one or the other, not both. If you cannot see the defect, run the linter on the file and act on the line it names rather than reading the whole file again."].join(`
1175
- `)}function Y6(e,t,n=!1){let r=`TX-${String(e).padStart(2,"0")}`;if(n)return`${r} was submitted with no tool called in it at all, so it was not attempted and is not being spent. It stays open.`;return t?`${r} was submitted with nothing changed, so it was not spent and is still open.`:`${r} was submitted with nothing changed again, so it is being spent and closed rather than held open, and the run carries on with whatever transactions are left.`}function X6(e){let t=`TX-${String(e.transaction).padStart(2,"0")}`,n=Math.max(1,e.before-e.silent);return[`Your turn ended without calling anything, so nothing was submitted. ${t} is still open and still yours.`,"",e.untouched?"No file has been changed in it yet.":"The changes you have made are still in place — nothing has been judged and nothing rolled back.","","A transaction is submitted by calling `submit_transaction`, and only by that. Call it when you have made the changes you planned and you are confident in them: the check runs and the verdict comes straight back to you. If you are not there yet, keep working — `run_check` will tell you where you stand as often as you want, and it settles nothing.",...e.check?["",`As things stand \`${e.check.label}\` does not pass, so there is still work to do.`,...e.check.output?[`It said:
1175
+ `)}function Y4(e,t,n=!1){let r=`TX-${String(e).padStart(2,"0")}`;if(n)return`${r} was submitted with no tool called in it at all, so it was not attempted and is not being spent. It stays open.`;return t?`${r} was submitted with nothing changed, so it was not spent and is still open.`:`${r} was submitted with nothing changed again, so it is being spent and closed rather than held open, and the run carries on with whatever transactions are left.`}function X4(e){let t=`TX-${String(e.transaction).padStart(2,"0")}`,n=Math.max(1,e.before-e.silent);return[`Your turn ended without calling anything, so nothing was submitted. ${t} is still open and still yours.`,"",e.untouched?"No file has been changed in it yet.":"The changes you have made are still in place — nothing has been judged and nothing rolled back.","","A transaction is submitted by calling `submit_transaction`, and only by that. Call it when you have made the changes you planned and you are confident in them: the check runs and the verdict comes straight back to you. If you are not there yet, keep working — `run_check` will tell you where you stand as often as you want, and it settles nothing.",...e.check?["",`As things stand \`${e.check.label}\` does not pass, so there is still work to do.`,...e.check.output?[`It said:
1176
1176
  ${e.check.output}`]:[]]:[],"",n===1?"One more turn that calls nothing and this transaction will be submitted for you and judged as it stands, which is a worse outcome than submitting it yourself.":`${n} more turns that call nothing and this transaction will be submitted for you and judged as it stands.`].join(`
1177
- `)}function J6(e,t){return`${`TX-${String(e).padStart(2,"0")}`} has now been submitted ${t} times with no tool called in it at any point, so the run is stopping here. No transaction was spent and no change was attempted: this is a run that never started work, not a set of attempts that failed.`}function ZI(e,t,n,r,o=!1,i=!1){let s=`TX-${String(e).padStart(2,"0")}`;if(t){if(n==="oracle")return`${s} kept — the check passed.`;if(n==="self-declared")return`${s} kept — self-declared, nothing here could check it.`;return o?`${s} kept but UNVERIFIED — the run was cut short before you said whether the change worked, and nothing here could check it. The changes are on disk; check them before relying on them.`:`${s} kept but UNVERIFIED — nothing here could check the change and it was never stated to work. The changes are on disk; check them before relying on them.`}let a=i?"carried":"discarded",d=i?" The check said something it has not said before in this run, so your changes stay on disk and the next transaction opens on top of them. Nothing has verified them: what you have is a different failure, not a fix.":" Your files are back as they were.";if(n==="self-declared"||n==="undeclared")return`${s} ${a} — the change was not verified.${d}`;if(r?.timedOut)return`${s} ${a} — the check did not finish.${d}`;if(r?.unmatched)return`${s} ${a} — the check ran, and what it reported is not what this task counts as working.${d}`;if(r?.summary)return`${s} ${a} — ${r.summary}${d}`;if(r?.exitCode==null)return`${s} ${a} — the check could not be run at all, so nothing was verified.${d}`;return`${s} ${a} — the check failed (exit ${r.exitCode}).${d}`}function eC(e){let t=["The user has turned the change protocol off. This is their decision about how this session runs; it is not a verdict on your work, and nothing has gone wrong.",""];if(e.transaction!==void 0&&e.verdict){let n=`TX-${String(e.transaction).padStart(2,"0")}`;if(t.push(`${n} was open, so it was judged once as the protocol stopped, on the same terms it would have been judged on anyway: ${e.verdict}`,""),e.kept===!1){let r=e.filesPutBack&&e.filesPutBack>0?`${e.filesPutBack} file${e.filesPutBack===1?" was":"s were"} put back`:"the files were put back";t.push(`So ${r}, and what you have read of them no longer describes what is on disk. Read a file again before you edit it — an edit sent against what you remember will be refused, and that refusal is this, not a fault.`,"",`What you found out in ${n} is still true even though its edits are gone. Do not simply make the same change again: it has already been shown not to work.`,"")}else t.push("Those changes are on disk and stay there.","")}else t.push("No transaction was open, so nothing on disk has changed.","");return t.push(`From here there are no transactions. No change budget, no attempt to fall back to, and no rollback: every edit you make applies at once and stays, and nothing will check it for you. \`${as}\`, \`${Br}\`, \`${Cc}\`, \`${Mc}\` and \`${Hr}\` have gone with it and calling one will fail.`,"","Carry on with the task you were given. Keep making one change at a time and confirming each one before the next — that was worth doing before the protocol was enforcing it, and it is worth doing now that nothing is."),t.join(`
1178
- `)}var Q6=3,gMe=5;function Z6(e){let t=e.max??Q6,n=e.settleAt??Math.max(t+1,gMe-Q6+t),r=e.transaction,o=0,i=!1,s=()=>{if(e.transaction!==r)r=e.transaction,o=0,i=!1};return{get streak(){return o},changed(){s(),o=0},checked(a){if(s(),a)return o=0,"ok";if(o+=1,o>=n)return"settle";if(o>=t&&!i)return i=!0,"nudge";return"ok"}}}var yMe=[le.EDITOR,le.APPLY_PATCH,Hr];function e4(e,t){return e.map((n)=>{if(!yMe.includes(n.name))return n;let r=n;return{...r,execute:async(o,i)=>(t(),r.execute(o,i))}})}function t4(e,t){return[`That was \`${t}\` run ${e} times in a row over files that have not changed since the run before it. It cannot tell you anything the first of them did not, and running it again will not either.`,"","Change something or look somewhere else. `check_file` is the sharper instrument here: it lists every problem in the file rather than the first one, and where brackets cross it names the line that is wrong rather than the line the parser gave up on.","","The transaction is still open, and this is not a verdict on it."].join(`
1179
- `)}function n4(e,t){return[`That was \`${t}\` run ${e} times in a row over files that have not changed since the run before it, so it cannot tell you anything the first of them did not.`,"","Re-reading the same failure is not progress, and the transaction is judged here rather than left open on it."].join(`
1180
- `)}function r4(e,t){return e.map((n)=>{let r=n;return{...r,execute:async(o,i)=>(t(n.name),r.execute(o,i))}})}import{createHash as wMe}from"node:crypto";import*as Yn from"node:fs/promises";import*as Gb from"node:path";var bMe={maxFiles:5000,maxFileBytes:4194304,maxTotalBytes:134217728};function vMe(e){return wMe("sha256").update(e).digest("hex")}async function ds(e,t={}){let n={...bMe,...t},r=new Map,o=[],i=0,s=async(a)=>{let d;try{d=await Yn.readdir(a,{withFileTypes:!0})}catch{return}for(let l of d){let c=Gb.join(a,l.name);if(l.isDirectory()){if(XW.has(l.name))continue;await s(c);continue}if(!l.isFile()){o.push(c);continue}if(r.size>=n.maxFiles||i>=n.maxTotalBytes){o.push(c);continue}let u;try{if((await Yn.stat(c)).size>n.maxFileBytes){o.push(c);continue}u=await Yn.readFile(c)}catch{o.push(c);continue}i+=u.byteLength,r.set(c,{hash:vMe(u),body:u})}};return await s(e),{files:r,root:e,skipped:o}}async function Ba(e,t={}){let n={restored:[],removed:[],recreated:[],uncovered:[...e.skipped]},r=await ds(e.root,t);for(let[o,i]of e.files){let s=r.files.get(o);if(!s){await Yn.mkdir(Gb.dirname(o),{recursive:!0}),await Yn.writeFile(o,i.body),n.recreated.push(o);continue}if(s.hash!==i.hash)await Yn.writeFile(o,i.body),n.restored.push(o)}for(let o of r.files.keys())if(!e.files.has(o))await Yn.rm(o,{force:!0}),n.removed.push(o);return n}async function o4(e,t={}){let n=await ds(e.root,t),r=[];for(let[o,i]of n.files)if(e.files.get(o)?.hash!==i.hash)r.push({path:o,body:i.body});return r}async function Kp(e,t={}){let n=await ds(e.root,t);if(n.files.size!==e.files.size)return!1;for(let[r,o]of e.files)if(n.files.get(r)?.hash!==o.hash)return!1;return!0}import*as i4 from"node:path";var kMe=[/\bSyntaxError\b/,/\bIndentationError\b/,/\bParseError\b/,/\bparse error\b/i,/\bUnexpected (token|identifier|end of input|EOF|string|number)\b/i,/\bmissing \) after argument list\b/i,/\binvalid syntax\b/i];function s4(e){return kMe.some((t)=>t.test(e))}function TMe(e,t){let n=xl(e,t);if(!n)return[];return n.split(`
1181
- `).filter((r)=>r.startsWith(" line "))}function a4(e,t){for(let n of e){let r=Iy(n.path,n.text),o=Ry(n.path)?TMe(n.path,n.text):[];if(r===void 0&&o.length===0)continue;let i=i4.relative(t,n.path)||n.path,s=r===void 0?"":` ${r}`;return[`The check never ran your change: ${i} does not parse.${s} What it measured was a file the engine refuses, so the verdict above says nothing about whether your fix was right.`,...o.length>0?["",...o]:[],"","That fault goes back with the rest of the work. `check_file` on a file you have just edited catches it before a transaction is spent on it."].join(`
1182
- `)}return null}class tC{options;history=[];uncoveredPaths=new Set;revisionLog;snapshot;openedWith;current=0;openedAt;adopted;adoptedEverPassed=!1;discardedSinceAdoption=0;reconsidering=!1;checkOutputs=new Set;checkHasRepeated=!1;carrying=!1;reconsiderationsUsed=0;constructor(e){this.options=e;this.revisionLog=e.revisions??ss()}get transaction(){return this.current}get oracle(){return this.adopted??this.options.oracle}get canAdoptOracle(){return this.oracle===void 0||this.reconsidering}get checkIsUnderReconsideration(){return this.reconsidering}adoptOracle(e){if(!this.canAdoptOracle)throw Error("This run already has a check, and it is frozen for the rest of the run.");if(this.adopted=e,this.adoptedEverPassed=!1,this.discardedSinceAdoption=0,this.reconsidering)this.reconsidering=!1,this.reconsiderationsUsed+=1;this.emit({type:"adopted",transaction:this.current,oracle:e})}async judgeAgainstBase(e){let t=this.snapshot;if(!t)throw Error("judgeAgainstBase() was called before a transaction was opened");let n=this.options.oracleTimeoutMs??aa;if(await Kp(t,this.options.snapshotLimits))return await da(e,{timeoutMs:n});let r=await ds(this.options.workspaceRoot,this.options.snapshotLimits),o=await this.stampsOfEdits(t,r);await Ba(t,this.options.snapshotLimits);try{return await da(e,{timeoutMs:n})}finally{await Ba(r,this.options.snapshotLimits),await this.carryStamps(o)}}async stampsOfEdits(e,t){let n=new Map;if(!this.options.carryReadStamp)return n;for(let[r,o]of t.files){if(e.files.get(r)?.hash===o.hash)continue;let i=await Tt(r);if(i!==void 0)n.set(r,i)}return n}async carryStamps(e){let t=this.options.carryReadStamp;if(!t)return;for(let[n,r]of e){let o=await Tt(n);if(o!==void 0&&o!==r)t(n,r,o)}}noteCheckOutput(e){let t=e.trim();if(this.checkOutputs.has(t))return this.checkHasRepeated=!0,!1;return this.checkOutputs.add(t),!0}async runCheck(){if(!this.snapshot)throw Error("runCheck() was called before a transaction was opened");let e=this.oracle;if(!e)throw Error("runCheck() was called with no check to run");let t=await da(e,{timeoutMs:this.options.oracleTimeoutMs??aa});if(this.noteCheckOutput(t.output),t.passed)this.adoptedEverPassed=!0;return t}get outcomes(){return this.history}get uncovered(){return[...this.uncoveredPaths]}get pending(){return this.snapshot}get revisions(){return this.revisionLog}async isUntouched(){return this.openedWith?await Kp(this.openedWith,this.options.snapshotLimits):!0}shouldReconsiderCheck(){let e=this.options.checkReconsideredAfter??0;if(e<=0)return!1;if(this.adopted===void 0||this.options.oracle!==void 0)return!1;if(this.adoptedEverPassed||this.reconsiderationsUsed>0)return!1;if(this.current>=this.options.maxTransactions)return!1;let t=Math.max(1,Math.min(e,this.options.maxTransactions-1));return this.discardedSinceAdoption>=t}async open(){this.current+=1,this.openedAt=Date.now(),this.reconsidering=this.shouldReconsiderCheck();let e=this.carrying?this.snapshot:void 0;if(this.carrying=!1,!e)this.revisionLog.reset();this.openedWith=await ds(this.options.workspaceRoot,this.options.snapshotLimits),this.snapshot=e??this.openedWith;for(let n of this.openedWith.skipped)this.uncoveredPaths.add(n);this.emit({type:"opened",transaction:this.current,oracle:this.oracle});let t=this.current>=this.options.maxTransactions?this.options.describeLastTransaction?.():void 0;return G6({transaction:this.current,maxChanges:this.options.maxChanges,maxTransactions:this.options.maxTransactions,...t?{lastTransactionNotice:t}:{},oracle:this.oracle,canProposeCheck:this.options.allowCheckProposal===!0&&this.canAdoptOracle,checkNeverPassed:this.adopted!==void 0&&!this.adoptedEverPassed,hostSuppliedCheck:this.adopted===void 0&&this.options.oracle!==void 0,canReplaceCheck:this.options.allowCheckProposal===!0&&this.reconsidering,history:this.history})}async settle(e={}){let t=this.snapshot;if(!t)throw Error("settle() was called before a transaction was opened");let n=this.openedWith??t,r=this.current,o=this.openedAt===void 0?void 0:Date.now()-this.openedAt;this.emit({type:"judging",transaction:r,oracle:this.oracle});let i=e.selfReport!==void 0||Boolean(e.account?.trim()),s=this.oracle?"oracle":i?"self-declared":"undeclared",a,d,l,c=!1;if(this.oracle){if(d=await da(this.oracle,{timeoutMs:this.options.oracleTimeoutMs??aa}),c=this.noteCheckOutput(d.output),a=d.passed,l=d.output,d.passed)this.adoptedEverPassed=!0}else a=SMe(e.selfReport),l=e.selfReport===void 0?"The change was never stated to work or not, and nothing here could check it.":"";let u=a?await Kp(n,this.options.snapshotLimits):!1;if(a){let b=ZI(r,a,s,d,e.forced===!0),v=u?`${b} No files were changed.`:b;return this.history.push({transaction:r,kept:a,source:s,plan:e.plan,account:e.account,evidence:l}),this.emit({type:"settled",transaction:r,kept:a,source:s,message:v,elapsedMs:o,verdict:d}),{kept:!0,message:v,verdict:d}}let h=c&&this.checkHasRepeated&&e.forced!==!0&&r<this.options.maxTransactions,p=this.adopted!==void 0||h?!await Kp(n,this.options.snapshotLimits):!1;if(this.adopted!==void 0&&p)this.discardedSinceAdoption+=1;let f=h&&p;this.carrying=f;let m=ZI(r,a,s,d,e.forced===!0,f),g=u?`${m} No files were changed.`:m,y=s4(l)?a4((await o4(t,this.options.snapshotLimits)).map((b)=>({path:b.path,text:b.body.toString("utf8")})),t.root):null,w=y?`${g}
1177
+ `)}function J4(e,t){return`${`TX-${String(e).padStart(2,"0")}`} has now been submitted ${t} times with no tool called in it at any point, so the run is stopping here. No transaction was spent and no change was attempted: this is a run that never started work, not a set of attempts that failed.`}function ZI(e,t,n,r,o=!1,i=!1){let s=`TX-${String(e).padStart(2,"0")}`;if(t){if(n==="oracle")return`${s} kept — the check passed.`;if(n==="self-declared")return`${s} kept — self-declared, nothing here could check it.`;return o?`${s} kept but UNVERIFIED — the run was cut short before you said whether the change worked, and nothing here could check it. The changes are on disk; check them before relying on them.`:`${s} kept but UNVERIFIED — nothing here could check the change and it was never stated to work. The changes are on disk; check them before relying on them.`}let a=i?"carried":"discarded",d=i?" The check said something it has not said before in this run, so your changes stay on disk and the next transaction opens on top of them. Nothing has verified them: what you have is a different failure, not a fix.":" Your files are back as they were.";if(n==="self-declared"||n==="undeclared")return`${s} ${a} — the change was not verified.${d}`;if(r?.timedOut)return`${s} ${a} — the check did not finish.${d}`;if(r?.unmatched)return`${s} ${a} — the check ran, and what it reported is not what this task counts as working.${d}`;if(r?.summary)return`${s} ${a} — ${r.summary}${d}`;if(r?.exitCode==null)return`${s} ${a} — the check could not be run at all, so nothing was verified.${d}`;return`${s} ${a} — the check failed (exit ${r.exitCode}).${d}`}function eC(e){let t=["The user has turned the change protocol off. This is their decision about how this session runs; it is not a verdict on your work, and nothing has gone wrong.",""];if(e.transaction!==void 0&&e.verdict){let n=`TX-${String(e.transaction).padStart(2,"0")}`;if(t.push(`${n} was open, so it was judged once as the protocol stopped, on the same terms it would have been judged on anyway: ${e.verdict}`,""),e.kept===!1){let r=e.filesPutBack&&e.filesPutBack>0?`${e.filesPutBack} file${e.filesPutBack===1?" was":"s were"} put back`:"the files were put back";t.push(`So ${r}, and what you have read of them no longer describes what is on disk. Read a file again before you edit it — an edit sent against what you remember will be refused, and that refusal is this, not a fault.`,"",`What you found out in ${n} is still true even though its edits are gone. Do not simply make the same change again: it has already been shown not to work.`,"")}else t.push("Those changes are on disk and stay there.","")}else t.push("No transaction was open, so nothing on disk has changed.","");return t.push(`From here there are no transactions. No change budget, no attempt to fall back to, and no rollback: every edit you make applies at once and stays, and nothing will check it for you. \`${as}\`, \`${Br}\`, \`${Cc}\`, \`${Mc}\` and \`${Hr}\` have gone with it and calling one will fail.`,"","Carry on with the task you were given. Keep making one change at a time and confirming each one before the next — that was worth doing before the protocol was enforcing it, and it is worth doing now that nothing is."),t.join(`
1178
+ `)}var Q4=3,gMe=5;function Z4(e){let t=e.max??Q4,n=e.settleAt??Math.max(t+1,gMe-Q4+t),r=e.transaction,o=0,i=!1,s=()=>{if(e.transaction!==r)r=e.transaction,o=0,i=!1};return{get streak(){return o},changed(){s(),o=0},checked(a){if(s(),a)return o=0,"ok";if(o+=1,o>=n)return"settle";if(o>=t&&!i)return i=!0,"nudge";return"ok"}}}var yMe=[le.EDITOR,le.APPLY_PATCH,Hr];function e6(e,t){return e.map((n)=>{if(!yMe.includes(n.name))return n;let r=n;return{...r,execute:async(o,i)=>(t(),r.execute(o,i))}})}function t6(e,t){return[`That was \`${t}\` run ${e} times in a row over files that have not changed since the run before it. It cannot tell you anything the first of them did not, and running it again will not either.`,"","Change something or look somewhere else. `check_file` is the sharper instrument here: it lists every problem in the file rather than the first one, and where brackets cross it names the line that is wrong rather than the line the parser gave up on.","","The transaction is still open, and this is not a verdict on it."].join(`
1179
+ `)}function n6(e,t){return[`That was \`${t}\` run ${e} times in a row over files that have not changed since the run before it, so it cannot tell you anything the first of them did not.`,"","Re-reading the same failure is not progress, and the transaction is judged here rather than left open on it."].join(`
1180
+ `)}function r6(e,t){return e.map((n)=>{let r=n;return{...r,execute:async(o,i)=>(t(n.name),r.execute(o,i))}})}import{createHash as wMe}from"node:crypto";import*as Yn from"node:fs/promises";import*as Gb from"node:path";var bMe={maxFiles:5000,maxFileBytes:4194304,maxTotalBytes:134217728};function vMe(e){return wMe("sha256").update(e).digest("hex")}async function ds(e,t={}){let n={...bMe,...t},r=new Map,o=[],i=0,s=async(a)=>{let d;try{d=await Yn.readdir(a,{withFileTypes:!0})}catch{return}for(let l of d){let c=Gb.join(a,l.name);if(l.isDirectory()){if(XW.has(l.name))continue;await s(c);continue}if(!l.isFile()){o.push(c);continue}if(r.size>=n.maxFiles||i>=n.maxTotalBytes){o.push(c);continue}let u;try{if((await Yn.stat(c)).size>n.maxFileBytes){o.push(c);continue}u=await Yn.readFile(c)}catch{o.push(c);continue}i+=u.byteLength,r.set(c,{hash:vMe(u),body:u})}};return await s(e),{files:r,root:e,skipped:o}}async function Ba(e,t={}){let n={restored:[],removed:[],recreated:[],uncovered:[...e.skipped]},r=await ds(e.root,t);for(let[o,i]of e.files){let s=r.files.get(o);if(!s){await Yn.mkdir(Gb.dirname(o),{recursive:!0}),await Yn.writeFile(o,i.body),n.recreated.push(o);continue}if(s.hash!==i.hash)await Yn.writeFile(o,i.body),n.restored.push(o)}for(let o of r.files.keys())if(!e.files.has(o))await Yn.rm(o,{force:!0}),n.removed.push(o);return n}async function o6(e,t={}){let n=await ds(e.root,t),r=[];for(let[o,i]of n.files)if(e.files.get(o)?.hash!==i.hash)r.push({path:o,body:i.body});return r}async function Kp(e,t={}){let n=await ds(e.root,t);if(n.files.size!==e.files.size)return!1;for(let[r,o]of e.files)if(n.files.get(r)?.hash!==o.hash)return!1;return!0}import*as i6 from"node:path";var kMe=[/\bSyntaxError\b/,/\bIndentationError\b/,/\bParseError\b/,/\bparse error\b/i,/\bUnexpected (token|identifier|end of input|EOF|string|number)\b/i,/\bmissing \) after argument list\b/i,/\binvalid syntax\b/i];function s6(e){return kMe.some((t)=>t.test(e))}function TMe(e,t){let n=xl(e,t);if(!n)return[];return n.split(`
1181
+ `).filter((r)=>r.startsWith(" line "))}function a6(e,t){for(let n of e){let r=Iy(n.path,n.text),o=Ry(n.path)?TMe(n.path,n.text):[];if(r===void 0&&o.length===0)continue;let i=i6.relative(t,n.path)||n.path,s=r===void 0?"":` ${r}`;return[`The check never ran your change: ${i} does not parse.${s} What it measured was a file the engine refuses, so the verdict above says nothing about whether your fix was right.`,...o.length>0?["",...o]:[],"","That fault goes back with the rest of the work. `check_file` on a file you have just edited catches it before a transaction is spent on it."].join(`
1182
+ `)}return null}class tC{options;history=[];uncoveredPaths=new Set;revisionLog;snapshot;openedWith;current=0;openedAt;adopted;adoptedEverPassed=!1;discardedSinceAdoption=0;reconsidering=!1;checkOutputs=new Set;checkHasRepeated=!1;carrying=!1;reconsiderationsUsed=0;constructor(e){this.options=e;this.revisionLog=e.revisions??ss()}get transaction(){return this.current}get oracle(){return this.adopted??this.options.oracle}get canAdoptOracle(){return this.oracle===void 0||this.reconsidering}get checkIsUnderReconsideration(){return this.reconsidering}adoptOracle(e){if(!this.canAdoptOracle)throw Error("This run already has a check, and it is frozen for the rest of the run.");if(this.adopted=e,this.adoptedEverPassed=!1,this.discardedSinceAdoption=0,this.reconsidering)this.reconsidering=!1,this.reconsiderationsUsed+=1;this.emit({type:"adopted",transaction:this.current,oracle:e})}async judgeAgainstBase(e){let t=this.snapshot;if(!t)throw Error("judgeAgainstBase() was called before a transaction was opened");let n=this.options.oracleTimeoutMs??aa;if(await Kp(t,this.options.snapshotLimits))return await da(e,{timeoutMs:n});let r=await ds(this.options.workspaceRoot,this.options.snapshotLimits),o=await this.stampsOfEdits(t,r);await Ba(t,this.options.snapshotLimits);try{return await da(e,{timeoutMs:n})}finally{await Ba(r,this.options.snapshotLimits),await this.carryStamps(o)}}async stampsOfEdits(e,t){let n=new Map;if(!this.options.carryReadStamp)return n;for(let[r,o]of t.files){if(e.files.get(r)?.hash===o.hash)continue;let i=await Tt(r);if(i!==void 0)n.set(r,i)}return n}async carryStamps(e){let t=this.options.carryReadStamp;if(!t)return;for(let[n,r]of e){let o=await Tt(n);if(o!==void 0&&o!==r)t(n,r,o)}}noteCheckOutput(e){let t=e.trim();if(this.checkOutputs.has(t))return this.checkHasRepeated=!0,!1;return this.checkOutputs.add(t),!0}async runCheck(){if(!this.snapshot)throw Error("runCheck() was called before a transaction was opened");let e=this.oracle;if(!e)throw Error("runCheck() was called with no check to run");let t=await da(e,{timeoutMs:this.options.oracleTimeoutMs??aa});if(this.noteCheckOutput(t.output),t.passed)this.adoptedEverPassed=!0;return t}get outcomes(){return this.history}get uncovered(){return[...this.uncoveredPaths]}get pending(){return this.snapshot}get revisions(){return this.revisionLog}async isUntouched(){return this.openedWith?await Kp(this.openedWith,this.options.snapshotLimits):!0}shouldReconsiderCheck(){let e=this.options.checkReconsideredAfter??0;if(e<=0)return!1;if(this.adopted===void 0||this.options.oracle!==void 0)return!1;if(this.adoptedEverPassed||this.reconsiderationsUsed>0)return!1;if(this.current>=this.options.maxTransactions)return!1;let t=Math.max(1,Math.min(e,this.options.maxTransactions-1));return this.discardedSinceAdoption>=t}async open(){this.current+=1,this.openedAt=Date.now(),this.reconsidering=this.shouldReconsiderCheck();let e=this.carrying?this.snapshot:void 0;if(this.carrying=!1,!e)this.revisionLog.reset();this.openedWith=await ds(this.options.workspaceRoot,this.options.snapshotLimits),this.snapshot=e??this.openedWith;for(let n of this.openedWith.skipped)this.uncoveredPaths.add(n);this.emit({type:"opened",transaction:this.current,oracle:this.oracle});let t=this.current>=this.options.maxTransactions?this.options.describeLastTransaction?.():void 0;return G4({transaction:this.current,maxChanges:this.options.maxChanges,maxTransactions:this.options.maxTransactions,...t?{lastTransactionNotice:t}:{},oracle:this.oracle,canProposeCheck:this.options.allowCheckProposal===!0&&this.canAdoptOracle,checkNeverPassed:this.adopted!==void 0&&!this.adoptedEverPassed,hostSuppliedCheck:this.adopted===void 0&&this.options.oracle!==void 0,canReplaceCheck:this.options.allowCheckProposal===!0&&this.reconsidering,history:this.history})}async settle(e={}){let t=this.snapshot;if(!t)throw Error("settle() was called before a transaction was opened");let n=this.openedWith??t,r=this.current,o=this.openedAt===void 0?void 0:Date.now()-this.openedAt;this.emit({type:"judging",transaction:r,oracle:this.oracle});let i=e.selfReport!==void 0||Boolean(e.account?.trim()),s=this.oracle?"oracle":i?"self-declared":"undeclared",a,d,l,c=!1;if(this.oracle){if(d=await da(this.oracle,{timeoutMs:this.options.oracleTimeoutMs??aa}),c=this.noteCheckOutput(d.output),a=d.passed,l=d.output,d.passed)this.adoptedEverPassed=!0}else a=SMe(e.selfReport),l=e.selfReport===void 0?"The change was never stated to work or not, and nothing here could check it.":"";let u=a?await Kp(n,this.options.snapshotLimits):!1;if(a){let b=ZI(r,a,s,d,e.forced===!0),v=u?`${b} No files were changed.`:b;return this.history.push({transaction:r,kept:a,source:s,plan:e.plan,account:e.account,evidence:l}),this.emit({type:"settled",transaction:r,kept:a,source:s,message:v,elapsedMs:o,verdict:d}),{kept:!0,message:v,verdict:d}}let h=c&&this.checkHasRepeated&&e.forced!==!0&&r<this.options.maxTransactions,p=this.adopted!==void 0||h?!await Kp(n,this.options.snapshotLimits):!1;if(this.adopted!==void 0&&p)this.discardedSinceAdoption+=1;let f=h&&p;this.carrying=f;let m=ZI(r,a,s,d,e.forced===!0,f),g=u?`${m} No files were changed.`:m,y=s6(l)?a6((await o6(t,this.options.snapshotLimits)).map((b)=>({path:b.path,text:b.body.toString("utf8")})),t.root):null,w=y?`${g}
1183
1183
 
1184
- ${y}`:g,k=f?{restored:[],removed:[],recreated:[],uncovered:[]}:await Ba(t,this.options.snapshotLimits);for(let b of k.uncovered)this.uncoveredPaths.add(b);if(this.options.forgetReads)for(let b of[...k.restored,...k.recreated,...k.removed])this.options.forgetReads(b);if(this.history.push({transaction:r,kept:a,carried:f,source:s,plan:e.plan,account:e.account,evidence:l}),this.emit({type:"settled",transaction:r,kept:a,carried:f,source:s,message:w,elapsedMs:o,verdict:d,restore:k}),r>=this.options.maxTransactions)return this.snapshot=void 0,this.openedWith=void 0,{kept:!1,message:w,verdict:d,restore:k};return{kept:!1,message:w,verdict:d,carried:f,restore:k,nextPrompt:await this.open()}}async discard(){if(!this.snapshot)return;let e=await Ba(this.snapshot,this.options.snapshotLimits);if(this.snapshot=void 0,this.openedWith=void 0,this.revisionLog.reset(),this.options.forgetReads)for(let t of[...e.restored,...e.recreated,...e.removed])this.options.forgetReads(t);return e}emit(e){this.options.onEvent?.(e)}}function SMe(e){if(e===void 0)return!0;return e==="success"}var Gp=6,Vb=6,_Me=1,EMe=6,d4=3;async function l4(e){if((e.config?.mode??"off")==="off")return;let n=await JW(e.workspaceRoot,{manual:e.config?.oracleCommand,expect:e.config?.oracleExpect}),r=e.approveCheck??e.config?.approveCheck,o=(e.proposeCheck??e.config?.proposeCheck)!==!1,i=!n&&r!==void 0&&o;if(!n&&!i&&!!o){e.logger?.log?.("[Atomic] Change protocol stood down: nothing in this workspace can be run to judge a change, and there is nobody here to approve one the model proposes. Name a check of your own to have it engage."),e.onStatus?.({armed:!1,message:"Change protocol stood down: nothing in this workspace can be run to judge a change, and there is nobody here to approve one the model proposes. Name a check of your own to have it engage."});return}let a=n?`Change protocol armed: each attempt is judged by \`${n.label}\` (${n.reason}), and an attempt that fails it is put back.`:i?"Change protocol armed with nothing to run: the model will propose a check and ask you to approve it. Until one is approved it judges its own work, which is labelled as such on every attempt.":"Change protocol armed with no check to run: the model judges its own work, which is the weaker of the two and is labelled as such on every attempt.";e.logger?.log?.(`[Atomic] ${a}`),e.onStatus?.({armed:!0,message:a});let d=e.forgetReads??e.config?.forgetReads,l=new tC({workspaceRoot:e.workspaceRoot,...e.revisions?{revisions:e.revisions}:{},maxChanges:e.config?.maxChanges??Gp,maxTransactions:e.config?.maxTransactions??Vb,oracle:n,allowCheckProposal:i,checkReconsideredAfter:e.checkReconsideredAfter??e.config?.checkReconsideredAfter??F6,...e.describeLastTransaction?{describeLastTransaction:e.describeLastTransaction}:{},oracleTimeoutMs:e.config?.oracleTimeoutMs,onEvent:e.onEvent,...d?{forgetReads:d}:{},...e.config?.carryReadStamp?{carryReadStamp:e.config.carryReadStamp}:{}}),c=[Kb({controller:l,forgetReads:d,onRestored:({path:T,deleted:A})=>e.logger?.log?.(`[Atomic] ${T} ${A?"deleted":"put back"} at the model's request.`),onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)})];c.push($6({controller:l,maxChanges:e.config?.maxChanges??Gp,onPlan:(T)=>e.logger?.log?.(`[Atomic] plan: ${T.length} change(s), ${T.filter((A)=>A.status==="done").length} landed.`)}));let u=Z6({get transaction(){return l.transaction}});if(c.push(_6({controller:l,canProposeCheck:i,onRun:async(T,A)=>{e.logger?.log?.(`[Atomic] ${A.label} run on request: ${T.passed?"passed":"failed"}.`);let R=u.checked(T.passed);if(R==="ok"||p)return;if(R==="nudge"){let N=t4(u.streak,A.label);return e.logger?.log?.(`[Atomic] ${N}`),N}let C=n4(u.streak,A.label);e.logger?.log?.(`[Atomic] ${C}`);let L=await v({...b?.transaction===l.transaction?{plan:b.plan}:{},account:C,forced:!0,notice:C});if(L.message)return L.message;return L.kept?`${C}
1184
+ ${y}`:g,k=f?{restored:[],removed:[],recreated:[],uncovered:[]}:await Ba(t,this.options.snapshotLimits);for(let b of k.uncovered)this.uncoveredPaths.add(b);if(this.options.forgetReads)for(let b of[...k.restored,...k.recreated,...k.removed])this.options.forgetReads(b);if(this.history.push({transaction:r,kept:a,carried:f,source:s,plan:e.plan,account:e.account,evidence:l}),this.emit({type:"settled",transaction:r,kept:a,carried:f,source:s,message:w,elapsedMs:o,verdict:d,restore:k}),r>=this.options.maxTransactions)return this.snapshot=void 0,this.openedWith=void 0,{kept:!1,message:w,verdict:d,restore:k};return{kept:!1,message:w,verdict:d,carried:f,restore:k,nextPrompt:await this.open()}}async discard(){if(!this.snapshot)return;let e=await Ba(this.snapshot,this.options.snapshotLimits);if(this.snapshot=void 0,this.openedWith=void 0,this.revisionLog.reset(),this.options.forgetReads)for(let t of[...e.restored,...e.recreated,...e.removed])this.options.forgetReads(t);return e}emit(e){this.options.onEvent?.(e)}}function SMe(e){if(e===void 0)return!0;return e==="success"}var Gp=6,Vb=6,_Me=1,EMe=6,d6=3;async function l6(e){if((e.config?.mode??"off")==="off")return;let n=await JW(e.workspaceRoot,{manual:e.config?.oracleCommand,expect:e.config?.oracleExpect}),r=e.approveCheck??e.config?.approveCheck,o=(e.proposeCheck??e.config?.proposeCheck)!==!1,i=!n&&r!==void 0&&o;if(!n&&!i&&!!o){e.logger?.log?.("[Atomic] Change protocol stood down: nothing in this workspace can be run to judge a change, and there is nobody here to approve one the model proposes. Name a check of your own to have it engage."),e.onStatus?.({armed:!1,message:"Change protocol stood down: nothing in this workspace can be run to judge a change, and there is nobody here to approve one the model proposes. Name a check of your own to have it engage."});return}let a=n?`Change protocol armed: each attempt is judged by \`${n.label}\` (${n.reason}), and an attempt that fails it is put back.`:i?"Change protocol armed with nothing to run: the model will propose a check and ask you to approve it. Until one is approved it judges its own work, which is labelled as such on every attempt.":"Change protocol armed with no check to run: the model judges its own work, which is the weaker of the two and is labelled as such on every attempt.";e.logger?.log?.(`[Atomic] ${a}`),e.onStatus?.({armed:!0,message:a});let d=e.forgetReads??e.config?.forgetReads,l=new tC({workspaceRoot:e.workspaceRoot,...e.revisions?{revisions:e.revisions}:{},maxChanges:e.config?.maxChanges??Gp,maxTransactions:e.config?.maxTransactions??Vb,oracle:n,allowCheckProposal:i,checkReconsideredAfter:e.checkReconsideredAfter??e.config?.checkReconsideredAfter??F4,...e.describeLastTransaction?{describeLastTransaction:e.describeLastTransaction}:{},oracleTimeoutMs:e.config?.oracleTimeoutMs,onEvent:e.onEvent,...d?{forgetReads:d}:{},...e.config?.carryReadStamp?{carryReadStamp:e.config.carryReadStamp}:{}}),c=[Kb({controller:l,forgetReads:d,onRestored:({path:T,deleted:A})=>e.logger?.log?.(`[Atomic] ${T} ${A?"deleted":"put back"} at the model's request.`),onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)})];c.push($4({controller:l,maxChanges:e.config?.maxChanges??Gp,onPlan:(T)=>e.logger?.log?.(`[Atomic] plan: ${T.length} change(s), ${T.filter((A)=>A.status==="done").length} landed.`)}));let u=Z4({get transaction(){return l.transaction}});if(c.push(_4({controller:l,canProposeCheck:i,onRun:async(T,A)=>{e.logger?.log?.(`[Atomic] ${A.label} run on request: ${T.passed?"passed":"failed"}.`);let R=u.checked(T.passed);if(R==="ok"||p)return;if(R==="nudge"){let N=t6(u.streak,A.label);return e.logger?.log?.(`[Atomic] ${N}`),N}let C=n6(u.streak,A.label);e.logger?.log?.(`[Atomic] ${C}`);let L=await v({...b?.transaction===l.transaction?{plan:b.plan}:{},account:C,forced:!0,notice:C});if(L.message)return L.message;return L.kept?`${C}
1185
1185
 
1186
1186
  Judged at that point the check passed, so the task is settled and this run is done.`:`${C}
1187
1187
 
1188
- That was the last transaction, so there is no next one. Say plainly what you tried and what the check still says.`},onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)})),c.push(K6({submit:async(T)=>{k=!0;try{return await E({text:T,deliberate:!0})??"Submitted, and that settles it: the task is done and this run is over. Say plainly what you changed."}finally{k=!1}},onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)})),i&&r)c.push(q6({workspaceRoot:e.workspaceRoot,controller:l,approve:r,maxProposals:e.maxCheckProposals??e.config?.maxCheckProposals,onAdopted:(T)=>{let A=`Change protocol: you approved \`${T.label}\`, and every attempt from here is judged by it.`;e.logger?.log?.(`[Atomic] ${A}`),e.onStatus?.({armed:!0,message:A})},onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)}));let h=await l.open(),p=!1,f=!1,m=0,g=0,y=0,w=0,k=!1,b,v=async(T)=>{m=0,g=0,y=0,w=0,b=void 0;let A=await l.settle({...T.plan?{plan:T.plan}:{},account:T.account,selfReport:T.selfReport,forced:T.forced});if(A.kept||!A.nextPrompt)return p=!0,{finished:!0,kept:A.kept};return{finished:!1,kept:!1,message:[T.notice,A.message,A.verdict?.output?`The check said:
1188
+ That was the last transaction, so there is no next one. Say plainly what you tried and what the check still says.`},onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)})),c.push(K4({submit:async(T)=>{k=!0;try{return await E({text:T,deliberate:!0})??"Submitted, and that settles it: the task is done and this run is over. Say plainly what you changed."}finally{k=!1}},onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)})),i&&r)c.push(q4({workspaceRoot:e.workspaceRoot,controller:l,approve:r,maxProposals:e.maxCheckProposals??e.config?.maxCheckProposals,onAdopted:(T)=>{let A=`Change protocol: you approved \`${T.label}\`, and every attempt from here is judged by it.`;e.logger?.log?.(`[Atomic] ${A}`),e.onStatus?.({armed:!0,message:A})},onError:(T,A)=>e.logger?.log?.(`${T}: ${String(A)}`)}));let h=await l.open(),p=!1,f=!1,m=0,g=0,y=0,w=0,k=!1,b,v=async(T)=>{m=0,g=0,y=0,w=0,b=void 0;let A=await l.settle({...T.plan?{plan:T.plan}:{},account:T.account,selfReport:T.selfReport,forced:T.forced});if(A.kept||!A.nextPrompt)return p=!0,{finished:!0,kept:A.kept};return{finished:!1,kept:!1,message:[T.notice,A.message,A.verdict?.output?`The check said:
1189
1189
  ${A.verdict.output}`:void 0,A.nextPrompt].filter((R)=>R!==void 0).join(`
1190
1190
 
1191
- `)}},E=async({text:T,forced:A,deliberate:R})=>{if(p)return;let C=await l.isUntouched(),L;if(l.outcomes.length===0&&C){let K=await S();if(!K||K.passed){p=!0;return}L=K}if(!R&&!A&&w<d4){let K=X6({transaction:l.transaction,silent:w,before:d4,untouched:C,...L?{check:{label:l.oracle?.label??"the check",...L.output?{output:L.output}:{}}}:{}});return e.logger?.log?.(`[Atomic] ${K.split(`
1192
- `)[0]}`),K}let N;if(C){let K=g===0;if(K)y+=1;else m+=1;if(K&&y>EMe){p=!0;let j=J6(l.transaction,y);e.logger?.log?.(`[Atomic] ${j}`),e.onEvent?.({type:"empty",transaction:l.transaction,message:j,continued:!1});return}let V=K||m<=_Me,B=Y6(l.transaction,V,K);if(e.logger?.log?.(`[Atomic] ${B}`),e.onEvent?.({type:"empty",transaction:l.transaction,message:B,continued:V}),V)return[B,V6({transaction:l.transaction,maxChanges:e.config?.maxChanges??Gp,maxTransactions:e.config?.maxTransactions??Vb,...L?{check:{label:l.oracle?.label??"the check",...L.output?{output:L.output}:{}}}:{},...g===0?{neverBegan:!0}:{}})].join(`
1191
+ `)}},E=async({text:T,forced:A,deliberate:R})=>{if(p)return;let C=await l.isUntouched(),L;if(l.outcomes.length===0&&C){let K=await S();if(!K||K.passed){p=!0;return}L=K}if(!R&&!A&&w<d6){let K=X4({transaction:l.transaction,silent:w,before:d6,untouched:C,...L?{check:{label:l.oracle?.label??"the check",...L.output?{output:L.output}:{}}}:{}});return e.logger?.log?.(`[Atomic] ${K.split(`
1192
+ `)[0]}`),K}let N;if(C){let K=g===0;if(K)y+=1;else m+=1;if(K&&y>EMe){p=!0;let j=J4(l.transaction,y);e.logger?.log?.(`[Atomic] ${j}`),e.onEvent?.({type:"empty",transaction:l.transaction,message:j,continued:!1});return}let V=K||m<=_Me,B=Y4(l.transaction,V,K);if(e.logger?.log?.(`[Atomic] ${B}`),e.onEvent?.({type:"empty",transaction:l.transaction,message:B,continued:V}),V)return[B,V4({transaction:l.transaction,maxChanges:e.config?.maxChanges??Gp,maxTransactions:e.config?.maxTransactions??Vb,...L?{check:{label:l.oracle?.label??"the check",...L.output?{output:L.output}:{}}}:{},...g===0?{neverBegan:!0}:{}})].join(`
1193
1193
 
1194
- `);N=B}let W=zp(T)??(b?.transaction===l.transaction?b.plan:void 0);return(await v({...W?{plan:W}:{},account:T,selfReport:n?void 0:AMe(T),forced:A,...N?{notice:N}:{}})).message},S=async()=>{if(!l.oracle)return;try{return await l.runCheck()}catch(T){e.logger?.log?.(`[Atomic] the check could not be run at the completion boundary, so the run was allowed to end: ${String(T)}`);return}},x=(T)=>`\`${T}\` is not available: the user turned the change protocol off. There are no transactions now -- edit the files directly, and say what you changed.`;return{controller:l,get oracle(){return l.oracle},tools:c.map((T)=>({...T,execute:async(A,R)=>{if(f)return x(T.name);return T.execute?.(A,R)}})),decorateTools:(T)=>{let A=qp(T,l,void 0,e.revisionOverlay),R=Rc(A,{source:{get pending(){return l.pending},get transaction(){return l.transaction},get log(){return l.revisions}},readFile:async(D)=>{try{return await xMe(D)}catch{return}}}),C=N6(R,{get transaction(){return l.transaction},onPlan:(D,K)=>{b={transaction:l.transaction,plan:D},e.onEvent?.({type:"plan",transaction:l.transaction,plan:D,from:K})}}),L=e4(C,()=>{u.changed()}),N=l.oracle,W=N?A6(L,{get transaction(){return l.transaction},checkLabel:N.label}):L;return r4(W,(D)=>{if(w=0,D===as)return;g+=1})},takeOpeningRules:()=>{let T=h;return h=void 0,T},async describeUnstartedWork(){if(p)return;if(!await l.isUntouched())return;return` The change protocol is engaged and ${`TX-${String(l.transaction).padStart(2,"0")}`} is open with nothing in it: no file has been changed yet. It does not replace your other instructions,`+" and it cannot advance on prose — reading a file, running the check and"+" editing are all tool calls, and one of them is the next thing to do. Start by reading what you are about to change."},async onCompletionAttempt({text:T,forced:A}){if(f)return;if(k)return;return w+=1,E({text:T,forced:A})},get disengaged(){return f},async disengage(){if(f)return;f=!0;let T=l.transaction;if(p||await l.isUntouched())return e.logger?.log?.("[Atomic] disengaged by the user with nothing open to judge."),eC({});let R=await l.settle({forced:!0}),C=R.kept?0:R.restore.restored.length+R.restore.removed.length+R.restore.recreated.length;return e.logger?.log?.(`[Atomic] disengaged by the user; TX-${String(T).padStart(2,"0")} ${R.kept?"kept":`discarded, ${C} file(s) put back`}.`),eC({transaction:T,verdict:R.message,kept:R.kept,filesPutBack:C})}}}function AMe(e){if(!e)return;let t=e.toLowerCase();if(["could not verify","couldn't verify","unable to verify","cannot verify","can't verify","could not test","unable to test","not able to test","i cannot tell","i can't tell","unverified","not verified"].some((o)=>t.includes(o)))return"unsure";return["still fails","still failing","still broken","did not work","didn't work","does not work","doesn't work","was not able to fix","could not fix","couldn't fix"].some((o)=>t.includes(o))?"failure":void 0}import{readFile as RMe}from"node:fs/promises";function c4(e){let t=e.log??ss(),n=e.readFile??(async(o)=>{try{return await RMe(o)}catch{return}}),r={pending:void 0,root:e.root,transaction:0,revisions:t};return{log:t,tools:[Kb({controller:r,scope:"session",...e.forgetReads?{forgetReads:e.forgetReads}:{},...e.onRestored?{onRestored:({path:o,deleted:i})=>e.onRestored?.({path:o,deleted:i})}:{},...e.onError?{onError:e.onError}:{}})],port:{spanFor:(o)=>f6(t.revisions(o)),tracked:()=>t.tracked(),noteCompaction:(o)=>t.noteCompaction(o)},decorateReads:(o)=>qp(o,r,XI),decorate:(o)=>Rc(qp(o,r,XI),{source:{...r,log:t},readFile:n,...e.lastCheck?{lastCheck:e.lastCheck}:{}})}}function Yb(e){let t=[],n=e.signals;if(n){if(t.push(`Failed or refused tool calls in the last 10 turns: ${n.failedCalls}.`),n.distress>0)t.push(`Distress language in the model's own reasoning over the same turns: ${n.distress} occurrence${n.distress===1?"":"s"}. Measured on its own this separates nothing — it fires on 46% of successful runs by strong models — so read it with the line above, not instead of it.`);if(n.hedgingRatio!==void 0)t.push(n.hedgingRatio>=1?`Hedging is running at ${n.hedgingRatio.toFixed(2)}× this run's own opening rate. A run that converges hedges less as it goes: over 317 replayed runs the ones that finished fell to 0.62×, and the ones that did not held at 0.86×.`:`Hedging has fallen to ${n.hedgingRatio.toFixed(2)}× this run's opening rate, which is the shape of a run that is converging rather than one that is stuck.`)}if(e.transactions&&e.transactions.opened>0){let{opened:r,discarded:o,carried:i}=e.transactions;t.push(`Transactions: ${r} opened, ${o} judged and rolled back${i?`, ${i} carried forward unverified`:""}.`)}for(let r of e.complexity??[])t.push(r);for(let r of e.appraisal??[])t.push(r);if(e.guardStoodDown)t.push("A terminal guard has already stood down once for this task: the run was going to end, and was held open instead.");if(t.length===0)return;if(e.iteration!==void 0)t.unshift(`Turn ${e.iteration} of this task.`);return t.push("None of this is a verdict on whether the task is hard or the model is stuck — nothing measured here separates those two on its own. It is the evidence, so you can weigh it against what you were told."),t.join(`
1195
- `)}var IMe=new Set(["completed","failed","canceled","rejected"]);function u4(e){return IMe.has(e)}function h4(e){return{kind:"text",text:e}}function p4(e){return{kind:"data",data:e}}function m4(e){return e.filter((t)=>t.kind==="text").map((t)=>t.text).join(`
1196
- `).trim()}function nC(e){return`TX-${String(e).padStart(2,"0")}`}function CMe(e){if(Nl(e))return`The check is: ${e.label}. It passes when the page loads, runs its frames and throws nothing.`;return e.expect?`The check is \`${e.label}\`. It passes when it finishes cleanly AND its output matches /${e.expect}/.`:`The check is \`${e.label}\`. Its exit status is the verdict.`}function PMe(e){let t=[`The work is inside ${nC(e.transaction)}, of at most ${e.maxTransactions} transactions this task gets.`];if(e.changesUsed===void 0)t.push(`A transaction carries at most ${e.maxChanges} changes. A change is an edit that lands; reading and running the check cost nothing.`);else{let n=Math.max(0,e.maxChanges-e.changesUsed);t.push(`${e.changesUsed} of its ${e.maxChanges} changes have been used, so ${n} changes are left. A change is an edit that lands; reading and running the check cost nothing.`)}if(e.oracle)t.push(CMe(e.oracle));if(e.plan?.trim())t.push("","It planned this, and it has not worked:",e.plan.trim());return t}function MMe(e){let t=[];for(let n of e){if(t.push("",`${nC(n.transaction)} — ${n.kept?"kept":"discarded"}`),n.plan?.trim())t.push(`plan: ${n.plan.trim()}`);if(n.account?.trim())t.push(`it said: ${n.account.trim()}`);if(n.evidence.trim())t.push(`result: ${n.evidence.trim()}`)}return t.push("","Everything in a discarded transaction was put back: those files are as they were before it. Nothing of that work survives on disk, so do not read the code as evidence that it was never tried — and do not try it again."),t}function OMe(e){if(e.transaction)return[`You can edit directly. Your changes go into ${nC(e.transaction.transaction)} along with the base model's, they count against the same change budget, and they are judged together: if the check does not pass, every change in the transaction is rolled back — yours included — and the task gets the next transaction with a record of what this one tried.`,"So run the check before you hand back. A delivery that has not been run is a guess, and it costs the task a whole transaction to find that out."];if(e.snapshotTaken)return["You can edit directly. There is no transaction here: what you change stands, and the base model continues from the workspace you leave behind. A snapshot was taken of the workspace before this escalation, so the whole of it can be put back if your changes turn out to be wrong — but that is a rollback of everything, not of one edit.","So verify what you change, and say plainly what you left in a state you are not sure about."];return["You can edit directly. What you change stands, and the base model continues from the workspace you leave behind — there is no rollback behind you here, so verify what you change and say plainly what you left in a state you are not sure about."]}function mi(e,t){let n=t.filter((r,o)=>r.trim()||o>0);if(!n.some((r)=>r.trim()))return[];return[`-- ${e} --`,...n,""]}function f4(e){let t=["== ESCALATION ==","","Another model is working on the task below and has handed it to you. It is not a user: it is a model with the same tools you have, in the same workspace, and it will read what you deliver and check it against what it asked for. Expect it to push back if the work does not hold up.","",`This is escalation ${e.escalation.index} of ${e.escalation.of} the task is allowed. After you deliver, it may come back to you at most ${e.followUpsAllowed} more times in this conversation, so a complete answer now is worth more than a fast one.`,""];t.push(...mi("WHAT IT WANTS FROM YOU",[e.goal.trim()])),t.push(...mi("WHAT IT WILL ACCEPT",e.expectation?.trim()?[e.expectation.trim()]:[])),t.push(...mi("THE TASK, AS THE USER STATED IT",e.task?.trim()?[e.task.trim()]:[]));let n=[];if(e.workspaceRoot?.trim())n.push(`Workspace root: ${e.workspaceRoot.trim()}`);if(e.filesInPlay?.length)n.push("Files it has been working in (a starting point, not a boundary):",...e.filesInPlay.map((r)=>` ${r}`));if(t.push(...mi("WHERE THE WORK IS",n)),t.push(...mi("WHAT THE HARNESS MEASURED",e.assessment?.trim()?["Measured by the harness, not reported by the model that asked you:",e.assessment.trim()]:[])),e.transaction){if(t.push(...mi("THE OPEN TRANSACTION",PMe(e.transaction))),e.transaction.history.length>0)t.push(...mi("WHAT EARLIER TRANSACTIONS TRIED",MMe(e.transaction.history)))}return t.push(...mi("WHAT YOUR CHANGES ARE WORTH",OMe(e))),t.push(...mi("HOW TO DELIVER",["Say what you changed, file by file, and why it is the fix rather than a way around the symptom.","Say what you ran and what it printed. If you could not run anything, say that instead of implying you did.","Say what you are unsure about. The model that asked you is going to check this; an honest reservation is worth more to it than a confident delivery it has to discover the hard way."])),`${t.join(`
1194
+ `);N=B}let W=zp(T)??(b?.transaction===l.transaction?b.plan:void 0);return(await v({...W?{plan:W}:{},account:T,selfReport:n?void 0:AMe(T),forced:A,...N?{notice:N}:{}})).message},S=async()=>{if(!l.oracle)return;try{return await l.runCheck()}catch(T){e.logger?.log?.(`[Atomic] the check could not be run at the completion boundary, so the run was allowed to end: ${String(T)}`);return}},x=(T)=>`\`${T}\` is not available: the user turned the change protocol off. There are no transactions now -- edit the files directly, and say what you changed.`;return{controller:l,get oracle(){return l.oracle},tools:c.map((T)=>({...T,execute:async(A,R)=>{if(f)return x(T.name);return T.execute?.(A,R)}})),decorateTools:(T)=>{let A=qp(T,l,void 0,e.revisionOverlay),R=Rc(A,{source:{get pending(){return l.pending},get transaction(){return l.transaction},get log(){return l.revisions}},readFile:async(D)=>{try{return await xMe(D)}catch{return}}}),C=N4(R,{get transaction(){return l.transaction},onPlan:(D,K)=>{b={transaction:l.transaction,plan:D},e.onEvent?.({type:"plan",transaction:l.transaction,plan:D,from:K})}}),L=e6(C,()=>{u.changed()}),N=l.oracle,W=N?A4(L,{get transaction(){return l.transaction},checkLabel:N.label}):L;return r6(W,(D)=>{if(w=0,D===as)return;g+=1})},takeOpeningRules:()=>{let T=h;return h=void 0,T},async describeUnstartedWork(){if(p)return;if(!await l.isUntouched())return;return` The change protocol is engaged and ${`TX-${String(l.transaction).padStart(2,"0")}`} is open with nothing in it: no file has been changed yet. It does not replace your other instructions,`+" and it cannot advance on prose — reading a file, running the check and"+" editing are all tool calls, and one of them is the next thing to do. Start by reading what you are about to change."},async onCompletionAttempt({text:T,forced:A}){if(f)return;if(k)return;return w+=1,E({text:T,forced:A})},get disengaged(){return f},async disengage(){if(f)return;f=!0;let T=l.transaction;if(p||await l.isUntouched())return e.logger?.log?.("[Atomic] disengaged by the user with nothing open to judge."),eC({});let R=await l.settle({forced:!0}),C=R.kept?0:R.restore.restored.length+R.restore.removed.length+R.restore.recreated.length;return e.logger?.log?.(`[Atomic] disengaged by the user; TX-${String(T).padStart(2,"0")} ${R.kept?"kept":`discarded, ${C} file(s) put back`}.`),eC({transaction:T,verdict:R.message,kept:R.kept,filesPutBack:C})}}}function AMe(e){if(!e)return;let t=e.toLowerCase();if(["could not verify","couldn't verify","unable to verify","cannot verify","can't verify","could not test","unable to test","not able to test","i cannot tell","i can't tell","unverified","not verified"].some((o)=>t.includes(o)))return"unsure";return["still fails","still failing","still broken","did not work","didn't work","does not work","doesn't work","was not able to fix","could not fix","couldn't fix"].some((o)=>t.includes(o))?"failure":void 0}import{readFile as RMe}from"node:fs/promises";function c6(e){let t=e.log??ss(),n=e.readFile??(async(o)=>{try{return await RMe(o)}catch{return}}),r={pending:void 0,root:e.root,transaction:0,revisions:t};return{log:t,tools:[Kb({controller:r,scope:"session",...e.forgetReads?{forgetReads:e.forgetReads}:{},...e.onRestored?{onRestored:({path:o,deleted:i})=>e.onRestored?.({path:o,deleted:i})}:{},...e.onError?{onError:e.onError}:{}})],port:{spanFor:(o)=>f4(t.revisions(o)),tracked:()=>t.tracked(),noteCompaction:(o)=>t.noteCompaction(o)},decorateReads:(o)=>qp(o,r,XI),decorate:(o)=>Rc(qp(o,r,XI),{source:{...r,log:t},readFile:n,...e.lastCheck?{lastCheck:e.lastCheck}:{}})}}function Yb(e){let t=[],n=e.signals;if(n){if(t.push(`Failed or refused tool calls in the last 10 turns: ${n.failedCalls}.`),n.distress>0)t.push(`Distress language in the model's own reasoning over the same turns: ${n.distress} occurrence${n.distress===1?"":"s"}. Measured on its own this separates nothing — it fires on 46% of successful runs by strong models — so read it with the line above, not instead of it.`);if(n.hedgingRatio!==void 0)t.push(n.hedgingRatio>=1?`Hedging is running at ${n.hedgingRatio.toFixed(2)}× this run's own opening rate. A run that converges hedges less as it goes: over 317 replayed runs the ones that finished fell to 0.62×, and the ones that did not held at 0.86×.`:`Hedging has fallen to ${n.hedgingRatio.toFixed(2)}× this run's opening rate, which is the shape of a run that is converging rather than one that is stuck.`)}if(e.transactions&&e.transactions.opened>0){let{opened:r,discarded:o,carried:i}=e.transactions;t.push(`Transactions: ${r} opened, ${o} judged and rolled back${i?`, ${i} carried forward unverified`:""}.`)}for(let r of e.complexity??[])t.push(r);for(let r of e.appraisal??[])t.push(r);if(e.guardStoodDown)t.push("A terminal guard has already stood down once for this task: the run was going to end, and was held open instead.");if(t.length===0)return;if(e.iteration!==void 0)t.unshift(`Turn ${e.iteration} of this task.`);return t.push("None of this is a verdict on whether the task is hard or the model is stuck — nothing measured here separates those two on its own. It is the evidence, so you can weigh it against what you were told."),t.join(`
1195
+ `)}var IMe=new Set(["completed","failed","canceled","rejected"]);function u6(e){return IMe.has(e)}function h6(e){return{kind:"text",text:e}}function p6(e){return{kind:"data",data:e}}function m6(e){return e.filter((t)=>t.kind==="text").map((t)=>t.text).join(`
1196
+ `).trim()}function nC(e){return`TX-${String(e).padStart(2,"0")}`}function CMe(e){if(Nl(e))return`The check is: ${e.label}. It passes when the page loads, runs its frames and throws nothing.`;return e.expect?`The check is \`${e.label}\`. It passes when it finishes cleanly AND its output matches /${e.expect}/.`:`The check is \`${e.label}\`. Its exit status is the verdict.`}function PMe(e){let t=[`The work is inside ${nC(e.transaction)}, of at most ${e.maxTransactions} transactions this task gets.`];if(e.changesUsed===void 0)t.push(`A transaction carries at most ${e.maxChanges} changes. A change is an edit that lands; reading and running the check cost nothing.`);else{let n=Math.max(0,e.maxChanges-e.changesUsed);t.push(`${e.changesUsed} of its ${e.maxChanges} changes have been used, so ${n} changes are left. A change is an edit that lands; reading and running the check cost nothing.`)}if(e.oracle)t.push(CMe(e.oracle));if(e.plan?.trim())t.push("","It planned this, and it has not worked:",e.plan.trim());return t}function MMe(e){let t=[];for(let n of e){if(t.push("",`${nC(n.transaction)} — ${n.kept?"kept":"discarded"}`),n.plan?.trim())t.push(`plan: ${n.plan.trim()}`);if(n.account?.trim())t.push(`it said: ${n.account.trim()}`);if(n.evidence.trim())t.push(`result: ${n.evidence.trim()}`)}return t.push("","Everything in a discarded transaction was put back: those files are as they were before it. Nothing of that work survives on disk, so do not read the code as evidence that it was never tried — and do not try it again."),t}function OMe(e){if(e.transaction)return[`You can edit directly. Your changes go into ${nC(e.transaction.transaction)} along with the base model's, they count against the same change budget, and they are judged together: if the check does not pass, every change in the transaction is rolled back — yours included — and the task gets the next transaction with a record of what this one tried.`,"So run the check before you hand back. A delivery that has not been run is a guess, and it costs the task a whole transaction to find that out."];if(e.snapshotTaken)return["You can edit directly. There is no transaction here: what you change stands, and the base model continues from the workspace you leave behind. A snapshot was taken of the workspace before this escalation, so the whole of it can be put back if your changes turn out to be wrong — but that is a rollback of everything, not of one edit.","So verify what you change, and say plainly what you left in a state you are not sure about."];return["You can edit directly. What you change stands, and the base model continues from the workspace you leave behind — there is no rollback behind you here, so verify what you change and say plainly what you left in a state you are not sure about."]}function mi(e,t){let n=t.filter((r,o)=>r.trim()||o>0);if(!n.some((r)=>r.trim()))return[];return[`-- ${e} --`,...n,""]}function f6(e){let t=["== ESCALATION ==","","Another model is working on the task below and has handed it to you. It is not a user: it is a model with the same tools you have, in the same workspace, and it will read what you deliver and check it against what it asked for. Expect it to push back if the work does not hold up.","",`This is escalation ${e.escalation.index} of ${e.escalation.of} the task is allowed. After you deliver, it may come back to you at most ${e.followUpsAllowed} more times in this conversation, so a complete answer now is worth more than a fast one.`,""];t.push(...mi("WHAT IT WANTS FROM YOU",[e.goal.trim()])),t.push(...mi("WHAT IT WILL ACCEPT",e.expectation?.trim()?[e.expectation.trim()]:[])),t.push(...mi("THE TASK, AS THE USER STATED IT",e.task?.trim()?[e.task.trim()]:[]));let n=[];if(e.workspaceRoot?.trim())n.push(`Workspace root: ${e.workspaceRoot.trim()}`);if(e.filesInPlay?.length)n.push("Files it has been working in (a starting point, not a boundary):",...e.filesInPlay.map((r)=>` ${r}`));if(t.push(...mi("WHERE THE WORK IS",n)),t.push(...mi("WHAT THE HARNESS MEASURED",e.assessment?.trim()?["Measured by the harness, not reported by the model that asked you:",e.assessment.trim()]:[])),e.transaction){if(t.push(...mi("THE OPEN TRANSACTION",PMe(e.transaction))),e.transaction.history.length>0)t.push(...mi("WHAT EARLIER TRANSACTIONS TRIED",MMe(e.transaction.history)))}return t.push(...mi("WHAT YOUR CHANGES ARE WORTH",OMe(e))),t.push(...mi("HOW TO DELIVER",["Say what you changed, file by file, and why it is the fix rather than a way around the symptom.","Say what you ran and what it printed. If you could not run anything, say that instead of implying you did.","Say what you are unsure about. The model that asked you is going to check this; an honest reservation is worth more to it than a confident delivery it has to discover the hard way."])),`${t.join(`
1197
1197
  `).replace(/\n{3,}/g,`
1198
1198
 
1199
1199
  `).trimEnd()}
1200
- `}function Xb(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,generateTokens:e.generateTokens+t.generateTokens,generateMs:e.generateMs+t.generateMs,wallMs:e.wallMs+t.wallMs,requests:e.requests+t.requests,asks:e.asks+t.asks}}var LMe={inputTokens:0,outputTokens:0,generateTokens:0,generateMs:0,wallMs:0,requests:0,asks:0};function g4(e){let t={...LMe},n,r=0,o={get used(){return r},get remaining(){return Math.max(0,e.maxEscalations-r)},get session(){return n},get usage(){return n?Xb(t,n.usage):{...t}},begin(){if(o.remaining<=0)throw Error(`This task has already escalated ${e.maxEscalations} time${e.maxEscalations===1?"":"s"}, which is the limit. There is no expert left to hand this to: finish it yourself, or tell the user what is blocking you.`);if(r+=1,!n||n.closed)n=e.createSession();return n},async refund(){if(r=Math.max(0,r-1),!n||n.deliveries>0)return;t=Xb(t,n.usage);let i=n;n=void 0;try{await i.close("the escalation did not happen")}catch{}},async end(){if(!n)return;if(!e.closeAfterEscalation)return;t=Xb(t,n.usage);let i=n;n=void 0,await i.close("escalation finished")},async dispose(){if(!n)return;t=Xb(t,n.usage);let i=n;n=void 0,await i.close("task ended")}};return o}function rC(){return{inputTokens:0,outputTokens:0,generateTokens:0,generateMs:0,wallMs:0,requests:0,asks:0}}function y4(e){let t=rC(),n=rC(),r,o=0,i=!1,s=0,a,d=(c)=>{if(c.type==="content_end"&&c.contentType==="tool"){s+=1,l(c.toolName);return}if(c.type==="content_end"&&c.contentType==="reasoning"){let h=c.reasoning?.trim();if(h)e.onUtterance?.({kind:"thinking",text:h});return}if(c.type==="content_end"&&c.contentType==="text"){let h=c.text?.trim();if(h)e.onUtterance?.({kind:"message",text:h});return}if(c.type!=="usage")return;n.requests+=1,n.inputTokens+=c.inputTokens??0,n.outputTokens+=c.outputTokens??0;let u=c.timings;if(u?.generateTokens&&u.generateMs)n.generateTokens+=u.generateTokens,n.generateMs+=u.generateMs;l()},l=(c)=>{if(!e.onProgress||a===void 0)return;e.onProgress({toolCalls:s,...c?{lastTool:c}:{},usage:{...n,wallMs:Date.now()-a,asks:1}})};return{get deliveries(){return o},get followUps(){return Math.max(0,o-1)},get closed(){return i},get usage(){return{...t}},async ask(c){if(i)throw Error("This expert conversation is closed. Escalate again to open a new one.");if(o>0&&o-1>=e.maxFollowUps)throw Error(`The expert has already answered ${e.maxFollowUps} follow-up${e.maxFollowUps===1?"":"s"}, which is the limit. Act on what it has given you, or escalate again with a narrower question.`);if(!r)r=await e.open({onEvent:d});n=rC(),s=0;let u=Date.now();a=u;let h=e.gate?await e.gate.run((p)=>(p(),r?.run(c))):await r.run(c);if(n.wallMs=Date.now()-u,n.asks=1,a=void 0,n.inputTokens===0&&n.outputTokens===0)n.inputTokens=h.usage?.inputTokens??0,n.outputTokens=h.usage?.outputTokens??0,n.requests=1;if(t.inputTokens+=n.inputTokens,t.outputTokens+=n.outputTokens,t.generateTokens+=n.generateTokens,t.generateMs+=n.generateMs,t.wallMs+=n.wallMs,t.requests+=n.requests,t.asks+=1,h.finishReason==="error"){let p=h.text?.trim();throw Error(`The expert's run failed and produced no answer${p?`: ${p}`:"."}`)}return o+=1,{text:h.text,iterations:h.iterations,finishReason:h.finishReason,usage:{...n}}},async close(c){if(i)return;i=!0;try{await r?.shutdown?.(c)}catch{r?.abort?.(c)}r=void 0}}}var NMe=[le.EDITOR,le.APPLY_PATCH,le.SED,Hr,as],DMe=[le.RUN_COMMANDS],w4=`== YOU ARE STANDING DOWN WHILE THE EXPERT WORKS ==
1200
+ `}function Xb(e,t){return{inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,generateTokens:e.generateTokens+t.generateTokens,generateMs:e.generateMs+t.generateMs,wallMs:e.wallMs+t.wallMs,requests:e.requests+t.requests,asks:e.asks+t.asks}}var LMe={inputTokens:0,outputTokens:0,generateTokens:0,generateMs:0,wallMs:0,requests:0,asks:0};function g6(e){let t={...LMe},n,r=0,o={get used(){return r},get remaining(){return Math.max(0,e.maxEscalations-r)},get session(){return n},get usage(){return n?Xb(t,n.usage):{...t}},begin(){if(o.remaining<=0)throw Error(`This task has already escalated ${e.maxEscalations} time${e.maxEscalations===1?"":"s"}, which is the limit. There is no expert left to hand this to: finish it yourself, or tell the user what is blocking you.`);if(r+=1,!n||n.closed)n=e.createSession();return n},async refund(){if(r=Math.max(0,r-1),!n||n.deliveries>0)return;t=Xb(t,n.usage);let i=n;n=void 0;try{await i.close("the escalation did not happen")}catch{}},async end(){if(!n)return;if(!e.closeAfterEscalation)return;t=Xb(t,n.usage);let i=n;n=void 0,await i.close("escalation finished")},async dispose(){if(!n)return;t=Xb(t,n.usage);let i=n;n=void 0,await i.close("task ended")}};return o}function rC(){return{inputTokens:0,outputTokens:0,generateTokens:0,generateMs:0,wallMs:0,requests:0,asks:0}}function y6(e){let t=rC(),n=rC(),r,o=0,i=!1,s=0,a,d=(c)=>{if(c.type==="content_end"&&c.contentType==="tool"){s+=1,l(c.toolName);return}if(c.type==="content_end"&&c.contentType==="reasoning"){let h=c.reasoning?.trim();if(h)e.onUtterance?.({kind:"thinking",text:h});return}if(c.type==="content_end"&&c.contentType==="text"){let h=c.text?.trim();if(h)e.onUtterance?.({kind:"message",text:h});return}if(c.type!=="usage")return;n.requests+=1,n.inputTokens+=c.inputTokens??0,n.outputTokens+=c.outputTokens??0;let u=c.timings;if(u?.generateTokens&&u.generateMs)n.generateTokens+=u.generateTokens,n.generateMs+=u.generateMs;l()},l=(c)=>{if(!e.onProgress||a===void 0)return;e.onProgress({toolCalls:s,...c?{lastTool:c}:{},usage:{...n,wallMs:Date.now()-a,asks:1}})};return{get deliveries(){return o},get followUps(){return Math.max(0,o-1)},get closed(){return i},get usage(){return{...t}},async ask(c){if(i)throw Error("This expert conversation is closed. Escalate again to open a new one.");if(o>0&&o-1>=e.maxFollowUps)throw Error(`The expert has already answered ${e.maxFollowUps} follow-up${e.maxFollowUps===1?"":"s"}, which is the limit. Act on what it has given you, or escalate again with a narrower question.`);if(!r)r=await e.open({onEvent:d});n=rC(),s=0;let u=Date.now();a=u;let h=e.gate?await e.gate.run((p)=>(p(),r?.run(c))):await r.run(c);if(n.wallMs=Date.now()-u,n.asks=1,a=void 0,n.inputTokens===0&&n.outputTokens===0)n.inputTokens=h.usage?.inputTokens??0,n.outputTokens=h.usage?.outputTokens??0,n.requests=1;if(t.inputTokens+=n.inputTokens,t.outputTokens+=n.outputTokens,t.generateTokens+=n.generateTokens,t.generateMs+=n.generateMs,t.wallMs+=n.wallMs,t.requests+=n.requests,t.asks+=1,h.finishReason==="error"){let p=h.text?.trim();throw Error(`The expert's run failed and produced no answer${p?`: ${p}`:"."}`)}return o+=1,{text:h.text,iterations:h.iterations,finishReason:h.finishReason,usage:{...n}}},async close(c){if(i)return;i=!0;try{await r?.shutdown?.(c)}catch{r?.abort?.(c)}r=void 0}}}var NMe=[le.EDITOR,le.APPLY_PATCH,le.SED,Hr,as],DMe=[le.RUN_COMMANDS],w6=`== YOU ARE STANDING DOWN WHILE THE EXPERT WORKS ==
1201
1201
 
1202
1202
  The expert is editing this workspace now. You are not. Until it delivers, every tool that writes a file is refused — you cannot edit, patch, restore or submit, and there is no way to override that. This is not a judgement about your work; it is that two models writing to one workspace destroy each other's changes, and the expert has the pen.
1203
1203
 
@@ -1207,57 +1207,57 @@ You may run commands, including the check. Do not run one that changes a file. A
1207
1207
 
1208
1208
  You may message the expert, and you should keep it rare: a message costs it a turn and pulls it off what it is doing. Send one when you have something it needs — an answer to a question, a correction the user gave you, or the judgement only you can make: that it is going in circles and should stop. You are authorised to call it off.
1209
1209
 
1210
- When the expert delivers, you have the pen back and the task is yours again.`;function b4(){let e=!1;return{get engaged(){return e},engage(){e=!0},release(){e=!1}}}function $Me(e){return`\`${e}\` is refused: you are standing down while the expert works on this workspace, and it writes.
1210
+ When the expert delivers, you have the pen back and the task is yours again.`;function b6(){let e=!1;return{get engaged(){return e},engage(){e=!0},release(){e=!1}}}function $Me(e){return`\`${e}\` is refused: you are standing down while the expert works on this workspace, and it writes.
1211
1211
 
1212
1212
  The expert has the pen until it delivers. Changing a file now would land on top of work in progress, and the expert would go on editing the version it thinks is there. Read, grep, run the check, read the revisions the notes name — all of that is open to you. If what you were about to change cannot wait, message the expert and say so.`}var FMe=`
1213
1213
 
1214
- [You are standing down while the expert works. Check that this did not change a file — if it did, say so to the expert now, because it is editing from what it believes is on disk.]`;function v4(e,t){return e.map((n)=>{let r=NMe.includes(n.name),o=DMe.includes(n.name);if(!r&&!o)return n;let i=n;return{...n,execute:async(s,a)=>{if(!t.engaged)return i.execute?.(s,a);if(r)return $Me(n.name);let d=await i.execute?.(s,a);return typeof d==="string"?d+FMe:d}}})}var Ast=[le.READ_FILES,le.SEARCH_CODEBASE,le.GREP,le.AWK,Lr];import{createTool as UMe}from"@cerebriline/shared";var BMe="wait_for_expert",HMe=`Wait for the expert, and be told what it has been doing.
1214
+ [You are standing down while the expert works. Check that this did not change a file — if it did, say so to the expert now, because it is editing from what it believes is on disk.]`;function v6(e,t){return e.map((n)=>{let r=NMe.includes(n.name),o=DMe.includes(n.name);if(!r&&!o)return n;let i=n;return{...n,execute:async(s,a)=>{if(!t.engaged)return i.execute?.(s,a);if(r)return $Me(n.name);let d=await i.execute?.(s,a);return typeof d==="string"?d+FMe:d}}})}var Cst=[le.READ_FILES,le.SEARCH_CODEBASE,le.GREP,le.AWK,Lr];import{createTool as UMe}from"@cerebriline/shared";var BMe="wait_for_expert",HMe=`Wait for the expert, and be told what it has been doing.
1215
1215
 
1216
1216
  While the expert works you are standing down from changes, and this is how you follow it. The call returns when there is something for you: a batch of notes covering everything the expert has done since you last looked, or its delivery once it is finished. It costs you one turn each time, which is why the notes arrive in batches rather than one per action.
1217
1217
 
1218
1218
  Each note names a tool the expert called, and where that call wrote a file it also gives the revision number holding what was written. Read the flow rather than auditing it — you are forming a view of whether the work is going somewhere, not checking receipts. Spot-check the parts that matter: \`read_files\` with \`revision: "#4"\` shows you the exact bytes a note is about, which is the only way to check a claim against what was actually written rather than against a file that has moved on since.
1219
1219
 
1220
- If what you see is the expert going round in circles — the same file rewritten again and again, a check failing the same way each time, nothing moving across several batches — say so. Call \`escalate\` with \`message\` to tell it what you see, or to tell it to stop. That judgement is yours, and nobody else is going to make it.`;function k4(e){return UMe({name:BMe,description:HMe,inputSchema:{type:"object",properties:{},required:[]},execute:async()=>{try{return(await e.collect()).text}catch(t){let n=t instanceof Error?t.message:String(t);e.onError?.("[Escalation] waiting for the expert failed",t);let r=Iw(t);if(r)return`The expert's run failed: ${n}
1220
+ If what you see is the expert going round in circles — the same file rewritten again and again, a check failing the same way each time, nothing moving across several batches — say so. Call \`escalate\` with \`message\` to tell it what you see, or to tell it to stop. That judgement is yours, and nobody else is going to make it.`;function k6(e){return UMe({name:BMe,description:HMe,inputSchema:{type:"object",properties:{},required:[]},execute:async()=>{try{return(await e.collect()).text}catch(t){let n=t instanceof Error?t.message:String(t);e.onError?.("[Escalation] waiting for the expert failed",t);let r=Iw(t);if(r)return`The expert's run failed: ${n}
1221
1221
 
1222
1222
  ${r}
1223
1223
 
1224
1224
  The task is yours — carry on without the expert.`;return`Waiting for the expert failed: ${n}
1225
1225
 
1226
- The expert may still be working. The task is yours either way — carry on with what you can do without changing files, and call \`escalate\` with \`finished: true\` if you want to take the workspace back.`}}})}var T4="No expert is working right now, so there is nothing to wait for. The workspace is yours — carry on with the task.";var WMe=3,jMe=20;function S4(e,t){let n=[];for(let[r,o]of t.files){let i=e.files.get(r);if(!i||i.hash!==o.hash)n.push(r)}for(let r of e.files.keys())if(!t.files.has(r))n.push(r);return n.sort()}function qMe(e){return/usage limit|quota|\b402\b|payment required|upgrade for higher limits|insufficient (?:credit|balance)/i.test(e)}function zMe(e,t,n){if(t.length===0)return e;let r=e instanceof Error?e.message:String(e);return new Rw(r,t.map((o)=>oC(n,o)),{cause:e})}function oC(e,t){let n=e.endsWith("/")?e:`${e}/`;return t.startsWith(n)?t.slice(n.length):t}function x4(e){let t=e.config,n=t?.maxEscalations??WMe,r=t?.maxFollowUps??jMe,o=e.takeSnapshot??((A)=>ds(A)),i=e.restoreSnapshot??((A)=>Ba(A)),s=0,a,d=g4({maxEscalations:n,closeAfterEscalation:t?.closeAfterEscalation===!0,createSession:()=>y4({maxFollowUps:r,open:e.openExpert,...e.gate?{gate:e.gate}:{},...e.onEvent?{onUtterance:(A)=>e.onEvent?.({type:"expert_said",index:s,of:n,kind:A.kind,text:A.text}),onProgress:(A)=>{a=A.usage,e.onEvent?.({type:"expert_progress",index:s,of:n,toolCalls:A.toolCalls,...A.lastTool?{lastTool:A.lastTool}:{},usage:A.usage})}}:{}})}),l,c=async(A)=>{let R=await o(e.workspaceRoot);if(!l)l=R;if(e.revisions&&e.revisions.source.pending===void 0)e.revisions.open(R,d.used||1);let C;a=void 0;try{C=await A()}catch(W){let D=await o(e.workspaceRoot).catch(()=>{return}),K=D?S4(R,D):[];for(let B of K)e.forgetReads?.(B);let V=W instanceof Error?W.message:String(W);throw e.onEvent?.({type:"escalation_failed",index:s,of:n,reason:V,changed:K.map((B)=>oC(e.workspaceRoot,B)),...a?{usage:a}:{},limitReached:qMe(V)}),zMe(W,K,e.workspaceRoot)}let L=await o(e.workspaceRoot),N=S4(R,L);for(let W of N)e.forgetReads?.(W);return{...C,changed:N}},u=(A)=>`
1226
+ The expert may still be working. The task is yours either way — carry on with what you can do without changing files, and call \`escalate\` with \`finished: true\` if you want to take the workspace back.`}}})}var T6="No expert is working right now, so there is nothing to wait for. The workspace is yours — carry on with the task.";var WMe=3,jMe=20;function S6(e,t){let n=[];for(let[r,o]of t.files){let i=e.files.get(r);if(!i||i.hash!==o.hash)n.push(r)}for(let r of e.files.keys())if(!t.files.has(r))n.push(r);return n.sort()}function qMe(e){return/usage limit|quota|\b402\b|payment required|upgrade for higher limits|insufficient (?:credit|balance)/i.test(e)}function zMe(e,t,n){if(t.length===0)return e;let r=e instanceof Error?e.message:String(e);return new Rw(r,t.map((o)=>oC(n,o)),{cause:e})}function oC(e,t){let n=e.endsWith("/")?e:`${e}/`;return t.startsWith(n)?t.slice(n.length):t}function x6(e){let t=e.config,n=t?.maxEscalations??WMe,r=t?.maxFollowUps??jMe,o=e.takeSnapshot??((A)=>ds(A)),i=e.restoreSnapshot??((A)=>Ba(A)),s=0,a,d=g6({maxEscalations:n,closeAfterEscalation:t?.closeAfterEscalation===!0,createSession:()=>y6({maxFollowUps:r,open:e.openExpert,...e.gate?{gate:e.gate}:{},...e.onEvent?{onUtterance:(A)=>e.onEvent?.({type:"expert_said",index:s,of:n,kind:A.kind,text:A.text}),onProgress:(A)=>{a=A.usage,e.onEvent?.({type:"expert_progress",index:s,of:n,toolCalls:A.toolCalls,...A.lastTool?{lastTool:A.lastTool}:{},usage:A.usage})}}:{}})}),l,c=async(A)=>{let R=await o(e.workspaceRoot);if(!l)l=R;if(e.revisions&&e.revisions.source.pending===void 0)e.revisions.open(R,d.used||1);let C;a=void 0;try{C=await A()}catch(W){let D=await o(e.workspaceRoot).catch(()=>{return}),K=D?S6(R,D):[];for(let B of K)e.forgetReads?.(B);let V=W instanceof Error?W.message:String(W);throw e.onEvent?.({type:"escalation_failed",index:s,of:n,reason:V,changed:K.map((B)=>oC(e.workspaceRoot,B)),...a?{usage:a}:{},limitReached:qMe(V)}),zMe(W,K,e.workspaceRoot)}let L=await o(e.workspaceRoot),N=S6(R,L);for(let W of N)e.forgetReads?.(W);return{...C,changed:N}},u=(A)=>`
1227
1227
 
1228
1228
  == FROM THE USER, JUST NOW ==
1229
1229
 
1230
1230
  ${A.trim()}`,h=(A)=>A.length===0?"":`
1231
1231
 
1232
- The expert changed ${A.length} file${A.length===1?"":"s"}: ${A.map((R)=>oC(e.workspaceRoot,R)).join(", ")}. Read ${A.length===1?"it":"them"} before you edit ${A.length===1?"it":"them"} — what you had read is no longer what is there.`,p,f,m,{standDown:g,notes:y}=e,w=e.watchTickMs??250,k=e.wait??((A)=>new Promise((R)=>setTimeout(R,A))),b=(A)=>{y?.setState("working"),g?.engage();let R=c(A).then((C)=>(f=C,y?.setState("completed"),C),(C)=>{throw m=C,y?.setState("failed"),C});R.catch(()=>{return}),p=R},v=(A)=>[`The expert has the work. This is escalation ${A} of ${n}, and it is running now — you were not made to wait for it.`,w4,"Call `wait_for_expert` now. It returns when the expert has done enough to be worth looking at, or when it delivers."].join(`
1232
+ The expert changed ${A.length} file${A.length===1?"":"s"}: ${A.map((R)=>oC(e.workspaceRoot,R)).join(", ")}. Read ${A.length===1?"it":"them"} before you edit ${A.length===1?"it":"them"} — what you had read is no longer what is there.`,p,f,m,{standDown:g,notes:y}=e,w=e.watchTickMs??250,k=e.wait??((A)=>new Promise((R)=>setTimeout(R,A))),b=(A)=>{y?.setState("working"),g?.engage();let R=c(A).then((C)=>(f=C,y?.setState("completed"),C),(C)=>{throw m=C,y?.setState("failed"),C});R.catch(()=>{return}),p=R},v=(A)=>[`The expert has the work. This is escalation ${A} of ${n}, and it is running now — you were not made to wait for it.`,w6,"Call `wait_for_expert` now. It returns when the expert has done enough to be worth looking at, or when it delivers."].join(`
1233
1233
 
1234
- `),E=(A)=>{let R=m4(A.parts);if(A.final)return`== THE EXPERT HAS FINISHED. What it did since you last looked ==
1234
+ `),E=(A)=>{let R=m6(A.parts);if(A.final)return`== THE EXPERT HAS FINISHED. What it did since you last looked ==
1235
1235
 
1236
1236
  ${R}`;return`== WHAT THE EXPERT HAS DONE SINCE YOU LAST LOOKED ==
1237
1237
 
1238
1238
  ${R}
1239
1239
 
1240
- Spot-check what matters — \`read_files\` with the revision a note names shows you exactly what was written — then call \`wait_for_expert\` again. If it is going round in circles, \`escalate\` with \`message\` and say so.`},S=async()=>{if(!p&&f===void 0&&m===void 0)return{kind:"none",text:T4};while(f===void 0&&m===void 0){let W=y?.take();if(W)return{kind:"batch",text:E(W)};await k(w)}if(p=void 0,g?.release(),m!==void 0){let W=m;if(m=void 0,d.session?.deliveries===0)await d.refund();throw W}let A=f;f=void 0,e.onEvent?.({type:"expert_replied",reply:A.text,changed:A.changed,usage:A.usage});let R=y?.take(),C=e.takeSteering?.(),L=d.session,N=L?Math.max(0,r-L.followUps):0;return{kind:"delivered",text:[R?E(R):"","== THE EXPERT HAS DELIVERED. THIS IS A DELIVERY, NOT A VERDICT ==",A.text.trim()||"(the expert returned nothing)",h(A.changed).trim(),"You have the pen back. Check what it did before you build on it: run the check yourself, read the files it says it changed, and satisfy yourself that what it did is a fix and not a way around the symptom. You are still the one accountable for this task.",N>0?`If it does not hold up, call \`escalate\` again with \`message\` and say exactly what you found — ${N} follow-up${N===1?"":"s"} left in this exchange, and they are much cheaper than another escalation. When you are satisfied, call it with \`finished: true\` to release the expert.`:"This exchange is out of follow-ups. Act on what you have, and call `escalate` with `finished: true` to release the expert.",C?u(C).trim():""].filter(Boolean).join(`
1240
+ Spot-check what matters — \`read_files\` with the revision a note names shows you exactly what was written — then call \`wait_for_expert\` again. If it is going round in circles, \`escalate\` with \`message\` and say so.`},S=async()=>{if(!p&&f===void 0&&m===void 0)return{kind:"none",text:T6};while(f===void 0&&m===void 0){let W=y?.take();if(W)return{kind:"batch",text:E(W)};await k(w)}if(p=void 0,g?.release(),m!==void 0){let W=m;if(m=void 0,d.session?.deliveries===0)await d.refund();throw W}let A=f;f=void 0,e.onEvent?.({type:"expert_replied",reply:A.text,changed:A.changed,usage:A.usage});let R=y?.take(),C=e.takeSteering?.(),L=d.session,N=L?Math.max(0,r-L.followUps):0;return{kind:"delivered",text:[R?E(R):"","== THE EXPERT HAS DELIVERED. THIS IS A DELIVERY, NOT A VERDICT ==",A.text.trim()||"(the expert returned nothing)",h(A.changed).trim(),"You have the pen back. Check what it did before you build on it: run the check yourself, read the files it says it changed, and satisfy yourself that what it did is a fix and not a way around the symptom. You are still the one accountable for this task.",N>0?`If it does not hold up, call \`escalate\` again with \`message\` and say exactly what you found — ${N} follow-up${N===1?"":"s"} left in this exchange, and they are much cheaper than another escalation. When you are satisfied, call it with \`finished: true\` to release the expert.`:"This exchange is out of follow-ups. Act on what you have, and call `escalate` with `finished: true` to release the expert.",C?u(C).trim():""].filter(Boolean).join(`
1241
1241
 
1242
1242
  `)}},x=async(A)=>{let R=d.session,C=R&&!R.closed&&d.used>0;if(!C&&A.finished&&!A.goal)return{reply:"",opened:!1,closed:!0,followUpsLeft:0,escalationsLeft:d.remaining};if(C){if(s=d.used,g&&p&&A.finished)return p=void 0,await d.end(),e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),g.release(),e.onEvent?.({type:"escalation_ended",held:t?.closeAfterEscalation!==!0,usage:d.usage}),{reply:"You called the expert off and the exchange is closed. You have the pen back, and whatever it had already changed is still on disk — read the files before you edit them.",opened:!1,closed:!0,followUpsLeft:0,escalationsLeft:d.remaining};if(g&&p){let H=A.message??A.goal,J=e.mailbox;if(H&&J)return J.send(H),e.onEvent?.({type:"expert_asked",message:H}),{reply:"Your message is waiting for the expert and it will read it on its next turn — it does not interrupt the turn it is in the middle of. Call `wait_for_expert` to see what it does about it.",opened:!1,handedOver:!0,followUpsLeft:Math.max(0,r-R.followUps),escalationsLeft:d.remaining};return{reply:"The expert is still working — it has not delivered yet, so there is nothing to push back on. Call `wait_for_expert` to be told what it has been doing.",opened:!1,handedOver:!0,followUpsLeft:Math.max(0,r-R.followUps),escalationsLeft:d.remaining}}let z=e.takeSteering?.(),M=(A.message??A.goal??"")+(z?u(z):""),X={text:"",usage:R.usage,changed:[]};if(M.trim()&&g)return e.onEvent?.({type:"expert_asked",message:M}),b(async()=>{let H=await R.ask(M);return{text:H.text,usage:H.usage}}),{reply:["Your reply is with the expert and it is working on it.","You are still standing down: no edits until it delivers. Call `wait_for_expert` to follow it."].join(`
1243
1243
 
1244
- `),opened:!1,handedOver:!0,followUpsLeft:Math.max(0,r-R.followUps),escalationsLeft:d.remaining};if(M.trim())e.onEvent?.({type:"expert_asked",message:M}),X=await c(async()=>{let H=await R.ask(M);return{text:H.text,usage:H.usage}}),e.onEvent?.({type:"expert_replied",reply:X.text,changed:X.changed,usage:X.usage});if(A.finished){let H=t?.closeAfterEscalation!==!0;return await d.end(),e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),g?.release(),e.onEvent?.({type:"escalation_ended",held:H,usage:d.usage}),{reply:X.text+h(X.changed),opened:!1,closed:!0,followUpsLeft:0,escalationsLeft:d.remaining}}let oe=e.takeSteering?.();return{reply:X.text+h(X.changed)+(oe?u(oe):""),opened:!1,followUpsLeft:Math.max(0,r-R.followUps),escalationsLeft:d.remaining}}let L=e.readTransaction?.(),N=await e.assess?.({...A.files?.length?{files:A.files}:{},...A.goal?{goal:A.goal}:{},...A.message?{reason:A.message}:{}}),W=d.used+1,D=f4({goal:A.goal??"",...A.expectation?{expectation:A.expectation}:{},...e.readTask?.()?{task:e.readTask?.()}:{},workspaceRoot:e.workspaceRoot,...A.files?.length?{filesInPlay:A.files}:{},...L?{transaction:L}:{},...N?{assessment:N}:{},escalation:{index:W,of:n},followUpsAllowed:r,snapshotTaken:!L});if(t?.requireApproval){let z=await e.approve?.({brief:D,index:W,of:n}),M=z===void 0?{approved:!1}:typeof z==="boolean"?{approved:z}:z;if(!M.approved){let X=M.feedback?.trim();return{reply:"The user did not approve this escalation. Nothing was spent and the expert was not called — carry on with the task yourself, and say plainly what you are blocked on if you cannot."+(X?`
1244
+ `),opened:!1,handedOver:!0,followUpsLeft:Math.max(0,r-R.followUps),escalationsLeft:d.remaining};if(M.trim())e.onEvent?.({type:"expert_asked",message:M}),X=await c(async()=>{let H=await R.ask(M);return{text:H.text,usage:H.usage}}),e.onEvent?.({type:"expert_replied",reply:X.text,changed:X.changed,usage:X.usage});if(A.finished){let H=t?.closeAfterEscalation!==!0;return await d.end(),e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),g?.release(),e.onEvent?.({type:"escalation_ended",held:H,usage:d.usage}),{reply:X.text+h(X.changed),opened:!1,closed:!0,followUpsLeft:0,escalationsLeft:d.remaining}}let oe=e.takeSteering?.();return{reply:X.text+h(X.changed)+(oe?u(oe):""),opened:!1,followUpsLeft:Math.max(0,r-R.followUps),escalationsLeft:d.remaining}}let L=e.readTransaction?.(),N=await e.assess?.({...A.files?.length?{files:A.files}:{},...A.goal?{goal:A.goal}:{},...A.message?{reason:A.message}:{}}),W=d.used+1,D=f6({goal:A.goal??"",...A.expectation?{expectation:A.expectation}:{},...e.readTask?.()?{task:e.readTask?.()}:{},workspaceRoot:e.workspaceRoot,...A.files?.length?{filesInPlay:A.files}:{},...L?{transaction:L}:{},...N?{assessment:N}:{},escalation:{index:W,of:n},followUpsAllowed:r,snapshotTaken:!L});if(t?.requireApproval){let z=await e.approve?.({brief:D,index:W,of:n}),M=z===void 0?{approved:!1}:typeof z==="boolean"?{approved:z}:z;if(!M.approved){let X=M.feedback?.trim();return{reply:"The user did not approve this escalation. Nothing was spent and the expert was not called — carry on with the task yourself, and say plainly what you are blocked on if you cannot."+(X?`
1245
1245
 
1246
- They said: ${X}`:""),opened:!1,closed:!0,followUpsLeft:0,escalationsLeft:d.remaining}}}let K=e.takeSteering?.(),V=K?D+u(K):D,B=d.begin();if(s=W,e.logger?.log?.(`[Escalation] Escalation ${W} of ${n}: handing over to the expert`),e.onEvent?.({type:"escalation_started",index:W,of:n,brief:D}),g)return b(async()=>{let z=await B.ask(V);return{text:z.text,usage:z.usage}}),{reply:v(W),opened:!0,handedOver:!0,followUpsLeft:r,escalationsLeft:d.remaining};let j;try{j=await c(async()=>{let z=await B.ask(V);return{text:z.text,usage:z.usage}})}catch(z){if(B.deliveries===0)await d.refund();throw z}if(e.onEvent?.({type:"expert_replied",reply:j.text,changed:j.changed,usage:j.usage}),A.finished)await d.end(),e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),e.onEvent?.({type:"escalation_ended",held:t?.closeAfterEscalation!==!0,usage:d.usage});let G=e.takeSteering?.();return{reply:j.text+h(j.changed)+(G?u(G):""),opened:!0,...A.finished?{closed:!0}:{},followUpsLeft:r,escalationsLeft:d.remaining}},T=t?.connection?[rj({consult:x,onError:(A,R)=>e.logger?.log?.(`${A}: ${String(R)}`)}),...g?[k4({collect:S,onError:(A,R)=>e.logger?.log?.(`${A}: ${String(R)}`)})]:[]]:[];return{tools:T,get used(){return d.used},get remaining(){return T.length===0?0:Math.max(0,n-d.used)},get usage(){return d.usage},async restore(){return l?await i(l):void 0},async dispose(){e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),g?.release(),p=void 0,await d.dispose()}}}var E4="This is evidence, not a verdict — a hard task looks like this too. Look at what the expert has actually changed before you act on it. If you decide it is going nowhere, `escalate` with `message` and say so, or tell it to stop.";function KMe(e){return`The expert is repeating itself. ${e}
1246
+ They said: ${X}`:""),opened:!1,closed:!0,followUpsLeft:0,escalationsLeft:d.remaining}}}let K=e.takeSteering?.(),V=K?D+u(K):D,B=d.begin();if(s=W,e.logger?.log?.(`[Escalation] Escalation ${W} of ${n}: handing over to the expert`),e.onEvent?.({type:"escalation_started",index:W,of:n,brief:D}),g)return b(async()=>{let z=await B.ask(V);return{text:z.text,usage:z.usage}}),{reply:v(W),opened:!0,handedOver:!0,followUpsLeft:r,escalationsLeft:d.remaining};let j;try{j=await c(async()=>{let z=await B.ask(V);return{text:z.text,usage:z.usage}})}catch(z){if(B.deliveries===0)await d.refund();throw z}if(e.onEvent?.({type:"expert_replied",reply:j.text,changed:j.changed,usage:j.usage}),A.finished)await d.end(),e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),e.onEvent?.({type:"escalation_ended",held:t?.closeAfterEscalation!==!0,usage:d.usage});let G=e.takeSteering?.();return{reply:j.text+h(j.changed)+(G?u(G):""),opened:!0,...A.finished?{closed:!0}:{},followUpsLeft:r,escalationsLeft:d.remaining}},T=t?.connection?[rj({consult:x,onError:(A,R)=>e.logger?.log?.(`${A}: ${String(R)}`)}),...g?[k6({collect:S,onError:(A,R)=>e.logger?.log?.(`${A}: ${String(R)}`)})]:[]]:[];return{tools:T,get used(){return d.used},get remaining(){return T.length===0?0:Math.max(0,n-d.used)},get usage(){return d.usage},async restore(){return l?await i(l):void 0},async dispose(){e.revisions?.purge(),e.guards?.reset(),e.mailbox?.clear(),g?.release(),p=void 0,await d.dispose()}}}var E6="This is evidence, not a verdict — a hard task looks like this too. Look at what the expert has actually changed before you act on it. If you decide it is going nowhere, `escalate` with `message` and say so, or tell it to stop.";function KMe(e){return`The expert is repeating itself. ${e}
1247
1247
 
1248
- ${E4}`}function _4(e){return`The expert's run has the shape of a stuck one. ${e}
1248
+ ${E6}`}function _6(e){return`The expert's run has the shape of a stuck one. ${e}
1249
1249
 
1250
- ${E4}`}function A4(e){let t=new Hd,n=new Yi(e.thresholds),r=wa(n,(i)=>{if(i.message)e.onVerdict({kind:"struggle",text:_4(i.message)})}),o=new Set;return{observe(i){if(r.observe(i),i.type!=="content_start"||i.contentType!=="tool"||!i.toolName)return;let s=t.inspect({name:i.toolName,input:i.input});if(s.kind==="ok"||!s.message)return;let a=`${s.kind}:${i.toolName}`;if(o.has(a))return;o.add(a),e.onVerdict({kind:"loop",text:KMe(s.message)})},reset(){t=new Hd,n=new Yi(e.thresholds),r=wa(n,(i)=>{if(i.message)e.onVerdict({kind:"struggle",text:_4(i.message)})}),o=new Set}}}function R4(){let e=[];return{send(t){let n=t.trim();if(n)e.push(n)},take(){if(e.length===0)return;return`== FROM THE MODEL SUPERVISING YOU, JUST NOW ==
1250
+ ${E6}`}function A6(e){let t=new Hd,n=new Yi(e.thresholds),r=wa(n,(i)=>{if(i.message)e.onVerdict({kind:"struggle",text:_6(i.message)})}),o=new Set;return{observe(i){if(r.observe(i),i.type!=="content_start"||i.contentType!=="tool"||!i.toolName)return;let s=t.inspect({name:i.toolName,input:i.input});if(s.kind==="ok"||!s.message)return;let a=`${s.kind}:${i.toolName}`;if(o.has(a))return;o.add(a),e.onVerdict({kind:"loop",text:KMe(s.message)})},reset(){t=new Hd,n=new Yi(e.thresholds),r=wa(n,(i)=>{if(i.message)e.onVerdict({kind:"struggle",text:_6(i.message)})}),o=new Set}}}function R6(){let e=[];return{send(t){let n=t.trim();if(n)e.push(n)},take(){if(e.length===0)return;return`== FROM THE MODEL SUPERVISING YOU, JUST NOW ==
1251
1251
 
1252
1252
  ${e.splice(0,e.length).join(`
1253
1253
 
1254
- `)}`},clear(){e.length=0}}}var GMe=30000;function VMe(e){return e!=="working"&&e!=="submitted"}function YMe(e){let t=e.count>1?` — ${e.count} calls`:"",n=e.files.length?` — ${e.files.map((o)=>`${o.path} (#${o.revision})`).join(", ")}`:"",r=e.error?` — failed: ${e.error}`:"";return`${e.tool??"a tool"}${t}${n}${r}`}function XMe(e){if(e.kind==="tool")return YMe(e);if(e.kind==="guard")return`[guard] ${e.text??""}`.trimEnd();return`The expert said: ${e.text??""}`.trimEnd()}function I4(e={}){let t=e.intervalMs??GMe,n=e.now??(()=>Date.now()),r=[],o="submitted",i=n(),s=!1,a=!1,d=(c,u,h)=>c.kind==="tool"&&c.tool===u&&!h&&c.files.length===0&&c.error===void 0,l=()=>a||r.some((c)=>c.kind==="message"||c.kind==="guard");return{noteTool(c){let u=[...c.files??[]],h=u.length>0||c.error!==void 0,p=r[r.length-1];if(p&&d(p,c.tool,h)){p.count+=1;return}r.push({kind:"tool",tool:c.tool,count:1,files:u,...c.error!==void 0?{error:c.error}:{}})},noteMessage(c){let u=c.trim();if(u)r.push({kind:"message",text:u,count:1,files:[]})},noteGuard(c){let u=c.trim();if(u)r.push({kind:"guard",text:u,count:1,files:[]})},setState(c){if(c===o)return;if(o=c,VMe(c))a=!0},get state(){return o},get pending(){return r.length},due(){if(s)return!1;if(l())return!0;if(r.length===0)return!1;return n()-i>=t},take(){if(!this.due())return;let c=r.splice(0,r.length);i=n(),a=!1;let u=u4(o);if(u)s=!0;let h=c.map(XMe),p=[h4(h.length?h.join(`
1255
- `):`The expert's task is ${o}.`),p4({state:o,final:u,notes:c.map((f)=>({kind:f.kind,...f.tool?{tool:f.tool}:{},...f.text?{text:f.text}:{},count:f.count,...f.files.length?{files:f.files}:{},...f.error!==void 0?{error:f.error}:{}}))})];return{state:o,final:u,notes:c,parts:p}}}}function C4(e,t){let n=(o)=>t.relative?.(o)??o,r=(o,i)=>{let s=[];for(let[a,d]of i)if((o.get(a)??0)<d)s.push({path:n(a),revision:d});return s.sort((a,d)=>a.path.localeCompare(d.path))};return e.map((o)=>{let i=o;return{...o,execute:async(s,a)=>{let d=new Map(t.heads());try{let l=await i.execute?.(s,a);return t.notes.noteTool({tool:o.name,files:r(d,t.heads())}),l}catch(l){throw t.notes.noteTool({tool:o.name,files:r(d,t.heads()),error:l instanceof Error?l.message:String(l)}),l}}}})}function P4(e){let t=["You are the expert on an escalation.","","Another model — not a user — is working on a task, has got stuck, and has handed it to you. It has the same tools you do and it is working in the same workspace. It escalated because you are the more capable model here, and because escalating costs its task something: a budget of escalations, and, where this endpoint is metered, real money. Treat the call as one that had to be justified.","","You can edit the workspace directly, and you should: what you hand back is the change, not a description of one. A suggested patch in a code block is the thing escalation exists to avoid — the model that asked you is stuck precisely at turning an idea into a working edit. Your tool calls go through the same approval rules as the session's own, so anything it would have been asked about, you will be asked about.","","Work from the brief you are given. It carries the task, the goal, the standard you will be held to and what has already been tried and rolled back; re-deriving that by reading the whole workspace spends the call on what you were already told. Read the code, by all means — read anything the brief points at — but read it to check the brief, not to replace it.","","When you deliver, the model that asked will check your work against what it asked for and push back if it does not hold. That is the arrangement, not a complaint: answer the objection it actually raises. If it is wrong, say so and say why — it is not your supervisor, and a delivery you have abandoned because you were challenged is worse than the disagreement."];if(e.workspaceRoot?.trim())t.push("",`The workspace root is ${e.workspaceRoot.trim()}. Paths in the brief are relative to it.`);if(e.sessionInstructions?.trim())t.push("","== THE RULES THIS WORKSPACE IS WORKED UNDER ==","","These are the session's own instructions. They apply to your edits exactly as they apply to the model that asked you.","",e.sessionInstructions.trim());return`${t.join(`
1254
+ `)}`},clear(){e.length=0}}}var GMe=30000;function VMe(e){return e!=="working"&&e!=="submitted"}function YMe(e){let t=e.count>1?` — ${e.count} calls`:"",n=e.files.length?` — ${e.files.map((o)=>`${o.path} (#${o.revision})`).join(", ")}`:"",r=e.error?` — failed: ${e.error}`:"";return`${e.tool??"a tool"}${t}${n}${r}`}function XMe(e){if(e.kind==="tool")return YMe(e);if(e.kind==="guard")return`[guard] ${e.text??""}`.trimEnd();return`The expert said: ${e.text??""}`.trimEnd()}function I6(e={}){let t=e.intervalMs??GMe,n=e.now??(()=>Date.now()),r=[],o="submitted",i=n(),s=!1,a=!1,d=(c,u,h)=>c.kind==="tool"&&c.tool===u&&!h&&c.files.length===0&&c.error===void 0,l=()=>a||r.some((c)=>c.kind==="message"||c.kind==="guard");return{noteTool(c){let u=[...c.files??[]],h=u.length>0||c.error!==void 0,p=r[r.length-1];if(p&&d(p,c.tool,h)){p.count+=1;return}r.push({kind:"tool",tool:c.tool,count:1,files:u,...c.error!==void 0?{error:c.error}:{}})},noteMessage(c){let u=c.trim();if(u)r.push({kind:"message",text:u,count:1,files:[]})},noteGuard(c){let u=c.trim();if(u)r.push({kind:"guard",text:u,count:1,files:[]})},setState(c){if(c===o)return;if(o=c,VMe(c))a=!0},get state(){return o},get pending(){return r.length},due(){if(s)return!1;if(l())return!0;if(r.length===0)return!1;return n()-i>=t},take(){if(!this.due())return;let c=r.splice(0,r.length);i=n(),a=!1;let u=u6(o);if(u)s=!0;let h=c.map(XMe),p=[h6(h.length?h.join(`
1255
+ `):`The expert's task is ${o}.`),p6({state:o,final:u,notes:c.map((f)=>({kind:f.kind,...f.tool?{tool:f.tool}:{},...f.text?{text:f.text}:{},count:f.count,...f.files.length?{files:f.files}:{},...f.error!==void 0?{error:f.error}:{}}))})];return{state:o,final:u,notes:c,parts:p}}}}function C6(e,t){let n=(o)=>t.relative?.(o)??o,r=(o,i)=>{let s=[];for(let[a,d]of i)if((o.get(a)??0)<d)s.push({path:n(a),revision:d});return s.sort((a,d)=>a.path.localeCompare(d.path))};return e.map((o)=>{let i=o;return{...o,execute:async(s,a)=>{let d=new Map(t.heads());try{let l=await i.execute?.(s,a);return t.notes.noteTool({tool:o.name,files:r(d,t.heads())}),l}catch(l){throw t.notes.noteTool({tool:o.name,files:r(d,t.heads()),error:l instanceof Error?l.message:String(l)}),l}}}})}function P6(e){let t=["You are the expert on an escalation.","","Another model — not a user — is working on a task, has got stuck, and has handed it to you. It has the same tools you do and it is working in the same workspace. It escalated because you are the more capable model here, and because escalating costs its task something: a budget of escalations, and, where this endpoint is metered, real money. Treat the call as one that had to be justified.","","You can edit the workspace directly, and you should: what you hand back is the change, not a description of one. A suggested patch in a code block is the thing escalation exists to avoid — the model that asked you is stuck precisely at turning an idea into a working edit. Your tool calls go through the same approval rules as the session's own, so anything it would have been asked about, you will be asked about.","","Work from the brief you are given. It carries the task, the goal, the standard you will be held to and what has already been tried and rolled back; re-deriving that by reading the whole workspace spends the call on what you were already told. Read the code, by all means — read anything the brief points at — but read it to check the brief, not to replace it.","","When you deliver, the model that asked will check your work against what it asked for and push back if it does not hold. That is the arrangement, not a complaint: answer the objection it actually raises. If it is wrong, say so and say why — it is not your supervisor, and a delivery you have abandoned because you were challenged is worse than the disagreement."];if(e.workspaceRoot?.trim())t.push("",`The workspace root is ${e.workspaceRoot.trim()}. Paths in the brief are relative to it.`);if(e.sessionInstructions?.trim())t.push("","== THE RULES THIS WORKSPACE IS WORKED UNDER ==","","These are the session's own instructions. They apply to your edits exactly as they apply to the model that asked you.","",e.sessionInstructions.trim());return`${t.join(`
1256
1256
  `).replace(/\n{3,}/g,`
1257
1257
 
1258
1258
  `).trimEnd()}
1259
- `}function M4(){let e=ss(),t,n=0;return{source:{get pending(){return t},get transaction(){return n},get log(){return e}},open(o,i){e=ss(),t=o,n=i},revisions(o){return e.revisions(o)},tracked(){return e.tracked()},heads(){let o=new Map;for(let i of e.tracked()){let s=e.revisions(i),a=s[s.length-1];if(a)o.set(i,a.index)}return o},purge(){e.reset(),e=ss(),t=void 0,n=0}}}function O4(e,t){let n,r=()=>({subAgentId:e.getAgentId(),conversationId:e.getConversationId(),parentAgentId:"lead",input:{name:"expert",task:n??""}}),o=async(i)=>{try{await i()}catch{}};return{async run(i){if(n===void 0)n=i,await o(()=>t.start(r()));try{let s=await e.run(i);return await o(()=>t.end({...r(),agentResult:s})),s}catch(s){throw await o(()=>t.end({...r(),agentResult:{messages:e.getMessages()},error:s instanceof Error?s:Error(String(s))})),s}},...e.shutdown?{shutdown:(i)=>e.shutdown?.(i)}:{},...e.abort?{abort:(i)=>e.abort?.(i)}:{}}}function JMe(e){return[`${e.guard} was about to end this run.${e.diagnosis?` ${e.diagnosis}`:""}`,"",`Instead you get one turn, and one thing to do with it: call \`${Pr}\` and hand this to the expert. Write the brief properly — what you were trying, what you ruled out, and what a correct result looks like — because that is all it gets. You have ${e.remaining} escalation${e.remaining===1?"":"s"} left.`,"","If this turn goes anywhere else, the run ends at the end of it. That is not a threat, it is the guard that was already firing: nothing here has been taken off the table, it has only been held open for one turn."].join(`
1260
- `)}function QMe(e){return`${e} ended this run. It stood down for one turn so the task could be handed to the expert, and that turn was spent on something else.`}function L4(e){let t=!1,n,r="",o=0;return{get spent(){return t},decide(i){if(t)return;let s=e.remaining();if(s<=0)return;return t=!0,n=o,r=i.guard,e.logger?.log?.(`[Escalation] ${i.guard} stood down for one turn; the expert can be handed the task.`),{action:"continue",guidance:JMe({guard:i.guard,...i.diagnosis?{diagnosis:i.diagnosis}:{},remaining:s})}},observe(i){switch(i.type){case"iteration_start":o=i.iteration;return;case"content_start":if(i.contentType==="tool"&&i.toolName===Pr)n=void 0;return;case"iteration_end":{if(n===void 0||i.iteration<=n)return;let s=r;n=void 0,e.stop(QMe(s));return}default:return}}}}import{tmpdir as HNe}from"node:os";import{join as WNe}from"node:path";import{DEFAULT_MAX_NO_TOOL_CALL_NUDGES as jNe,setToolIntentGuardEnabled as qNe}from"@cerebriline/agents";import{supportsModelTool as wV}from"@cerebriline/llms";import{hasRuntimeConfigExtension as zNe,resolveMcpTimeoutSeconds as KNe}from"@cerebriline/shared";import{nanoid as GNe}from"nanoid";import{isPromptTemplateCompactionId as nat,splitFrontmatter as rat,validatePromptTemplate as oat}from"@cerebriline/shared";import sat from"yaml";import{existsSync as sC}from"node:fs";import{dirname as dC,isAbsolute as ZMe,join as Jb,relative as eOe,resolve as N4}from"node:path";import{fileURLToPath as tOe}from"node:url";var lC="bundled-skills";function nOe(){try{return dC(tOe(import.meta.url))}catch{return"."}}var aC;function Qb(e=nOe()){if(aC?.from===e)return aC.directory;let t,n=[Jb(e,lC),Jb(dC(process.execPath),lC)].find((r)=>sC(r));if(n)t=n;else{let r=e;for(let o=0;o<7;o++){let i=Jb(r,"assets","skills");if(sC(i)&&sC(Jb(r,"package.json"))){t=i;break}let s=dC(r);if(s===r)break;r=s}}return aC={from:e,directory:t},t}function cC(e,t=Qb()){if(!t)return!1;let n=eOe(N4(t),N4(e));return n!==""&&!n.startsWith("..")&&!ZMe(n)}function D4(e){return e.trim().toLowerCase()}function $4(e,t){return fn().bundledSkills?.[D4(e)]?.enabled??t}function Zb(e,t){let n=fn();ka({...n,bundledSkills:{...n.bundledSkills,[D4(e)]:{enabled:t}}})}import{PROMPT_TEMPLATE_COMPACTION_IDS as wat}from"@cerebriline/shared";import{applyPromptTemplateToTools as _at}from"@cerebriline/shared";import{DEFAULT_PROMPT_TEMPLATE_NAME as Dat,PROMPT_TEMPLATE_DEFAULT_MARKER as $at,promptTemplateMatchBlocks as Fat,resolvePromptTemplate as Uat}from"@cerebriline/shared";import{primeDeclaredNumCtx as Kat,readDeclaredFamily as Gat}from"@cerebriline/llms";import{isOllamaNativeProvider as Yat,renderPromptTemplate as Xat}from"@cerebriline/shared";import{createTool as adt}from"@cerebriline/shared";import{createTool as ndt}from"@cerebriline/shared";import{createTool as Odt}from"@cerebriline/shared";import{createTool as hdt}from"@cerebriline/shared";import{createTool as wdt}from"@cerebriline/shared";import{createTool as Wdt}from"@cerebriline/shared";import{createTool as Gdt}from"@cerebriline/shared";import{createTool as Xdt}from"@cerebriline/shared";import{createHash as cOe}from"node:crypto";import{watch as uOe}from"node:fs";import{readdir as hOe,readFile as pOe}from"node:fs/promises";import{isAbsolute as mOe,join as fOe,relative as gOe,resolve as H4}from"node:path";function yOe(e){return cOe("sha1").update(e).digest("hex")}function q4(e){return Boolean(e&&typeof e==="object"&&"code"in e)}function W4(e){return q4(e)&&e.code==="ENOENT"}function j4(e){return q4(e)&&(e.code==="EACCES"||e.code==="EPERM")}class tv{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;unwatchedRoots=new Set;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(e,t){if(e.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=e,this.debounceMs=t?.debounceMs??75,this.emitParseErrors=t?.emitParseErrors??!1;for(let n of e){if(this.definitionsByType.has(n.type))throw Error(`Duplicate unified config definition type '${n.type}'.`);this.definitionsByType.set(n.type,n),this.recordsByType.set(n.type,new Map),this.discoveredDirectoriesByType.set(n.type,new Set);for(let r of n.unwatchedDirectories??[])this.unwatchedRoots.add(H4(r));for(let r of n.directories){let o=this.baseTypesByDirectory.get(r);if(o)o.add(n.type);else this.baseTypesByDirectory.set(r,new Set([n.type]))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let e of this.watchersByDirectory.values())e.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let e of this.definitions)await this.refreshTypeInternal(e)})}async refreshType(e){let t=this.definitionsByType.get(e);if(!t)throw Error(`Unknown unified config type '${e}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(t)})}getSnapshot(e){let t=this.recordsByType.get(e);return new Map([...t?.entries()??[]].map(([n,r])=>[n,{...r}]))}getAllSnapshots(){let e=new Map;for(let[t,n]of this.recordsByType.entries())e.set(t,new Map([...n.entries()].map(([r,o])=>[r,{...o}])));return e}emit(e){for(let t of this.listeners)t(e)}enqueueRefresh(e){return this.refreshQueue=this.refreshQueue.then(e,e),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let e=this.buildDesiredTypesByDirectory();for(let[t,n]of this.watchersByDirectory.entries()){if(e.has(t))continue;n.close(),this.watchersByDirectory.delete(t)}this.watchedTypesByDirectory=e;for(let t of e.keys()){if(this.watchersByDirectory.has(t))continue;try{let n=uOe(t,()=>{let r=this.watchedTypesByDirectory.get(t);if(!r)return;for(let o of r)this.pendingTypes.add(o);this.scheduleFlush()});this.watchersByDirectory.set(t,n),n.on("error",(r)=>{let o=this.watchedTypesByDirectory.get(t);if(!o)return;for(let i of o)this.emit({kind:"error",type:i,error:r,filePath:t})})}catch(n){if(!W4(n)&&!j4(n)){let r=e.get(t);if(!r)continue;for(let o of r)this.emit({kind:"error",type:o,error:n,filePath:t})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let e=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let t of e){let n=this.definitionsByType.get(t);if(!n)continue;await this.refreshTypeInternal(n)}})},this.debounceMs)}async refreshTypeInternal(e){let{records:t,discoveredDirectories:n}=await this.loadDefinition(e),r=this.recordsByType.get(e.type)??new Map;for(let[o,i]of r.entries()){if(t.has(o))continue;this.emit({kind:"remove",type:e.type,id:o,filePath:i.filePath})}for(let[o,i]of t.entries()){let s=r.get(o);if(s&&s.filePath===i.filePath&&s.fingerprint===i.fingerprint)continue;this.emit({kind:"upsert",record:{type:i.type,id:o,item:i.item,filePath:i.filePath}})}if(this.recordsByType.set(e.type,t),this.discoveredDirectoriesByType.set(e.type,n),this.started)this.syncDirectoryWatchers()}async loadDefinition(e){let t=new Map,n=new Set;for(let r of e.directories){n.add(r);let o=e.discoverFiles?await e.discoverFiles(r):await this.readDirectoryFileCandidates(r);for(let i of o){let{fileName:s,filePath:a}=i;if(n.add(i.directoryPath),e.includeFile&&!e.includeFile(s,a))continue;try{let d=await pOe(a,"utf8"),l={type:e.type,directoryPath:i.directoryPath,fileName:s,filePath:a,content:d},c=e.parseFile(l),u=e.resolveId(c,l).trim();if(!u)continue;t.set(u,{type:e.type,id:u,item:c,filePath:a,fingerprint:yOe(d)})}catch(d){if(this.emitParseErrors)this.emit({kind:"error",type:e.type,error:d,filePath:a})}}}return{records:t,discoveredDirectories:n}}isUnwatched(e){if(this.unwatchedRoots.size===0)return!1;let t=H4(e);for(let n of this.unwatchedRoots){let r=gOe(n,t);if(r===""||!r.startsWith("..")&&!mOe(r))return!0}return!1}buildDesiredTypesByDirectory(){let e=new Map;for(let[t,n]of this.baseTypesByDirectory.entries()){if(this.isUnwatched(t))continue;e.set(t,new Set(n))}for(let[t,n]of this.discoveredDirectoriesByType.entries())for(let r of n){if(this.isUnwatched(r))continue;let o=e.get(r);if(o)o.add(t);else e.set(r,new Set([t]))}return e}async readDirectoryFileCandidates(e){try{return(await hOe(e,{withFileTypes:!0})).filter((n)=>n.isFile()).map((n)=>({directoryPath:e,fileName:n.name,filePath:fOe(e,n.name)})).sort((n,r)=>n.fileName.localeCompare(r.fileName))}catch(t){if(W4(t)||j4(t))return[];throw t}}}import{readdir as mC,readFile as wOe,realpath as pC,stat as Jp}from"node:fs/promises";import{basename as gi,dirname as bOe,extname as nv,isAbsolute as vOe,join as Xn,relative as kOe,resolve as fi}from"node:path";import{stripUtf8Bom as TOe}from"@cerebriline/shared";import{AGENTS_RULES_FILE_NAME as z4,RULES_CONFIG_DIRECTORY_NAME as SOe,resolveGlobalAgentsRulesPath as xOe,resolveRulesConfigSearchPaths as _Oe,resolveSkillsConfigSearchPaths as EOe,resolveWorkflowsConfigSearchPaths as AOe,SKILLS_CONFIG_DIRECTORY_NAME as G4,WORKFLOWS_CONFIG_DIRECTORY_NAME as V4}from"@cerebriline/shared/storage";import ROe from"yaml";var Yp="SKILL.md",IOe="managed.json",COe=new Set([".md",".markdown",".txt"]);function Xp(e){return e.trim().toLowerCase()}function Ha(e){let t=e;return t?.code==="ENOENT"||t?.code==="ENOTDIR"||t?.code==="EACCES"||t?.code==="EPERM"||t?.code==="ELOOP"}function rv(e){return COe.has(nv(e).toLowerCase())}function Y4(e){let t=[],n=new Set;for(let r of e){let o=fi(r);if(n.has(o))continue;n.add(o),t.push(r)}return t}function X4(e){if(e?.directories||e?.bundledSkillsDirectory===!1)return;return e?.bundledSkillsDirectory??Qb()}function POe(e){let t=e.disabled!==!0,n={...e,bundled:!0};return Object.defineProperty(n,"disabled",{enumerable:!0,get:()=>$4(e.name,t)?void 0:!0}),n}function MOe(e){let t=[...e?.directories??e8(e?.workspacePath)],n=X4(e);if(n)t.unshift(n);if(e?.pluginSkillDirectories)t.push(...e.pluginSkillDirectories);else if(e?.includePluginSkills)t.push(...JG({pluginPaths:e.pluginPaths,workspacePath:e.workspacePath,cwd:e.cwd??e.workspacePath}));if(e?.agentPluginSkills)t.push(...e.agentPluginSkills.map((r)=>r.directoryPath));return Y4(t)}function K4(e,t){let n=kOe(e,t);return n===""||!n.startsWith("..")&&!vOe(n)}async function OOe(e){try{let[t,n,r]=await Promise.all([pC(e.pluginRoot),pC(e.directoryPath),pC(e.filePath)]);if(t!==fi(e.pluginRoot)||!K4(t,n)||!K4(t,r)||!(await Jp(n)).isDirectory()||!(await Jp(r)).isFile())return[];return[{directoryPath:e.directoryPath,fileName:Yp,filePath:r}]}catch(t){if(Ha(t))return[];throw t}}async function fC(e){try{let t=await mC(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=Xn(e,r.name),i=Xn(o,IOe);try{let s=await wOe(i,"utf8"),a=JSON.parse(s);if(a&&typeof a==="object")n.push(o)}catch(s){if(Ha(s))continue;if(s?.name==="SyntaxError")continue;throw s}}return n.sort((r,o)=>r.localeCompare(o))}catch(t){if(Ha(t))return[];throw t}}function gC(e){let t=TOe(e),n=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,r=t.match(n);if(!r)return{data:{},body:t,hadFrontmatter:!1};let[,o,i]=r;try{let s=ROe.parse(o);return{data:s&&typeof s==="object"&&!Array.isArray(s)?s:{},body:i,hadFrontmatter:!0}}catch(s){let a=s instanceof Error?s.message:String(s);return{data:{},body:t,hadFrontmatter:!0,parseError:a}}}function ov(e,t,n){if(e===void 0||e===null){if(n)throw Error(`Missing required frontmatter field '${t}'.`);return}if(typeof e!=="string")throw Error(`Frontmatter field '${t}' must be a string.`);let r=e.trim();if(!r&&n)throw Error(`Frontmatter field '${t}' cannot be empty.`);return r||void 0}function Oc(e,t){if(e===void 0||e===null)return;if(typeof e!=="boolean")throw Error(`Frontmatter field '${t}' must be a boolean.`);return e}function LOe(e,t){if(gi(e.filePath).toLowerCase()!==z4.toLowerCase())return gi(e.filePath,nv(e.filePath));if(t&&fi(e.filePath)===fi(t,z4))return"Workspace AGENTS.md";if(fi(e.filePath)===fi(xOe()))return"Global AGENTS.md";return gi(e.filePath,nv(e.filePath))}function J4(e,t){let{data:n,body:r,parseError:o}=gC(e);if(o)throw Error(`Failed to parse YAML frontmatter: ${o}`);let i=r.trim();if(!i)throw Error("Missing instructions body in skill file.");let a=ov(n.name,"name",!1)??t.trim();if(!a)throw Error("Missing skill name.");return{name:a,description:ov(n.description,"description",!1),disabled:Oc(n.disabled,"disabled")??(Oc(n.enabled,"enabled")===!1?!0:void 0),instructions:i,frontmatter:n}}function Q4(e,t){let{data:n,body:r,parseError:o}=gC(e);if(o)throw Error(`Failed to parse YAML frontmatter: ${o}`);let i=r.trim();if(!i)throw Error("Missing instructions body in rule file.");let s=ov(n.name,"name",!1)??t.trim();if(!s)throw Error("Missing rule name.");return{name:s,disabled:Oc(n.disabled,"disabled")??(Oc(n.enabled,"enabled")===!1?!0:void 0),instructions:i,frontmatter:n}}function Z4(e,t){let{data:n,body:r,parseError:o}=gC(e);if(o)throw Error(`Failed to parse YAML frontmatter: ${o}`);let i=r.trim();if(!i)throw Error("Missing instructions body in workflow file.");let s=ov(n.name,"name",!1)??t.trim();if(!s)throw Error("Missing workflow name.");return{name:s,disabled:Oc(n.disabled,"disabled")??(Oc(n.enabled,"enabled")===!1?!0:void 0),instructions:i,frontmatter:n}}function e8(e){return EOe(e)}function t8(e){return _Oe(e)}function n8(e){return AOe(e)}async function r8(e){if(gi(e)===".cline"){let t=await fC(e);return(await Promise.all(t.map((r)=>r8(Xn(r,G4))))).flat()}try{let t=await mC(e,{withFileTypes:!0}),n=[];for(let r of t){if(r.isFile()&&r.name===Yp){n.push({directoryPath:e,fileName:r.name,filePath:Xn(e,r.name)});continue}let o=Xn(e,r.name);if(r.isDirectory()||r.isSymbolicLink()&&await Jp(o).then((s)=>s.isDirectory()).catch((s)=>{if(Ha(s))return!1;throw s}))n.push({directoryPath:o,fileName:Yp,filePath:Xn(o,Yp)})}return n}catch(t){if(Ha(t))return[];throw t}}async function iv(e){if(gi(e)===".cline"){let t=await fC(e);return(await Promise.all(t.map((r)=>iv(Xn(r,"rules.md"))))).flat()}try{if((await Jp(e)).isFile())return[{directoryPath:bOe(e),fileName:gi(e),filePath:e}]}catch(t){if(!Ha(t))throw t}try{let n=(await mC(e,{withFileTypes:!0})).filter((o)=>o.isFile()&&rv(o.name)).map((o)=>({directoryPath:e,fileName:o.name,filePath:Xn(e,o.name)})),r=Xn(e,"AGENTS.md");try{if((await Jp(r)).isFile()){if(!n.some((s)=>s.fileName==="AGENTS.md"))n.push({directoryPath:e,fileName:"AGENTS.md",filePath:r})}}catch{}return n}catch(t){if(Ha(t))return[];throw t}}async function NOe(e){if(gi(e)===".cline"){let t=await fC(e);return(await Promise.all(t.map((r)=>iv(Xn(r,V4))))).flat()}return iv(e)}function o8(e){let t=MOe(e),n=X4(e),r=new Map((e?.agentPluginSkills??[]).map((i)=>[fi(i.directoryPath),i])),o=e?.workspacePath?Xn(e.workspacePath,".cline"):void 0;return{type:"skill",directories:o?Y4([...t,o]):t,...n?{unwatchedDirectories:[n]}:{},discoverFiles:(i)=>{let s=r.get(fi(i));return s?OOe(s):r8(i)},includeFile:(i)=>i===Yp,parseFile:(i)=>{let s=r.get(fi(i.directoryPath));if(!s){let d=J4(i.content,gi(i.directoryPath));if(!cC(i.filePath,n))return d;return POe(d)}let a=wp(i.content,s.metadata.name);return{name:a.metadata.name,description:a.metadata.description,instructions:a.instructions,frontmatter:a.frontmatter,source:{type:"agent-plugin",pluginName:s.pluginName,pluginRoot:s.pluginRoot,skillRoot:s.directoryPath,filePath:s.filePath}}},resolveId:(i)=>i.source?.type==="agent-plugin"?`${Xp(i.source.pluginName)}:${Xp(i.name)}`:Xp(i.name)}}function i8(e){let t=e?.directories??t8(e?.workspacePath),n=e?.workspacePath?Xn(e.workspacePath,".cline"):void 0;return{type:"rule",directories:n?[...t,n]:t,discoverFiles:iv,includeFile:(r,o)=>r===".clinerules"||rv(r)||rv(o),parseFile:(r)=>Q4(r.content,LOe(r,e?.workspacePath)),resolveId:(r)=>Xp(r.name)}}function s8(e){let t=e?.directories??n8(e?.workspacePath),n=e?.workspacePath?Xn(e.workspacePath,".cline"):void 0;return{type:"workflow",directories:n?[...t,n]:t,discoverFiles:NOe,includeFile:(r)=>rv(r),parseFile:(r)=>Z4(r.content,gi(r.filePath,nv(r.filePath))),resolveId:(r)=>Xp(r.name)}}function a8(e){let t=[o8(e?.skills),i8(e?.rules),s8(e?.workflows)];return new tv(t,{debounceMs:e?.debounceMs,emitParseErrors:e?.emitParseErrors})}function DOe(e){return e.disabled!==!0}function d8(e){if(e.length===0)return"";return`
1259
+ `}function M6(){let e=ss(),t,n=0;return{source:{get pending(){return t},get transaction(){return n},get log(){return e}},open(o,i){e=ss(),t=o,n=i},revisions(o){return e.revisions(o)},tracked(){return e.tracked()},heads(){let o=new Map;for(let i of e.tracked()){let s=e.revisions(i),a=s[s.length-1];if(a)o.set(i,a.index)}return o},purge(){e.reset(),e=ss(),t=void 0,n=0}}}function O6(e,t){let n,r=()=>({subAgentId:e.getAgentId(),conversationId:e.getConversationId(),parentAgentId:"lead",input:{name:"expert",task:n??""}}),o=async(i)=>{try{await i()}catch{}};return{async run(i){if(n===void 0)n=i,await o(()=>t.start(r()));try{let s=await e.run(i);return await o(()=>t.end({...r(),agentResult:s})),s}catch(s){throw await o(()=>t.end({...r(),agentResult:{messages:e.getMessages()},error:s instanceof Error?s:Error(String(s))})),s}},...e.shutdown?{shutdown:(i)=>e.shutdown?.(i)}:{},...e.abort?{abort:(i)=>e.abort?.(i)}:{}}}function JMe(e){return[`${e.guard} was about to end this run.${e.diagnosis?` ${e.diagnosis}`:""}`,"",`Instead you get one turn, and one thing to do with it: call \`${Pr}\` and hand this to the expert. Write the brief properly — what you were trying, what you ruled out, and what a correct result looks like — because that is all it gets. You have ${e.remaining} escalation${e.remaining===1?"":"s"} left.`,"","If this turn goes anywhere else, the run ends at the end of it. That is not a threat, it is the guard that was already firing: nothing here has been taken off the table, it has only been held open for one turn."].join(`
1260
+ `)}function QMe(e){return`${e} ended this run. It stood down for one turn so the task could be handed to the expert, and that turn was spent on something else.`}function L6(e){let t=!1,n,r="",o=0;return{get spent(){return t},decide(i){if(t)return;let s=e.remaining();if(s<=0)return;return t=!0,n=o,r=i.guard,e.logger?.log?.(`[Escalation] ${i.guard} stood down for one turn; the expert can be handed the task.`),{action:"continue",guidance:JMe({guard:i.guard,...i.diagnosis?{diagnosis:i.diagnosis}:{},remaining:s})}},observe(i){switch(i.type){case"iteration_start":o=i.iteration;return;case"content_start":if(i.contentType==="tool"&&i.toolName===Pr)n=void 0;return;case"iteration_end":{if(n===void 0||i.iteration<=n)return;let s=r;n=void 0,e.stop(QMe(s));return}default:return}}}}import{tmpdir as HNe}from"node:os";import{join as WNe}from"node:path";import{DEFAULT_MAX_NO_TOOL_CALL_NUDGES as jNe,setToolIntentGuardEnabled as qNe}from"@cerebriline/agents";import{supportsModelTool as wV}from"@cerebriline/llms";import{hasRuntimeConfigExtension as zNe,resolveMcpTimeoutSeconds as KNe}from"@cerebriline/shared";import{nanoid as GNe}from"nanoid";import{isPromptTemplateCompactionId as iat,splitFrontmatter as sat,validatePromptTemplate as aat}from"@cerebriline/shared";import lat from"yaml";import{existsSync as sC}from"node:fs";import{dirname as dC,isAbsolute as ZMe,join as Jb,relative as eOe,resolve as N6}from"node:path";import{fileURLToPath as tOe}from"node:url";var lC="bundled-skills";function nOe(){try{return dC(tOe(import.meta.url))}catch{return"."}}var aC;function Qb(e=nOe()){if(aC?.from===e)return aC.directory;let t,n=[Jb(e,lC),Jb(dC(process.execPath),lC)].find((r)=>sC(r));if(n)t=n;else{let r=e;for(let o=0;o<7;o++){let i=Jb(r,"assets","skills");if(sC(i)&&sC(Jb(r,"package.json"))){t=i;break}let s=dC(r);if(s===r)break;r=s}}return aC={from:e,directory:t},t}function cC(e,t=Qb()){if(!t)return!1;let n=eOe(N6(t),N6(e));return n!==""&&!n.startsWith("..")&&!ZMe(n)}function D6(e){return e.trim().toLowerCase()}function $6(e,t){return fn().bundledSkills?.[D6(e)]?.enabled??t}function Zb(e,t){let n=fn();ka({...n,bundledSkills:{...n.bundledSkills,[D6(e)]:{enabled:t}}})}import{PROMPT_TEMPLATE_COMPACTION_IDS as kat}from"@cerebriline/shared";import{applyPromptTemplateToTools as Rat}from"@cerebriline/shared";import{DEFAULT_PROMPT_TEMPLATE_NAME as Uat,PROMPT_TEMPLATE_DEFAULT_MARKER as Bat,promptTemplateMatchBlocks as Hat,resolvePromptTemplate as Wat}from"@cerebriline/shared";import{primeDeclaredNumCtx as Yat,readDeclaredFamily as Xat}from"@cerebriline/llms";import{isOllamaNativeProvider as Qat,renderPromptTemplate as Zat}from"@cerebriline/shared";import{createTool as ldt}from"@cerebriline/shared";import{createTool as odt}from"@cerebriline/shared";import{createTool as Ndt}from"@cerebriline/shared";import{createTool as mdt}from"@cerebriline/shared";import{createTool as vdt}from"@cerebriline/shared";import{createTool as qdt}from"@cerebriline/shared";import{createTool as Ydt}from"@cerebriline/shared";import{createTool as Qdt}from"@cerebriline/shared";import{createHash as cOe}from"node:crypto";import{watch as uOe}from"node:fs";import{readdir as hOe,readFile as pOe}from"node:fs/promises";import{isAbsolute as mOe,join as fOe,relative as gOe,resolve as H6}from"node:path";function yOe(e){return cOe("sha1").update(e).digest("hex")}function q6(e){return Boolean(e&&typeof e==="object"&&"code"in e)}function W6(e){return q6(e)&&e.code==="ENOENT"}function j6(e){return q6(e)&&(e.code==="EACCES"||e.code==="EPERM")}class tv{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;unwatchedRoots=new Set;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor(e,t){if(e.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=e,this.debounceMs=t?.debounceMs??75,this.emitParseErrors=t?.emitParseErrors??!1;for(let n of e){if(this.definitionsByType.has(n.type))throw Error(`Duplicate unified config definition type '${n.type}'.`);this.definitionsByType.set(n.type,n),this.recordsByType.set(n.type,new Map),this.discoveredDirectoriesByType.set(n.type,new Set);for(let r of n.unwatchedDirectories??[])this.unwatchedRoots.add(H6(r));for(let r of n.directories){let o=this.baseTypesByDirectory.get(r);if(o)o.add(n.type);else this.baseTypesByDirectory.set(r,new Set([n.type]))}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let e of this.watchersByDirectory.values())e.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let e of this.definitions)await this.refreshTypeInternal(e)})}async refreshType(e){let t=this.definitionsByType.get(e);if(!t)throw Error(`Unknown unified config type '${e}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(t)})}getSnapshot(e){let t=this.recordsByType.get(e);return new Map([...t?.entries()??[]].map(([n,r])=>[n,{...r}]))}getAllSnapshots(){let e=new Map;for(let[t,n]of this.recordsByType.entries())e.set(t,new Map([...n.entries()].map(([r,o])=>[r,{...o}])));return e}emit(e){for(let t of this.listeners)t(e)}enqueueRefresh(e){return this.refreshQueue=this.refreshQueue.then(e,e),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let e=this.buildDesiredTypesByDirectory();for(let[t,n]of this.watchersByDirectory.entries()){if(e.has(t))continue;n.close(),this.watchersByDirectory.delete(t)}this.watchedTypesByDirectory=e;for(let t of e.keys()){if(this.watchersByDirectory.has(t))continue;try{let n=uOe(t,()=>{let r=this.watchedTypesByDirectory.get(t);if(!r)return;for(let o of r)this.pendingTypes.add(o);this.scheduleFlush()});this.watchersByDirectory.set(t,n),n.on("error",(r)=>{let o=this.watchedTypesByDirectory.get(t);if(!o)return;for(let i of o)this.emit({kind:"error",type:i,error:r,filePath:t})})}catch(n){if(!W6(n)&&!j6(n)){let r=e.get(t);if(!r)continue;for(let o of r)this.emit({kind:"error",type:o,error:n,filePath:t})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let e=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let t of e){let n=this.definitionsByType.get(t);if(!n)continue;await this.refreshTypeInternal(n)}})},this.debounceMs)}async refreshTypeInternal(e){let{records:t,discoveredDirectories:n}=await this.loadDefinition(e),r=this.recordsByType.get(e.type)??new Map;for(let[o,i]of r.entries()){if(t.has(o))continue;this.emit({kind:"remove",type:e.type,id:o,filePath:i.filePath})}for(let[o,i]of t.entries()){let s=r.get(o);if(s&&s.filePath===i.filePath&&s.fingerprint===i.fingerprint)continue;this.emit({kind:"upsert",record:{type:i.type,id:o,item:i.item,filePath:i.filePath}})}if(this.recordsByType.set(e.type,t),this.discoveredDirectoriesByType.set(e.type,n),this.started)this.syncDirectoryWatchers()}async loadDefinition(e){let t=new Map,n=new Set;for(let r of e.directories){n.add(r);let o=e.discoverFiles?await e.discoverFiles(r):await this.readDirectoryFileCandidates(r);for(let i of o){let{fileName:s,filePath:a}=i;if(n.add(i.directoryPath),e.includeFile&&!e.includeFile(s,a))continue;try{let d=await pOe(a,"utf8"),l={type:e.type,directoryPath:i.directoryPath,fileName:s,filePath:a,content:d},c=e.parseFile(l),u=e.resolveId(c,l).trim();if(!u)continue;t.set(u,{type:e.type,id:u,item:c,filePath:a,fingerprint:yOe(d)})}catch(d){if(this.emitParseErrors)this.emit({kind:"error",type:e.type,error:d,filePath:a})}}}return{records:t,discoveredDirectories:n}}isUnwatched(e){if(this.unwatchedRoots.size===0)return!1;let t=H6(e);for(let n of this.unwatchedRoots){let r=gOe(n,t);if(r===""||!r.startsWith("..")&&!mOe(r))return!0}return!1}buildDesiredTypesByDirectory(){let e=new Map;for(let[t,n]of this.baseTypesByDirectory.entries()){if(this.isUnwatched(t))continue;e.set(t,new Set(n))}for(let[t,n]of this.discoveredDirectoriesByType.entries())for(let r of n){if(this.isUnwatched(r))continue;let o=e.get(r);if(o)o.add(t);else e.set(r,new Set([t]))}return e}async readDirectoryFileCandidates(e){try{return(await hOe(e,{withFileTypes:!0})).filter((n)=>n.isFile()).map((n)=>({directoryPath:e,fileName:n.name,filePath:fOe(e,n.name)})).sort((n,r)=>n.fileName.localeCompare(r.fileName))}catch(t){if(W6(t)||j6(t))return[];throw t}}}import{readdir as mC,readFile as wOe,realpath as pC,stat as Jp}from"node:fs/promises";import{basename as gi,dirname as bOe,extname as nv,isAbsolute as vOe,join as Xn,relative as kOe,resolve as fi}from"node:path";import{stripUtf8Bom as TOe}from"@cerebriline/shared";import{AGENTS_RULES_FILE_NAME as z6,RULES_CONFIG_DIRECTORY_NAME as SOe,resolveGlobalAgentsRulesPath as xOe,resolveRulesConfigSearchPaths as _Oe,resolveSkillsConfigSearchPaths as EOe,resolveWorkflowsConfigSearchPaths as AOe,SKILLS_CONFIG_DIRECTORY_NAME as G6,WORKFLOWS_CONFIG_DIRECTORY_NAME as V6}from"@cerebriline/shared/storage";import ROe from"yaml";var Yp="SKILL.md",IOe="managed.json",COe=new Set([".md",".markdown",".txt"]);function Xp(e){return e.trim().toLowerCase()}function Ha(e){let t=e;return t?.code==="ENOENT"||t?.code==="ENOTDIR"||t?.code==="EACCES"||t?.code==="EPERM"||t?.code==="ELOOP"}function rv(e){return COe.has(nv(e).toLowerCase())}function Y6(e){let t=[],n=new Set;for(let r of e){let o=fi(r);if(n.has(o))continue;n.add(o),t.push(r)}return t}function X6(e){if(e?.directories||e?.bundledSkillsDirectory===!1)return;return e?.bundledSkillsDirectory??Qb()}function POe(e){let t=e.disabled!==!0,n={...e,bundled:!0};return Object.defineProperty(n,"disabled",{enumerable:!0,get:()=>$6(e.name,t)?void 0:!0}),n}function MOe(e){let t=[...e?.directories??e8(e?.workspacePath)],n=X6(e);if(n)t.unshift(n);if(e?.pluginSkillDirectories)t.push(...e.pluginSkillDirectories);else if(e?.includePluginSkills)t.push(...JG({pluginPaths:e.pluginPaths,workspacePath:e.workspacePath,cwd:e.cwd??e.workspacePath}));if(e?.agentPluginSkills)t.push(...e.agentPluginSkills.map((r)=>r.directoryPath));return Y6(t)}function K6(e,t){let n=kOe(e,t);return n===""||!n.startsWith("..")&&!vOe(n)}async function OOe(e){try{let[t,n,r]=await Promise.all([pC(e.pluginRoot),pC(e.directoryPath),pC(e.filePath)]);if(t!==fi(e.pluginRoot)||!K6(t,n)||!K6(t,r)||!(await Jp(n)).isDirectory()||!(await Jp(r)).isFile())return[];return[{directoryPath:e.directoryPath,fileName:Yp,filePath:r}]}catch(t){if(Ha(t))return[];throw t}}async function fC(e){try{let t=await mC(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isDirectory())continue;let o=Xn(e,r.name),i=Xn(o,IOe);try{let s=await wOe(i,"utf8"),a=JSON.parse(s);if(a&&typeof a==="object")n.push(o)}catch(s){if(Ha(s))continue;if(s?.name==="SyntaxError")continue;throw s}}return n.sort((r,o)=>r.localeCompare(o))}catch(t){if(Ha(t))return[];throw t}}function gC(e){let t=TOe(e),n=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,r=t.match(n);if(!r)return{data:{},body:t,hadFrontmatter:!1};let[,o,i]=r;try{let s=ROe.parse(o);return{data:s&&typeof s==="object"&&!Array.isArray(s)?s:{},body:i,hadFrontmatter:!0}}catch(s){let a=s instanceof Error?s.message:String(s);return{data:{},body:t,hadFrontmatter:!0,parseError:a}}}function ov(e,t,n){if(e===void 0||e===null){if(n)throw Error(`Missing required frontmatter field '${t}'.`);return}if(typeof e!=="string")throw Error(`Frontmatter field '${t}' must be a string.`);let r=e.trim();if(!r&&n)throw Error(`Frontmatter field '${t}' cannot be empty.`);return r||void 0}function Oc(e,t){if(e===void 0||e===null)return;if(typeof e!=="boolean")throw Error(`Frontmatter field '${t}' must be a boolean.`);return e}function LOe(e,t){if(gi(e.filePath).toLowerCase()!==z6.toLowerCase())return gi(e.filePath,nv(e.filePath));if(t&&fi(e.filePath)===fi(t,z6))return"Workspace AGENTS.md";if(fi(e.filePath)===fi(xOe()))return"Global AGENTS.md";return gi(e.filePath,nv(e.filePath))}function J6(e,t){let{data:n,body:r,parseError:o}=gC(e);if(o)throw Error(`Failed to parse YAML frontmatter: ${o}`);let i=r.trim();if(!i)throw Error("Missing instructions body in skill file.");let a=ov(n.name,"name",!1)??t.trim();if(!a)throw Error("Missing skill name.");return{name:a,description:ov(n.description,"description",!1),disabled:Oc(n.disabled,"disabled")??(Oc(n.enabled,"enabled")===!1?!0:void 0),instructions:i,frontmatter:n}}function Q6(e,t){let{data:n,body:r,parseError:o}=gC(e);if(o)throw Error(`Failed to parse YAML frontmatter: ${o}`);let i=r.trim();if(!i)throw Error("Missing instructions body in rule file.");let s=ov(n.name,"name",!1)??t.trim();if(!s)throw Error("Missing rule name.");return{name:s,disabled:Oc(n.disabled,"disabled")??(Oc(n.enabled,"enabled")===!1?!0:void 0),instructions:i,frontmatter:n}}function Z6(e,t){let{data:n,body:r,parseError:o}=gC(e);if(o)throw Error(`Failed to parse YAML frontmatter: ${o}`);let i=r.trim();if(!i)throw Error("Missing instructions body in workflow file.");let s=ov(n.name,"name",!1)??t.trim();if(!s)throw Error("Missing workflow name.");return{name:s,disabled:Oc(n.disabled,"disabled")??(Oc(n.enabled,"enabled")===!1?!0:void 0),instructions:i,frontmatter:n}}function e8(e){return EOe(e)}function t8(e){return _Oe(e)}function n8(e){return AOe(e)}async function r8(e){if(gi(e)===".cline"){let t=await fC(e);return(await Promise.all(t.map((r)=>r8(Xn(r,G6))))).flat()}try{let t=await mC(e,{withFileTypes:!0}),n=[];for(let r of t){if(r.isFile()&&r.name===Yp){n.push({directoryPath:e,fileName:r.name,filePath:Xn(e,r.name)});continue}let o=Xn(e,r.name);if(r.isDirectory()||r.isSymbolicLink()&&await Jp(o).then((s)=>s.isDirectory()).catch((s)=>{if(Ha(s))return!1;throw s}))n.push({directoryPath:o,fileName:Yp,filePath:Xn(o,Yp)})}return n}catch(t){if(Ha(t))return[];throw t}}async function iv(e){if(gi(e)===".cline"){let t=await fC(e);return(await Promise.all(t.map((r)=>iv(Xn(r,"rules.md"))))).flat()}try{if((await Jp(e)).isFile())return[{directoryPath:bOe(e),fileName:gi(e),filePath:e}]}catch(t){if(!Ha(t))throw t}try{let n=(await mC(e,{withFileTypes:!0})).filter((o)=>o.isFile()&&rv(o.name)).map((o)=>({directoryPath:e,fileName:o.name,filePath:Xn(e,o.name)})),r=Xn(e,"AGENTS.md");try{if((await Jp(r)).isFile()){if(!n.some((s)=>s.fileName==="AGENTS.md"))n.push({directoryPath:e,fileName:"AGENTS.md",filePath:r})}}catch{}return n}catch(t){if(Ha(t))return[];throw t}}async function NOe(e){if(gi(e)===".cline"){let t=await fC(e);return(await Promise.all(t.map((r)=>iv(Xn(r,V6))))).flat()}return iv(e)}function o8(e){let t=MOe(e),n=X6(e),r=new Map((e?.agentPluginSkills??[]).map((i)=>[fi(i.directoryPath),i])),o=e?.workspacePath?Xn(e.workspacePath,".cline"):void 0;return{type:"skill",directories:o?Y6([...t,o]):t,...n?{unwatchedDirectories:[n]}:{},discoverFiles:(i)=>{let s=r.get(fi(i));return s?OOe(s):r8(i)},includeFile:(i)=>i===Yp,parseFile:(i)=>{let s=r.get(fi(i.directoryPath));if(!s){let d=J6(i.content,gi(i.directoryPath));if(!cC(i.filePath,n))return d;return POe(d)}let a=wp(i.content,s.metadata.name);return{name:a.metadata.name,description:a.metadata.description,instructions:a.instructions,frontmatter:a.frontmatter,source:{type:"agent-plugin",pluginName:s.pluginName,pluginRoot:s.pluginRoot,skillRoot:s.directoryPath,filePath:s.filePath}}},resolveId:(i)=>i.source?.type==="agent-plugin"?`${Xp(i.source.pluginName)}:${Xp(i.name)}`:Xp(i.name)}}function i8(e){let t=e?.directories??t8(e?.workspacePath),n=e?.workspacePath?Xn(e.workspacePath,".cline"):void 0;return{type:"rule",directories:n?[...t,n]:t,discoverFiles:iv,includeFile:(r,o)=>r===".clinerules"||rv(r)||rv(o),parseFile:(r)=>Q6(r.content,LOe(r,e?.workspacePath)),resolveId:(r)=>Xp(r.name)}}function s8(e){let t=e?.directories??n8(e?.workspacePath),n=e?.workspacePath?Xn(e.workspacePath,".cline"):void 0;return{type:"workflow",directories:n?[...t,n]:t,discoverFiles:NOe,includeFile:(r)=>rv(r),parseFile:(r)=>Z6(r.content,gi(r.filePath,nv(r.filePath))),resolveId:(r)=>Xp(r.name)}}function a8(e){let t=[o8(e?.skills),i8(e?.rules),s8(e?.workflows)];return new tv(t,{debounceMs:e?.debounceMs,emitParseErrors:e?.emitParseErrors})}function DOe(e){return e.disabled!==!0}function d8(e){if(e.length===0)return"";return`
1261
1261
 
1262
1262
  # Rules
1263
1263
  ${e.map((n)=>`## ${n.name}
@@ -1277,7 +1277,7 @@ ${i}${e.instructions}
1277
1277
 
1278
1278
  ${s}`:o.instructions}})}}}function dv(e){return e.trim().replace(/^\/+/,"").toLowerCase()}function f8(e,t){let n=e.map((i)=>i.createSkillsExecutor?.(t)).filter((i)=>i!==void 0),r=()=>n.flatMap((i)=>(i.configuredSkills??[]).map((s)=>({metadata:s,executor:i}))),o=async(i,s,a)=>{let d=dv(i);if(!d)return"Missing skill name.";let l=r(),c=l.filter(({metadata:f})=>dv(f.id)===d),u=c.length>0?c:l.filter(({metadata:f})=>{let m=dv(f.id);return dv(f.name)===d||m.endsWith(`:${d}`)}),h=u.filter(({metadata:f})=>!f.disabled);if(h.length===1)return h[0].executor(h[0].metadata.id,s,a);if(h.length>1)return`Skill "${i}" is ambiguous. Use one of: ${h.map(({metadata:f})=>f.id).join(", ")}`;if(u.length>0)return`Skill "${i}" is configured but disabled.`;let p=l.filter(({metadata:f})=>!f.disabled).map(({metadata:f})=>f.id).sort((f,m)=>f.localeCompare(m));return p.length>0?`Skill "${i}" not found. Available skills: ${p.join(", ")}`:"No skills are currently available."};return Object.defineProperty(o,"configuredSkills",{get:()=>r().map(({metadata:i})=>i),enumerable:!0,configurable:!1}),o}function vC(e){if(e.length===0)throw Error("At least one user instruction service is required.");if(e.length===1)return e[0];let t=(r)=>{let o=new Map;for(let i of e)for(let s of i.listRecords(r))if(!o.has(s.id))o.set(s.id,s);return[...o.values()]},n=()=>{let r=new Map;for(let o of e)for(let i of o.listRuntimeCommands()){let s=ls(i.name);if(s&&!r.has(s))r.set(s,i)}return[...r.values()].sort((o,i)=>o.name.localeCompare(i.name))};return{start:async()=>{await Promise.all(e.map((r)=>r.start()))},stop:()=>{for(let r of e)r.stop()},refreshType:async(r)=>{await Promise.all(e.map((o)=>o.refreshType(r)))},listRecords:t,listRuntimeCommands:n,resolveRuntimeSlashCommand:(r,o)=>{for(let i of e){let s=i.resolveRuntimeSlashCommand(r,o);if(s!==r)return s}return r},hasConfiguredSkills:(r)=>e.some((o)=>o.hasConfiguredSkills(r)),createSkillsExecutor:(r)=>f8(e,r),createExtension:(r)=>({name:"cline-combined-user-instructions",manifest:{capabilities:[r.includeRules?"rules":void 0,r.registerSkillsTool?"tools":void 0,r.includeSkills||r.includeWorkflows?"commands":void 0].filter((o)=>Boolean(o))},setup(o){if(r.includeRules)o.registerRule({id:"cline-combined-user-instructions:rules",source:"combined-user-instructions",content:()=>sv(t("rule"))});if(r.registerSkillsTool)o.registerTool(Ho(f8(e,r.allowedSkillNames)));for(let i of n().filter((s)=>s.kind==="skill"&&r.includeSkills||s.kind==="workflow"&&r.includeWorkflows))o.registerCommand({name:i.name,description:i.description,handler:(s)=>{let a=s.trim();return a?`${i.instructions}
1279
1279
 
1280
- ${a}`:i.instructions}})}})}}class g8{watcher;ready;stopped=!1;constructor(e){this.watcher=a8(e)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(e){await this.start(),await this.watcher.refreshType(e)}listRecords(e){return[...this.watcher.getSnapshot(e).entries()].map(([t,n])=>({type:e,id:t,filePath:n.filePath,item:n.item}))}listRuntimeCommands(){return Qp(this.watcher)}resolveRuntimeSlashCommand(e,t){return p8(e,this.watcher,t)}hasConfiguredSkills(e){return Zp(this.watcher,e).some((t)=>!t.disabled)}createSkillsExecutor(e){return bC(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),e)}createExtension(e){return m8({...e,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function Lc(e){return new g8(e)}import{spawn as HLe}from"node:child_process";import{mkdir as WLe}from"node:fs/promises";import{StringDecoder as q8}from"node:string_decoder";import{formatMcpTimeoutErrorMessage as jLe,isMcpTimeoutConfigured as z8}from"@cerebriline/shared";import{Client as qLe}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as PLe}from"node:crypto";import{UnauthorizedError as F8}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as Zct}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as MLe,SseError as OLe}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as LLe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";OC();import{formatMcpTimeoutErrorMessage as RLe,resolveMcpTimeoutSeconds as ILe}from"@cerebriline/shared";import{ErrorCode as CLe,McpError as D8}from"@modelcontextprotocol/sdk/types.js";function hv(e){return ILe(e)*1000}function om(e,t,n){if(!(e instanceof D8)||e.code!==CLe.RequestTimeout)return e;return new D8(e.code,RLe(t,n),e.data)}var NLe=new Set([301,302,303,307,308]),$8=20,DLe=new Set(["authorization","cookie","proxy-authorization"]),$Le=new Set(["mcp-protocol-version","mcp-session-id"]);function FLe(e){if(!e.headers||!e.restrictConfiguredHeadersToOrigin)return e.headers;let t=Object.entries(e.headers).filter(([n])=>{let r=n.toLowerCase();if($Le.has(r))return!1;return r!=="authorization"||!e.oauthProvider});return t.length>0?Object.fromEntries(t):void 0}function ULe(e){let t=new URL(e.endpointUrl).origin,n=new Set(Object.keys(e.configuredHeaders).map((i)=>i.toLowerCase())),r=e.baseFetch??globalThis.fetch,o=(i)=>{let s=[];i.forEach((a,d)=>{let l=d.toLowerCase();if(n.has(l)||DLe.has(l))s.push(d)});for(let a of s)i.delete(a)};return async(i,s)=>{let a=i instanceof Request?new Request(i,s):new Request(String(i),s),d=new URL(a.url),l=a.method,c=l==="GET"||l==="HEAD"?void 0:await a.clone().arrayBuffer(),u=new Headers(a.headers);if(d.origin!==t)o(u);for(let h=0;;h+=1){let p=await r(d,{method:l,headers:u,body:c,redirect:"manual",signal:a.signal});if(!NLe.has(p.status))return p;if(h>=$8)throw await p.body?.cancel().catch(()=>{return}),Error(`MCP endpoint exceeded ${$8} redirects.`);let f=p.headers.get("location");if(!f)return p;let m=new URL(f,d);if(await p.body?.cancel().catch(()=>{return}),m.origin!==t)o(u);if(p.status===303&&l!=="GET"&&l!=="HEAD"||(p.status===301||p.status===302)&&l==="POST")l="GET",c=void 0,u.delete("content-length"),u.delete("content-type");d=m}}}function BLe(e){return{client_name:"Cerebriline",redirect_uris:[e],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function LC(e){return e?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0}function pv(e,t){return e?.client_id===t?.client_id&&e?.client_secret===t?.client_secret}function im(e,t,n){if(!pv(t.clientInformation,n))throw new Nc(e)}function NC(e){let t={};try{t=CC(e.serverName,{filePath:e.settingsPath})??{}}catch{t={}}let n,r,o=()=>e.clientInformation??t.clientInformation,i=e.clientInformation?{clientId:e.clientInformation.client_id,...e.clientInformation.client_secret?{clientSecret:e.clientInformation.client_secret}:{}}:null,s=async(d)=>{try{t=await PC(e.serverName,d,{filePath:e.settingsPath,expectedOAuthClient:i})}catch(l){if(e.settingsPath||l instanceof Nc)throw l;t=tm(d(t))??{}}};return{provider:{get redirectUrl(){return t.redirectUrl??e.redirectUrl},get clientMetadata(){return BLe(t.redirectUrl??e.redirectUrl)},state:()=>(r=PLe(),r),clientInformation:o,saveClientInformation:async(d)=>{let l=t.clientInformation;await s((c)=>{im(e.serverName,c,l);let u=!pv(c.clientInformation,d);return{...c,clientInformation:d,...u?{tokens:void 0,lastAuthenticatedAt:void 0}:{},redirectUrl:e.redirectUrl,lastError:void 0}})},tokens:()=>o()?.client_id&&pv(t.clientInformation,o())?t.tokens:void 0,saveTokens:async(d)=>{let l=Date.now(),c=o();if(!c?.client_id)throw Error("Cannot save MCP OAuth tokens without a client ID.");await s((u)=>{if(u.clientInformation||!e.clientInformation)im(e.serverName,u,c);return{...u,tokens:d,clientInformation:c,redirectUrl:e.redirectUrl,lastError:void 0,lastAuthenticatedAt:l}})},redirectToAuthorization:async(d)=>{n=d.toString(),await e.onAuthorizationUrl?.(n)},saveCodeVerifier:async(d)=>{let l=o();await s((c)=>(im(e.serverName,c,l),{...c,codeVerifier:d,redirectUrl:e.redirectUrl}))},codeVerifier:()=>{if(!t.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${e.serverName}".`);return t.codeVerifier},invalidateCredentials:async(d)=>{let l=t.clientInformation;await s((c)=>{if(im(e.serverName,c,l),d==="all")return{lastError:c.lastError,redirectUrl:c.redirectUrl};return{...c,...d==="client"?{clientInformation:void 0}:{},...d==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...d==="verifier"?{codeVerifier:void 0}:{},...d==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(d)=>{let l=t.clientInformation;await s((c)=>(im(e.serverName,c,l),{...c,discoveryState:d}))},discoveryState:()=>t.discoveryState},getLastAuthorizationUrl:()=>n,getLastOAuthState:()=>r,resetInteractiveState:async()=>{await s((d)=>{let l=e.clientInformation,c=l!==void 0&&!pv(d.clientInformation,l);return{...d,...l?{clientInformation:l}:{},...c?{tokens:void 0,lastAuthenticatedAt:void 0}:{},codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:e.redirectUrl}})},markError:async(d)=>{await s((l)=>({...l,lastError:d}))},markConnectionError:async(d)=>{await s((l)=>({...l,lastError:d,authorizationRequired:void 0}))},markAuthorizationRequired:async(d)=>{await s((l)=>({...l,lastError:d,authorizationRequired:!0}))},clearError:async()=>{await s((d)=>({...d,lastError:void 0,authorizationRequired:void 0}))}}}function U8(e){let t=e.registration.transport;if(t.type==="stdio")throw Error(`MCP server "${e.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let n=FLe({headers:t.headers,oauthProvider:e.oauthProvider,restrictConfiguredHeadersToOrigin:e.restrictConfiguredHeadersToOrigin}),r=n?{headers:n}:void 0,o=e.restrictConfiguredHeadersToOrigin&&n?ULe({endpointUrl:t.url,configuredHeaders:n,baseFetch:e.fetch}):e.fetch,i=e.oauthProvider?o:async(s,a)=>{let d=await(o??globalThis.fetch)(s,a);if(d.status===401)throw await d.body?.cancel().catch(()=>{return}),new F8("MCP server requires authorization");return d};if(t.type==="sse")return new MLe(new URL(t.url),{authProvider:e.oauthProvider,requestInit:r,eventSourceInit:{fetch:(s,a)=>(o??globalThis.fetch)(s,a)},fetch:i});return new LLe(new URL(t.url),{authProvider:e.oauthProvider,requestInit:r,fetch:i})}function DC(e){return e instanceof F8||e instanceof OLe&&e.code===401}var zLe="2024-11-05",K8=1e4,KLe=1e4,B8="http://127.0.0.1:1456/mcp/oauth/callback",H8=250,$C=2000;function Wa(e){return e instanceof Error?e.message:String(e)}async function mv(e,t){return new Promise((n)=>{let r=!1,o=(s)=>{if(r)return;r=!0,clearTimeout(i),n(s)},i=setTimeout(()=>o(!1),t);i.unref(),e.then(()=>o(!0),()=>o(!0))})}function GLe(e,t,n){let r=Wa(t),o=Wa(n);if(r===o)return t instanceof Error?t:Error(r);return Error(`MCP server "${e}" failed to initialize. Newline-delimited attempt: ${r} Content-Length framed attempt: ${o}`)}function W8(e){return Buffer.from(`${JSON.stringify(e)}
1280
+ ${a}`:i.instructions}})}})}}class g8{watcher;ready;stopped=!1;constructor(e){this.watcher=a8(e)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType(e){await this.start(),await this.watcher.refreshType(e)}listRecords(e){return[...this.watcher.getSnapshot(e).entries()].map(([t,n])=>({type:e,id:t,filePath:n.filePath,item:n.item}))}listRuntimeCommands(){return Qp(this.watcher)}resolveRuntimeSlashCommand(e,t){return p8(e,this.watcher,t)}hasConfiguredSkills(e){return Zp(this.watcher,e).some((t)=>!t.disabled)}createSkillsExecutor(e){return bC(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),e)}createExtension(e){return m8({...e,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function Lc(e){return new g8(e)}import{spawn as HLe}from"node:child_process";import{mkdir as WLe}from"node:fs/promises";import{StringDecoder as q8}from"node:string_decoder";import{formatMcpTimeoutErrorMessage as jLe,isMcpTimeoutConfigured as z8}from"@cerebriline/shared";import{Client as qLe}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as PLe}from"node:crypto";import{UnauthorizedError as F8}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as tut}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as MLe,SseError as OLe}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as LLe}from"@modelcontextprotocol/sdk/client/streamableHttp.js";OC();import{formatMcpTimeoutErrorMessage as RLe,resolveMcpTimeoutSeconds as ILe}from"@cerebriline/shared";import{ErrorCode as CLe,McpError as D8}from"@modelcontextprotocol/sdk/types.js";function hv(e){return ILe(e)*1000}function om(e,t,n){if(!(e instanceof D8)||e.code!==CLe.RequestTimeout)return e;return new D8(e.code,RLe(t,n),e.data)}var NLe=new Set([301,302,303,307,308]),$8=20,DLe=new Set(["authorization","cookie","proxy-authorization"]),$Le=new Set(["mcp-protocol-version","mcp-session-id"]);function FLe(e){if(!e.headers||!e.restrictConfiguredHeadersToOrigin)return e.headers;let t=Object.entries(e.headers).filter(([n])=>{let r=n.toLowerCase();if($Le.has(r))return!1;return r!=="authorization"||!e.oauthProvider});return t.length>0?Object.fromEntries(t):void 0}function ULe(e){let t=new URL(e.endpointUrl).origin,n=new Set(Object.keys(e.configuredHeaders).map((i)=>i.toLowerCase())),r=e.baseFetch??globalThis.fetch,o=(i)=>{let s=[];i.forEach((a,d)=>{let l=d.toLowerCase();if(n.has(l)||DLe.has(l))s.push(d)});for(let a of s)i.delete(a)};return async(i,s)=>{let a=i instanceof Request?new Request(i,s):new Request(String(i),s),d=new URL(a.url),l=a.method,c=l==="GET"||l==="HEAD"?void 0:await a.clone().arrayBuffer(),u=new Headers(a.headers);if(d.origin!==t)o(u);for(let h=0;;h+=1){let p=await r(d,{method:l,headers:u,body:c,redirect:"manual",signal:a.signal});if(!NLe.has(p.status))return p;if(h>=$8)throw await p.body?.cancel().catch(()=>{return}),Error(`MCP endpoint exceeded ${$8} redirects.`);let f=p.headers.get("location");if(!f)return p;let m=new URL(f,d);if(await p.body?.cancel().catch(()=>{return}),m.origin!==t)o(u);if(p.status===303&&l!=="GET"&&l!=="HEAD"||(p.status===301||p.status===302)&&l==="POST")l="GET",c=void 0,u.delete("content-length"),u.delete("content-type");d=m}}}function BLe(e){return{client_name:"Cerebriline",redirect_uris:[e],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function LC(e){return e?{client_id:e.clientId,...e.clientSecret?{client_secret:e.clientSecret}:{}}:void 0}function pv(e,t){return e?.client_id===t?.client_id&&e?.client_secret===t?.client_secret}function im(e,t,n){if(!pv(t.clientInformation,n))throw new Nc(e)}function NC(e){let t={};try{t=CC(e.serverName,{filePath:e.settingsPath})??{}}catch{t={}}let n,r,o=()=>e.clientInformation??t.clientInformation,i=e.clientInformation?{clientId:e.clientInformation.client_id,...e.clientInformation.client_secret?{clientSecret:e.clientInformation.client_secret}:{}}:null,s=async(d)=>{try{t=await PC(e.serverName,d,{filePath:e.settingsPath,expectedOAuthClient:i})}catch(l){if(e.settingsPath||l instanceof Nc)throw l;t=tm(d(t))??{}}};return{provider:{get redirectUrl(){return t.redirectUrl??e.redirectUrl},get clientMetadata(){return BLe(t.redirectUrl??e.redirectUrl)},state:()=>(r=PLe(),r),clientInformation:o,saveClientInformation:async(d)=>{let l=t.clientInformation;await s((c)=>{im(e.serverName,c,l);let u=!pv(c.clientInformation,d);return{...c,clientInformation:d,...u?{tokens:void 0,lastAuthenticatedAt:void 0}:{},redirectUrl:e.redirectUrl,lastError:void 0}})},tokens:()=>o()?.client_id&&pv(t.clientInformation,o())?t.tokens:void 0,saveTokens:async(d)=>{let l=Date.now(),c=o();if(!c?.client_id)throw Error("Cannot save MCP OAuth tokens without a client ID.");await s((u)=>{if(u.clientInformation||!e.clientInformation)im(e.serverName,u,c);return{...u,tokens:d,clientInformation:c,redirectUrl:e.redirectUrl,lastError:void 0,lastAuthenticatedAt:l}})},redirectToAuthorization:async(d)=>{n=d.toString(),await e.onAuthorizationUrl?.(n)},saveCodeVerifier:async(d)=>{let l=o();await s((c)=>(im(e.serverName,c,l),{...c,codeVerifier:d,redirectUrl:e.redirectUrl}))},codeVerifier:()=>{if(!t.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${e.serverName}".`);return t.codeVerifier},invalidateCredentials:async(d)=>{let l=t.clientInformation;await s((c)=>{if(im(e.serverName,c,l),d==="all")return{lastError:c.lastError,redirectUrl:c.redirectUrl};return{...c,...d==="client"?{clientInformation:void 0}:{},...d==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...d==="verifier"?{codeVerifier:void 0}:{},...d==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(d)=>{let l=t.clientInformation;await s((c)=>(im(e.serverName,c,l),{...c,discoveryState:d}))},discoveryState:()=>t.discoveryState},getLastAuthorizationUrl:()=>n,getLastOAuthState:()=>r,resetInteractiveState:async()=>{await s((d)=>{let l=e.clientInformation,c=l!==void 0&&!pv(d.clientInformation,l);return{...d,...l?{clientInformation:l}:{},...c?{tokens:void 0,lastAuthenticatedAt:void 0}:{},codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:e.redirectUrl}})},markError:async(d)=>{await s((l)=>({...l,lastError:d}))},markConnectionError:async(d)=>{await s((l)=>({...l,lastError:d,authorizationRequired:void 0}))},markAuthorizationRequired:async(d)=>{await s((l)=>({...l,lastError:d,authorizationRequired:!0}))},clearError:async()=>{await s((d)=>({...d,lastError:void 0,authorizationRequired:void 0}))}}}function U8(e){let t=e.registration.transport;if(t.type==="stdio")throw Error(`MCP server "${e.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let n=FLe({headers:t.headers,oauthProvider:e.oauthProvider,restrictConfiguredHeadersToOrigin:e.restrictConfiguredHeadersToOrigin}),r=n?{headers:n}:void 0,o=e.restrictConfiguredHeadersToOrigin&&n?ULe({endpointUrl:t.url,configuredHeaders:n,baseFetch:e.fetch}):e.fetch,i=e.oauthProvider?o:async(s,a)=>{let d=await(o??globalThis.fetch)(s,a);if(d.status===401)throw await d.body?.cancel().catch(()=>{return}),new F8("MCP server requires authorization");return d};if(t.type==="sse")return new MLe(new URL(t.url),{authProvider:e.oauthProvider,requestInit:r,eventSourceInit:{fetch:(s,a)=>(o??globalThis.fetch)(s,a)},fetch:i});return new LLe(new URL(t.url),{authProvider:e.oauthProvider,requestInit:r,fetch:i})}function DC(e){return e instanceof F8||e instanceof OLe&&e.code===401}var zLe="2024-11-05",K8=1e4,KLe=1e4,B8="http://127.0.0.1:1456/mcp/oauth/callback",H8=250,$C=2000;function Wa(e){return e instanceof Error?e.message:String(e)}async function mv(e,t){return new Promise((n)=>{let r=!1,o=(s)=>{if(r)return;r=!0,clearTimeout(i),n(s)},i=setTimeout(()=>o(!1),t);i.unref(),e.then(()=>o(!0),()=>o(!0))})}function GLe(e,t,n){let r=Wa(t),o=Wa(n);if(r===o)return t instanceof Error?t:Error(r);return Error(`MCP server "${e}" failed to initialize. Newline-delimited attempt: ${r} Content-Length framed attempt: ${o}`)}function W8(e){return Buffer.from(`${JSON.stringify(e)}
1281
1281
  `,"utf8")}function j8(e){let t=Buffer.from(JSON.stringify(e),"utf8");return Buffer.concat([Buffer.from(`Content-Length: ${t.byteLength}\r
1282
1282
  \r
1283
1283
  `,"utf8"),t])}class FC{buffer="";decoder=new q8("utf8");push(e){this.buffer+=this.decoder.write(e);let t=[];while(!0){let n=this.buffer.indexOf(`\r
@@ -1285,7 +1285,7 @@ ${a}`:i.instructions}})}})}}class g8{watcher;ready;stopped=!1;constructor(e){thi
1285
1285
  `);if(n<0)break;let o=this.buffer.slice(0,n).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!o)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let i=Number.parseInt(o[1],10),s=n+4,a=s+i;if(this.buffer.length<a)break;t.push(this.buffer.slice(s,a)),this.buffer=this.buffer.slice(a)}return t}}class UC{buffer="";decoder=new q8("utf8");push(e){this.buffer+=this.decoder.write(e);let t=[];while(!0){let n=this.buffer.indexOf(`
1286
1286
  `);if(n<0)break;let r=this.buffer.slice(0,n).trim();if(this.buffer=this.buffer.slice(n+1),r.length>0)t.push(r)}return t}}class G8{registration;process;processClose;nextRequestId=1;pending=new Map;framedParser=new FC;newlineParser=new UC;stderrBuffer="";stdinFailure;stdinFailureTimer;connected=!1;protocolMode="newline";requestTimeoutMs;connectAttemptTimeoutMs;constructor(e){this.registration=e,this.requestTimeoutMs=hv(e.timeoutSeconds),this.connectAttemptTimeoutMs=z8(e.timeoutSeconds)?this.requestTimeoutMs:K8}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let e={protocolVersion:zLe,capabilities:{},clientInfo:{name:"@cerebriline/core",version:"0.0.0"}};await this.ensureAgentPluginDataDirectory(),this.spawnProcess("newline");try{await this.request("initialize",e,this.connectAttemptTimeoutMs)}catch(t){await this.disconnect().catch(()=>{}),this.spawnProcess("framed");try{await this.request("initialize",e,this.connectAttemptTimeoutMs)}catch(n){throw await this.disconnect().catch(()=>{}),GLe(this.registration.name,t,n)}}this.notify("notifications/initialized"),this.connected=!0}async ensureAgentPluginDataDirectory(){if(this.registration.metadata?.source!=="agent-plugin")return;let e=this.registration.metadata.pluginDataPath;if(typeof e!=="string"||e.length===0)return;await WLe(e,{recursive:!0})}async disconnect(){let e=this.process,t=this.processClose;if(this.connected=!1,this.process=void 0,this.processClose=void 0,this.clearStdinFailureTimer(),this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!t)return;if(!e){if(!await mv(t,$C))throw Error(`MCP process for "${this.registration.name}" did not close during disconnect.`);return}if(!e.stdin.destroyed)e.stdin.end();if(await mv(t,H8))return;if(e.kill(),await mv(t,$C))return;if(e.kill("SIGKILL"),!await mv(t,$C))throw Error(`MCP process for "${this.registration.name}" did not exit during disconnect.`)}async listTools(){return((await this.request("tools/list")).tools??[]).filter((t)=>typeof t?.name==="string"&&typeof t.inputSchema==="object"&&t.inputSchema!==null).map((t)=>({name:t.name,description:t.description,inputSchema:t.inputSchema,...t.annotations?.readOnlyHint===!0?{readOnlyHint:!0}:{}}))}async callTool(e){return this.request("tools/call",{name:e.name,arguments:e.arguments??{}},void 0,e.context?.signal)}spawnProcess(e){let t=this.registration.transport;if(t.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${t.type}`);this.framedParser=new FC,this.newlineParser=new UC,this.stderrBuffer="",this.stdinFailure=void 0,this.clearStdinFailureTimer(),this.protocolMode=e;let n=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},r=HLe(t.command,t.args??[],{cwd:t.cwd,env:{...process.env,...t.env??{}},stdio:["pipe","pipe","pipe"],...n});this.process=r,this.processClose=new Promise((o)=>{r.once("close",()=>o())}),r.stdout.on("data",(o)=>this.handleStdout(o)),r.stderr.on("data",(o)=>{if(this.process!==r)return;if(this.stderrBuffer+=o.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),r.once("error",(o)=>{if(this.process!==r)return;this.failAllPending(Error(`MCP process error: ${Wa(o)}`))}),r.stdin.on("error",(o)=>{if(this.process!==r)return;if(this.stdinFailure??=Wa(o),this.stdinFailureTimer!==void 0)return;this.stdinFailureTimer=setTimeout(()=>{if(this.stdinFailureTimer=void 0,this.process!==r)return;this.failAllPending(Error(`MCP server "${this.registration.name}" stopped reading its input before the request was fully delivered (${this.stdinFailure}) and did not exit.`)),this.disconnect().catch(()=>{})},H8),this.stdinFailureTimer.unref()}),r.once("exit",(o,i)=>{if(this.process!==r)return;this.connected=!1,this.process=void 0,this.clearStdinFailureTimer();let s=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${o??"null"}, signal=${i??"null"}).${s}${this.describeStdinFailure()}`))})}handleStdout(e){try{let t=this.protocolMode==="framed"?this.framedParser.push(e):this.newlineParser.push(e);for(let n of t){let r=JSON.parse(n);if(typeof r.id!=="number")continue;let o=this.takePending(r.id);if(!o)continue;if(r.error){let i=r.error.message||`MCP request failed with code ${r.error.code??"unknown"}`;o.reject(Error(i));continue}o.resolve(r.result)}}catch(t){this.handleProtocolFailure(t)}}handleProtocolFailure(e){let t=this.process;if(!t)return;this.connected=!1,this.process=void 0;let n=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${Wa(e)}.${n}`)),t.kill()}async request(e,t,n=this.requestTimeoutMs,r){let o=this.process;if(!o?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let i=this.nextRequestId++,s={jsonrpc:"2.0",id:i,method:e,...t?{params:t}:{}},a=new Promise((d,l)=>{let c=setTimeout(()=>{this.takePending(i),l(this.createTimeoutError(e,n))},n),u=r?()=>{let h=this.takePending(i);if(!h)return;let p=r.reason instanceof Error?r.reason:Object.assign(Error(`MCP request aborted for "${this.registration.name}" (${e}).`),{name:"AbortError"});h.reject(p)}:void 0;if(this.pending.set(i,{resolve:d,reject:l,timeout:c,signal:r,onAbort:u}),r&&u){if(r.addEventListener("abort",u,{once:!0}),r.aborted)u()}});if(!this.pending.has(i))return a;try{o.stdin.write(this.protocolMode==="framed"?j8(s):W8(s))}catch(d){let l=this.takePending(i);if(l)l.reject(d instanceof Error?d:Error(String(d)))}return a}createTimeoutError(e,t){return Error(jLe(this.registration.name,t,e)+this.describeStdinFailure())}clearStdinFailureTimer(){if(this.stdinFailureTimer!==void 0)clearTimeout(this.stdinFailureTimer),this.stdinFailureTimer=void 0}describeStdinFailure(){return this.stdinFailure===void 0?"":` The server stopped reading its input before the request was fully delivered (${this.stdinFailure}).`}notify(e,t){let n=this.process;if(!n?.stdin.writable)return;let r={jsonrpc:"2.0",method:e,...t?{params:t}:{}};n.stdin.write(this.protocolMode==="framed"?j8(r):W8(r))}failAllPending(e){for(let t of[...this.pending.keys()]){let n=this.takePending(t);if(!n)continue;n.reject(e)}}takePending(e){let t=this.pending.get(e);if(!t)return;if(this.pending.delete(e),clearTimeout(t.timeout),t.signal&&t.onAbort)t.signal.removeEventListener("abort",t.onAbort);return t}}class V8{registration;options;client;authContext;requestTimeoutMs;connectAttemptTimeoutMs;constructor(e,t){this.registration=e;this.options=t;this.requestTimeoutMs=hv(e.timeoutSeconds),this.connectAttemptTimeoutMs=z8(e.timeoutSeconds)?this.requestTimeoutMs:KLe}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let e=NC({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??B8,clientInformation:LC(this.registration.oauthClient)});this.authContext=e;let t=await e.provider.tokens()?e.provider:void 0,n;try{n=new qLe({name:this.options.clientName?.trim()||"@cerebriline/core",version:this.options.clientVersion?.trim()||"0.0.0"});let r=U8({registration:this.registration,oauthProvider:t,fetch:this.options.fetch,restrictConfiguredHeadersToOrigin:this.options.restrictConfiguredHeadersToOrigin});await n.connect(r,{timeout:this.connectAttemptTimeoutMs}),await e.clearError(),this.client=n}catch(r){await n?.close().catch(()=>{});let o=om(r,this.registration.name,this.connectAttemptTimeoutMs),i=DC(r),s=i?this.formatUnauthorizedMessage(e.getLastAuthorizationUrl()):Wa(o);if(i&&!this.hasStaticAuthorizationHeader())await e.markAuthorizationRequired(s);else await e.markConnectionError(s);throw Error(s)}}async disconnect(){let e=this.client;this.client=void 0,await e?.close()}async listTools(){let e=await this.ensureConnectedClient();try{return(await e.listTools(void 0,{timeout:this.requestTimeoutMs})).tools.map((n)=>({name:n.name,description:n.description,inputSchema:n.inputSchema&&typeof n.inputSchema==="object"&&!Array.isArray(n.inputSchema)?n.inputSchema:{},...n.annotations?.readOnlyHint===!0?{readOnlyHint:!0}:{}}))}catch(t){return await this.handleOperationError(t)}}async callTool(e){let t=await this.ensureConnectedClient();try{return await t.callTool({name:e.name,arguments:e.arguments??{}},void 0,{timeout:this.requestTimeoutMs,signal:e.context?.signal})}catch(n){return await this.handleOperationError(n)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage(e){if(this.hasStaticAuthorizationHeader())return`MCP server "${this.registration.name}" rejected its configured Authorization header. Update or remove that header before connecting with OAuth.`;let t=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!e)return`${t} Run authorizeMcpServerOAuth for this server.`;return`${t} Run authorizeMcpServerOAuth for this server and complete this URL: ${e}`}hasStaticAuthorizationHeader(){let e=this.registration.transport;if(e.type==="stdio")return!1;return Object.keys(e.headers??{}).some((t)=>t.toLowerCase()==="authorization")}async handleOperationError(e){let t=this.authContext??NC({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??B8,clientInformation:LC(this.registration.oauthClient)}),n=om(e,this.registration.name,this.requestTimeoutMs),r=DC(e),o=r?this.formatUnauthorizedMessage(t.getLastAuthorizationUrl()):Wa(n);if(r&&!this.hasStaticAuthorizationHeader())await t.markAuthorizationRequired(o);else await t.markConnectionError(o);throw Error(o)}}function fv(e={}){return(t)=>t.transport.type==="stdio"?new G8(t):new V8(t,e)}OC();import{isMcpTimeoutConfigured as Y8,resolveMcpTimeoutSeconds as X8}from"@cerebriline/shared";var VLe=5000;function gr(){return Date.now()}function YLe(e){return e.map((t)=>({name:t.name,description:t.description,inputSchema:t.inputSchema,...t.readOnlyHint?{readOnlyHint:!0}:{}}))}class gv{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor(e){this.clientFactory=e.clientFactory,this.toolsCacheTtlMs=e.toolsCacheTtlMs??VLe}async registerServer(e){await this.runExclusive(e.name,async()=>{let t=this.servers.get(e.name);if(!t){this.servers.set(e.name,{registration:{...e},status:"disconnected",updatedAt:gr()});return}let n=JSON.stringify(t.registration.transport)!==JSON.stringify(e.transport),r=Y8(t.registration.timeoutSeconds)!==Y8(e.timeoutSeconds)||X8(t.registration.timeoutSeconds)!==X8(e.timeoutSeconds);if(t.registration={...e},t.updatedAt=gr(),n||r)await this.disconnectState(t),t.client=void 0,t.toolCache=void 0,t.toolCacheUpdatedAt=void 0})}async unregisterServer(e){await this.runExclusive(e,async()=>{let t=this.requireServer(e);await this.disconnectState(t),this.servers.delete(e)})}async connectServer(e){await this.runExclusive(e,async()=>{let t=this.requireServer(e);await this.connectState(t)})}async disconnectServer(e){await this.runExclusive(e,async()=>{let t=this.requireServer(e);await this.disconnectState(t)})}async setServerDisabled(e,t){await this.runExclusive(e,async()=>{let n=this.requireServer(e);if(n.registration={...n.registration,disabled:t},n.updatedAt=gr(),t)await this.disconnectState(n)})}listServers(){return[...this.servers.values()].map((e)=>({name:e.registration.name,status:e.status,disabled:e.registration.disabled===!0,lastError:e.lastError,toolCount:e.toolCache?.length??0,updatedAt:e.updatedAt,metadata:e.registration.metadata})).sort((e,t)=>e.name.localeCompare(t.name))}async listTools(e){let t=this.requireServer(e),n=t.toolCacheUpdatedAt??0;if(t.toolCache&&gr()-n<=this.toolsCacheTtlMs)return t.toolCache;return this.refreshTools(e)}async refreshTools(e){return this.runExclusive(e,async()=>{let t=this.requireServer(e),r=await(await this.ensureConnectedClient(t)).listTools(),o=YLe(r);return t.toolCache=o,t.toolCacheUpdatedAt=gr(),t.updatedAt=gr(),o})}async callTool(e){return this.runExclusive(e.serverName,async()=>{let t=this.requireServer(e.serverName),n=await this.ensureConnectedClient(t);return t.updatedAt=gr(),n.callTool({name:e.toolName,arguments:e.arguments,context:e.context})})}async dispose(){let e=[...this.servers.keys()],t=[];for(let n of e)try{await this.unregisterServer(n)}catch(r){t.push(r)}if(t.length>0)throw AggregateError(t,"MCP manager dispose failed")}async ensureConnectedClient(e){if(await this.connectState(e),!e.client)throw Error(`MCP server "${e.registration.name}" does not have an initialized client.`);return e.client}async connectState(e){if(e.registration.disabled)throw Error(`MCP server "${e.registration.name}" is disabled and cannot be connected.`);if(e.status==="connected"&&e.client)return;e.status="connecting",e.updatedAt=gr();let t=e.client;try{t??=await this.clientFactory(e.registration),e.client=t,await t.connect(),e.status="connected",e.lastError=void 0,e.updatedAt=gr()}catch(n){throw await t?.disconnect().catch(()=>{}),e.status="disconnected",e.lastError=n instanceof Error?n.message:String(n),e.updatedAt=gr(),n}}async disconnectState(e){if(!e.client){e.status="disconnected",e.updatedAt=gr();return}try{await e.client.disconnect()}finally{e.status="disconnected",e.updatedAt=gr()}}requireServer(e){let t=this.servers.get(e);if(!t)throw Error(`Unknown MCP server: ${e}`);return t}async runExclusive(e,t){let n=this.operationLocks.get(e)??Promise.resolve(),r,o=new Promise((s)=>{r=s}),i=n.catch(()=>{return}).then(()=>o);this.operationLocks.set(e,i),await n.catch(()=>{return});try{return await t()}finally{if(r?.(),this.operationLocks.get(e)===i)this.operationLocks.delete(e)}}}import{createHash as XLe}from"node:crypto";var J8=64,JLe=/[^a-zA-Z0-9_-]+/g,Q8=8,QLe=1,ZLe="mcp_tool";function eNe(e){return XLe("sha1").update(e).digest("hex").slice(0,Q8)}function tNe(e){return e.replace(JLe,"_")}var yv=({serverName:e,toolName:t})=>{let n=`${e}__${t}`,r=tNe(n);if(r===n&&n.length<=J8)return n;let o=eNe(n),i=J8-QLe-Q8;return`${r.slice(0,i)||ZLe}_${o}`};import{createTool as nNe}from"@cerebriline/shared";function rNe(e,t){let n=t.description?.trim(),r=`From the "${e}" MCP server.`;return n?`${n}
1287
1287
 
1288
- ${r}`:`Execute MCP tool "${t.name}". ${r}`}async function BC(e){let t=await e.provider.listTools(e.serverName),n=e.nameTransform??yv;return t.map((r)=>{let o=n({serverName:e.serverName,toolName:r.name});return nNe({name:o,resultPolicy:"cache-oversized",description:rNe(e.serverName,r),inputSchema:r.inputSchema,source:"mcp",readOnly:r.readOnlyHint===!0,timeoutMs:e.timeoutMs,retryable:e.retryable,maxRetries:e.maxRetries,execute:async(i,s)=>e.provider.callTool({serverName:e.serverName,toolName:r.name,arguments:i&&typeof i==="object"&&!Array.isArray(i)?i:void 0,context:s})})})}import{isCodeIndexWorkspace as nht}from"@cerebriline/shared";import{DEFAULT_LIBRARY_SETTINGS as Gut}from"@cerebriline/shared";import{resolveClineDataDir as Yut}from"@cerebriline/shared/storage";function wv(e,t){if(!e)return;if(!t)return e;return{available:(n)=>e.available(n),search:(n,r,o)=>e.search(n,r,o,{readFile:async(i)=>(await t.read(i)).toString("utf8")})}}function bv(e){if(!e)return;return{canAdmit:e.can_admit!==!1,headroomSessions:typeof e.headroom_sessions==="number"?e.headroom_sessions:-1,reason:e.reason??""}}var oNe=2000;function iNe(e,t){return new Promise((n)=>{if(e<=0||t?.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);t?.addEventListener("abort",r,{once:!0})})}function Z8(e){let t=Math.max(0,e.holdRetryMs??oNe),n=e.sleep??iNe,r=e.logger,o,i=!0,s="",a=0,d=[],l=()=>{d.shift()?.()},c=async(u)=>{let h,p=new Promise((m)=>{if(h=m,h)d.push(h)});await Promise.race([p,n(t,u)]);let f=h?d.indexOf(h):-1;if(f>=0)d.splice(f,1)};return{acquire:async(u)=>{for(;;){if(u?.aborted)throw Error("Admission wait cancelled");if(o===void 0){i=!1;let h;try{h=await e.capacity()}catch(p){r?.log?.("PolyKV capacity could not be read; admitting without it",{severity:"warn",error:p instanceof Error?p.message:String(p)}),h=void 0}if(h===void 0)o=Number.POSITIVE_INFINITY,s="capacity unavailable; not holding";else if(!h.canAdmit){s=h.reason,r?.log?.("PolyKV is holding the round",{severity:"info",reason:h.reason,headroomSessions:h.headroomSessions}),await c(u);continue}else s=h.reason,o=h.headroomSessions<0?Number.POSITIVE_INFINITY:Math.max(1,h.headroomSessions)}if(o>0)return o-=1,a+=1,{reason:s};o=void 0,await c(u)}},canAdmitMore:async()=>{if(o!==void 0&&o>0)return!0;if(!i)return!1;i=!1;let u;try{u=await e.capacity()}catch{return o=Number.POSITIVE_INFINITY,!0}if(u===void 0)return o=Number.POSITIVE_INFINITY,s="capacity unavailable; not holding",!0;if(!u.canAdmit)return s=u.reason,o=void 0,!1;return s=u.reason,o=u.headroomSessions<0?Number.POSITIVE_INFINITY:Math.max(1,u.headroomSessions),o>0},tryAcquire:async()=>{if(o!==void 0&&o>0)return o-=1,a+=1,{reason:s};if(!i)return;i=!1;let u;try{u=await e.capacity()}catch(h){r?.log?.("PolyKV capacity could not be read; admitting without it",{severity:"warn",error:h instanceof Error?h.message:String(h)}),u=void 0}if(u===void 0)o=Number.POSITIVE_INFINITY,s="capacity unavailable; not holding";else if(!u.canAdmit){s=u.reason,o=void 0;return}else s=u.reason,o=u.headroomSessions<0?Number.POSITIVE_INFINITY:Math.max(1,u.headroomSessions);if(o>0)return o-=1,a+=1,{reason:s};o=void 0;return},release:()=>{if(a>0)a-=1;i=!0,l()}}}import{access as mNe}from"node:fs/promises";import{createTool as fNe,validateWithZod as gNe,zodToJsonSchema as yNe}from"@cerebriline/shared";import{resolveAgentConfigSearchPaths as wNe}from"@cerebriline/shared/storage";import{z as On}from"zod";import{mkdir as sNe,writeFile as aNe}from"node:fs/promises";import{basename as dNe,dirname as lNe,join as cNe,resolve as eV}from"node:path";import{agentFileName as uNe,renderAgentFile as hNe,validateAgentFields as pNe}from"@cerebriline/shared";async function tV(e){pNe(e.agent);let t=cNe(e.directory,uNe(e.agent.name));if(lNe(eV(t))!==eV(e.directory))throw Error(`"${e.agent.name}" is not a usable agent name.`);let n=await e.fileExists(t);if(n&&!e.overwrite)throw Error(`An agent already exists at ${dNe(t)}. Pass overwrite to replace it, or choose another name.`);return await sNe(e.directory,{recursive:!0}),await aNe(t,hNe(e.agent),"utf-8"),{path:t,overwritten:n}}var nV=On.object({name:On.string().trim().min(1).describe("Short identifier for the agent, e.g. 'network-troubleshooting'. Becomes the file name and the name the lead model refers to it by."),description:On.string().trim().min(1).describe("One line saying what this agent is for. This is the only thing read when choosing which agent to hand work to, so say when to use it, not just what it is."),systemPrompt:On.string().trim().min(1).describe("The agent's own system prompt: who it is, how it works, what it must not do. Written to the body of the file."),scope:On.enum(["workspace","global"]).optional().describe("'workspace' writes to .cline/agents in this project (default); 'global' writes to the Cline data directory so every project sees it."),profile:On.string().trim().optional().describe("A saved API configuration profile the agent runs on, by name. Use this to run an agent on a different model from the session's."),providerId:On.string().trim().optional(),modelId:On.string().trim().optional(),tools:On.array(On.string()).optional().describe("Restrict the agent to these tools. Omit to give it the session's toolset."),skills:On.array(On.string()).optional().describe("Restrict the agent to these skills, by name. Omit to give it all of them."),maxIterations:On.number().int().positive().optional(),overwrite:On.boolean().optional().describe("Replace an agent of the same name. Without this, an existing agent is left alone and an error says so.")});async function bNe(e){try{return await mNe(e),!0}catch{return!1}}function rV(e){return fNe({name:"create_agent",description:"Create a Cline agent the user can delegate work to. Agents are markdown files with YAML frontmatter; each one becomes a subagent_<name> tool and can run on its own model. Use this when the user asks for an agent, a specialist, or a helper for a kind of task.",inputSchema:yNe(nV),execute:async(n)=>{let r=gNe(nV,n),o=r.scope??"workspace",i=wNe(e.workspaceRoot),s=e.workspaceRoot&&i.length>1?i[0]:void 0,a=i[i.length-1],d=o==="global"?a:s;if(!d)throw Error("There is no workspace open, so a workspace agent has nowhere to go. Use scope 'global' instead.");let l={name:r.name,description:r.description,systemPrompt:r.systemPrompt,profile:r.profile,providerId:r.providerId,modelId:r.modelId,tools:r.tools,skills:r.skills,maxIterations:r.maxIterations},c=await tV({directory:d,agent:l,overwrite:r.overwrite,fileExists:bNe});return{path:c.path,name:r.name.trim(),scope:o,overwritten:c.overwritten,note:"Agent files are loaded when a session starts, so this agent becomes available in the next session rather than this one."}},timeoutMs:15000,retryable:!1})}import{validateWithZod as vNe,zodToJsonSchema as kNe}from"@cerebriline/shared";var TNe=new Set(["check_file","ask_lsp","list_files"]),oV="ask_question";function SNe(e,t){let n=["This agent stopped to ask a question instead of finishing its task. Nothing was asked of the user.","",`Question: ${e.trim()}`];if(t.length>0)n.push("Options:",...t.map((r)=>`- ${r}`));return n.push("","Answer it by running the agent again with the answer in its task, answer it yourself if you can, or ask the user with `ask_question` if only they know."),n.join(`
1288
+ ${r}`:`Execute MCP tool "${t.name}". ${r}`}async function BC(e){let t=await e.provider.listTools(e.serverName),n=e.nameTransform??yv;return t.map((r)=>{let o=n({serverName:e.serverName,toolName:r.name});return nNe({name:o,resultPolicy:"cache-oversized",description:rNe(e.serverName,r),inputSchema:r.inputSchema,source:"mcp",readOnly:r.readOnlyHint===!0,timeoutMs:e.timeoutMs,retryable:e.retryable,maxRetries:e.maxRetries,execute:async(i,s)=>e.provider.callTool({serverName:e.serverName,toolName:r.name,arguments:i&&typeof i==="object"&&!Array.isArray(i)?i:void 0,context:s})})})}import{isCodeIndexWorkspace as oht}from"@cerebriline/shared";import{DEFAULT_LIBRARY_SETTINGS as Yut}from"@cerebriline/shared";import{resolveClineDataDir as Jut}from"@cerebriline/shared/storage";function wv(e,t){if(!e)return;if(!t)return e;return{available:(n)=>e.available(n),search:(n,r,o)=>e.search(n,r,o,{readFile:async(i)=>(await t.read(i)).toString("utf8")})}}function bv(e){if(!e)return;return{canAdmit:e.can_admit!==!1,headroomSessions:typeof e.headroom_sessions==="number"?e.headroom_sessions:-1,reason:e.reason??""}}var oNe=2000;function iNe(e,t){return new Promise((n)=>{if(e<=0||t?.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);t?.addEventListener("abort",r,{once:!0})})}function Z8(e){let t=Math.max(0,e.holdRetryMs??oNe),n=e.sleep??iNe,r=e.logger,o,i=!0,s="",a=0,d=[],l=()=>{d.shift()?.()},c=async(u)=>{let h,p=new Promise((m)=>{if(h=m,h)d.push(h)});await Promise.race([p,n(t,u)]);let f=h?d.indexOf(h):-1;if(f>=0)d.splice(f,1)};return{acquire:async(u)=>{for(;;){if(u?.aborted)throw Error("Admission wait cancelled");if(o===void 0){i=!1;let h;try{h=await e.capacity()}catch(p){r?.log?.("PolyKV capacity could not be read; admitting without it",{severity:"warn",error:p instanceof Error?p.message:String(p)}),h=void 0}if(h===void 0)o=Number.POSITIVE_INFINITY,s="capacity unavailable; not holding";else if(!h.canAdmit){s=h.reason,r?.log?.("PolyKV is holding the round",{severity:"info",reason:h.reason,headroomSessions:h.headroomSessions}),await c(u);continue}else s=h.reason,o=h.headroomSessions<0?Number.POSITIVE_INFINITY:Math.max(1,h.headroomSessions)}if(o>0)return o-=1,a+=1,{reason:s};o=void 0,await c(u)}},canAdmitMore:async()=>{if(o!==void 0&&o>0)return!0;if(!i)return!1;i=!1;let u;try{u=await e.capacity()}catch{return o=Number.POSITIVE_INFINITY,!0}if(u===void 0)return o=Number.POSITIVE_INFINITY,s="capacity unavailable; not holding",!0;if(!u.canAdmit)return s=u.reason,o=void 0,!1;return s=u.reason,o=u.headroomSessions<0?Number.POSITIVE_INFINITY:Math.max(1,u.headroomSessions),o>0},tryAcquire:async()=>{if(o!==void 0&&o>0)return o-=1,a+=1,{reason:s};if(!i)return;i=!1;let u;try{u=await e.capacity()}catch(h){r?.log?.("PolyKV capacity could not be read; admitting without it",{severity:"warn",error:h instanceof Error?h.message:String(h)}),u=void 0}if(u===void 0)o=Number.POSITIVE_INFINITY,s="capacity unavailable; not holding";else if(!u.canAdmit){s=u.reason,o=void 0;return}else s=u.reason,o=u.headroomSessions<0?Number.POSITIVE_INFINITY:Math.max(1,u.headroomSessions);if(o>0)return o-=1,a+=1,{reason:s};o=void 0;return},release:()=>{if(a>0)a-=1;i=!0,l()}}}import{access as mNe}from"node:fs/promises";import{createTool as fNe,validateWithZod as gNe,zodToJsonSchema as yNe}from"@cerebriline/shared";import{resolveAgentConfigSearchPaths as wNe}from"@cerebriline/shared/storage";import{z as On}from"zod";import{mkdir as sNe,writeFile as aNe}from"node:fs/promises";import{basename as dNe,dirname as lNe,join as cNe,resolve as eV}from"node:path";import{agentFileName as uNe,renderAgentFile as hNe,validateAgentFields as pNe}from"@cerebriline/shared";async function tV(e){pNe(e.agent);let t=cNe(e.directory,uNe(e.agent.name));if(lNe(eV(t))!==eV(e.directory))throw Error(`"${e.agent.name}" is not a usable agent name.`);let n=await e.fileExists(t);if(n&&!e.overwrite)throw Error(`An agent already exists at ${dNe(t)}. Pass overwrite to replace it, or choose another name.`);return await sNe(e.directory,{recursive:!0}),await aNe(t,hNe(e.agent),"utf-8"),{path:t,overwritten:n}}var nV=On.object({name:On.string().trim().min(1).describe("Short identifier for the agent, e.g. 'network-troubleshooting'. Becomes the file name and the name the lead model refers to it by."),description:On.string().trim().min(1).describe("One line saying what this agent is for. This is the only thing read when choosing which agent to hand work to, so say when to use it, not just what it is."),systemPrompt:On.string().trim().min(1).describe("The agent's own system prompt: who it is, how it works, what it must not do. Written to the body of the file."),scope:On.enum(["workspace","global"]).optional().describe("'workspace' writes to .cline/agents in this project (default); 'global' writes to the Cline data directory so every project sees it."),profile:On.string().trim().optional().describe("A saved API configuration profile the agent runs on, by name. Use this to run an agent on a different model from the session's."),providerId:On.string().trim().optional(),modelId:On.string().trim().optional(),tools:On.array(On.string()).optional().describe("Restrict the agent to these tools. Omit to give it the session's toolset."),skills:On.array(On.string()).optional().describe("Restrict the agent to these skills, by name. Omit to give it all of them."),maxIterations:On.number().int().positive().optional(),overwrite:On.boolean().optional().describe("Replace an agent of the same name. Without this, an existing agent is left alone and an error says so.")});async function bNe(e){try{return await mNe(e),!0}catch{return!1}}function rV(e){return fNe({name:"create_agent",description:"Create a Cline agent the user can delegate work to. Agents are markdown files with YAML frontmatter; each one becomes a subagent_<name> tool and can run on its own model. Use this when the user asks for an agent, a specialist, or a helper for a kind of task.",inputSchema:yNe(nV),execute:async(n)=>{let r=gNe(nV,n),o=r.scope??"workspace",i=wNe(e.workspaceRoot),s=e.workspaceRoot&&i.length>1?i[0]:void 0,a=i[i.length-1],d=o==="global"?a:s;if(!d)throw Error("There is no workspace open, so a workspace agent has nowhere to go. Use scope 'global' instead.");let l={name:r.name,description:r.description,systemPrompt:r.systemPrompt,profile:r.profile,providerId:r.providerId,modelId:r.modelId,tools:r.tools,skills:r.skills,maxIterations:r.maxIterations},c=await tV({directory:d,agent:l,overwrite:r.overwrite,fileExists:bNe});return{path:c.path,name:r.name.trim(),scope:o,overwritten:c.overwritten,note:"Agent files are loaded when a session starts, so this agent becomes available in the next session rather than this one."}},timeoutMs:15000,retryable:!1})}import{validateWithZod as vNe,zodToJsonSchema as kNe}from"@cerebriline/shared";var TNe=new Set(["check_file","ask_lsp","list_files"]),oV="ask_question";function SNe(e,t){let n=["This agent stopped to ask a question instead of finishing its task. Nothing was asked of the user.","",`Question: ${e.trim()}`];if(t.length>0)n.push("Options:",...t.map((r)=>`- ${r}`));return n.push("","Answer it by running the agent again with the answer in its task, answer it yourself if you can, or ask the user with `ask_question` if only they know."),n.join(`
1289
1289
  `)}function xNe(){return{name:oV,description:"Ask the agent that started you a question, when you cannot finish the task without an answer. This ends your run: your question, with 2-5 options, is your report, and the lead decides what happens next -- it may run you again with the answer. Ask only what you cannot find out with your tools. Output: none you will see; the call is the last thing you do.",inputSchema:kNe(Fs),lifecycle:{completesRun:!0},retryable:!1,maxRetries:0,execute:async(e)=>{let t=vNe(Fs,e);return SNe(t.question,t.options)}}}function sm(e,t){let n=(t??[]).filter((i)=>TNe.has(i.name)),r=new Set(n.map((i)=>i.name));return[...e.filter((i)=>!r.has(i.name)),...n].map((i)=>i.name===oV?xNe():i)}import{appendFileSync as LNe,existsSync as Fc,mkdirSync as cV,readdirSync as NNe,readFileSync as WC,renameSync as uV,statSync as DNe,writeFileSync as hV}from"node:fs";import{join as jC}from"node:path";import{resolveTeamDataDir as $Ne}from"@cerebriline/shared/storage";import{existsSync as _Ne,mkdirSync as ENe}from"node:fs";import{join as ANe}from"node:path";import{safeJsonParse as lV}from"@cerebriline/shared";import{loadSqliteDb as RNe,nowIso as Dc}from"@cerebriline/shared/db";import{resolveDbDataDir as INe}from"@cerebriline/shared/storage";function CNe(){return INe()}function PNe(e){let t=lV(e);if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!r||typeof r!=="object")continue;let o=r,{agentId:i,rolePrompt:s}=o;if(typeof i!=="string"||!i.trim())continue;if(typeof s!=="string"||!s.trim())continue;let a={agentId:i.trim(),rolePrompt:s};if(typeof o.modelId==="string"&&o.modelId.trim())a.modelId=o.modelId.trim();if(typeof o.maxIterations==="number"&&Number.isFinite(o.maxIterations))a.maxIterations=Math.max(1,Math.floor(o.maxIterations));if(typeof o.temperature==="number"&&Number.isFinite(o.temperature)&&o.temperature>=0)a.temperature=o.temperature;if(typeof o.seed==="number"&&Number.isInteger(o.seed))a.seed=o.seed;if(o.seedRandom===!0)a.seedRandom=!0;if(typeof o.temperatureBase==="number"&&Number.isFinite(o.temperatureBase)&&o.temperatureBase>=0)a.temperatureBase=o.temperatureBase;if(typeof o.temperatureRange==="number"&&Number.isFinite(o.temperatureRange)&&o.temperatureRange>=0&&o.temperatureRange<=100)a.temperatureRange=o.temperatureRange;n.push(a)}return n}var iV=ts,HC=2000,MNe=2592000000,sV=["agent_event","run_progress"],aV=2,ONe=["team_tasks","team_runs","team_outcomes","team_outcome_fragments","team_mailbox","team_mission_log"];function $c(e){if(e===void 0||e===null)return null;let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t.toISOString()}function am(e,t){if(typeof e!=="string"||e.length===0)return t;return lV(e)??t}var dm=(e)=>typeof e==="string"?e:"";function dV(e){return{teamId:e.teamId,teamName:e.teamName,reset:!0,members:e.members,tasks:e.tasks,mailbox:e.mailbox,missionLog:e.missionLog,runs:e.runs,outcomes:e.outcomes,outcomeFragments:e.outcomeFragments}}class vv{teamDirPath;db;retentionPerTeam;retentionMs;constructor(e={}){this.teamDirPath=e.teamDir??CNe(),this.retentionPerTeam=e.eventRetentionPerTeam??HC,this.retentionMs=e.eventRetentionMs??MNe}init(){this.getRawDb()}close(){this.db?.close?.(),this.db=void 0}ensureTeamDir(){if(!_Ne(this.teamDirPath))ENe(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return ANe(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let e=RNe(this.dbPath());return this.ensureSchema(e),this.db=e,e}ensureSchema(e){if(e.exec("PRAGMA journal_mode = WAL;"),e.exec("PRAGMA busy_timeout = 5000;"),e.exec(`
1290
1290
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
1291
1291
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
@@ -1459,7 +1459,7 @@ ${r}`:`Execute MCP tool "${t.name}". ${r}`}async function BC(e){let t=await e.pr
1459
1459
  `).filter(Boolean),r=[],o=0;for(let s=n.length-1;s>=0&&r.length<HC;s--){let a=n[s];if(o+=Buffer.byteLength(a,"utf8")+1,o>pV/2&&r.length>0)break;r.push(a)}r.reverse();let i=`${e}.tmp`;hV(i,`${r.join(`
1460
1460
  `)}
1461
1461
  `,"utf8"),uV(i,e)}persistRuntime(e,t,n){this.ensureTeamSubdir(e);let r={version:1,updatedAt:mV(),teamState:{...t,runs:t.runs.map((s)=>({...s,result:Ao(s.result)}))},teammates:n},o=this.statePath(e),i=`${o}.tmp`;hV(i,`${JSON.stringify(r,null,2)}
1462
- `,"utf8"),uV(i,o)}markInProgressRunsInterrupted(e,t){let n=this.readEnvelope(e);if(!n?.teamState?.runs?.length)return[];let r=n.teamState.runs.filter((i)=>i.status==="queued"||i.status==="running").map((i)=>i.id);if(r.length===0)return[];let o=new Date;return n.teamState={...n.teamState,runs:n.teamState.runs.map((i)=>i.status==="queued"||i.status==="running"?{...i,status:"interrupted",error:t,endedAt:o}:i)},this.persistRuntime(e,n.teamState,n.teammates),r}ensureTeamDir(){if(!Fc(this.teamDirPath))cV(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(e){let t=jC(this.ensureTeamDir(),gn(e));if(!Fc(t))cV(t,{recursive:!0});return t}statePath(e){return jC(this.ensureTeamDir(),gn(e),"state.json")}historyPath(e){return jC(this.ensureTeamDir(),gn(e),"task-history.jsonl")}readEnvelope(e){let t=this.statePath(e);if(!Fc(t))return;try{let n=JSON.parse(WC(t,"utf8"));if(n?.version===1&&n.teamState)return n}catch{}return}}function fV(e={}){try{let t=new vv(e);return t.init(),t}catch{let t=new kv({teamDir:e.teamDir});return t.init(),t}}import{chmodSync as FNe,existsSync as qC}from"node:fs";import{join as zC}from"node:path";function Tv(e){if(!e)return;if(process.platform==="win32"){let t=zC(e,"cerebriline-sandbox.exe"),n=zC(e,"hook.dll");if(!qC(t)||!qC(n))return;return{launcher:t,hook:n,platforms:["win32"]}}if(process.platform==="linux")return gV(e,"","linux");if(process.platform==="darwin")return gV(e,"darwin-","darwin");return}function gV(e,t,n){let r={x64:"x64",arm64:"arm64"}[process.arch],i=(r?[`cerebriline-sandbox-${t}${r}`,"cerebriline-sandbox"]:["cerebriline-sandbox"]).map((s)=>zC(e,s)).find(qC);if(!i)return;try{FNe(i,493)}catch{}return{launcher:i,hook:i,platforms:[n]}}var UNe=300,BNe=60000,yV=5000;class KC{opts;pendingEvents=[];teammatesDirty=!1;timer;lastFlushAt=0;disposed=!1;constructor(e){this.opts={batchMs:UNe,telemetryFlushMs:BNe,now:Date.now,...e}}onEvent(e){if(this.disposed)return;if(!pi(e)){if(this.opts.now()-this.lastFlushAt>=this.opts.telemetryFlushMs)this.schedule();return}if(this.pendingEvents.push({type:e.type,payload:is(e)}),NI(e)){this.flush();return}this.schedule()}markTeammatesDirty(){this.teammatesDirty=!0}markStateDirty(){if(this.disposed)return;this.schedule()}flush(){this.clearTimer();let e=this.opts.source();if(!e)return;if(!e.hasPendingStateDelta()&&this.pendingEvents.length===0&&!this.teammatesDirty)return;let n=this.pendingEvents,r=this.teammatesDirty;this.pendingEvents=[],this.teammatesDirty=!1;let o=e.drainStateDelta();try{this.opts.store.persistBatch(this.opts.teamKey,{events:n,delta:o,teammates:this.opts.teammates(),getFullState:()=>e.exportState()}),this.lastFlushAt=this.opts.now()}catch(i){e.requeueStateDelta(o);let s=n.concat(this.pendingEvents);if(this.pendingEvents=s.length>yV?s.slice(-yV):s,this.teammatesDirty=this.teammatesDirty||r,!this.disposed)this.schedule();try{this.opts.onError?.(i)}catch{}}}dispose(){if(this.disposed)return;this.disposed=!0,this.flush()}schedule(){if(this.timer)return;this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},this.opts.batchMs),this.timer.unref?.()}clearTimer(){if(this.timer)clearTimeout(this.timer),this.timer=void 0}}function Sv(e,t){return zNe(e,t)}function bV(e,t){let n=t?.["*"]??{},r=t?.[e]??{};return{...n,...r}.enabled!==!1}function VNe(e,t){return e.filter((n)=>bV(n.name,t))}function _v(e,t){return Ji(VNe(e,t))}function YNe(e){if(e?.readLimitEnabled===!1)return Number.POSITIVE_INFINITY;let t=e?.readLimitChars;return typeof t==="number"&&Number.isFinite(t)&&t>0?Math.floor(t):void 0}function XNe(e,t){if(!t?.length)return e;let n={...e??{}};for(let r of t){let o=r.trim();if(!o)continue;n[o]={...n[o]??{},enabled:!1}}return n}var JNe={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function QNe(e){let t=e.trim().toLowerCase();return JNe[t]??t}function ZNe(e,t){if(t.tools===void 0)return e;let n=new Set(t.tools.map(QNe));if(t.skills!==void 0)n.add("skills");return e.filter((r)=>n.has(r.name))}function eDe(){return`team-${GNe(5)}`}function Ev(e,t,n,r,o,i,s,a,d,l,c,u,h,p,f,m){let g=go[yo({mode:n})],y=Ky(t,r,n,o??zy);return _v(dp({cwd:e,telemetry:d,qaCredentials:l,executorOptions:p?.workspace?{...p.workspace.executorOptions,...f?{extractDocument:f}:{},...h!==void 0?{fileRead:{maxReadChars:h}}:{}}:{bash:{executionController:c,...m?{wrapSpawn:m}:{}},...u?{receipts:u}:{},...f?{extractDocument:f}:{},...h!==void 0?{fileRead:{maxReadChars:h}}:{}},...g,enableSkills:!!s,...y,enableExtractDocument:g.enableExtractDocument===!0&&bV(le.EXTRACT_DOCUMENT,i),...p&&!p.workspace?.allowCommands?{enableBash:!1}:{},executors:{...s?{skills:s}:{},...p?.workspace?a?.semanticSearch?{semanticSearch:wv(a.semanticSearch,p.workspace.executorOptions.overlay)}:{}:a??{}}}),i)}function tDe(e){return Ev(e.cwd,e.providerId,e.mode,e.modelId,e.toolRoutingRules,e.toolPolicies,nDe,e.toolExecutors).some((t)=>t.name==="skills")}var nDe=async()=>"";async function rDe(e){let t=jr(),n=e.includeSettings&&nm({filePath:t});if(!n&&!e.agentPluginServers?.length)return{tools:[]};let r=fv({settingsPath:t}),o=fv({restrictConfiguredHeadersToOrigin:!0}),i=new gv({clientFactory:(u)=>u.metadata?.source==="agent-plugin"?o(u):r(u)}),s=[];if(n)try{s=await MC(i,{filePath:t})}catch(u){let h=u instanceof Error?u.message:String(u);e.logger?.log(`[mcp] Failed to load MCP settings, skipping settings-backed MCP tools: ${h}`)}let a=new Set(s.map((u)=>u.name));for(let u of e.agentPluginServers??[]){let h=u.registration;if(a.has(h.name)){e.logger?.log(`[agent-plugins] MCP server '${h.name}' conflicts with an existing server and was skipped.`,{severity:"error"});continue}try{await i.registerServer(h),s.push(h),a.add(h.name)}catch(p){let f=p instanceof Error?p.message:String(p);e.logger?.log(`[agent-plugins] Failed to register MCP server '${h.name}', skipping: ${f}`,{severity:"error"})}}if(s.length===0)return await i.dispose().catch(()=>{}),{tools:[]};let d=s.filter((u)=>u.disabled!==!0),l=await Promise.allSettled(d.map((u)=>BC({serverName:u.name,provider:i,timeoutMs:KNe(u.timeoutSeconds)*1000}))),c=[];for(let[u,h]of l.entries())if(h.status==="fulfilled")c.push(...h.value);else{let p=h.reason instanceof Error?h.reason.message:String(h.reason);e.logger?.log(`[mcp] Failed to load tools from MCP server "${d[u].name}", skipping: ${p}`)}return{tools:c,shutdown:async()=>{await i.dispose()}}}function xv(e){return`configured:${e}`}function GC(e){return`teammate:${e}`}function oDe(e){return{handBack:(t)=>e().handBack(GC(t),t),release:async(t)=>{await e().close(GC(t),t)}}}function iDe(e,t){if(!e)return;try{e.cancelOutstandingWork(`${VC}${t}`)}catch{}for(let n of e.getTeammateIds())try{e.shutdownTeammate(n,`${VC}${t}`)}catch{}}var VC="runtime_shutdown:";function sDe(e){if(e===void 0)return!1;if(e.startsWith(VC))return!0;switch(e){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function cs(e){return CI({providerId:e.providerId,modelId:e.modelId,agentNodes:(e.agentNodes??[]).map((t)=>({...t,connection:t.connection})),polykvAgentsPriorityZero:e.polykvAgentsPriorityZero,overflowCapacity:e.maxConcurrentAgents,lead:{apiKey:e.apiKey,baseUrl:e.baseUrl,headers:e.headers,providerConfig:e.providerConfig,knownModels:e.knownModels,thinking:e.thinking,reasoningEffort:e.reasoningEffort,thinkingBudgetTokens:e.thinkingBudgetTokens,maxTokensPerTurn:e.maxTokensPerTurn,maxToolResultChars:e.maxToolResultChars,staleReadRewrites:e.staleReadRewrites,toolResultFormat:e.toolResultFormat,temperature:e.temperature}})}function aDe(e){let t=new Set(e.offered),n=["spawn_agent","spawn_swarm"].filter((d)=>!t.has(d));if(n.length===0)return{};let r;if(!e.subagentsEnabled)r="sub-agents are switched off in this session's settings.";else if(e.serialised)r=`${e.multipleNodes?"every configured node serves 1 request at a time":"this endpoint serves 1 request at a time"}, so a spawned agent would run after you rather than beside you.`;else return{};let o=e.offered.filter((d)=>d.startsWith("subagent_")),i=o.length>0?`Do the work yourself, or hand one job at a time to a configured agent: ${o.join(", ")}.`:"Do the work yourself.",s=e.subagentsEnabled?`Only the user can change this, by raising the profile's parallel sessions${e.multipleNodes?" or a node's capacity":""}.`:"Only the user can change this, in the settings.",a={};for(let d of n)a[d]=`${r} ${i} Do not call ${d} again in this session; it will be refused the same way. ${s}`;return a}function dDe(e){let t=go[yo({mode:e.mode})];return{sessionId:e.sessionId||"",mode:e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act",enableTools:e.enableTools!==!1,enableSpawnAgent:e.enableSpawnAgent??t.enableSpawnAgent??!0,enableAgentTeams:ns({maxConcurrentAgents:e.maxConcurrentAgents,nodes:cs(e)})&&e.enableAgentTeams===!0,disableMcpSettingsTools:e.disableMcpSettingsTools===!0,yolo:e.yolo===!0,missionLogIntervalSteps:typeof e.missionLogIntervalSteps==="number"&&Number.isFinite(e.missionLogIntervalSteps)?e.missionLogIntervalSteps:3,missionLogIntervalMs:typeof e.missionLogIntervalMs==="number"&&Number.isFinite(e.missionLogIntervalMs)?e.missionLogIntervalMs:120000}}class YC{teamRuntimeEntries=new Map;async build(e){let{config:t,hooks:n,extensions:r,logger:o,telemetry:i,createSpawnTool:s,createSwarmTool:a,onTeamRestored:d,userInstructionService:l,configExtensions:c,toolExecutors:u}=e,h=e.onTeamEvent??(()=>{}),p=dDe(t),f=[];if(p.enableTools&&p.mode!=="yolo"&&SA("web_search")&&wV({providerId:t.providerId,modelId:t.modelId},"web_search"))f.push({name:"web_search"});if(p.enableTools&&wV({providerId:t.providerId,modelId:t.modelId},"image_generation"))f.push({name:"image_generation",outputFormat:"png"});let m=t.workspaceRoot??t.cwd,g=XNe(e.toolPolicies??t.toolPolicies,t.enableExtractDocument===!0?t.providerConfig?.tools?.disabled:[...t.providerConfig?.tools?.disabled??[],le.EXTRACT_DOCUMENT]),y=YNe(t.providerConfig?.tools),w=Ta(),k=[],b=t.teamName?.trim()||eDe(),v=t.sessionId?.trim()||b,E=p.enableSpawnAgent?MI({workspaceRoot:m}):{configs:[],errors:[],searchPaths:[]},S=E.configs.some((Y)=>Y.skills!==void 0),x=Sv(c,"rules"),T=Sv(c,"skills"),A=T||S,R=Sv(c,"workflows"),C=Sv(c,"plugins"),L=x||T||R,N=!1,W=[],D=l,K;for(let Y of E.errors)(o??t.logger)?.log?.(`[agents] Failed to load agent config at ${Y.path}: ${Y.error.message}`);if(p.enableSpawnAgent){(o??t.logger)?.log?.(E.configs.length>0?`[agents] ${E.configs.length} configured agent(s): ${E.configs.map((Q)=>Q.name).join(", ")}`:`[agents] No configured agents found. Looked in: ${E.searchPaths.join(", ")||"(no search path)"}`);let Y=E.configs.filter((Q)=>Q.profile!==void 0&&t.resolveProfileConnection?.(Q.profile)===void 0);for(let Q of Y){let ee=t.listProfileNames?.()??[];(o??t.logger)?.log?.(`[agents] "${Q.name}" names the API configuration profile "${Q.profile}", which no longer exists, and will fail when called. `+(ee.length>0?`Available profiles: ${ee.join(", ")}.`:"This host has no saved profiles."),{severity:"warn"})}}if(!D&&(L||S))D=Lc({skills:A?{workspacePath:m,includePluginSkills:C,pluginSkillDirectories:C?e.pluginSkillDirectories:void 0,pluginPaths:t.pluginPaths,cwd:t.cwd,agentPluginSkills:C?e.agentPluginSkills:void 0}:{workspacePath:m},rules:{workspacePath:t.cwd},workflows:{workspacePath:t.cwd}}),W.push(D);else if(D&&C&&e.agentPluginSkills?.length&&(L||S)){let Y=Lc({skills:{directories:[],agentPluginSkills:e.agentPluginSkills},rules:{directories:[]},workflows:{directories:[]}});W.push(Y),D=vC([D,Y])}if(D)await D.start().catch(()=>{});let V=p.enableTools&&T&&Boolean(D)&&D?.hasConfiguredSkills(t.skills)===!0&&tDe({cwd:t.cwd,providerId:t.providerId,mode:p.mode,modelId:t.modelId,toolRoutingRules:t.toolRoutingRules,toolPolicies:g,toolExecutors:u}),B=D&&L?D.createExtension({includeRules:x,includeSkills:T,includeWorkflows:R,registerSkillsTool:V,allowedSkillNames:t.skills}):void 0,j=p.mode==="plan"&&p.enableTools?XT({telemetry:i??t.telemetry}):void 0,G=[B,j].filter((Y)=>Y!==void 0),z=G.length>0?[...r??t.extensions??[],...G]:r??t.extensions;if(p.enableTools){k.push(...Ev(t.cwd,t.providerId,p.mode,t.modelId,t.toolRoutingRules,g,void 0,u,i??t.telemetry,t.qaCredentials,e.runCommandExecutionController,e.readReceipts,y,void 0,oa(t),pK({enabled:t.leadSandboxConfine===!0,workspaceRoot:t.workspaceRoot??t.cwd,binaries:Tv(t.sandboxBinariesDir),tempRoot:WNe(HNe(),"cerebriline-sandbox-tmp")})));let Y=C?e.agentPluginMcpServers:void 0;if(!p.disableMcpSettingsTools||Y?.length){let Q=await rDe({logger:t.logger,includeSettings:!p.disableMcpSettingsTools,agentPluginServers:Y});k.push(...Q.tools),K=Q.shutdown}}let M,X=p.enableAgentTeams?fV():void 0,oe=X?.loadRuntime(v),H=oe?.state,J=oe?.teammates??[],he=new Map(J.map((Y)=>[Y.agentId,Y])),se=X?new KC({teamKey:v,store:X,source:()=>M,teammates:()=>Array.from(he.values()),onError:(Y)=>(o??t.logger)?.log?.(`[team] failed to persist team state: ${Y instanceof Error?Y.message:String(Y)}`)}):void 0,re=t.sessionId||b,Ge,I=[],_=!1,F=t.delegatedAgentConnection,O=Nr({providerId:F?.providerId??t.providerId,baseUrl:F?.baseUrl??t.baseUrl}),ue=t.providerConfig,ne=ue&&$o(ue)?Z8({capacity:async()=>bv(await Sd({sessionId:t.sessionId,providerConfig:ue,logger:o??t.logger})),...o??t.logger?{logger:o??t.logger}:{}}):void 0,fe=hR(t.maxConcurrentAgents,uR(t.agentSlotLimits),ne?(Y)=>Y===O?ne:void 0:void 0,ue&&$o(ue)?(Y)=>Y===O?()=>tT(ue):void 0:void 0),Ce=F?{...F}:{},We=cs(t).map((Y)=>({...Y,connection:Y.connection})),Se=oi({providerId:t.providerId,modelId:t.modelId,distinctId:e.distinctId,sessionId:t.sessionId,cwd:t.cwd,apiKey:t.apiKey??"",baseUrl:t.baseUrl,headers:t.headers,providerConfig:t.providerConfig,knownModels:t.knownModels,thinking:t.thinking,reasoningEffort:t.reasoningEffort,thinkingBudgetTokens:t.thinkingBudgetTokens,maxTokensPerTurn:t.maxTokensPerTurn,maxToolResultChars:t.maxToolResultChars,staleReadRewrites:t.staleReadRewrites,toolResultFormat:t.toolResultFormat,temperature:t.temperature,maxIterations:t.maxIterations,...t.compaction?.cappedThinkingBudgetMessage?{thinkingBudgetMessage:t.compaction.cappedThinkingBudgetMessage}:{},hooks:n,extensions:z,logger:o??t.logger,telemetry:e.telemetry??t.telemetry,workspaceMetadata:t.workspaceMetadata,createPrepareTurn:e.createDelegatedPrepareTurn,condenseDiscardedReasoning:e.condenseDiscardedReasoning,onLoopCut:e.onDelegatedLoopCut,slotGate:fe.for(Nr({providerId:Ce.providerId??t.providerId,baseUrl:Ce.baseUrl??t.baseUrl})),slotGates:fe,...Ce},Object.keys(Ce)),Le=PI({nodes:We,base:Se});if(Le)Se.setNodePlacement?.(Le),(o??t.logger)?.log(`[Agents] ${We.length} agent node(s): ${We.map((Y)=>`${Y.id} p${Y.priority} x${Number.isFinite(Y.capacity)?Y.capacity:"uncapped"} ${Y.connection.providerId??t.providerId}/${Y.connection.modelId??t.modelId}`).join(", ")}`);if(F)(o??t.logger)?.log(`[Agents] Delegated agents run on provider=${F.providerId} model=${F.modelId}, not the session's`);let it=!ns({maxConcurrentAgents:t.maxConcurrentAgents,nodes:cs(t)});if(!ns({maxConcurrentAgents:t.maxConcurrentAgents,nodes:cs(t)})&&(t.enableSpawnAgent!==!1||t.enableAgentTeams!==!1))(o??t.logger)?.log(`[Agents] spawn_agent and the team tools are withheld: ${(t.agentNodes?.length??0)>1?"every configured node serves 1 request at a time":"this endpoint serves 1 request at a time"}, so a delegated agent would run after the agent that spawned it rather than beside it. Raise the profile's parallel sessions${(t.agentNodes?.length??0)>1?" or a node's capacity":""} to offer them.`);let dt=[],_e=new Map;if(p.enableSpawnAgent){if(k.push(..._v([rV({workspaceRoot:m})],g)),E.configs.length>0)dt=_v(yR({configProvider:Se,agents:E.configs,...t.sessionId?{sessionId:t.sessionId}:{},logger:o??t.logger,resolveProviderConnection:t.resolveProviderConnection,resolveProfileConnection:t.resolveProfileConnection,listProfileNames:t.listProfileNames,createSubAgentTools:async(Y,Q,ee)=>{if(!p.enableTools)return[];let be=e.delegatedSandboxes?.(),ge=ee.toolCallId?xv(ee.toolCallId):void 0,Ee=be&&ge?await be.open(ge):void 0;if(ge&&Ee)_e.set(ge,Y.name);return ZNe(sm(Ev(t.cwd,Y.providerId??t.providerId,p.mode,Y.modelId??t.modelId,t.toolRoutingRules,g,Y.skills!==void 0&&D?.createSkillsExecutor?D.createSkillsExecutor(Y.skills):void 0,u,i??t.telemetry,t.qaCredentials,e.runCommandExecutionController,e.readReceipts,y,{workspace:Ee},oa(t)),t.extraTools),Y)},hookErrorMode:t.hookErrorMode,toolPolicies:g,requestToolApproval:e.requestToolApproval,commandSandboxFor:(Y)=>Y?ab(e.delegatedSandboxes?.(),xv(Y)):void 0,onSubAgentEvent:e.onSubAgentEvent,onSubAgentStart:e.onSubAgentStart,onSubAgentEnd:async(Y)=>{let Q=Y.toolCallId?xv(Y.toolCallId):void 0,ee=e.delegatedSandboxes?.();if(Q&&ee?.has(Q)){let be=_e.get(Q)??"agent";_e.delete(Q);let ge=await ee.close(Q,be);if(Y.result&&typeof Y.result.text==="string")Y.result.text+=Ia(Y.result.text,Y.result.finishReason,be,ge)}await e.onSubAgentEnd?.(Y)},onSubAgentSettled:async(Y)=>{if(!Y.toolCallId)return;let Q=xv(Y.toolCallId);_e.delete(Q),await e.delegatedSandboxes?.().close(Q,Y.name)}}),g),k.push(...dt)}if(!this.teamRuntimeEntries.has(re))this.teamRuntimeEntries.set(re,{delegatedAgentConfigProvider:Se});let Ue=()=>{if(!p.enableAgentTeams)return;let Y=this.teamRuntimeEntries.get(re)??{delegatedAgentConfigProvider:Se};if(this.teamRuntimeEntries.set(re,Y),M=Y.runtime,!M){if(M=new Ub({teamName:b,leadAgentId:t.sessionId||"lead",sessionId:t.sessionId,maxConcurrentRuns:t.maxConcurrentAgents===0?Number.POSITIVE_INFINITY:t.maxConcurrentAgents,missionLogIntervalSteps:p.missionLogIntervalSteps,missionLogIntervalMs:p.missionLogIntervalMs,acceptTeammateConnectionUpdates:(Q)=>Se.acceptedConnectionUpdates?.(Q)??Q,...e.delegatedSandboxes?{teammateWorkspaces:oDe(e.delegatedSandboxes)}:{},onStateDirty:()=>se?.markStateDirty(),onTeamEvent:(Q)=>{if(h(Q),se){if(Q.type==="teammate_spawned"&&Q.teammate?.rolePrompt){let ee={agentId:Q.agentId,rolePrompt:Q.teammate.rolePrompt,modelId:Q.teammate.modelId,maxIterations:Q.teammate.maxIterations,...Q.teammate.temperature!==void 0?{temperature:Q.teammate.temperature}:{},...Q.teammate.seed!==void 0?{seed:Q.teammate.seed}:{},...Q.teammate.seedRandom?{seedRandom:!0}:{},...Q.teammate.temperatureBase!==void 0?{temperatureBase:Q.teammate.temperatureBase}:{},...Q.teammate.temperatureRange!==void 0?{temperatureRange:Q.teammate.temperatureRange}:{}};he.set(ee.agentId,ee),se.markTeammatesDirty()}if(Q.type==="teammate_shutdown"&&!sDe(Q.reason))he.delete(Q.agentId),se.markTeammatesDirty();if(Q.type==="team_cleaned")he.clear(),se.markTeammatesDirty();se.onEvent(Q)}}}),H)M.hydrateState(H),_=!0;Y.runtime=M}if(!N){if(!M)return;N=!0;let Q=QA({runtime:M,leadAgentId:t.sessionId||"lead",restoredFromPersistence:Boolean(H),restoredTeammates:J,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(ee)=>{I=ee,Ge?.addTools(ee)},createBaseTools:p.enableTools?(ee)=>Ev(t.cwd,t.providerId,p.mode,t.modelId,t.toolRoutingRules,g,void 0,u,i??t.telemetry,t.qaCredentials,e.runCommandExecutionController,e.readReceipts,y,{workspace:e.delegatedSandboxes?.().openSync(GC(ee))},oa(t)):void 0,teammateConfigProvider:Se});if(_)M.recoverActiveRuns("runtime_recovered");if(Q.restoredFromPersistence)d?.();k.push(...Q.tools)}return M};if(p.enableSpawnAgent&&s&&ns({maxConcurrentAgents:t.maxConcurrentAgents,nodes:cs(t)})){let Y=[t.providerConfig,t.delegatedAgentConnection?.providerConfig,...cs(t).map((Ee)=>Ee.connection.providerConfig)].filter((Ee)=>Ee?.polykv?.swarm===!0),Q;if(a&&Y.length>0){if((await Promise.all(Y.map((vt)=>tT(vt).catch(()=>!1)))).some(Boolean))Q=a()}let ee=new Map(dt.map((Ee)=>[si(Ee.name),Ee])),be=new Map(E.configs.map((Ee)=>[si(Ee.name),Ee])),ge=s({...Q?{swarm:Q}:{},...p.enableAgentTeams?{teammates:!0}:{},...ee.size>0?{configuredAgents:()=>ee,configuredAgentConfigs:()=>be}:{}});k.push({...ge,execute:async(Ee,vt)=>(Ue(),ge.execute(Ee,vt))}),k.push(Dh())}if(p.enableAgentTeams){if(Ue(),!k.some((Y)=>Y.name===wo))k.push(Dh())}let xt=dt.length>0||k.some((Y)=>Y.name==="spawn_agent");if(t.sessionId&&xt)k.push(...Aw({sessionId:t.sessionId}));else if(t.sessionId&&p.enableAgentTeams)k.push(...Aw({sessionId:t.sessionId}).filter((Y)=>nj.has(Y.name)));if(t.sessionId&&(p.enableAgentTeams||xt))k.push(JE({sessionId:t.sessionId,configProvider:()=>this.teamRuntimeEntries.get(re)?.delegatedAgentConfigProvider??Se,teammates:()=>{let Y=this.teamRuntimeEntries.get(re)?.runtime?.exportState();return Y?{members:Y.members,runs:Y.runs}:void 0}}));let Jt=_v(k,g),Zn=Jt.some((Y)=>Y.name==="submit_and_exit"&&Y.lifecycle?.completesRun===!0),Ze=p.enableAgentTeams?()=>{let Y=this.teamRuntimeEntries.get(re)?.runtime;if(!Y)return;let Q=Y.listTasks(),ee=Q.some((Ee)=>Ee.status==="in_progress"||Ee.status==="pending"),be=Y.listRuns({}),ge=be.some((Ee)=>Ee.status==="running"||Ee.status==="queued");if(ee||ge){let Ee=Q.filter((kt)=>kt.status==="in_progress"||kt.status==="pending").map((kt)=>`${kt.id} (${kt.status}): ${kt.title}`).join(", "),vt=be.filter((kt)=>kt.status==="running"||kt.status==="queued").map((kt)=>`${kt.id} (${kt.status})`).join(", "),Nt=[];if(Ee)Nt.push(`Unfinished tasks: ${Ee}`);if(vt)Nt.push(`Active runs: ${vt}`);return`[SYSTEM] You still have team obligations. ${Nt.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,un=t.sessionId&&xt?I2(t.sessionId):void 0,Gr=Ze&&un?()=>Ze()??un():Ze??un;qNe(t.toolIntentGuard!==!1);let kr={...Zn?{requireCompletionTool:!0}:{},...Gr?{completionGuard:Gr}:{},maxNoToolCallNudges:jNe,...t.strongNudges===!1?{strongNudges:!1}:{}},Tr=aDe({offered:Jt.map((Y)=>Y.name),subagentsEnabled:p.enableSpawnAgent,serialised:it,multipleNodes:(t.agentNodes?.length??0)>1});return{tools:Jt,modelTools:f,...Object.keys(Tr).length>0?{unavailableToolReasons:Tr}:{},configuredAgents:E.configs,logger:o??t.logger,telemetry:i??t.telemetry,teamRuntime:M,teamRestoredFromPersistence:Boolean(H),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(re)?.delegatedAgentConfigProvider??Se,extensions:z,completionPolicy:kr,registerLeadAgent:(Y)=>{if(Ge=Y,I.length>0)Y.addTools(Ji(I,[...w]))},shutdown:async(Y)=>{iDe(M,Y),se?.dispose(),X?.close(),this.teamRuntimeEntries.delete(re),await K?.();for(let Q of W)Q.stop()}}}}import{normalizeUserInput as lDe}from"@cerebriline/shared";import{nanoid as cDe}from"nanoid";class kV{list(e){return e?Jn(e):[]}update(e,t){if(!e)return{sessionId:t.sessionId,prompts:[],updated:!1};let n=t.promptId.trim(),r=e.pendingPrompts.findIndex((d)=>d.id===n);if(r<0)return{sessionId:t.sessionId,prompts:Jn(e),updated:!1};let o=e.pendingPrompts[r];if(!o)return{sessionId:t.sessionId,prompts:Jn(e),updated:!1};let i=t.prompt===void 0?o.prompt:lDe(t.prompt).trim();if(!i)throw Error("prompt cannot be empty");let s=t.delivery??o.delivery,a={...o,prompt:i,mode:t.mode??o.mode,delivery:s};return e.pendingPrompts.splice(r,1),hDe(e,a,r,o.delivery),{sessionId:t.sessionId,prompts:Jn(e),prompt:Av(a),updated:!0}}delete(e,t){if(!e)return{sessionId:t.sessionId,prompts:[],removed:!1};let n=t.promptId.trim(),r=e.pendingPrompts.findIndex((i)=>i.id===n);if(r<0)return{sessionId:t.sessionId,prompts:Jn(e),removed:!1};let[o]=e.pendingPrompts.splice(r,1);return{sessionId:t.sessionId,prompts:Jn(e),prompt:o?Av(o):void 0,removed:!0}}enqueue(e,t){let{prompt:n,mode:r,delivery:o,userImages:i,userFiles:s,origin:a,noteKind:d,refresh:l}=t;if(a==="harness"&&d){let u=e.pendingPrompts.find((h)=>h.origin==="harness"&&h.noteKind===d);if(u)return u.prompt=d==="recap"?KW(u.prompt,n):n,u.refresh=l,Jn(e)}let c=e.pendingPrompts.findIndex((u)=>u.prompt===n);if(c>=0){let[u]=e.pendingPrompts.splice(c,1),h={...u,prompt:n,mode:r??u.mode,userImages:i??u.userImages,userFiles:s??u.userFiles};if(o==="steer"||u.delivery==="steer")e.pendingPrompts.unshift({...h,delivery:"steer"});else e.pendingPrompts.push(h)}else{let u={id:`pending_${Date.now()}_${cDe(5)}`,prompt:n,mode:r,delivery:o,userImages:i,userFiles:s,...a==="harness"?{origin:a}:{},...a==="harness"&&d?{noteKind:d}:{},...a==="harness"&&l?{refresh:l}:{}};if(o==="steer")e.pendingPrompts.unshift(u);else e.pendingPrompts.push(u)}return Jn(e)}consumeSteer(e){for(;;){let t=e.pendingPrompts.findIndex((r)=>r.delivery==="steer");if(t<0)return{prompts:Jn(e)};let[n]=e.pendingPrompts.splice(t,1);if(n&&vV(n))return{entry:n,prompts:Jn(e)}}}shiftNext(e){for(;;){let t=e.pendingPrompts.shift();if(!t||vV(t))return{entry:t,prompts:Jn(e)}}}requeueFront(e,t){return e.pendingPrompts.unshift(t),Jn(e)}clear(e){return e.pendingPrompts.length=0,[]}dropHarnessNotes(e){let t=e.pendingPrompts.length,n=e.pendingPrompts.filter((r)=>r.origin!=="harness");return e.pendingPrompts.length=0,e.pendingPrompts.push(...n),t-n.length}}class XC{deps;service=new kV;constructor(e){this.deps=e}list(e){return this.service.list(this.deps.getSession(e))}steerFirst(e){let t=this.deps.getSession(e),n=t?.pendingPrompts[0];if(!n||n.delivery==="steer")return{sessionId:e,prompts:this.service.list(t),updated:!1};return this.update({sessionId:e,promptId:n.id,delivery:"steer"})}update(e){let t=this.deps.getSession(e.sessionId);if(!t)return{sessionId:e.sessionId,prompts:[],updated:!1};let n=this.service.update(t,e);if(this.emitPrompts(t),n.updated&&n.prompt?.delivery==="steer"&&!t.aborting)t.agent.notifyPendingUserMessage();return this.scheduleDrain(e.sessionId,t),n}delete(e){let t=this.deps.getSession(e.sessionId);if(!t)return{sessionId:e.sessionId,prompts:[],removed:!1};let n=this.service.delete(t,e);return this.emitPrompts(t),this.scheduleDrain(e.sessionId,t),n}enqueue(e,t){let n=this.deps.getSession(e);if(!n)return;if(this.service.enqueue(n,t),this.emitPrompts(n),t.delivery==="steer"&&!n.aborting)n.agent.notifyPendingUserMessage();this.scheduleDrain(e,n)}consumeSteer(e){let t=this.deps.getSession(e);if(!t)return;let n=t.pendingPrompts.length,{entry:r}=this.service.consumeSteer(t);if(!r){if(t.pendingPrompts.length!==n)this.emitPrompts(t);return}return this.emitPrompts(t),this.emitSubmitted(t,r),r}discardQueue(e){if(e.pendingPrompts.length===0)return;this.service.clear(e),this.emitPrompts(e)}dropHarnessNotes(e){if(this.service.dropHarnessNotes(e)>0)this.emitPrompts(e)}emitPrompts(e){this.deps.emit({type:"pending_prompts",payload:{sessionId:e.sessionId,prompts:Jn(e)}})}scheduleDrain(e,t){if(t.pendingPrompts.length===0||t.aborting||t.drainingPendingPrompts||!t.agent.canStartRun())return;queueMicrotask(()=>{this.drain(e)})}async drain(e){let t=this.deps.getSession(e);if(!t)return;if(t.aborting||t.drainingPendingPrompts)return;if(!t.agent.canStartRun())return;let n=t.pendingPrompts.length,{entry:r}=this.service.shiftNext(t);if(!r){if(t.pendingPrompts.length!==n)this.emitPrompts(t);return}this.emitPrompts(t),this.emitSubmitted(t,r),t.drainingPendingPrompts=!0;let o=!0;try{let i=await this.deps.send({sessionId:e,prompt:r.prompt,...r.mode?{mode:r.mode}:{},userImages:r.userImages,userFiles:r.userFiles});if(uDe(i))o=!1}catch{o=!1,this.service.requeueFront(t,r),this.emitPrompts(t)}finally{if(t.drainingPendingPrompts=!1,o&&t.pendingPrompts.length>0&&t.status!=="failed"&&t.status!=="cancelled")queueMicrotask(()=>{this.drain(e)})}}emitSubmitted(e,t){let n=Av(t);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:e.sessionId,id:n.id,prompt:n.prompt,delivery:n.delivery,attachmentCount:n.attachmentCount,userImages:n.userImages,userFiles:n.userFiles,...n.origin?{origin:n.origin}:{}}})}}function vV(e){if(!e.refresh)return!0;let t;try{t=e.refresh()}catch{return!0}if(t===void 0||t.trim()==="")return!1;return e.prompt=t,!0}function uDe(e){return typeof e==="object"&&e!==null&&"finishReason"in e&&e.finishReason==="error"}function Av(e){return{id:e.id,prompt:e.prompt,delivery:e.delivery,attachmentCount:(e.userImages?.length??0)+(e.userFiles?.length??0),userImages:e.userImages,userFiles:e.userFiles,...e.origin==="harness"?{origin:e.origin}:{}}}function Jn(e){return e.pendingPrompts.map(Av)}function hDe(e,t,n,r){if(t.delivery==="steer")e.pendingPrompts.unshift(t);else if(r==="steer")e.pendingPrompts.push(t);else e.pendingPrompts.splice(n,0,t)}import{formatDisplayUserInput as Opt,normalizeUserInput as Lpt}from"@cerebriline/shared";import{resolveSessionDataDir as Dpt}from"@cerebriline/shared/storage";import{existsSync as JC}from"node:fs";import{readFile as pDe}from"node:fs/promises";import{join as mDe}from"node:path";class QC{listeners=new Set;subscribe(e,t){let n={listener:e,sessionId:t?.sessionId?.trim()||void 0};return this.listeners.add(n),()=>{this.listeners.delete(n)}}emit(e){let t=e.payload.sessionId?.trim();for(let n of this.listeners){if(n.sessionId&&n.sessionId!==t)continue;n.listener(e)}}get size(){return this.listeners.size}}function TV(e,t,n){let r=e?.trim();if(r&&JC(r))return r;let o=n?.trim();if(o){let i=mDe(o,t,`${t}.messages.json`);if(JC(i))return i}return r||void 0}async function Uc(e){let t=e?.trim();if(!t||!JC(t))return[];try{let n=(await pDe(t,"utf8")).trim();if(!n)return[];let r=JSON.parse(n);if(Array.isArray(r))return r;if(r&&typeof r==="object"&&!Array.isArray(r)){let o=r.messages;if(Array.isArray(o))return o}return[]}catch{return[]}}function ZC(e){return e?{...e}:void 0}async function SV(e,t){if(!(e.hookName==="tool_call"||!!e.parent_agent_id))return;await t.queueSpawnRequest(e);let r=await t.upsertSubagentSessionFromHook(e);if(!r)return;await t.appendSubagentHookAudit(r,e),await t.applySubagentStatus(r,e)}function xV(e){let t=Ca(e.session_id)?.rootSessionId??mc(e.session_id)?.rootSessionId;return{sessionId:e.session_id,source:e.source,pid:e.pid,startedAt:e.started_at,endedAt:e.ended_at??null,exitCode:e.exit_code??null,status:e.status,interactive:e.interactive,provider:e.provider,model:e.model,cwd:e.cwd,workspaceRoot:e.workspace_root,teamName:e.team_name,enableTools:e.enable_tools,enableSpawn:e.enable_spawn,enableTeams:e.enable_teams,isSubagent:t!==void 0,...t!==void 0?{parentSessionId:t}:{},prompt:e.prompt,metadata:e.metadata,messagesPath:e.messages_path,updatedAt:e.ended_at??e.started_at}}class Rv{deps;constructor(e){this.deps=e}lastKnownIdentityBySession=new Map;static MAX_IDENTITY_SNAPSHOTS=512;dispatchAgentEvent(e,t,n){let r=this.deps.getSession(e),o={sessionId:e,config:t,liveSession:r,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},i=CR(n);if(!!r&&(!i.agentId||i.agentId===eP(r.agent))){let a={agentId:eP(r.agent),conversationId:r.agent.getConversationId(),...r?.runtime.teamRuntime?{teamRole:"lead"}:{}};this.rememberSessionIdentity(e,a),pb(o,n,{...a,isPrimaryAgentEvent:!0});return}pb(o,n,{...r?{}:this.lastKnownIdentityBySession.get(e),isPrimaryAgentEvent:!1})}rememberSessionIdentity(e,t){if(this.lastKnownIdentityBySession.delete(e),this.lastKnownIdentityBySession.set(e,t),this.lastKnownIdentityBySession.size>Rv.MAX_IDENTITY_SNAPSHOTS){let n=this.lastKnownIdentityBySession.keys().next().value;if(n!==void 0)this.lastKnownIdentityBySession.delete(n)}}async handleTeamEvent(e,t){let n=this.deps.getSession(e);if(n){if(WI(n,t),t.type==="agent_event"){let r={sessionId:e,config:n.config,liveSession:n,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};pb(r,t.event,{agentId:t.agentId,teamRole:"teammate",teamAgentId:t.agentId,isPrimaryAgentEvent:!1})}if(t.type==="teammate_spawned"){let r=ui({agentId:t.teammate.runtimeAgentId??t.agentId,conversationId:t.teammate.conversationId,parentAgentId:t.teammate.parentAgentId,createdByAgentId:eP(n.agent),teamId:n.runtime.teamRuntime?.getTeamId(),teamName:n.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:t.agentId});if(r)ld(n.config.telemetry,{ulid:e,modelId:t.teammate.modelId??n.config.modelId,provider:n.config.providerId,...r})}}if(await jI(e,t,this.deps.invokeBackendOptional),n&&(t.type!=="agent_event"||t.activityChanged===!0))qI(n,e,t,this.deps.emit)}async handlePluginEvent(e,t,n,r){if(t.name==="plugin_log"){this.handlePluginLog(e,t.payload);return}if(t.name==="plugin_telemetry"){this.handlePluginTelemetry(e,t.payload,r);return}if(t.name==="automation_event"){let l=this.deps.getSession(e)?.config.extensionContext?.automation??n;if(!l)return;let c=t.payload&&typeof t.payload==="object"?t.payload:void 0;if(!c)return;await l.ingestEvent(c);return}if(t.name!=="steer_message"&&t.name!=="queue_message"&&t.name!=="pending_prompt")return;let o=t.payload&&typeof t.payload==="object"?t.payload:void 0,i=typeof o?.sessionId==="string"&&o.sessionId.trim().length>0?o.sessionId.trim():e,s=typeof o?.prompt==="string"?o.prompt.trim():"";if(!s)return;let a=t.name==="steer_message"?"steer":t.name==="queue_message"?"queue":o?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(i,{prompt:s,delivery:a})}handlePluginTelemetry(e,t,n){let o=this.deps.getSession(e)?.config.telemetry??n;if(!o||!t||typeof t!=="object")return;let i=t,s=typeof i.pluginName==="string"&&i.pluginName?i.pluginName:"unknown";if(i.kind==="event"){let a=typeof i.event==="string"?i.event.trim():"";if(!a)return;let d={...i.properties&&typeof i.properties==="object"?i.properties:{},plugin_name:s,session_id:e};if(i.required===!0)o.captureRequired(`plugin.${a}`,d);else o.capture({event:`plugin.${a}`,properties:d});return}if(i.kind==="metric"){let a=typeof i.name==="string"?i.name.trim():"",d=typeof i.value==="number"?i.value:NaN;if(!a||Number.isNaN(d))return;let l={...i.attributes&&typeof i.attributes==="object"?i.attributes:{},plugin_name:s},c=typeof i.description==="string"?i.description:void 0,u=i.required===!0,h=`plugin.${a}`;if(i.metric==="counter")o.recordCounter(h,d,l,c,u);else if(i.metric==="histogram")o.recordHistogram(h,d,l,c,u);else if(i.metric==="gauge")o.recordGauge(h,d,l,c,u)}}handlePluginLog(e,t,n){let r=this.deps.getSession(e),o=n??r?.config.extensionContext?.logger??r?.config.logger;if(!o||!t||typeof t!=="object")return;let i=t,s=typeof i.message==="string"?i.message:"";if(!s)return;let a=i.metadata&&typeof i.metadata==="object"?{...i.metadata}:{};if(a.sessionId??=e,typeof i.pluginName==="string"&&i.pluginName)a.pluginName=i.pluginName;if(i.level==="debug"){o.debug(s,a);return}if(i.level==="error"){if(o.error)o.error(s,a);else o.log(s,{...a,severity:"error"});return}o.log(s,a)}}function eP(e){return e.getAgentId()}function tP(e){return{sessionId:e.sessionId,source:e.source,pid:process.pid,startedAt:e.startedAt,endedAt:e.endedAt??null,exitCode:e.exitCode??null,status:e.status,interactive:e.interactive,provider:e.config.providerId,model:e.config.modelId,cwd:e.config.cwd,workspaceRoot:hi(e.config),teamName:e.config.teamName?.trim()||void 0,enableTools:e.config.enableTools,enableSpawn:e.config.enableSpawnAgent,enableTeams:e.config.enableAgentTeams,parentSessionId:typeof e.sessionMetadata?.parentSessionId==="string"?e.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof e.sessionMetadata?.parentAgentId==="string"?e.sessionMetadata.parentAgentId:void 0,agentId:typeof e.sessionMetadata?.agentId==="string"?e.sessionMetadata.agentId:void 0,conversationId:typeof e.sessionMetadata?.conversationId==="string"?e.sessionMetadata.conversationId:void 0,isSubagent:typeof e.sessionMetadata?.isSubagent==="boolean"?e.sessionMetadata.isSubagent:!1,prompt:e.pendingPrompt,metadata:e.sessionMetadata,messagesPath:e.artifacts?.messagesPath,updatedAt:e.updatedAt??e.endedAt??e.startedAt}}function nP(e,t){let n=e[t];return typeof n==="function"?n:null}async function _V(e,t,...n){let r=nP(e,t);if(!r)throw Error(`session service method not available: ${t}`);return Promise.resolve(r.apply(e,n))}async function EV(e,t,...n){let r=nP(e,t);if(!r)return;await Promise.resolve(r.apply(e,n))}async function AV(e,t,...n){let r=nP(e,t);if(!r)return;return await Promise.resolve(r.apply(e,n))}import{clearPolykvSession as Iv,releasePolykvAgent as rP,setPolykvSession as fDe}from"@cerebriline/llms";function IV(e,t,n){let r=n?{extractDocument:n}:{};if(!e)return{executors:t,enableBash:!1,...n?{executorOptions:r}:{}};let o=wv(t?.semanticSearch,e.executorOptions.overlay);return{executorOptions:{...e.executorOptions,...r},...o?{executors:{semanticSearch:o}}:{},...e.allowCommands?{}:{enableBash:!1}}}function Cv(e,t,n){return{onSubAgentEvent:(r)=>e.onAgentEvent(n,t,r),onSubAgentStart:(r)=>{let o=e.getSession(n)?.runtime.teamRuntime;e.subAgentStarts.set(r.subAgentId,{startedAt:Date.now(),rootSessionId:n});let i=ui({agentId:r.subAgentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamId:o?.getTeamId(),teamName:o?.getTeamName(),createdByAgentId:r.parentAgentId});if(i)ld(t.telemetry,{ulid:n,modelId:t.modelId,provider:t.providerId,...i});vk(t.telemetry,{event:"started",ulid:n,durationMs:0,parentId:r.parentAgentId,agentId:r.subAgentId,...i}),e.invokeBackendOptional("handleSubAgentStart",n,r)},onSubAgentEnd:async(r)=>{let o=e.getSession(n)?.runtime.teamRuntime,i=e.subAgentStarts.get(r.subAgentId),s=i?Date.now()-i.startedAt:0,a=r.result?.text?r.result.text.split(`
1462
+ `,"utf8"),uV(i,o)}markInProgressRunsInterrupted(e,t){let n=this.readEnvelope(e);if(!n?.teamState?.runs?.length)return[];let r=n.teamState.runs.filter((i)=>i.status==="queued"||i.status==="running").map((i)=>i.id);if(r.length===0)return[];let o=new Date;return n.teamState={...n.teamState,runs:n.teamState.runs.map((i)=>i.status==="queued"||i.status==="running"?{...i,status:"interrupted",error:t,endedAt:o}:i)},this.persistRuntime(e,n.teamState,n.teammates),r}ensureTeamDir(){if(!Fc(this.teamDirPath))cV(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir(e){let t=jC(this.ensureTeamDir(),gn(e));if(!Fc(t))cV(t,{recursive:!0});return t}statePath(e){return jC(this.ensureTeamDir(),gn(e),"state.json")}historyPath(e){return jC(this.ensureTeamDir(),gn(e),"task-history.jsonl")}readEnvelope(e){let t=this.statePath(e);if(!Fc(t))return;try{let n=JSON.parse(WC(t,"utf8"));if(n?.version===1&&n.teamState)return n}catch{}return}}function fV(e={}){try{let t=new vv(e);return t.init(),t}catch{let t=new kv({teamDir:e.teamDir});return t.init(),t}}import{chmodSync as FNe,existsSync as qC}from"node:fs";import{join as zC}from"node:path";function Tv(e){if(!e)return;if(process.platform==="win32"){let t=zC(e,"cerebriline-sandbox.exe"),n=zC(e,"hook.dll");if(!qC(t)||!qC(n))return;return{launcher:t,hook:n,platforms:["win32"]}}if(process.platform==="linux")return gV(e,"","linux");if(process.platform==="darwin")return gV(e,"darwin-","darwin");return}function gV(e,t,n){let r={x64:"x64",arm64:"arm64"}[process.arch],i=(r?[`cerebriline-sandbox-${t}${r}`,"cerebriline-sandbox"]:["cerebriline-sandbox"]).map((s)=>zC(e,s)).find(qC);if(!i)return;try{FNe(i,493)}catch{}return{launcher:i,hook:i,platforms:[n]}}var UNe=300,BNe=60000,yV=5000;class KC{opts;pendingEvents=[];teammatesDirty=!1;timer;lastFlushAt=0;disposed=!1;constructor(e){this.opts={batchMs:UNe,telemetryFlushMs:BNe,now:Date.now,...e}}onEvent(e){if(this.disposed)return;if(!pi(e)){if(this.opts.now()-this.lastFlushAt>=this.opts.telemetryFlushMs)this.schedule();return}if(this.pendingEvents.push({type:e.type,payload:is(e)}),NI(e)){this.flush();return}this.schedule()}markTeammatesDirty(){this.teammatesDirty=!0}markStateDirty(){if(this.disposed)return;this.schedule()}flush(){this.clearTimer();let e=this.opts.source();if(!e)return;if(!e.hasPendingStateDelta()&&this.pendingEvents.length===0&&!this.teammatesDirty)return;let n=this.pendingEvents,r=this.teammatesDirty;this.pendingEvents=[],this.teammatesDirty=!1;let o=e.drainStateDelta();try{this.opts.store.persistBatch(this.opts.teamKey,{events:n,delta:o,teammates:this.opts.teammates(),getFullState:()=>e.exportState()}),this.lastFlushAt=this.opts.now()}catch(i){e.requeueStateDelta(o);let s=n.concat(this.pendingEvents);if(this.pendingEvents=s.length>yV?s.slice(-yV):s,this.teammatesDirty=this.teammatesDirty||r,!this.disposed)this.schedule();try{this.opts.onError?.(i)}catch{}}}dispose(){if(this.disposed)return;this.disposed=!0,this.flush()}schedule(){if(this.timer)return;this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},this.opts.batchMs),this.timer.unref?.()}clearTimer(){if(this.timer)clearTimeout(this.timer),this.timer=void 0}}function Sv(e,t){return zNe(e,t)}function bV(e,t){let n=t?.["*"]??{},r=t?.[e]??{};return{...n,...r}.enabled!==!1}function VNe(e,t){return e.filter((n)=>bV(n.name,t))}function _v(e,t){return Ji(VNe(e,t))}function YNe(e){if(e?.readLimitEnabled===!1)return Number.POSITIVE_INFINITY;let t=e?.readLimitChars;return typeof t==="number"&&Number.isFinite(t)&&t>0?Math.floor(t):void 0}function XNe(e,t){if(!t?.length)return e;let n={...e??{}};for(let r of t){let o=r.trim();if(!o)continue;n[o]={...n[o]??{},enabled:!1}}return n}var JNe={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function QNe(e){let t=e.trim().toLowerCase();return JNe[t]??t}function ZNe(e,t){if(t.tools===void 0)return e;let n=new Set(t.tools.map(QNe));if(t.skills!==void 0)n.add("skills");return e.filter((r)=>n.has(r.name))}function eDe(){return`team-${GNe(5)}`}function Ev(e,t,n,r,o,i,s,a,d,l,c,u,h,p,f,m){let g=go[yo({mode:n})],y=Ky(t,r,n,o??zy);return _v(dp({cwd:e,telemetry:d,qaCredentials:l,executorOptions:p?.workspace?{...p.workspace.executorOptions,...f?{extractDocument:f}:{},...h!==void 0?{fileRead:{maxReadChars:h}}:{}}:{bash:{executionController:c,...m?{wrapSpawn:m}:{}},...u?{receipts:u}:{},...f?{extractDocument:f}:{},...h!==void 0?{fileRead:{maxReadChars:h}}:{}},...g,enableSkills:!!s,...y,enableExtractDocument:g.enableExtractDocument===!0&&bV(le.EXTRACT_DOCUMENT,i),...p&&!p.workspace?.allowCommands?{enableBash:!1}:{},executors:{...s?{skills:s}:{},...p?.workspace?a?.semanticSearch?{semanticSearch:wv(a.semanticSearch,p.workspace.executorOptions.overlay)}:{}:a??{}}}),i)}function tDe(e){return Ev(e.cwd,e.providerId,e.mode,e.modelId,e.toolRoutingRules,e.toolPolicies,nDe,e.toolExecutors).some((t)=>t.name==="skills")}var nDe=async()=>"";async function rDe(e){let t=jr(),n=e.includeSettings&&nm({filePath:t});if(!n&&!e.agentPluginServers?.length)return{tools:[]};let r=fv({settingsPath:t}),o=fv({restrictConfiguredHeadersToOrigin:!0}),i=new gv({clientFactory:(u)=>u.metadata?.source==="agent-plugin"?o(u):r(u)}),s=[];if(n)try{s=await MC(i,{filePath:t})}catch(u){let h=u instanceof Error?u.message:String(u);e.logger?.log(`[mcp] Failed to load MCP settings, skipping settings-backed MCP tools: ${h}`)}let a=new Set(s.map((u)=>u.name));for(let u of e.agentPluginServers??[]){let h=u.registration;if(a.has(h.name)){e.logger?.log(`[agent-plugins] MCP server '${h.name}' conflicts with an existing server and was skipped.`,{severity:"error"});continue}try{await i.registerServer(h),s.push(h),a.add(h.name)}catch(p){let f=p instanceof Error?p.message:String(p);e.logger?.log(`[agent-plugins] Failed to register MCP server '${h.name}', skipping: ${f}`,{severity:"error"})}}if(s.length===0)return await i.dispose().catch(()=>{}),{tools:[]};let d=s.filter((u)=>u.disabled!==!0),l=await Promise.allSettled(d.map((u)=>BC({serverName:u.name,provider:i,timeoutMs:KNe(u.timeoutSeconds)*1000}))),c=[];for(let[u,h]of l.entries())if(h.status==="fulfilled")c.push(...h.value);else{let p=h.reason instanceof Error?h.reason.message:String(h.reason);e.logger?.log(`[mcp] Failed to load tools from MCP server "${d[u].name}", skipping: ${p}`)}return{tools:c,shutdown:async()=>{await i.dispose()}}}function xv(e){return`configured:${e}`}function GC(e){return`teammate:${e}`}function oDe(e){return{handBack:(t)=>e().handBack(GC(t),t),release:async(t)=>{await e().close(GC(t),t)}}}function iDe(e,t){if(!e)return;try{e.cancelOutstandingWork(`${VC}${t}`)}catch{}for(let n of e.getTeammateIds())try{e.shutdownTeammate(n,`${VC}${t}`)}catch{}}var VC="runtime_shutdown:";function sDe(e){if(e===void 0)return!1;if(e.startsWith(VC))return!0;switch(e){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function cs(e){return CI({providerId:e.providerId,modelId:e.modelId,agentNodes:(e.agentNodes??[]).map((t)=>({...t,connection:t.connection})),polykvAgentsPriorityZero:e.polykvAgentsPriorityZero,overflowCapacity:e.maxConcurrentAgents,lead:{apiKey:e.apiKey,baseUrl:e.baseUrl,headers:e.headers,providerConfig:e.providerConfig,knownModels:e.knownModels,thinking:e.thinking,reasoningEffort:e.reasoningEffort,thinkingBudgetTokens:e.thinkingBudgetTokens,maxTokensPerTurn:e.maxTokensPerTurn,maxToolResultChars:e.maxToolResultChars,staleReadRewrites:e.staleReadRewrites,toolResultFormat:e.toolResultFormat,temperature:e.temperature}})}function aDe(e){let t=new Set(e.offered),n=["spawn_agent","spawn_swarm"].filter((d)=>!t.has(d));if(n.length===0)return{};let r;if(!e.subagentsEnabled)r="sub-agents are switched off in this session's settings.";else if(e.serialised)r=`${e.multipleNodes?"every configured node serves 1 request at a time":"this endpoint serves 1 request at a time"}, so a spawned agent would run after you rather than beside you.`;else return{};let o=e.offered.filter((d)=>d.startsWith("subagent_")),i=o.length>0?`Do the work yourself, or hand one job at a time to a configured agent: ${o.join(", ")}.`:"Do the work yourself.",s=e.subagentsEnabled?`Only the user can change this, by raising the profile's parallel sessions${e.multipleNodes?" or a node's capacity":""}.`:"Only the user can change this, in the settings.",a={};for(let d of n)a[d]=`${r} ${i} Do not call ${d} again in this session; it will be refused the same way. ${s}`;return a}function dDe(e){let t=go[yo({mode:e.mode})];return{sessionId:e.sessionId||"",mode:e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act",enableTools:e.enableTools!==!1,enableSpawnAgent:e.enableSpawnAgent??t.enableSpawnAgent??!0,enableAgentTeams:ns({maxConcurrentAgents:e.maxConcurrentAgents,nodes:cs(e)})&&e.enableAgentTeams===!0,disableMcpSettingsTools:e.disableMcpSettingsTools===!0,yolo:e.yolo===!0,missionLogIntervalSteps:typeof e.missionLogIntervalSteps==="number"&&Number.isFinite(e.missionLogIntervalSteps)?e.missionLogIntervalSteps:3,missionLogIntervalMs:typeof e.missionLogIntervalMs==="number"&&Number.isFinite(e.missionLogIntervalMs)?e.missionLogIntervalMs:120000}}class YC{teamRuntimeEntries=new Map;async build(e){let{config:t,hooks:n,extensions:r,logger:o,telemetry:i,createSpawnTool:s,createSwarmTool:a,onTeamRestored:d,userInstructionService:l,configExtensions:c,toolExecutors:u}=e,h=e.onTeamEvent??(()=>{}),p=dDe(t),f=[];if(p.enableTools&&p.mode!=="yolo"&&SA("web_search")&&wV({providerId:t.providerId,modelId:t.modelId},"web_search"))f.push({name:"web_search"});if(p.enableTools&&wV({providerId:t.providerId,modelId:t.modelId},"image_generation"))f.push({name:"image_generation",outputFormat:"png"});let m=t.workspaceRoot??t.cwd,g=XNe(e.toolPolicies??t.toolPolicies,t.enableExtractDocument===!0?t.providerConfig?.tools?.disabled:[...t.providerConfig?.tools?.disabled??[],le.EXTRACT_DOCUMENT]),y=YNe(t.providerConfig?.tools),w=Ta(),k=[],b=t.teamName?.trim()||eDe(),v=t.sessionId?.trim()||b,E=p.enableSpawnAgent?MI({workspaceRoot:m}):{configs:[],errors:[],searchPaths:[]},S=E.configs.some((Y)=>Y.skills!==void 0),x=Sv(c,"rules"),T=Sv(c,"skills"),A=T||S,R=Sv(c,"workflows"),C=Sv(c,"plugins"),L=x||T||R,N=!1,W=[],D=l,K;for(let Y of E.errors)(o??t.logger)?.log?.(`[agents] Failed to load agent config at ${Y.path}: ${Y.error.message}`);if(p.enableSpawnAgent){(o??t.logger)?.log?.(E.configs.length>0?`[agents] ${E.configs.length} configured agent(s): ${E.configs.map((Q)=>Q.name).join(", ")}`:`[agents] No configured agents found. Looked in: ${E.searchPaths.join(", ")||"(no search path)"}`);let Y=E.configs.filter((Q)=>Q.profile!==void 0&&t.resolveProfileConnection?.(Q.profile)===void 0);for(let Q of Y){let ee=t.listProfileNames?.()??[];(o??t.logger)?.log?.(`[agents] "${Q.name}" names the API configuration profile "${Q.profile}", which no longer exists, and will fail when called. `+(ee.length>0?`Available profiles: ${ee.join(", ")}.`:"This host has no saved profiles."),{severity:"warn"})}}if(!D&&(L||S))D=Lc({skills:A?{workspacePath:m,includePluginSkills:C,pluginSkillDirectories:C?e.pluginSkillDirectories:void 0,pluginPaths:t.pluginPaths,cwd:t.cwd,agentPluginSkills:C?e.agentPluginSkills:void 0}:{workspacePath:m},rules:{workspacePath:t.cwd},workflows:{workspacePath:t.cwd}}),W.push(D);else if(D&&C&&e.agentPluginSkills?.length&&(L||S)){let Y=Lc({skills:{directories:[],agentPluginSkills:e.agentPluginSkills},rules:{directories:[]},workflows:{directories:[]}});W.push(Y),D=vC([D,Y])}if(D)await D.start().catch(()=>{});let V=p.enableTools&&T&&Boolean(D)&&D?.hasConfiguredSkills(t.skills)===!0&&tDe({cwd:t.cwd,providerId:t.providerId,mode:p.mode,modelId:t.modelId,toolRoutingRules:t.toolRoutingRules,toolPolicies:g,toolExecutors:u}),B=D&&L?D.createExtension({includeRules:x,includeSkills:T,includeWorkflows:R,registerSkillsTool:V,allowedSkillNames:t.skills}):void 0,j=p.mode==="plan"&&p.enableTools?XT({telemetry:i??t.telemetry}):void 0,G=[B,j].filter((Y)=>Y!==void 0),z=G.length>0?[...r??t.extensions??[],...G]:r??t.extensions;if(p.enableTools){k.push(...Ev(t.cwd,t.providerId,p.mode,t.modelId,t.toolRoutingRules,g,void 0,u,i??t.telemetry,t.qaCredentials,e.runCommandExecutionController,e.readReceipts,y,void 0,oa(t),pK({enabled:t.leadSandboxConfine===!0,workspaceRoot:t.workspaceRoot??t.cwd,binaries:Tv(t.sandboxBinariesDir),tempRoot:WNe(HNe(),"cerebriline-sandbox-tmp")})));let Y=C?e.agentPluginMcpServers:void 0;if(!p.disableMcpSettingsTools||Y?.length){let Q=await rDe({logger:t.logger,includeSettings:!p.disableMcpSettingsTools,agentPluginServers:Y});k.push(...Q.tools),K=Q.shutdown}}let M,X=p.enableAgentTeams?fV():void 0,oe=X?.loadRuntime(v),H=oe?.state,J=oe?.teammates??[],he=new Map(J.map((Y)=>[Y.agentId,Y])),se=X?new KC({teamKey:v,store:X,source:()=>M,teammates:()=>Array.from(he.values()),onError:(Y)=>(o??t.logger)?.log?.(`[team] failed to persist team state: ${Y instanceof Error?Y.message:String(Y)}`)}):void 0,re=t.sessionId||b,Ge,I=[],_=!1,F=t.delegatedAgentConnection,O=Nr({providerId:F?.providerId??t.providerId,baseUrl:F?.baseUrl??t.baseUrl}),ue=t.providerConfig,ne=ue&&$o(ue)?Z8({capacity:async()=>bv(await Sd({sessionId:t.sessionId,providerConfig:ue,logger:o??t.logger})),...o??t.logger?{logger:o??t.logger}:{}}):void 0,fe=hR(t.maxConcurrentAgents,uR(t.agentSlotLimits),ne?(Y)=>Y===O?ne:void 0:void 0,ue&&$o(ue)?(Y)=>Y===O?()=>tT(ue):void 0:void 0),Ce=F?{...F}:{},We=cs(t).map((Y)=>({...Y,connection:Y.connection})),Se=oi({providerId:t.providerId,modelId:t.modelId,distinctId:e.distinctId,sessionId:t.sessionId,cwd:t.cwd,apiKey:t.apiKey??"",baseUrl:t.baseUrl,headers:t.headers,providerConfig:t.providerConfig,knownModels:t.knownModels,thinking:t.thinking,reasoningEffort:t.reasoningEffort,thinkingBudgetTokens:t.thinkingBudgetTokens,maxTokensPerTurn:t.maxTokensPerTurn,maxToolResultChars:t.maxToolResultChars,staleReadRewrites:t.staleReadRewrites,toolResultFormat:t.toolResultFormat,temperature:t.temperature,maxIterations:t.maxIterations,...t.compaction?.cappedThinkingBudgetMessage?{thinkingBudgetMessage:t.compaction.cappedThinkingBudgetMessage}:{},hooks:n,extensions:z,logger:o??t.logger,telemetry:e.telemetry??t.telemetry,workspaceMetadata:t.workspaceMetadata,createPrepareTurn:e.createDelegatedPrepareTurn,condenseDiscardedReasoning:e.condenseDiscardedReasoning,onLoopCut:e.onDelegatedLoopCut,slotGate:fe.for(Nr({providerId:Ce.providerId??t.providerId,baseUrl:Ce.baseUrl??t.baseUrl})),slotGates:fe,...Ce},Object.keys(Ce)),Le=PI({nodes:We,base:Se});if(Le)Se.setNodePlacement?.(Le),(o??t.logger)?.log(`[Agents] ${We.length} agent node(s): ${We.map((Y)=>`${Y.id} p${Y.priority} x${Number.isFinite(Y.capacity)?Y.capacity:"uncapped"} ${Y.connection.providerId??t.providerId}/${Y.connection.modelId??t.modelId}`).join(", ")}`);if(F)(o??t.logger)?.log(`[Agents] Delegated agents run on provider=${F.providerId} model=${F.modelId}, not the session's`);let it=!ns({maxConcurrentAgents:t.maxConcurrentAgents,nodes:cs(t)});if(!ns({maxConcurrentAgents:t.maxConcurrentAgents,nodes:cs(t)})&&(t.enableSpawnAgent!==!1||t.enableAgentTeams!==!1))(o??t.logger)?.log(`[Agents] spawn_agent and the team tools are withheld: ${(t.agentNodes?.length??0)>1?"every configured node serves 1 request at a time":"this endpoint serves 1 request at a time"}, so a delegated agent would run after the agent that spawned it rather than beside it. Raise the profile's parallel sessions${(t.agentNodes?.length??0)>1?" or a node's capacity":""} to offer them.`);let dt=[],_e=new Map;if(p.enableSpawnAgent){if(k.push(..._v([rV({workspaceRoot:m})],g)),E.configs.length>0)dt=_v(yR({configProvider:Se,agents:E.configs,...t.sessionId?{sessionId:t.sessionId}:{},logger:o??t.logger,resolveProviderConnection:t.resolveProviderConnection,resolveProfileConnection:t.resolveProfileConnection,listProfileNames:t.listProfileNames,createSubAgentTools:async(Y,Q,ee)=>{if(!p.enableTools)return[];let be=e.delegatedSandboxes?.(),ge=ee.toolCallId?xv(ee.toolCallId):void 0,Ee=be&&ge?await be.open(ge):void 0;if(ge&&Ee)_e.set(ge,Y.name);return ZNe(sm(Ev(t.cwd,Y.providerId??t.providerId,p.mode,Y.modelId??t.modelId,t.toolRoutingRules,g,Y.skills!==void 0&&D?.createSkillsExecutor?D.createSkillsExecutor(Y.skills):void 0,u,i??t.telemetry,t.qaCredentials,e.runCommandExecutionController,e.readReceipts,y,{workspace:Ee},oa(t)),t.extraTools),Y)},hookErrorMode:t.hookErrorMode,toolPolicies:g,requestToolApproval:e.requestToolApproval,commandSandboxFor:(Y)=>Y?ab(e.delegatedSandboxes?.(),xv(Y)):void 0,onSubAgentEvent:e.onSubAgentEvent,onSubAgentStart:e.onSubAgentStart,onSubAgentEnd:async(Y)=>{let Q=Y.toolCallId?xv(Y.toolCallId):void 0,ee=e.delegatedSandboxes?.();if(Q&&ee?.has(Q)){let be=_e.get(Q)??"agent";_e.delete(Q);let ge=await ee.close(Q,be);if(Y.result&&typeof Y.result.text==="string")Y.result.text+=Ia(Y.result.text,Y.result.finishReason,be,ge)}await e.onSubAgentEnd?.(Y)},onSubAgentSettled:async(Y)=>{if(!Y.toolCallId)return;let Q=xv(Y.toolCallId);_e.delete(Q),await e.delegatedSandboxes?.().close(Q,Y.name)}}),g),k.push(...dt)}if(!this.teamRuntimeEntries.has(re))this.teamRuntimeEntries.set(re,{delegatedAgentConfigProvider:Se});let Ue=()=>{if(!p.enableAgentTeams)return;let Y=this.teamRuntimeEntries.get(re)??{delegatedAgentConfigProvider:Se};if(this.teamRuntimeEntries.set(re,Y),M=Y.runtime,!M){if(M=new Ub({teamName:b,leadAgentId:t.sessionId||"lead",sessionId:t.sessionId,maxConcurrentRuns:t.maxConcurrentAgents===0?Number.POSITIVE_INFINITY:t.maxConcurrentAgents,missionLogIntervalSteps:p.missionLogIntervalSteps,missionLogIntervalMs:p.missionLogIntervalMs,acceptTeammateConnectionUpdates:(Q)=>Se.acceptedConnectionUpdates?.(Q)??Q,...e.delegatedSandboxes?{teammateWorkspaces:oDe(e.delegatedSandboxes)}:{},onStateDirty:()=>se?.markStateDirty(),onTeamEvent:(Q)=>{if(h(Q),se){if(Q.type==="teammate_spawned"&&Q.teammate?.rolePrompt){let ee={agentId:Q.agentId,rolePrompt:Q.teammate.rolePrompt,modelId:Q.teammate.modelId,maxIterations:Q.teammate.maxIterations,...Q.teammate.temperature!==void 0?{temperature:Q.teammate.temperature}:{},...Q.teammate.seed!==void 0?{seed:Q.teammate.seed}:{},...Q.teammate.seedRandom?{seedRandom:!0}:{},...Q.teammate.temperatureBase!==void 0?{temperatureBase:Q.teammate.temperatureBase}:{},...Q.teammate.temperatureRange!==void 0?{temperatureRange:Q.teammate.temperatureRange}:{}};he.set(ee.agentId,ee),se.markTeammatesDirty()}if(Q.type==="teammate_shutdown"&&!sDe(Q.reason))he.delete(Q.agentId),se.markTeammatesDirty();if(Q.type==="team_cleaned")he.clear(),se.markTeammatesDirty();se.onEvent(Q)}}}),H)M.hydrateState(H),_=!0;Y.runtime=M}if(!N){if(!M)return;N=!0;let Q=QA({runtime:M,leadAgentId:t.sessionId||"lead",restoredFromPersistence:Boolean(H),restoredTeammates:J,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(ee)=>{I=ee,Ge?.addTools(ee)},createBaseTools:p.enableTools?(ee)=>Ev(t.cwd,t.providerId,p.mode,t.modelId,t.toolRoutingRules,g,void 0,u,i??t.telemetry,t.qaCredentials,e.runCommandExecutionController,e.readReceipts,y,{workspace:e.delegatedSandboxes?.().openSync(GC(ee))},oa(t)):void 0,teammateConfigProvider:Se});if(_)M.recoverActiveRuns("runtime_recovered");if(Q.restoredFromPersistence)d?.();k.push(...Q.tools)}return M};if(p.enableSpawnAgent&&s&&ns({maxConcurrentAgents:t.maxConcurrentAgents,nodes:cs(t)})){let Y=[t.providerConfig,t.delegatedAgentConnection?.providerConfig,...cs(t).map((Ee)=>Ee.connection.providerConfig)].filter((Ee)=>Ee?.polykv?.swarm===!0),Q;if(a&&Y.length>0){if((await Promise.all(Y.map((vt)=>tT(vt).catch(()=>!1)))).some(Boolean))Q=a()}let ee=new Map(dt.map((Ee)=>[si(Ee.name),Ee])),be=new Map(E.configs.map((Ee)=>[si(Ee.name),Ee])),ge=s({...Q?{swarm:Q}:{},...p.enableAgentTeams?{teammates:!0}:{},...ee.size>0?{configuredAgents:()=>ee,configuredAgentConfigs:()=>be}:{}});k.push({...ge,execute:async(Ee,vt)=>(Ue(),ge.execute(Ee,vt))}),k.push(Dh())}if(p.enableAgentTeams){if(Ue(),!k.some((Y)=>Y.name===wo))k.push(Dh())}let xt=dt.length>0||k.some((Y)=>Y.name==="spawn_agent");if(t.sessionId&&xt)k.push(...Aw({sessionId:t.sessionId}));else if(t.sessionId&&p.enableAgentTeams)k.push(...Aw({sessionId:t.sessionId}).filter((Y)=>nj.has(Y.name)));if(t.sessionId&&(p.enableAgentTeams||xt))k.push(JE({sessionId:t.sessionId,configProvider:()=>this.teamRuntimeEntries.get(re)?.delegatedAgentConfigProvider??Se,teammates:()=>{let Y=this.teamRuntimeEntries.get(re)?.runtime?.exportState();return Y?{members:Y.members,runs:Y.runs}:void 0}}));let Jt=_v(k,g),Zn=Jt.some((Y)=>Y.name==="submit_and_exit"&&Y.lifecycle?.completesRun===!0),Ze=p.enableAgentTeams?()=>{let Y=this.teamRuntimeEntries.get(re)?.runtime;if(!Y)return;let Q=Y.listTasks(),ee=Q.some((Ee)=>Ee.status==="in_progress"||Ee.status==="pending"),be=Y.listRuns({}),ge=be.some((Ee)=>Ee.status==="running"||Ee.status==="queued");if(ee||ge){let Ee=Q.filter((kt)=>kt.status==="in_progress"||kt.status==="pending").map((kt)=>`${kt.id} (${kt.status}): ${kt.title}`).join(", "),vt=be.filter((kt)=>kt.status==="running"||kt.status==="queued").map((kt)=>`${kt.id} (${kt.status})`).join(", "),Nt=[];if(Ee)Nt.push(`Unfinished tasks: ${Ee}`);if(vt)Nt.push(`Active runs: ${vt}`);return`[SYSTEM] You still have team obligations. ${Nt.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,un=t.sessionId&&xt?I2(t.sessionId):void 0,Gr=Ze&&un?()=>Ze()??un():Ze??un;qNe(t.toolIntentGuard!==!1);let kr={...Zn?{requireCompletionTool:!0}:{},...Gr?{completionGuard:Gr}:{},maxNoToolCallNudges:jNe,...t.strongNudges===!1?{strongNudges:!1}:{}},Tr=aDe({offered:Jt.map((Y)=>Y.name),subagentsEnabled:p.enableSpawnAgent,serialised:it,multipleNodes:(t.agentNodes?.length??0)>1});return{tools:Jt,modelTools:f,...Object.keys(Tr).length>0?{unavailableToolReasons:Tr}:{},configuredAgents:E.configs,logger:o??t.logger,telemetry:i??t.telemetry,teamRuntime:M,teamRestoredFromPersistence:Boolean(H),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(re)?.delegatedAgentConfigProvider??Se,extensions:z,completionPolicy:kr,registerLeadAgent:(Y)=>{if(Ge=Y,I.length>0)Y.addTools(Ji(I,[...w]))},shutdown:async(Y)=>{iDe(M,Y),se?.dispose(),X?.close(),this.teamRuntimeEntries.delete(re),await K?.();for(let Q of W)Q.stop()}}}}import{normalizeUserInput as lDe}from"@cerebriline/shared";import{nanoid as cDe}from"nanoid";class kV{list(e){return e?Jn(e):[]}update(e,t){if(!e)return{sessionId:t.sessionId,prompts:[],updated:!1};let n=t.promptId.trim(),r=e.pendingPrompts.findIndex((d)=>d.id===n);if(r<0)return{sessionId:t.sessionId,prompts:Jn(e),updated:!1};let o=e.pendingPrompts[r];if(!o)return{sessionId:t.sessionId,prompts:Jn(e),updated:!1};let i=t.prompt===void 0?o.prompt:lDe(t.prompt).trim();if(!i)throw Error("prompt cannot be empty");let s=t.delivery??o.delivery,a={...o,prompt:i,mode:t.mode??o.mode,delivery:s};return e.pendingPrompts.splice(r,1),hDe(e,a,r,o.delivery),{sessionId:t.sessionId,prompts:Jn(e),prompt:Av(a),updated:!0}}delete(e,t){if(!e)return{sessionId:t.sessionId,prompts:[],removed:!1};let n=t.promptId.trim(),r=e.pendingPrompts.findIndex((i)=>i.id===n);if(r<0)return{sessionId:t.sessionId,prompts:Jn(e),removed:!1};let[o]=e.pendingPrompts.splice(r,1);return{sessionId:t.sessionId,prompts:Jn(e),prompt:o?Av(o):void 0,removed:!0}}enqueue(e,t){let{prompt:n,mode:r,delivery:o,userImages:i,userFiles:s,origin:a,noteKind:d,refresh:l}=t;if(a==="harness"&&d){let u=e.pendingPrompts.find((h)=>h.origin==="harness"&&h.noteKind===d);if(u)return u.prompt=d==="recap"?KW(u.prompt,n):n,u.refresh=l,Jn(e)}let c=e.pendingPrompts.findIndex((u)=>u.prompt===n);if(c>=0){let[u]=e.pendingPrompts.splice(c,1),h={...u,prompt:n,mode:r??u.mode,userImages:i??u.userImages,userFiles:s??u.userFiles};if(o==="steer"||u.delivery==="steer")e.pendingPrompts.unshift({...h,delivery:"steer"});else e.pendingPrompts.push(h)}else{let u={id:`pending_${Date.now()}_${cDe(5)}`,prompt:n,mode:r,delivery:o,userImages:i,userFiles:s,...a==="harness"?{origin:a}:{},...a==="harness"&&d?{noteKind:d}:{},...a==="harness"&&l?{refresh:l}:{}};if(o==="steer")e.pendingPrompts.unshift(u);else e.pendingPrompts.push(u)}return Jn(e)}consumeSteer(e){for(;;){let t=e.pendingPrompts.findIndex((r)=>r.delivery==="steer");if(t<0)return{prompts:Jn(e)};let[n]=e.pendingPrompts.splice(t,1);if(n&&vV(n))return{entry:n,prompts:Jn(e)}}}shiftNext(e){for(;;){let t=e.pendingPrompts.shift();if(!t||vV(t))return{entry:t,prompts:Jn(e)}}}requeueFront(e,t){return e.pendingPrompts.unshift(t),Jn(e)}clear(e){return e.pendingPrompts.length=0,[]}dropHarnessNotes(e){let t=e.pendingPrompts.length,n=e.pendingPrompts.filter((r)=>r.origin!=="harness");return e.pendingPrompts.length=0,e.pendingPrompts.push(...n),t-n.length}}class XC{deps;service=new kV;constructor(e){this.deps=e}list(e){return this.service.list(this.deps.getSession(e))}steerFirst(e){let t=this.deps.getSession(e),n=t?.pendingPrompts[0];if(!n||n.delivery==="steer")return{sessionId:e,prompts:this.service.list(t),updated:!1};return this.update({sessionId:e,promptId:n.id,delivery:"steer"})}update(e){let t=this.deps.getSession(e.sessionId);if(!t)return{sessionId:e.sessionId,prompts:[],updated:!1};let n=this.service.update(t,e);if(this.emitPrompts(t),n.updated&&n.prompt?.delivery==="steer"&&!t.aborting)t.agent.notifyPendingUserMessage();return this.scheduleDrain(e.sessionId,t),n}delete(e){let t=this.deps.getSession(e.sessionId);if(!t)return{sessionId:e.sessionId,prompts:[],removed:!1};let n=this.service.delete(t,e);return this.emitPrompts(t),this.scheduleDrain(e.sessionId,t),n}enqueue(e,t){let n=this.deps.getSession(e);if(!n)return;if(this.service.enqueue(n,t),this.emitPrompts(n),t.delivery==="steer"&&!n.aborting)n.agent.notifyPendingUserMessage();this.scheduleDrain(e,n)}consumeSteer(e){let t=this.deps.getSession(e);if(!t)return;let n=t.pendingPrompts.length,{entry:r}=this.service.consumeSteer(t);if(!r){if(t.pendingPrompts.length!==n)this.emitPrompts(t);return}return this.emitPrompts(t),this.emitSubmitted(t,r),r}discardQueue(e){if(e.pendingPrompts.length===0)return;this.service.clear(e),this.emitPrompts(e)}dropHarnessNotes(e){if(this.service.dropHarnessNotes(e)>0)this.emitPrompts(e)}emitPrompts(e){this.deps.emit({type:"pending_prompts",payload:{sessionId:e.sessionId,prompts:Jn(e)}})}scheduleDrain(e,t){if(t.pendingPrompts.length===0||t.aborting||t.drainingPendingPrompts||!t.agent.canStartRun())return;queueMicrotask(()=>{this.drain(e)})}async drain(e){let t=this.deps.getSession(e);if(!t)return;if(t.aborting||t.drainingPendingPrompts)return;if(!t.agent.canStartRun())return;let n=t.pendingPrompts.length,{entry:r}=this.service.shiftNext(t);if(!r){if(t.pendingPrompts.length!==n)this.emitPrompts(t);return}this.emitPrompts(t),this.emitSubmitted(t,r),t.drainingPendingPrompts=!0;let o=!0;try{let i=await this.deps.send({sessionId:e,prompt:r.prompt,...r.mode?{mode:r.mode}:{},userImages:r.userImages,userFiles:r.userFiles});if(uDe(i))o=!1}catch{o=!1,this.service.requeueFront(t,r),this.emitPrompts(t)}finally{if(t.drainingPendingPrompts=!1,o&&t.pendingPrompts.length>0&&t.status!=="failed"&&t.status!=="cancelled")queueMicrotask(()=>{this.drain(e)})}}emitSubmitted(e,t){let n=Av(t);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:e.sessionId,id:n.id,prompt:n.prompt,delivery:n.delivery,attachmentCount:n.attachmentCount,userImages:n.userImages,userFiles:n.userFiles,...n.origin?{origin:n.origin}:{}}})}}function vV(e){if(!e.refresh)return!0;let t;try{t=e.refresh()}catch{return!0}if(t===void 0||t.trim()==="")return!1;return e.prompt=t,!0}function uDe(e){return typeof e==="object"&&e!==null&&"finishReason"in e&&e.finishReason==="error"}function Av(e){return{id:e.id,prompt:e.prompt,delivery:e.delivery,attachmentCount:(e.userImages?.length??0)+(e.userFiles?.length??0),userImages:e.userImages,userFiles:e.userFiles,...e.origin==="harness"?{origin:e.origin}:{}}}function Jn(e){return e.pendingPrompts.map(Av)}function hDe(e,t,n,r){if(t.delivery==="steer")e.pendingPrompts.unshift(t);else if(r==="steer")e.pendingPrompts.push(t);else e.pendingPrompts.splice(n,0,t)}import{formatDisplayUserInput as Npt,normalizeUserInput as Dpt}from"@cerebriline/shared";import{resolveSessionDataDir as Fpt}from"@cerebriline/shared/storage";import{existsSync as JC}from"node:fs";import{readFile as pDe}from"node:fs/promises";import{join as mDe}from"node:path";class QC{listeners=new Set;subscribe(e,t){let n={listener:e,sessionId:t?.sessionId?.trim()||void 0};return this.listeners.add(n),()=>{this.listeners.delete(n)}}emit(e){let t=e.payload.sessionId?.trim();for(let n of this.listeners){if(n.sessionId&&n.sessionId!==t)continue;n.listener(e)}}get size(){return this.listeners.size}}function TV(e,t,n){let r=e?.trim();if(r&&JC(r))return r;let o=n?.trim();if(o){let i=mDe(o,t,`${t}.messages.json`);if(JC(i))return i}return r||void 0}async function Uc(e){let t=e?.trim();if(!t||!JC(t))return[];try{let n=(await pDe(t,"utf8")).trim();if(!n)return[];let r=JSON.parse(n);if(Array.isArray(r))return r;if(r&&typeof r==="object"&&!Array.isArray(r)){let o=r.messages;if(Array.isArray(o))return o}return[]}catch{return[]}}function ZC(e){return e?{...e}:void 0}async function SV(e,t){if(!(e.hookName==="tool_call"||!!e.parent_agent_id))return;await t.queueSpawnRequest(e);let r=await t.upsertSubagentSessionFromHook(e);if(!r)return;await t.appendSubagentHookAudit(r,e),await t.applySubagentStatus(r,e)}function xV(e){let t=Ca(e.session_id)?.rootSessionId??mc(e.session_id)?.rootSessionId;return{sessionId:e.session_id,source:e.source,pid:e.pid,startedAt:e.started_at,endedAt:e.ended_at??null,exitCode:e.exit_code??null,status:e.status,interactive:e.interactive,provider:e.provider,model:e.model,cwd:e.cwd,workspaceRoot:e.workspace_root,teamName:e.team_name,enableTools:e.enable_tools,enableSpawn:e.enable_spawn,enableTeams:e.enable_teams,isSubagent:t!==void 0,...t!==void 0?{parentSessionId:t}:{},prompt:e.prompt,metadata:e.metadata,messagesPath:e.messages_path,updatedAt:e.ended_at??e.started_at}}class Rv{deps;constructor(e){this.deps=e}lastKnownIdentityBySession=new Map;static MAX_IDENTITY_SNAPSHOTS=512;dispatchAgentEvent(e,t,n){let r=this.deps.getSession(e),o={sessionId:e,config:t,liveSession:r,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},i=CR(n);if(!!r&&(!i.agentId||i.agentId===eP(r.agent))){let a={agentId:eP(r.agent),conversationId:r.agent.getConversationId(),...r?.runtime.teamRuntime?{teamRole:"lead"}:{}};this.rememberSessionIdentity(e,a),pb(o,n,{...a,isPrimaryAgentEvent:!0});return}pb(o,n,{...r?{}:this.lastKnownIdentityBySession.get(e),isPrimaryAgentEvent:!1})}rememberSessionIdentity(e,t){if(this.lastKnownIdentityBySession.delete(e),this.lastKnownIdentityBySession.set(e,t),this.lastKnownIdentityBySession.size>Rv.MAX_IDENTITY_SNAPSHOTS){let n=this.lastKnownIdentityBySession.keys().next().value;if(n!==void 0)this.lastKnownIdentityBySession.delete(n)}}async handleTeamEvent(e,t){let n=this.deps.getSession(e);if(n){if(WI(n,t),t.type==="agent_event"){let r={sessionId:e,config:n.config,liveSession:n,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};pb(r,t.event,{agentId:t.agentId,teamRole:"teammate",teamAgentId:t.agentId,isPrimaryAgentEvent:!1})}if(t.type==="teammate_spawned"){let r=ui({agentId:t.teammate.runtimeAgentId??t.agentId,conversationId:t.teammate.conversationId,parentAgentId:t.teammate.parentAgentId,createdByAgentId:eP(n.agent),teamId:n.runtime.teamRuntime?.getTeamId(),teamName:n.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:t.agentId});if(r)ld(n.config.telemetry,{ulid:e,modelId:t.teammate.modelId??n.config.modelId,provider:n.config.providerId,...r})}}if(await jI(e,t,this.deps.invokeBackendOptional),n&&(t.type!=="agent_event"||t.activityChanged===!0))qI(n,e,t,this.deps.emit)}async handlePluginEvent(e,t,n,r){if(t.name==="plugin_log"){this.handlePluginLog(e,t.payload);return}if(t.name==="plugin_telemetry"){this.handlePluginTelemetry(e,t.payload,r);return}if(t.name==="automation_event"){let l=this.deps.getSession(e)?.config.extensionContext?.automation??n;if(!l)return;let c=t.payload&&typeof t.payload==="object"?t.payload:void 0;if(!c)return;await l.ingestEvent(c);return}if(t.name!=="steer_message"&&t.name!=="queue_message"&&t.name!=="pending_prompt")return;let o=t.payload&&typeof t.payload==="object"?t.payload:void 0,i=typeof o?.sessionId==="string"&&o.sessionId.trim().length>0?o.sessionId.trim():e,s=typeof o?.prompt==="string"?o.prompt.trim():"";if(!s)return;let a=t.name==="steer_message"?"steer":t.name==="queue_message"?"queue":o?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(i,{prompt:s,delivery:a})}handlePluginTelemetry(e,t,n){let o=this.deps.getSession(e)?.config.telemetry??n;if(!o||!t||typeof t!=="object")return;let i=t,s=typeof i.pluginName==="string"&&i.pluginName?i.pluginName:"unknown";if(i.kind==="event"){let a=typeof i.event==="string"?i.event.trim():"";if(!a)return;let d={...i.properties&&typeof i.properties==="object"?i.properties:{},plugin_name:s,session_id:e};if(i.required===!0)o.captureRequired(`plugin.${a}`,d);else o.capture({event:`plugin.${a}`,properties:d});return}if(i.kind==="metric"){let a=typeof i.name==="string"?i.name.trim():"",d=typeof i.value==="number"?i.value:NaN;if(!a||Number.isNaN(d))return;let l={...i.attributes&&typeof i.attributes==="object"?i.attributes:{},plugin_name:s},c=typeof i.description==="string"?i.description:void 0,u=i.required===!0,h=`plugin.${a}`;if(i.metric==="counter")o.recordCounter(h,d,l,c,u);else if(i.metric==="histogram")o.recordHistogram(h,d,l,c,u);else if(i.metric==="gauge")o.recordGauge(h,d,l,c,u)}}handlePluginLog(e,t,n){let r=this.deps.getSession(e),o=n??r?.config.extensionContext?.logger??r?.config.logger;if(!o||!t||typeof t!=="object")return;let i=t,s=typeof i.message==="string"?i.message:"";if(!s)return;let a=i.metadata&&typeof i.metadata==="object"?{...i.metadata}:{};if(a.sessionId??=e,typeof i.pluginName==="string"&&i.pluginName)a.pluginName=i.pluginName;if(i.level==="debug"){o.debug(s,a);return}if(i.level==="error"){if(o.error)o.error(s,a);else o.log(s,{...a,severity:"error"});return}o.log(s,a)}}function eP(e){return e.getAgentId()}function tP(e){return{sessionId:e.sessionId,source:e.source,pid:process.pid,startedAt:e.startedAt,endedAt:e.endedAt??null,exitCode:e.exitCode??null,status:e.status,interactive:e.interactive,provider:e.config.providerId,model:e.config.modelId,cwd:e.config.cwd,workspaceRoot:hi(e.config),teamName:e.config.teamName?.trim()||void 0,enableTools:e.config.enableTools,enableSpawn:e.config.enableSpawnAgent,enableTeams:e.config.enableAgentTeams,parentSessionId:typeof e.sessionMetadata?.parentSessionId==="string"?e.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof e.sessionMetadata?.parentAgentId==="string"?e.sessionMetadata.parentAgentId:void 0,agentId:typeof e.sessionMetadata?.agentId==="string"?e.sessionMetadata.agentId:void 0,conversationId:typeof e.sessionMetadata?.conversationId==="string"?e.sessionMetadata.conversationId:void 0,isSubagent:typeof e.sessionMetadata?.isSubagent==="boolean"?e.sessionMetadata.isSubagent:!1,prompt:e.pendingPrompt,metadata:e.sessionMetadata,messagesPath:e.artifacts?.messagesPath,updatedAt:e.updatedAt??e.endedAt??e.startedAt}}function nP(e,t){let n=e[t];return typeof n==="function"?n:null}async function _V(e,t,...n){let r=nP(e,t);if(!r)throw Error(`session service method not available: ${t}`);return Promise.resolve(r.apply(e,n))}async function EV(e,t,...n){let r=nP(e,t);if(!r)return;await Promise.resolve(r.apply(e,n))}async function AV(e,t,...n){let r=nP(e,t);if(!r)return;return await Promise.resolve(r.apply(e,n))}import{clearPolykvSession as Iv,releasePolykvAgent as rP,setPolykvSession as fDe}from"@cerebriline/llms";function IV(e,t,n){let r=n?{extractDocument:n}:{};if(!e)return{executors:t,enableBash:!1,...n?{executorOptions:r}:{}};let o=wv(t?.semanticSearch,e.executorOptions.overlay);return{executorOptions:{...e.executorOptions,...r},...o?{executors:{semanticSearch:o}}:{},...e.allowCommands?{}:{enableBash:!1}}}function Cv(e,t,n){return{onSubAgentEvent:(r)=>e.onAgentEvent(n,t,r),onSubAgentStart:(r)=>{let o=e.getSession(n)?.runtime.teamRuntime;e.subAgentStarts.set(r.subAgentId,{startedAt:Date.now(),rootSessionId:n});let i=ui({agentId:r.subAgentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamId:o?.getTeamId(),teamName:o?.getTeamName(),createdByAgentId:r.parentAgentId});if(i)ld(t.telemetry,{ulid:n,modelId:t.modelId,provider:t.providerId,...i});vk(t.telemetry,{event:"started",ulid:n,durationMs:0,parentId:r.parentAgentId,agentId:r.subAgentId,...i}),e.invokeBackendOptional("handleSubAgentStart",n,r)},onSubAgentEnd:async(r)=>{let o=e.getSession(n)?.runtime.teamRuntime,i=e.subAgentStarts.get(r.subAgentId),s=i?Date.now()-i.startedAt:0,a=r.result?.text?r.result.text.split(`
1463
1463
  `).length:0;if(vk(t.telemetry,{event:"ended",ulid:n,durationMs:s,outputLines:a,errorMessage:r.error?String(r.error):void 0,agentId:r.subAgentId,parentId:r.parentAgentId,...ui({agentId:r.subAgentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamId:o?.getTeamId(),teamName:o?.getTeamName(),createdByAgentId:r.parentAgentId})}),e.subAgentStarts.delete(r.subAgentId),r.toolCallId&&e.sandboxes?.has(r.toolCallId)){let d=r.input.name??"agent",l=await e.sandboxes.close(r.toolCallId,d);gDe(r,d,l)}e.invokeBackendOptional("handleSubAgentEnd",n,r)},onSubAgentSettled:async(r)=>{if(r.toolCallId)await e.sandboxes?.close(r.toolCallId,r.name)}}}function gDe(e,t,n){if(!e.result||typeof e.result.text!=="string")return;e.result.text+=Ia(e.result.text,e.result.finishReason,t,n)}function oP(e,t,n,r,o){let i=Cv(e,t,n),s=async(a,d)=>{let l=d?.toolCallId,c=e.sandboxes&&l&&t.enableTools?await e.sandboxes.open(l):void 0,u=t.enableTools?sm(dp({cwd:t.cwd,telemetry:t.telemetry,...go[yo({mode:t.mode})],enableExtractDocument:t.enableExtractDocument===!0&&go[yo({mode:t.mode})].enableExtractDocument,...IV(c,r,oa(t))}),t.extraTools):[];if(t.enableSpawnAgent)u.push(oP(e,t,n,r));return Ji(u)};return sc({...o?{sessionId:n}:{},...o?.swarm?{swarm:o.swarm}:{},...o?.teammates?{teammates:!0}:{},...o?.configuredAgents?{configuredAgents:o.configuredAgents}:{},...o?.configuredAgentConfigs?{configuredAgentConfigs:o.configuredAgentConfigs}:{},configProvider:{getRuntimeConfig:()=>e.getSession(n)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:t.providerId,modelId:t.modelId,cwd:t.cwd,apiKey:t.apiKey,baseUrl:t.baseUrl,headers:t.headers,providerConfig:t.providerConfig,knownModels:t.knownModels,thinking:t.thinking,maxIterations:t.maxIterations,hooks:t.hooks,extensions:t.extensions,logger:t.logger,telemetry:t.telemetry},getConnectionConfig:()=>e.getSession(n)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:t.providerId,modelId:t.modelId,apiKey:t.apiKey,baseUrl:t.baseUrl,headers:t.headers,providerConfig:t.providerConfig,knownModels:t.knownModels,thinking:t.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:s,commandSandboxFor:(a)=>ab(e.sandboxes,a),...i})}function yDe(e,t){if(e&&typeof e==="object")e.handback=t}function RV(e,t){let n=t&&typeof t==="object"?t.handback:void 0;if(n)e?.handedBack("reducer",n)}function CV(e,t,n,r){let o=Cv(e,t,n),i={providerId:t.providerId,...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...t.headers!==void 0?{headers:t.headers}:{},...t.providerConfig?.polykv!==void 0?{polykv:t.providerConfig.polykv}:{}},s=()=>e.getSession(n)?.runtime.delegatedAgentConfigProvider??{getRuntimeConfig:()=>({providerId:t.providerId,modelId:t.modelId,cwd:t.cwd,apiKey:t.apiKey,baseUrl:t.baseUrl,headers:t.headers,providerConfig:t.providerConfig,knownModels:t.knownModels,thinking:t.thinking,maxIterations:t.maxIterations,hooks:t.hooks,extensions:t.extensions,logger:t.logger,telemetry:t.telemetry}),getConnectionConfig:()=>({providerId:t.providerId,modelId:t.modelId,apiKey:t.apiKey,baseUrl:t.baseUrl,headers:t.headers,providerConfig:t.providerConfig,knownModels:t.knownModels,thinking:t.thinking}),updateConnectionDefaults:()=>{}},a=(u,h)=>({...u,getRuntimeConfig:()=>({...u.getRuntimeConfig(),sessionId:h})}),d,l=(u,h)=>u.providerId===h.providerId&&u.baseUrl===h.baseUrl,c=async(u)=>{let h=u.control,p=()=>h?.signal??u.signal,f=s(),m=`${n}:swarm:${u.name}:${Date.now().toString(36)}`,g=`${m}:${Math.random().toString(36).slice(2,8)}`,y=e.sandboxes&&t.enableTools?await e.sandboxes.open(g):void 0,w=t.enableTools?Ji(sm(dp({cwd:t.cwd,telemetry:t.telemetry,...go[yo({mode:t.mode})],enableExtractDocument:t.enableExtractDocument===!0&&go[yo({mode:t.mode})].enableExtractDocument,...IV(y,r,oa(t))}),t.extraTools)).filter((B)=>u.tools===void 0||u.tools.includes(B.name)):[],k=fa(u.emitUpdate,(B)=>o.onSubAgentEvent?.(B),Date.now,{onCompaction:Vl(`swarm worker ${u.name}`,t.logger),...h?.id?{outputId:h.id}:{}}),b=Hl(Fl({sessionId:n,name:u.name,...t.logger?.log?{logger:{log:(B)=>t.logger?.log?.(B)}}:{}}),u.emitUpdate,h),v=Gl(m,u.emitUpdate,t.logger,(B)=>b.waiting($l(B))),E=u.maxIterations??t.maxIterations,S=u.check?TR(y):void 0,x=u.check?`${u.task}
1464
1464
 
1465
1465
  ${Hi(u.check,S!==void 0)}`:u.task,T=Ki(),A,R,C=Mr(u.sampling),L,N=async(B,j,G,z,M)=>{let X=l(f.getRuntimeConfig(),B.getRuntimeConfig());Iv(m);let oe=Boolean(u.poolId&&X),H=B.getConnectionConfig();Wl(u.emitUpdate,{providerId:H.providerId,modelId:H.modelId,knownModels:H.knownModels,maxIterations:t.maxIterations});let J=!oe&&$o({providerId:H.providerId,baseUrl:H.baseUrl,polykv:H.providerConfig?.polykv}),he=await rp({instructions:u.systemPrompt,task:qi(x,h?.instructions),pooled:J,cwd:B.getRuntimeConfig().cwd});if(await es(C,H),oe&&u.poolId)fDe(m,{poolId:u.poolId,prefixTokens:0,layout:"borrowed"});let se=cA({...lA(E),...t.compaction?.cappedThinkingBudgetMessage?{thinkingBudgetMessage:t.compaction.cappedThinkingBudgetMessage}:{},onTransition:(_,F)=>t.logger?.log?.(`[swarm] ${u.name}: worker ${_} (${F})`)}),re=u.check?Wi({check:u.check,cwd:e.sandboxes?.workspaceRoot??t.cwd,...S?{wrapSpawn:S}:{}}):void 0,Ge=ii({kind:"subagent",struggle:se,...re?{check:re}:{},...u.takeMessage||h?{consumePendingUserMessage:async()=>(h?.takeMessage??u.takeMessage)?.()}:{},prompt:he.systemPrompt,engineSessionId:m,...J?{polykvWorker:{group:n,layers:he.layers}}:{},pinnedHead:he.pinnedHead,configProvider:a(B,m),...C?{sampling:C,onSampling:(_)=>{L=_,jl(u.emitUpdate,_)}}:{},tools:w,maxIterations:E,parentAgentId:n,...p()?{abortSignal:p()}:{},onEvent:(_)=>{if(Yl(_))j(),b.progressed();k.observe(_)},recoverTurnFault:G??ur({label:`swarm worker ${u.name}`,onWaiting:b.waiting,baseUrl:()=>H.baseUrl,headers:()=>H.headers,...p()?{signal:p()}:{},...u.emitUpdate?{emitUpdate:u.emitUpdate}:{},...t.logger?.log?{logger:{log:(_)=>t.logger?.log?.(_)}}:{}})});R=Ge.getAgentId?.(),h?.track(Ge);let I=await Gi({agent:Ge,start:async()=>{if(z&&z.messages.length>0)return Ge.restore(z.messages),await Ge.continue(op(z.reason));return he.pinnedHead.length>0?await Ge.runWithHead(he.pinnedHead,he.task):await Ge.run(he.task)},name:u.name,supervisor:se,...E!==void 0?{maxIterations:E}:{},sessionId:n,...h?.id?{cancelId:h.id}:{},...p()?{signal:p()}:{},...u.emitUpdate?{emitUpdate:u.emitUpdate}:{},...re?{check:re}:{},releaseEngineSession:async()=>{Iv(m),await rP(m)},lifetime:T,resumeThrough:Jl({...M&&f.getRuntimeConfig().nodePlacement?{placement:f.getRuntimeConfig().nodePlacement,nodeId:M}:{},...!M&&f.getRuntimeConfig().slotGate?{slotGate:f.getRuntimeConfig().slotGate}:{},signal:p})});return A=I,I.result},W=(B)=>({...B,...R?{agentId:R}:{},...A?.maxIterations!==void 0?{maxIterations:A.maxIterations}:{},...A?.stopReason?{stopReason:A.stopReason}:{},...A?.state?{state:A.state}:{},...A?.oracle?{oracle:A.oracle}:{}}),D,K,V=(B)=>h?h.continuable(B,async(j)=>{Iv(m),await Kl(u.emitUpdate,m,j.reason)}):B(void 0);try{let B=f.getRuntimeConfig().nodePlacement;if(B){let z=await V((M)=>Xl({placement:B,...p()?{signal:p()}:{},...u.emitUpdate?{emitUpdate:u.emitUpdate}:{},...t.logger?{logger:t.logger}:{},label:`swarm worker ${u.name}`,onWaiting:b.waiting,...h?{relocate:(X,oe)=>h.requeue({reason:oe,avoidNodeId:X})}:{},...M?{requeued:M.avoidNodeId?{avoidNodeId:M.avoidNodeId}:{}}:{},run:(X,oe,H)=>N(X.configProvider,oe,H,M,X.nodeId),beforeRetry:async()=>{await rP(m)}}));return D=W({...z.result,placed:z.placed,...L?{sampling:L}:{}}),D}let j=f.getRuntimeConfig().slotGate,G=(z,M)=>HI(()=>N(f,M,void 0,z),{onRetry:(X,oe)=>t.logger?.log?.(`[PolyKV] ${u.name} refused: the session's window is full; waiting ${oe/1000}s for a worker to finish (attempt ${X})`)});if(D=W(await V((z)=>{let M=(X)=>(u.emitUpdate?.({queued:!1}),G(z,X));return j?j.run(M):M(()=>{})})),L)D={...D,sampling:L};return D}catch(B){throw K=B,B}finally{await T.end(async()=>{if(y){let j=await e.sandboxes?.close(g,u.name).catch(()=>[]);yDe(D??K,j??[])}Iv(m),v(),b.dispose();let B=await rP(m).catch(()=>{return});ql(t.logger?.log?(j)=>t.logger?.log?.(j):void 0,B,"[PolyKV]")})}};return ip({sessionId:n,pools:{snapshot:async()=>{let u=await oL({sessionId:n,providerConfig:i,logger:t.logger});if(!u)return;return{poolId:u.poolId,release:u.borrowed?async()=>{return}:()=>iL({poolId:u.poolId,providerConfig:i,logger:t.logger})}},headroom:async()=>bv(await Sd({sessionId:n,providerConfig:i,logger:t.logger}))?.headroomSessions,admit:async()=>{let u=s().getRuntimeConfig();if(u.nodePlacement)return u.nodePlacement.waiting===0;let h=u.slotGate;return h?await h.canAdmitMore():!0}},reduce:async(u,h)=>{if(!d)return;let p;try{p=await c({name:"reducer",systemPrompt:XA,task:u.map(qw).join(`
@@ -1472,13 +1472,13 @@ ${Hi(u.check,S!==void 0)}`:u.task,T=Ki(),A,R,C=Mr(u.sampling),L,N=async(B,j,G,z,
1472
1472
  `),IDe=`(No reply: this side turn used all ${Bc} of its own turns before answering. That limit is the side turn's own, not the agents' -- it says nothing about how far they got.)`;async function LV(e){let t=[];try{let n=(e.leadTools??[]).filter((a)=>dP.has(a.name)),r=e.createRunner([...EDe(e.sessionId,t),...n]);r.restore(_De(e.messages,xDe(e.sessionId)));let o=e.source==="system"?ADe:RDe,i=n.some((a)=>a.name==="agents_status")?" `agents_status` shows what each agent is doing and why.":"",s=await r.continue(`${o.replace("{LEAD_TOOLS}",i)}
1473
1473
  ${e.message}`);if(s.finishReason==="max_iterations")return{reply:IDe,actions:t,failed:!0,failure:"iteration_cap"};if(s.finishReason==="error")return{reply:"My reply between the agents' progress failed before I could answer. Your message is queued for my next turn.",actions:t,failed:!0,failure:"error"};return{reply:s.text.trim(),actions:t}}catch(n){return{reply:`I could not answer while the agents run: ${n instanceof Error?n.message:String(n)}. Your message is queued for when the round returns.`,actions:t,failed:!0,failure:"error"}}}function aP(e,t){let n=e.trim().replace(/\s*\n\s*/g," ");return t!==void 0&&n.length>t?`${n.slice(0,t-1)}…`:n}function CDe(e){let t=e.split(`
1474
1474
  `).map((n)=>/^- ([^:]+):/.exec(n.trim())?.[1]?.trim()).filter((n)=>Boolean(n));return t.length>0?t.join(", "):"agents"}var PDe=600;function NV(e,t,n="user"){let r=n==="system"?`- report (stalled: ${CDe(e)}):`:`- user: "${aP(e)}" ->`,o=n==="system"&&t.actions.some((a)=>a.startsWith("Stopped")),i=t.actions.length>0?`; did: ${aP(t.actions.join(" "))}${o?" Their tasks are yours now.":""}`:"",s=!t.failed?`you replied: "${aP(t.reply||"(nothing)",PDe)}"${i}`:i?`side turn stopped before replying${i}`:`NOT ANSWERED (${t.failure==="iteration_cap"?`the side turn used its own ${Bc} turns, not the agents'`:"the side turn failed; agents unaffected"}): answer it now.`;return`${zW}
1475
- ${r} ${s}`}var $V=5000,cP;function WDe(e,t){if(cP)return;cP=FD().then(()=>{return}).catch((n)=>{cP=void 0,e?.error?.("Detached command log recovery failed",{error:n}),yr(t,{component:"core",operation:"command.detached_log_recovery",error:n,severity:"warn",handled:!0})})}function cm(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function jDe(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e,n=cm(t.inputTokens),r=cm(t.outputTokens),o=cm(t.cacheReadTokens),i=cm(t.cacheWriteTokens),s=cm(t.totalCost);if(n===void 0||r===void 0||o===void 0||i===void 0||s===void 0)return;return{inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:i,totalCost:s}}function qDe(e,t){return{inputTokens:Math.max(e.inputTokens,t.inputTokens),outputTokens:Math.max(e.outputTokens,t.outputTokens),cacheReadTokens:Math.max(e.cacheReadTokens,t.cacheReadTokens),cacheWriteTokens:Math.max(e.cacheWriteTokens,t.cacheWriteTokens),totalCost:Math.max(e.totalCost,t.totalCost)}}var zDe=10,KDe=8000;async function GDe(e,t){let n;try{return await Promise.race([e.catch(()=>{return}),new Promise((r)=>{n=setTimeout(()=>r(void 0),t)})])}finally{if(n)clearTimeout(n)}}async function FV(e,t){if(!e?.length)return{lines:[],high:!1,broken:!1};let{readFile:n}=await import("node:fs/promises");await Promise.resolve().then(() => oR());let a=[],d=!1,l=!1;for(let c of e.slice(0,zDe)){let u=BV(c)||!t?c:yi(t,c);try{let h=await n(u,"utf8"),p=await Qw(u,h);if(p){a.push(Zw(p,c)),d=d||vz(p);continue}if(await xz(u,h)===!1)l=!0,a.push(`${c} no longer parses — the grammar cannot read it end to end, so whatever is wrong with it is structural rather than in one expression.`)}catch{}}return{lines:a,high:d,broken:l}}function VDe(e){let t=0;for(let n of e.messages){let r=n.metadata;if(r?.kind!=="compaction_summary")continue;let o=r.generation;t=Math.max(t,typeof o==="number"&&Number.isFinite(o)?o:1)}return t}function UV(e,t){if(!t)return!1;if(e.source_message_count!==t.source_message_count)return e.source_message_count<t.source_message_count;return Date.parse(e.updated_at)<Date.parse(t.updated_at)}var YDe=/^(?:spawn_agent|spawn_swarm|team_run_task|subagent_[\w-]+)$/;class um{pendingAtomicDisengage=new Set;runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;distinctId;defaultLogger;defaultFetch;events=new QC;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;sideCallUnsubscribes=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;backgroundDelegations=new Map;sideTurnConfigs=new Map;sideTurns=new Map;leadNudgeUnsubscribes=new Map;roundUnsubscribes=new Map;eventBridge;sessionVersioning=new Dp;runCommandExecutionController=new Nh;constructor(e){let t=NDe();if(t)HDe(t);let n=$a(e.distinctId);if(this.distinctId=n,this.sessionService=e.sessionService,this.runtimeBuilder=e.runtimeBuilder??new YC,this.createAgentInstance=e.createAgent??((r)=>new Sa(r)),this.defaultCapabilities=kc(e.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=e.toolPolicies,this.providerSettingsManager=e.providerSettingsManager??new Vn,this.oauthTokenManager=e.oauthTokenManager??new Ap({providerSettingsManager:this.providerSettingsManager,telemetry:e.telemetry}),this.defaultTelemetry=e.telemetry,this.defaultLogger=e.logger,e.distinctId!==void 0)this.defaultTelemetry?.setDistinctId(n);this.defaultFetch=e.fetch,WDe(this.defaultLogger,this.defaultTelemetry),this.pendingPromptsController=new XC({getSession:(r)=>this.sessions.get(r),emit:(r)=>this.emit(r),send:(r)=>this.runTurn(r)}),this.pendingPrompts={steerFirst:async(r)=>this.pendingPromptsController.steerFirst(r.sessionId),list:async(r)=>this.pendingPromptsController.list(r.sessionId),update:async(r)=>this.pendingPromptsController.update(r),delete:async(r)=>this.pendingPromptsController.delete(r)},this.eventBridge=new Rv({getSession:(r)=>this.sessions.get(r),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(r)=>this.emit(r),persistMessages:(r,o,i)=>{this.invoke("persistSessionMessages",r,o,i).catch((s)=>{let a=this.sessions.get(r);(a?.config.logger??this.defaultLogger)?.error?.("Failed to persist session messages from agent event",{sessionId:r,error:s}),yr(a?.config.telemetry??this.defaultTelemetry,{component:"core",operation:"session.persist_messages_on_agent_event",error:s,severity:"warn",handled:!0,context:{sessionId:r,providerId:a?.config.providerId,modelId:a?.config.modelId}})})},enqueuePendingPrompt:(r,o)=>this.pendingPromptsController.enqueue(r,o),invokeBackendOptional:(r,...o)=>this.invokeOptional(r,...o)})}async applyInitialOAuthCredentials(e){if(e.config.apiKey?.trim())return e;let t=await this.oauthTokenManager.resolveProviderApiKey({providerId:e.config.providerId});if(!t?.apiKey)return e;return{...e,config:{...e.config,apiKey:t.apiKey}}}async startSession(e){let t=e.config.sessionId?.trim()??"",n=t||FDe(),r=t.length>0&&(e.initialMessages?.length??0)>0&&!e.prompt?.trim(),o=Boolean(e.config.cwd?.trim()||e.config.workspaceRoot?.trim()),i=r&&!o?await this.invokeOptionalValue("readSessionManifest",n):void 0,s=i?{...e.config,cwd:i.cwd,workspaceRoot:i.workspace_root}:await RW(e.config);return await this.startResolvedSession({...e,config:s},n,t.length>0,i)}async startResolvedSession(e,t,n,r){let o=e.source??Gt.CLI,i=ft(),s=await this.applyInitialOAuthCredentials(e),a=s.initialMessages??[];if(s.config.enableAgentTeams===!1&&TK(a))(s.localRuntime?.logger??this.defaultLogger)?.log(kK,{sessionId:t});let d=a.length>0?IR(a):Cn(),l=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!l)throw Error("session service method not available: ensureSessionsDir");let c=yi(l,t),u=yi(c,`${t}.messages.json`),h=yi(c,`${t}.json`);He(t).attachStore(yi(c,`${t}.rounds.json`));let p=hi(e.config),f=e.interactive===!0&&!s.prompt?.trim(),m=rs.parse({version:1,session_id:t,source:o,pid:process.pid,started_at:i,status:f?"idle":"running",interactive:e.interactive===!0,provider:s.config.providerId,model:s.config.modelId,cwd:s.config.cwd,workspace_root:p,team_name:s.config.teamName,enable_tools:s.config.enableTools,enable_spawn:s.config.enableSpawnAgent,enable_teams:s.config.enableAgentTeams,prompt:s.prompt?.trim()||void 0,messages_path:u}),g,y,w=n&&a.length>0&&!s.prompt?.trim();if(w){let P=r??await this.invokeOptionalValue("readSessionManifest",t);if(P)m=P,g={manifestPath:h,messagesPath:P.messages_path||u,compactionPath:P.compaction_path,manifest:P},y=await this.invokeOptionalValue("readSessionCompactionState",t)}let k=await this.seedAggregateUsageFromArtifacts({initialUsage:d,sessionDir:c,rootMessagesPath:g?.messagesPath??u,manifest:m});this.usageBySession.set(t,d),this.aggregateUsageBySession.set(t,k);let b=kc(this.defaultCapabilities,e.capabilities),v=b?.toolExecutors??this.toolExecutors,E=e.localRuntime,S=E?.extensionContext?.logger??E?.logger,x=E?.extensionContext?.automation,T=E?.extensionContext?.telemetry??E?.telemetry??this.defaultTelemetry,A,R={getSession:(P)=>this.sessions.get(P),subAgentStarts:this.subAgentStarts,onAgentEvent:(P,ye,nt)=>this.eventBridge.dispatchAgentEvent(P,ye,nt),invokeBackendOptional:(P,...ye)=>this.invokeOptional(P,...ye)},C,L=()=>{if(C)return C;let P=s.config.subagentCommandsEnabled===!0,ye=s.config.workspaceRoot??s.config.cwd??process.cwd(),nt=yi(c,"agent-overlays"),lt=Tv(s.config.sandboxBinariesDir),Wt={workspaceRoot:ye,...lt?{binaries:lt}:{},...s.config.subagentSandboxConfine===!1?{confine:!1}:{},overlayRootFor:(Dn)=>yi(nt,Dn.replace(/[^A-Za-z0-9_.-]/g,"_"))};return C=bK({provider:Wt,commandsEnabled:P,revisionLog:()=>this.sessions.get(t)?.revisionLog}),C},N=()=>({sandboxes:L()}),W=di(g?.manifest.metadata),D=di(Gn(s.sessionMetadata,{mode:s.mode??W?.mode,trigger:s.mode?void 0:W?.trigger})),K=n&&a.length>0?g?.manifest??r??await this.invokeOptionalValue("readSessionManifest",t):void 0,V=h6({stored:K?.metadata,hasHistory:a.length>0,configured:s.config.toolResultFormat});A=await A3({input:{...s,config:{...s.config,toolResultFormat:V}},localRuntime:e.localRuntime,sessionId:t,sessionOrigin:D,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultLogger:this.defaultLogger,defaultCapabilities:b,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(P)=>{if(P.name==="plugin_log"){this.eventBridge.handlePluginLog(t,P.payload,S);return}this.eventBridge.handlePluginEvent(t,P,x,T)},onTeamEvent:(P)=>{this.eventBridge.handleTeamEvent(t,P),A.config.onTeamEvent?.(P)},createSpawnTool:(P)=>oP({...R,...N()},A.config,t,v,P),createSwarmTool:()=>CV({...R,...N()},A.config,t,v),delegatedSandboxes:L,createSubAgentLifecycleCallbacks:(P)=>Cv({...R,...N()},P,t),readSessionMetadata:async()=>(await this.getSession(t))?.metadata,writeSessionMetadata:async(P)=>{await this.persistSessionMetadata(t,()=>P)}});let B=Gn(xI({...g?.manifest.metadata??{},...s.sessionMetadata??{},[VI]:V},A.gitState),{mode:D?.mode,trigger:D?.trigger,version:A.config.extensionContext?.client?.version});if(!g)m.metadata=B;let j=c4({root:A.config.workspaceRoot??A.config.cwd??process.cwd(),...A.config.atomicProtocol?.forgetReads?{forgetReads:A.config.atomicProtocol.forgetReads}:{}}),G=A.config.checkpoint?.enabled!==!1,z=j.port,M=A.config.compaction?{...A.config,compaction:{...A.config.compaction,...G?{revisions:z}:{},toolLedgerEnabled:!0}}:A.config,X=A.providerConfig,oe=Cf(M,{sideCallOf:t});this.sideCallUnsubscribes.get(t)?.(),this.sideCallUnsubscribes.set(t,DDe(t,(P)=>{this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"side_call_room",state:P.kind}})}));let H={enabled:M.compaction?.cappedThinkingEnabled,budgetTokens:M.compaction?.thinkingBudgetTokens??(M.providerConfig??X)?.thinkingBudgetTokens,budgetMessage:M.compaction?.cappedThinkingBudgetMessage,promptTemplate:M.compaction?.cappedThinkingPrompt,providerConfig:{...M.providerConfig??X,...M.toolResultFormat?{toolResultFormat:M.toolResultFormat}:{}},summarizer:M.compaction?.summarizer,logger:M.logger},J=gT(H),he={...H,sideCallOf:t},se=gT(he),re=await this.runtimeBuilder.build({...A.runtimeBuilderInput,distinctId:this.distinctId,runCommandExecutionController:this.runCommandExecutionController,createDelegatedPrepareTurn:(P)=>{let ye,nt=P?Cf({...M,providerId:P.providerId,modelId:P.modelId,providerConfig:P.providerConfig,sessionId:P.engineSessionId??M.sessionId}):oe;return yT(UT({compact:nt,getState:()=>ye,logger:M.logger,saveState:(lt)=>{ye=lt}}),H)},condenseDiscardedReasoning:J,onDelegatedLoopCut:(P)=>iP(yi(c,MV(P.agentId)),P)});if(re.teamRuntime&&!M.teamName?.trim()){let P=re.teamRuntime.getTeamName();M.teamName=P,A.config.teamName=P}let Ge=async()=>{let P=this.sessions.get(t);if(!P||!ou(P.config.providerId))return!1;try{return await this.syncOAuthCredentials(P,{forceRefresh:!0}),!0}catch{return!1}};re.delegatedAgentConfigProvider?.updateConnectionDefaults({onAuthError:Ge});let I=[...re.tools,...M.extraTools??[]],_=M.taskProgress,F=_?.enabled?new lg({..._.reminderInterval!==void 0?{reminderInterval:_.reminderInterval}:{},..._.onUpdate?{onUpdate:_.onUpdate}:{}}):void 0;F?.hydrate(t$(a));let ue=F&&!I.some((P)=>P.name===eo)?[...I,lS()]:I,ne=ue.some((P)=>P.name===Lr)?ue:[...ue,Oz({cwd:M.cwd,...M.checkFile?.lintCommand?{lintCommand:M.checkFile.lintCommand}:{}})],fe=ne.some((P)=>P.name===lR)?ne:[...ne,Zz({cwd:M.cwd,createLister:()=>Qz(M.workspaceRoot??M.cwd)})],Ce=M.editVerification,We=Ce?.mode??"nudge",Se={editTools:Ce?.editTools??[le.EDITOR,le.APPLY_PATCH],checkTools:Ce?.checkTools??[Lr],attempts:We==="require"?4:2,cwd:M.cwd??process.cwd(),fileExists:MDe},Le=We==="off"||Se.checkTools.length===0?void 0:new dR(Se),dt=Wz(fe,{cwd:M.cwd??process.cwd(),shellName:le.RUN_COMMANDS,checkerName:Lr,onChecked:(P)=>Le?.recordChecked(P)}),_e=F?dt.map((P)=>Mu(P,F)):dt,Ue=Le?_e.map((P)=>Gz(P,Le)):_e,xt=F?n$(F):void 0,Jt=Le?zz(Le,Se):void 0,Zn=re.completionPolicy?.completionGuard,Ze=[];if(Zn)Ze.push({kind:"team_obligation",guard:Zn,notice:"Delegated work for this run is still open — asking the model to collect it before it finishes."});if(Jt)Ze.push({kind:"edit_verification",guard:Jt,notice:"Edited files have not been checked since the last edit — asking the model to check them before it finishes."});if(xt)Ze.push({kind:"checklist_close_out",guard:xt,notice:"The checklist still has open items — asking the model to close them before it finishes."});let un=new Map,Gr=Ze.length>0?{...re.completionPolicy,completionGuard:()=>{for(let{kind:P,guard:ye,notice:nt}of Ze){let lt=ye();if(lt!==void 0){let Wt=(un.get(P)??0)+1;return un.set(P,Wt),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:nt,metadata:{kind:P,reason:P,phase:"nudge",attempt:Wt}}),lt}}return}}:re.completionPolicy,kr=re.completionPolicy?.afterToolsReminder,Tr=F?{...Gr,afterToolsReminder:()=>kr?.()??F.takePendingReminder()}:Gr,Y,Q,ee,be=0,ge=M4(),Ee=M.escalation?.alternateWithBase===!0?b4():void 0,vt=Ee&&M.escalation?.relayNothing!==!0?I4():void 0,Nt=vt?R4():void 0,kt=vt?A4({onVerdict:(P)=>vt.noteGuard(P.text)}):void 0,et=await l4({...Ee?{revisionOverlay:{source:{get pending(){return ge.source.pending},get transaction(){return ge.source.transaction},get revisions(){return ge.source.log}},wording:w6,live:()=>Ee.engaged}}:{},workspaceRoot:M.workspaceRoot??M.cwd??process.cwd(),config:M.atomicProtocol,revisions:j.log,logger:{log:(P)=>M.logger?.log?.(P)},describeLastTransaction:()=>ee?.(),onStatus:(P)=>{Y=P},onEvent:(P)=>{if(P.type==="opened")Q?.noteTransaction(P.transaction);if(P.type==="settled"&&!P.kept&&!P.carried)Q?.noteTransactionOutcome("discarded");if(P.type==="empty"){Q?.noteTransactionOutcome("empty"),M.logger?.debug?.(P.message),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"atomic_empty_attempt",transaction:P.transaction,continued:P.continued}});return}if(P.type==="plan"){if(P.from!=="reasoning")return;this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:`Plan for transaction ${P.transaction}:
1475
+ ${r} ${s}`}var $V=5000,cP;function WDe(e,t){if(cP)return;cP=FD().then(()=>{return}).catch((n)=>{cP=void 0,e?.error?.("Detached command log recovery failed",{error:n}),yr(t,{component:"core",operation:"command.detached_log_recovery",error:n,severity:"warn",handled:!0})})}function cm(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function jDe(e){if(!e||typeof e!=="object"||Array.isArray(e))return;let t=e,n=cm(t.inputTokens),r=cm(t.outputTokens),o=cm(t.cacheReadTokens),i=cm(t.cacheWriteTokens),s=cm(t.totalCost);if(n===void 0||r===void 0||o===void 0||i===void 0||s===void 0)return;return{inputTokens:n,outputTokens:r,cacheReadTokens:o,cacheWriteTokens:i,totalCost:s}}function qDe(e,t){return{inputTokens:Math.max(e.inputTokens,t.inputTokens),outputTokens:Math.max(e.outputTokens,t.outputTokens),cacheReadTokens:Math.max(e.cacheReadTokens,t.cacheReadTokens),cacheWriteTokens:Math.max(e.cacheWriteTokens,t.cacheWriteTokens),totalCost:Math.max(e.totalCost,t.totalCost)}}var zDe=10,KDe=8000;async function GDe(e,t){let n;try{return await Promise.race([e.catch(()=>{return}),new Promise((r)=>{n=setTimeout(()=>r(void 0),t)})])}finally{if(n)clearTimeout(n)}}async function FV(e,t){if(!e?.length)return{lines:[],high:!1,broken:!1};let{readFile:n}=await import("node:fs/promises");await Promise.resolve().then(() => oR());let a=[],d=!1,l=!1;for(let c of e.slice(0,zDe)){let u=BV(c)||!t?c:yi(t,c);try{let h=await n(u,"utf8"),p=await Qw(u,h);if(p){a.push(Zw(p,c)),d=d||vz(p);continue}if(await xz(u,h)===!1)l=!0,a.push(`${c} no longer parses — the grammar cannot read it end to end, so whatever is wrong with it is structural rather than in one expression.`)}catch{}}return{lines:a,high:d,broken:l}}function VDe(e){let t=0;for(let n of e.messages){let r=n.metadata;if(r?.kind!=="compaction_summary")continue;let o=r.generation;t=Math.max(t,typeof o==="number"&&Number.isFinite(o)?o:1)}return t}function UV(e,t){if(!t)return!1;if(e.source_message_count!==t.source_message_count)return e.source_message_count<t.source_message_count;return Date.parse(e.updated_at)<Date.parse(t.updated_at)}var YDe=/^(?:spawn_agent|spawn_swarm|team_run_task|subagent_[\w-]+)$/;class um{pendingAtomicDisengage=new Set;runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;distinctId;defaultLogger;defaultFetch;events=new QC;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;sideCallUnsubscribes=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;backgroundDelegations=new Map;sideTurnConfigs=new Map;sideTurns=new Map;leadNudgeUnsubscribes=new Map;roundUnsubscribes=new Map;eventBridge;sessionVersioning=new Dp;runCommandExecutionController=new Nh;constructor(e){let t=NDe();if(t)HDe(t);let n=$a(e.distinctId);if(this.distinctId=n,this.sessionService=e.sessionService,this.runtimeBuilder=e.runtimeBuilder??new YC,this.createAgentInstance=e.createAgent??((r)=>new Sa(r)),this.defaultCapabilities=kc(e.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=e.toolPolicies,this.providerSettingsManager=e.providerSettingsManager??new Vn,this.oauthTokenManager=e.oauthTokenManager??new Ap({providerSettingsManager:this.providerSettingsManager,telemetry:e.telemetry}),this.defaultTelemetry=e.telemetry,this.defaultLogger=e.logger,e.distinctId!==void 0)this.defaultTelemetry?.setDistinctId(n);this.defaultFetch=e.fetch,WDe(this.defaultLogger,this.defaultTelemetry),this.pendingPromptsController=new XC({getSession:(r)=>this.sessions.get(r),emit:(r)=>this.emit(r),send:(r)=>this.runTurn(r)}),this.pendingPrompts={steerFirst:async(r)=>this.pendingPromptsController.steerFirst(r.sessionId),list:async(r)=>this.pendingPromptsController.list(r.sessionId),update:async(r)=>this.pendingPromptsController.update(r),delete:async(r)=>this.pendingPromptsController.delete(r)},this.eventBridge=new Rv({getSession:(r)=>this.sessions.get(r),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(r)=>this.emit(r),persistMessages:(r,o,i)=>{this.invoke("persistSessionMessages",r,o,i).catch((s)=>{let a=this.sessions.get(r);(a?.config.logger??this.defaultLogger)?.error?.("Failed to persist session messages from agent event",{sessionId:r,error:s}),yr(a?.config.telemetry??this.defaultTelemetry,{component:"core",operation:"session.persist_messages_on_agent_event",error:s,severity:"warn",handled:!0,context:{sessionId:r,providerId:a?.config.providerId,modelId:a?.config.modelId}})})},enqueuePendingPrompt:(r,o)=>this.pendingPromptsController.enqueue(r,o),invokeBackendOptional:(r,...o)=>this.invokeOptional(r,...o)})}async applyInitialOAuthCredentials(e){if(e.config.apiKey?.trim())return e;let t=await this.oauthTokenManager.resolveProviderApiKey({providerId:e.config.providerId});if(!t?.apiKey)return e;return{...e,config:{...e.config,apiKey:t.apiKey}}}async startSession(e){let t=e.config.sessionId?.trim()??"",n=t||FDe(),r=t.length>0&&(e.initialMessages?.length??0)>0&&!e.prompt?.trim(),o=Boolean(e.config.cwd?.trim()||e.config.workspaceRoot?.trim()),i=r&&!o?await this.invokeOptionalValue("readSessionManifest",n):void 0,s=i?{...e.config,cwd:i.cwd,workspaceRoot:i.workspace_root}:await RW(e.config);return await this.startResolvedSession({...e,config:s},n,t.length>0,i)}async startResolvedSession(e,t,n,r){let o=e.source??Gt.CLI,i=ft(),s=await this.applyInitialOAuthCredentials(e),a=s.initialMessages??[];if(s.config.enableAgentTeams===!1&&TK(a))(s.localRuntime?.logger??this.defaultLogger)?.log(kK,{sessionId:t});let d=a.length>0?IR(a):Cn(),l=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!l)throw Error("session service method not available: ensureSessionsDir");let c=yi(l,t),u=yi(c,`${t}.messages.json`),h=yi(c,`${t}.json`);He(t).attachStore(yi(c,`${t}.rounds.json`));let p=hi(e.config),f=e.interactive===!0&&!s.prompt?.trim(),m=rs.parse({version:1,session_id:t,source:o,pid:process.pid,started_at:i,status:f?"idle":"running",interactive:e.interactive===!0,provider:s.config.providerId,model:s.config.modelId,cwd:s.config.cwd,workspace_root:p,team_name:s.config.teamName,enable_tools:s.config.enableTools,enable_spawn:s.config.enableSpawnAgent,enable_teams:s.config.enableAgentTeams,prompt:s.prompt?.trim()||void 0,messages_path:u}),g,y,w=n&&a.length>0&&!s.prompt?.trim();if(w){let P=r??await this.invokeOptionalValue("readSessionManifest",t);if(P)m=P,g={manifestPath:h,messagesPath:P.messages_path||u,compactionPath:P.compaction_path,manifest:P},y=await this.invokeOptionalValue("readSessionCompactionState",t)}let k=await this.seedAggregateUsageFromArtifacts({initialUsage:d,sessionDir:c,rootMessagesPath:g?.messagesPath??u,manifest:m});this.usageBySession.set(t,d),this.aggregateUsageBySession.set(t,k);let b=kc(this.defaultCapabilities,e.capabilities),v=b?.toolExecutors??this.toolExecutors,E=e.localRuntime,S=E?.extensionContext?.logger??E?.logger,x=E?.extensionContext?.automation,T=E?.extensionContext?.telemetry??E?.telemetry??this.defaultTelemetry,A,R={getSession:(P)=>this.sessions.get(P),subAgentStarts:this.subAgentStarts,onAgentEvent:(P,ye,nt)=>this.eventBridge.dispatchAgentEvent(P,ye,nt),invokeBackendOptional:(P,...ye)=>this.invokeOptional(P,...ye)},C,L=()=>{if(C)return C;let P=s.config.subagentCommandsEnabled===!0,ye=s.config.workspaceRoot??s.config.cwd??process.cwd(),nt=yi(c,"agent-overlays"),lt=Tv(s.config.sandboxBinariesDir),Wt={workspaceRoot:ye,...lt?{binaries:lt}:{},...s.config.subagentSandboxConfine===!1?{confine:!1}:{},overlayRootFor:(Dn)=>yi(nt,Dn.replace(/[^A-Za-z0-9_.-]/g,"_"))};return C=bK({provider:Wt,commandsEnabled:P,revisionLog:()=>this.sessions.get(t)?.revisionLog}),C},N=()=>({sandboxes:L()}),W=di(g?.manifest.metadata),D=di(Gn(s.sessionMetadata,{mode:s.mode??W?.mode,trigger:s.mode?void 0:W?.trigger})),K=n&&a.length>0?g?.manifest??r??await this.invokeOptionalValue("readSessionManifest",t):void 0,V=h4({stored:K?.metadata,hasHistory:a.length>0,configured:s.config.toolResultFormat});A=await A3({input:{...s,config:{...s.config,toolResultFormat:V}},localRuntime:e.localRuntime,sessionId:t,sessionOrigin:D,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultLogger:this.defaultLogger,defaultCapabilities:b,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(P)=>{if(P.name==="plugin_log"){this.eventBridge.handlePluginLog(t,P.payload,S);return}this.eventBridge.handlePluginEvent(t,P,x,T)},onTeamEvent:(P)=>{this.eventBridge.handleTeamEvent(t,P),A.config.onTeamEvent?.(P)},createSpawnTool:(P)=>oP({...R,...N()},A.config,t,v,P),createSwarmTool:()=>CV({...R,...N()},A.config,t,v),delegatedSandboxes:L,createSubAgentLifecycleCallbacks:(P)=>Cv({...R,...N()},P,t),readSessionMetadata:async()=>(await this.getSession(t))?.metadata,writeSessionMetadata:async(P)=>{await this.persistSessionMetadata(t,()=>P)}});let B=Gn(xI({...g?.manifest.metadata??{},...s.sessionMetadata??{},[VI]:V},A.gitState),{mode:D?.mode,trigger:D?.trigger,version:A.config.extensionContext?.client?.version});if(!g)m.metadata=B;let j=c6({root:A.config.workspaceRoot??A.config.cwd??process.cwd(),...A.config.atomicProtocol?.forgetReads?{forgetReads:A.config.atomicProtocol.forgetReads}:{}}),G=A.config.checkpoint?.enabled!==!1,z=j.port,M=A.config.compaction?{...A.config,compaction:{...A.config.compaction,...G?{revisions:z}:{},toolLedgerEnabled:!0}}:A.config,X=A.providerConfig,oe=Cf(M,{sideCallOf:t});this.sideCallUnsubscribes.get(t)?.(),this.sideCallUnsubscribes.set(t,DDe(t,(P)=>{this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"side_call_room",state:P.kind}})}));let H={enabled:M.compaction?.cappedThinkingEnabled,budgetTokens:M.compaction?.thinkingBudgetTokens??(M.providerConfig??X)?.thinkingBudgetTokens,budgetMessage:M.compaction?.cappedThinkingBudgetMessage,promptTemplate:M.compaction?.cappedThinkingPrompt,providerConfig:{...M.providerConfig??X,...M.toolResultFormat?{toolResultFormat:M.toolResultFormat}:{}},summarizer:M.compaction?.summarizer,logger:M.logger},J=gT(H),he={...H,sideCallOf:t},se=gT(he),re=await this.runtimeBuilder.build({...A.runtimeBuilderInput,distinctId:this.distinctId,runCommandExecutionController:this.runCommandExecutionController,createDelegatedPrepareTurn:(P)=>{let ye,nt=P?Cf({...M,providerId:P.providerId,modelId:P.modelId,providerConfig:P.providerConfig,sessionId:P.engineSessionId??M.sessionId}):oe;return yT(UT({compact:nt,getState:()=>ye,logger:M.logger,saveState:(lt)=>{ye=lt}}),H)},condenseDiscardedReasoning:J,onDelegatedLoopCut:(P)=>iP(yi(c,MV(P.agentId)),P)});if(re.teamRuntime&&!M.teamName?.trim()){let P=re.teamRuntime.getTeamName();M.teamName=P,A.config.teamName=P}let Ge=async()=>{let P=this.sessions.get(t);if(!P||!ou(P.config.providerId))return!1;try{return await this.syncOAuthCredentials(P,{forceRefresh:!0}),!0}catch{return!1}};re.delegatedAgentConfigProvider?.updateConnectionDefaults({onAuthError:Ge});let I=[...re.tools,...M.extraTools??[]],_=M.taskProgress,F=_?.enabled?new lg({..._.reminderInterval!==void 0?{reminderInterval:_.reminderInterval}:{},..._.onUpdate?{onUpdate:_.onUpdate}:{}}):void 0;F?.hydrate(t$(a));let ue=F&&!I.some((P)=>P.name===eo)?[...I,lS()]:I,ne=ue.some((P)=>P.name===Lr)?ue:[...ue,Oz({cwd:M.cwd,...M.checkFile?.lintCommand?{lintCommand:M.checkFile.lintCommand}:{}})],fe=ne.some((P)=>P.name===lR)?ne:[...ne,Zz({cwd:M.cwd,createLister:()=>Qz(M.workspaceRoot??M.cwd)})],Ce=M.editVerification,We=Ce?.mode??"nudge",Se={editTools:Ce?.editTools??[le.EDITOR,le.APPLY_PATCH],checkTools:Ce?.checkTools??[Lr],attempts:We==="require"?4:2,cwd:M.cwd??process.cwd(),fileExists:MDe},Le=We==="off"||Se.checkTools.length===0?void 0:new dR(Se),dt=Wz(fe,{cwd:M.cwd??process.cwd(),shellName:le.RUN_COMMANDS,checkerName:Lr,onChecked:(P)=>Le?.recordChecked(P)}),_e=F?dt.map((P)=>Mu(P,F)):dt,Ue=Le?_e.map((P)=>Gz(P,Le)):_e,xt=F?n$(F):void 0,Jt=Le?zz(Le,Se):void 0,Zn=re.completionPolicy?.completionGuard,Ze=[];if(Zn)Ze.push({kind:"team_obligation",guard:Zn,notice:"Delegated work for this run is still open — asking the model to collect it before it finishes."});if(Jt)Ze.push({kind:"edit_verification",guard:Jt,notice:"Edited files have not been checked since the last edit — asking the model to check them before it finishes."});if(xt)Ze.push({kind:"checklist_close_out",guard:xt,notice:"The checklist still has open items — asking the model to close them before it finishes."});let un=new Map,Gr=Ze.length>0?{...re.completionPolicy,completionGuard:()=>{for(let{kind:P,guard:ye,notice:nt}of Ze){let lt=ye();if(lt!==void 0){let Wt=(un.get(P)??0)+1;return un.set(P,Wt),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:nt,metadata:{kind:P,reason:P,phase:"nudge",attempt:Wt}}),lt}}return}}:re.completionPolicy,kr=re.completionPolicy?.afterToolsReminder,Tr=F?{...Gr,afterToolsReminder:()=>kr?.()??F.takePendingReminder()}:Gr,Y,Q,ee,be=0,ge=M6(),Ee=M.escalation?.alternateWithBase===!0?b6():void 0,vt=Ee&&M.escalation?.relayNothing!==!0?I6():void 0,Nt=vt?R6():void 0,kt=vt?A6({onVerdict:(P)=>vt.noteGuard(P.text)}):void 0,et=await l6({...Ee?{revisionOverlay:{source:{get pending(){return ge.source.pending},get transaction(){return ge.source.transaction},get revisions(){return ge.source.log}},wording:w4,live:()=>Ee.engaged}}:{},workspaceRoot:M.workspaceRoot??M.cwd??process.cwd(),config:M.atomicProtocol,revisions:j.log,logger:{log:(P)=>M.logger?.log?.(P)},describeLastTransaction:()=>ee?.(),onStatus:(P)=>{Y=P},onEvent:(P)=>{if(P.type==="opened")Q?.noteTransaction(P.transaction);if(P.type==="settled"&&!P.kept&&!P.carried)Q?.noteTransactionOutcome("discarded");if(P.type==="empty"){Q?.noteTransactionOutcome("empty"),M.logger?.debug?.(P.message),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"atomic_empty_attempt",transaction:P.transaction,continued:P.continued}});return}if(P.type==="plan"){if(P.from!=="reasoning")return;this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:`Plan for transaction ${P.transaction}:
1476
1476
 
1477
- ${P.plan}`,metadata:{kind:"atomic_plan",transaction:P.transaction,from:P.from}});return}if(P.type!=="settled")return;M.logger?.debug?.(P.message);let ye=P.restore;this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"atomic_transaction",transaction:P.transaction,kept:P.kept,...P.carried?{carried:!0}:{},source:P.source,...P.elapsedMs!==void 0?{elapsedMs:P.elapsedMs}:{},...P.verdict?.output?{output:P.verdict.output}:{},...ye?{filesPutBack:ye.restored.length+ye.recreated.length+ye.removed.length}:{}}})}}),Zc=[],Ve=M.escalation?.connection,me=x4({revisions:ge,...Ee?{standDown:Ee}:{},...vt?{notes:vt}:{},...kt?{guards:kt}:{},...Nt?{mailbox:Nt}:{},workspaceRoot:M.workspaceRoot??M.cwd??process.cwd(),config:M.escalation,logger:{log:(P)=>M.logger?.log?.(P)},openExpert:async({onEvent:P})=>{let ye=re.delegatedAgentConfigProvider?.getRuntimeConfig();if(!ye||!Ve)throw Error("No expert is configured for this session, so there is nothing to escalate to.");let nt={providerId:Ve.providerId,modelId:Ve.modelId,...Ve.apiKey!==void 0?{apiKey:Ve.apiKey}:{},...Ve.baseUrl!==void 0?{baseUrl:Ve.baseUrl}:{},...Ve.headers!==void 0?{headers:Ve.headers}:{},...Ve.knownModels!==void 0?{knownModels:Ve.knownModels}:{},...Ve.providerConfig!==void 0?{providerConfig:Ve.providerConfig}:{},...Ve.maxToolResultChars!==void 0?{maxToolResultChars:Ve.maxToolResultChars}:{}},lt=oi({...ye,...nt},Object.keys(nt)),Wt=M.escalation?.promptTemplate,Dn=[P4({workspaceRoot:M.workspaceRoot??M.cwd}),Wt?.system?.trim()].filter((Zt)=>Boolean(Zt)).join(`
1477
+ ${P.plan}`,metadata:{kind:"atomic_plan",transaction:P.transaction,from:P.from}});return}if(P.type!=="settled")return;M.logger?.debug?.(P.message);let ye=P.restore;this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"atomic_transaction",transaction:P.transaction,kept:P.kept,...P.carried?{carried:!0}:{},source:P.source,...P.elapsedMs!==void 0?{elapsedMs:P.elapsedMs}:{},...P.verdict?.output?{output:P.verdict.output}:{},...ye?{filesPutBack:ye.restored.length+ye.recreated.length+ye.removed.length}:{}}})}}),Zc=[],Ve=M.escalation?.connection,me=x6({revisions:ge,...Ee?{standDown:Ee}:{},...vt?{notes:vt}:{},...kt?{guards:kt}:{},...Nt?{mailbox:Nt}:{},workspaceRoot:M.workspaceRoot??M.cwd??process.cwd(),config:M.escalation,logger:{log:(P)=>M.logger?.log?.(P)},openExpert:async({onEvent:P})=>{let ye=re.delegatedAgentConfigProvider?.getRuntimeConfig();if(!ye||!Ve)throw Error("No expert is configured for this session, so there is nothing to escalate to.");let nt={providerId:Ve.providerId,modelId:Ve.modelId,...Ve.apiKey!==void 0?{apiKey:Ve.apiKey}:{},...Ve.baseUrl!==void 0?{baseUrl:Ve.baseUrl}:{},...Ve.headers!==void 0?{headers:Ve.headers}:{},...Ve.knownModels!==void 0?{knownModels:Ve.knownModels}:{},...Ve.providerConfig!==void 0?{providerConfig:Ve.providerConfig}:{},...Ve.maxToolResultChars!==void 0?{maxToolResultChars:Ve.maxToolResultChars}:{}},lt=oi({...ye,...nt},Object.keys(nt)),Wt=M.escalation?.promptTemplate,Dn=[P6({workspaceRoot:M.workspaceRoot??M.cwd}),Wt?.system?.trim()].filter((Zt)=>Boolean(Zt)).join(`
1478
1478
 
1479
- `),Wm=Wt?$De(Zc,Wt,{}).map((Zt)=>({...Zt,description:Zt.description??""})):Zc,ws=Rc(Wm,{source:ge.source,readFile:async(Zt)=>{try{return await LDe(Zt)}catch{return}}}),IJ=vt?C4(ws,{notes:vt,heads:()=>ge.heads(),relative:(Zt)=>{let pk=M.workspaceRoot??M.cwd??process.cwd(),J0=pk.endsWith("/")?pk:`${pk}/`;return Zt.startsWith(J0)?Zt.slice(J0.length):Zt}}):ws,CJ=ii({kind:"subagent",prompt:Dn,configProvider:lt,tools:IJ,onEvent:kt?(Zt)=>{kt.observe(Zt),P(Zt)}:P,toolPolicies:A.toolPolicies,requestToolApproval:A.requestToolApproval,hookErrorMode:M.hookErrorMode,...Nt?{consumePendingUserMessage:()=>Nt.take()}:{}});return O4(CJ,{start:(Zt)=>R.invokeBackendOptional("handleSubAgentStart",t,Zt),end:(Zt)=>R.invokeBackendOptional("handleSubAgentEnd",t,Zt)})},...(()=>{let P=Ve?re.delegatedAgentConfigProvider?.getRuntimeConfig().slotGates?.for(Nr({providerId:Ve.providerId,baseUrl:Ve.baseUrl})):void 0;return P?{gate:P}:{}})(),readTransaction:()=>{let P=et?.controller;if(!P||P.transaction===0)return;return{transaction:P.transaction,maxChanges:M.atomicProtocol?.maxChanges??Gp,maxTransactions:M.atomicProtocol?.maxTransactions??Vb,...P.oracle?{oracle:P.oracle}:{},history:P.outcomes}},assess:async(P)=>{let ye=et?.controller,nt=ye?.outcomes??[],lt=(await FV(P.files,M.workspaceRoot??M.cwd)).lines,Wt={...lt.length>0?{complexity:lt}:{},...be>0?{iteration:be}:{},...Q?{signals:Q.signalsAt(be)}:{},...ye&&ye.transaction>0?{transactions:{opened:ye.transaction,discarded:nt.filter((ws)=>!ws.kept&&!ws.carried).length,carried:nt.filter((ws)=>ws.carried).length}}:{},...Vr?.spent?{guardStoodDown:!0}:{}},Dn=M.escalation?.appraise;if(!Dn)return Yb(Wt);let Wm=await GDe(Dn({task:this.sessions.get(t)?.pendingPrompt??m.prompt,...P.goal?{goal:P.goal}:{},...P.reason?{reason:P.reason}:{},measured:Yb(Wt)??""}),KDe);return Yb({...Wt,...Wm?.length?{appraisal:Wm}:{}})},...M.escalation?.approve?{approve:M.escalation.approve}:{},readTask:()=>this.sessions.get(t)?.pendingPrompt??m.prompt,takeSteering:()=>this.pendingPromptsController.consumeSteer(t)?.prompt,...M.atomicProtocol?.forgetReads?{forgetReads:M.atomicProtocol.forgetReads}:{},onEvent:(P)=>{if(P.type==="escalation_started"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:`Escalation ${P.index} of ${P.of}: the task has been handed to the expert.
1479
+ `),Wm=Wt?$De(Zc,Wt,{}).map((Zt)=>({...Zt,description:Zt.description??""})):Zc,ws=Rc(Wm,{source:ge.source,readFile:async(Zt)=>{try{return await LDe(Zt)}catch{return}}}),IJ=vt?C6(ws,{notes:vt,heads:()=>ge.heads(),relative:(Zt)=>{let pk=M.workspaceRoot??M.cwd??process.cwd(),J0=pk.endsWith("/")?pk:`${pk}/`;return Zt.startsWith(J0)?Zt.slice(J0.length):Zt}}):ws,CJ=ii({kind:"subagent",prompt:Dn,configProvider:lt,tools:IJ,onEvent:kt?(Zt)=>{kt.observe(Zt),P(Zt)}:P,toolPolicies:A.toolPolicies,requestToolApproval:A.requestToolApproval,hookErrorMode:M.hookErrorMode,...Nt?{consumePendingUserMessage:()=>Nt.take()}:{}});return O6(CJ,{start:(Zt)=>R.invokeBackendOptional("handleSubAgentStart",t,Zt),end:(Zt)=>R.invokeBackendOptional("handleSubAgentEnd",t,Zt)})},...(()=>{let P=Ve?re.delegatedAgentConfigProvider?.getRuntimeConfig().slotGates?.for(Nr({providerId:Ve.providerId,baseUrl:Ve.baseUrl})):void 0;return P?{gate:P}:{}})(),readTransaction:()=>{let P=et?.controller;if(!P||P.transaction===0)return;return{transaction:P.transaction,maxChanges:M.atomicProtocol?.maxChanges??Gp,maxTransactions:M.atomicProtocol?.maxTransactions??Vb,...P.oracle?{oracle:P.oracle}:{},history:P.outcomes}},assess:async(P)=>{let ye=et?.controller,nt=ye?.outcomes??[],lt=(await FV(P.files,M.workspaceRoot??M.cwd)).lines,Wt={...lt.length>0?{complexity:lt}:{},...be>0?{iteration:be}:{},...Q?{signals:Q.signalsAt(be)}:{},...ye&&ye.transaction>0?{transactions:{opened:ye.transaction,discarded:nt.filter((ws)=>!ws.kept&&!ws.carried).length,carried:nt.filter((ws)=>ws.carried).length}}:{},...Vr?.spent?{guardStoodDown:!0}:{}},Dn=M.escalation?.appraise;if(!Dn)return Yb(Wt);let Wm=await GDe(Dn({task:this.sessions.get(t)?.pendingPrompt??m.prompt,...P.goal?{goal:P.goal}:{},...P.reason?{reason:P.reason}:{},measured:Yb(Wt)??""}),KDe);return Yb({...Wt,...Wm?.length?{appraisal:Wm}:{}})},...M.escalation?.approve?{approve:M.escalation.approve}:{},readTask:()=>this.sessions.get(t)?.pendingPrompt??m.prompt,takeSteering:()=>this.pendingPromptsController.consumeSteer(t)?.prompt,...M.atomicProtocol?.forgetReads?{forgetReads:M.atomicProtocol.forgetReads}:{},onEvent:(P)=>{if(P.type==="escalation_started"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:`Escalation ${P.index} of ${P.of}: the task has been handed to the expert.
1480
1480
 
1481
- ${P.brief}`,metadata:{kind:"escalation_started",index:P.index,of:P.of,brief:P.brief}});return}if(P.type==="expert_said"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.text,metadata:{kind:P.kind==="thinking"?"expert_thinking":"expert_message",index:P.index,of:P.of}});return}if(P.type==="expert_progress"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:`The expert is working: ${P.toolCalls} tool call${P.toolCalls===1?"":"s"} so far.`,metadata:{kind:"expert_progress",index:P.index,of:P.of,toolCalls:P.toolCalls,...P.lastTool?{lastTool:P.lastTool}:{},usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}});return}if(P.type==="expert_asked"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"escalation_message"}});return}if(P.type==="escalation_failed"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.limitReached?`The expert stopped: its account reached its usage limit. ${P.reason}`:`The expert's run failed: ${P.reason}`,metadata:{kind:"escalation_failed",index:P.index,of:P.of,reason:P.reason,changed:P.changed,limitReached:P.limitReached,...P.usage?{usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}:{}}});return}if(P.type==="expert_replied"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.reply,metadata:{kind:"expert_reply",changed:P.changed,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}});return}this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.held?"The expert conversation is on hold. It keeps its context, so a second escalation costs a message rather than the whole exchange again.":"The expert conversation is closed and its slot released.",metadata:{kind:"escalation_ended",held:P.held,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}})}}),wi=et?et.decorateTools([...Ue,...et.tools]):G?j.decorate([...Ue,...j.tools]):Ue.some((P)=>YDe.test(P.name))?j.decorateReads([...Ue,...j.tools]):Ue;Zc=Ue.filter((P)=>!Ew.has(P.name));let Vr=me.tools.length>0?L4({remaining:()=>me.remaining,stop:(P)=>{M.logger?.log?.(`[Escalation] ${P}`),this.sessions.get(t)?.agent.abort(Error(P))},logger:{log:(P)=>M.logger?.log?.(P)}}):void 0;ee=()=>{let P=me.remaining;return P>0?dA({diagnosis:"This is the last transaction this task gets. Whatever it ends as is what the run ends as.",remaining:P}):void 0};let gs=Cw(),ae=M.enableSpawnAgent!==!1&&ns({maxConcurrentAgents:M.maxConcurrentAgents,nodes:cs(M)}),Fe=me.tools.length>0||ae;Q=Fe?new Yi(M.escalation?.struggleThresholds):void 0;let Te=Q?wa(Q,(P)=>{let ye=me.remaining;if(!P.message)return;if(P.kind==="nudge"){FV(P.files,M.workspaceRoot??M.cwd).then(({lines:lt,high:Wt,broken:Dn})=>{gs.hold(oj({diagnosis:P.message,complexity:lt,high:Wt,broken:Dn,...P.reason?{reason:P.reason}:{},canDelegate:ae,remaining:ye})),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:"the run has the shape of a stuck one",metadata:{kind:"struggle",phase:"nudge",...P.reason?{reason:P.reason}:{},remaining:ye,high:Wt,broken:Dn}})});return}if(ye<=0)return;let nt=dA({diagnosis:P.message,remaining:ye});M.logger?.debug?.(`[Escalation] ${P.message}`),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:"the run has the shape of a stuck one — the expert was offered",metadata:{kind:"struggle",phase:"offer",...P.reason?{reason:P.reason}:{},remaining:ye}}),gs.hold(nt)}):void 0,gt=Fe?Pw(me.tools.length>0?[...wi,...me.tools]:wi,gs):wi,Qt=Ee?v4(gt,Ee):gt,ys=et?{...Tr,onCompletionAttempt:(P)=>et.onCompletionAttempt(P),describeUnstartedWork:()=>et.describeUnstartedWork()}:Tr,dk=re.extensions??A.extensions,lk=s.initialCompactionState,ck,uk=lk??y,Y0=w?M3(m.metadata):void 0,_J=Y0?jN({config:M,importedFrom:Y0.tool,next:oe}):oe,EJ=uk?{...uk,conversation_id:uk.conversation_id?.trim()||t}:void 0,X0=0,AJ=yT(UT({compact:_J,getState:()=>ck?.compactionState,logger:M.logger,saveState:async(P,ye)=>{let nt=ck;if(!nt)return;let lt={...P,conversation_id:nt.sessionId},Wt=VDe(lt);if(Wt>X0)X0=Wt,Q?.noteCompaction();try{if(!(await this.persistActiveSessionCompactionState(nt,lt,ye)).updated)M.logger?.debug?.("Skipped stale session compaction state",{sessionId:nt.sessionId,sourceMessageCount:lt.source_message_count})}catch(Dn){M.logger?.error?.("Failed to persist session compaction state",{sessionId:nt.sessionId,error:Dn}),yr(M.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:Dn,context:{sessionId:nt.sessionId,providerId:M.providerId,modelId:M.modelId}})}}}),he),rd={distinctId:this.distinctId,sessionId:t,providerId:X.providerId,modelId:X.modelId,apiKey:X.apiKey,baseUrl:X.baseUrl,headers:X.headers,onAuthError:Ge,knownModels:X.knownModels,providerConfig:X,thinking:M.thinking,reasoningEffort:M.reasoningEffort??X.reasoningEffort,thinkingBudgetTokens:M.thinkingBudgetTokens,maxTokensPerTurn:M.maxTokensPerTurn,maxToolResultChars:M.maxToolResultChars,toolResultFormat:M.toolResultFormat,staleReadRewrites:M.staleReadRewrites,temperature:M.temperature,systemPrompt:M.systemPrompt,maxIterations:M.maxIterations,execution:M.execution,prepareTurn:AJ,condenseDiscardedReasoning:se,recoverTurnFault:ur({label:"lead",baseUrl:()=>X.baseUrl,headers:()=>X.headers,...M.logger?{logger:M.logger}:{}}),recoverTurnFaultKinds:["refusal"],tools:Qt,modelTools:re.modelTools,hooks:A.hooks,extensions:dk,hookErrorMode:M.hookErrorMode,initialMessages:A.effectiveInput.initialMessages,userFileContentLoader:PV,toolPolicies:A.toolPolicies,...re.unavailableToolReasons?{unavailableToolReasons:re.unavailableToolReasons}:{},requestToolApproval:A.requestToolApproval?async(P)=>{let ye=A.requestToolApproval,nt=this.sessions.get(t);if(nt)await this.markTurnPending(nt);try{if(!ye)return{approved:!1,reason:"Tool approval callback is not configured."};return await ye(P)}finally{let lt=this.sessions.get(t);if(lt?.status==="pending")await this.markTurnRunning(lt)}}:void 0,telemetry:M.telemetry,onConsecutiveMistakeLimitReached:Vr?async(P)=>Vr.decide({guard:P.forced?"The repeated-call loop guard":"The consecutive-mistake limit",...P.details?{diagnosis:P.details}:{}})??await M.onConsecutiveMistakeLimitReached?.(P)??{action:"stop"}:M.onConsecutiveMistakeLimitReached,onLoopCut:(P)=>iP(yi(c,`${t}.cuts.jsonl`),P),onReasoningLoopLimitReached:Vr?async(P)=>Vr.decide({guard:"The reasoning-loop guard",diagnosis:P.diagnosis})??await M.onReasoningLoopLimitReached?.(P)??{action:"stop"}:M.onReasoningLoopLimitReached,completionPolicy:ys,consumePendingUserMessage:async()=>{if(this.pendingAtomicDisengage.delete(t)){let ye=await this.sessions.get(t)?.atomicProtocol?.disengage();if(ye)return _c(ye,M.mode)}let P=this.pendingPromptsController.consumeSteer(t);return P?_c(P.prompt,P.mode??M.mode):void 0},describeImages:M.describeImages,alwaysDescribeImages:M.alwaysDescribeImages,logger:re.logger??M.logger,extensionContext:M.extensionContext,onEvent:(P)=>{if(P.type==="iteration_start")be=P.iteration;Te?.observe(P),Vr?.observe(P),this.eventBridge.dispatchAgentEvent(t,M,P)}};rd.hooks={...rd.hooks,onEvent:async(P)=>{if(await A.hooks?.onEvent?.(P),P.type!=="assistant-message")return;let ye=this.sessions.get(t);if(!ye)return;let nt=ye.agent.getMessages();try{await this.invoke("persistSessionMessages",t,nt,M.systemPrompt)}catch(lt){M.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:t,error:lt}),yr(M.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:lt,severity:"warn",handled:!0,context:{sessionId:t,providerId:M.providerId,modelId:M.modelId}})}}};let od=this.createAgentInstance(rd);if(rd.onEvent)od.subscribeEvents(rd.onEvent);this.sideTurnConfigs.set(t,rd),He(t).messageWaiting=()=>this.sessions.get(t)?.pendingPrompts.some((P)=>P.delivery==="steer"&&P.noteKind!=="queued")===!0,this.leadNudgeUnsubscribes.get(t)?.(),this.leadNudgeUnsubscribes.set(t,o2(t,(P,ye)=>this.nudgeLead(t,P,ye))),this.roundUnsubscribes.get(t)?.();let RJ=He(t);this.roundUnsubscribes.set(t,RJ.onSettled((P)=>this.deliverRound(t,P))),re.registerLeadAgent?.(od);let hk=ui({agentId:od.getAgentId(),conversationId:od.getConversationId(),teamId:re.teamRuntime?.getTeamId(),teamName:re.teamRuntime?.getTeamName(),teamRole:re.teamRuntime?"lead":void 0});if(O3(M,t,n,p,hk),hk)ld(M.telemetry,{ulid:t,modelId:M.modelId,provider:M.providerId,...hk});if(re.teamRuntime)RM(M.telemetry,{ulid:t,teamId:re.teamRuntime.getTeamId(),teamName:re.teamRuntime.getTeamName(),leadAgentId:od.getAgentId(),restoredFromPersistence:re.teamRestoredFromPersistence===!0});let je={sessionId:t,config:M,sessionMetadata:B,...g?{artifacts:g}:{},source:o,startedAt:g?.manifest.started_at??i,updatedAt:g?.manifest.ended_at??g?.manifest.started_at??i,pendingPrompt:m.prompt,runtime:re,revisionLog:j.log,agent:od,started:!1,status:g?.manifest.status??(f?"idle":"running"),aborting:!1,interactive:e.interactive===!0,persistedMessages:a,compactionState:EJ,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,...et?{atomicProtocol:et}:{},...me.tools.length>0?{escalation:me}:{},...Y?{pendingAtomicStatus:Y}:{},pluginSandboxShutdown:A.pluginSandboxShutdown,delegatedSandboxesShutdown:async()=>{await C?.closeAll()},submitAndExitObserved:!1,taskCompletedEmitted:!1,lastInteractiveTurnFinishReason:void 0};if(ck=je,je.compactionState&&!this.isCompactionStateForSession(je.sessionId,je.compactionState,je))je.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:je.sessionId,conversationId:je.compactionState.conversation_id}),je.compactionState=void 0;this.sessions.set(t,je);for(let P of He(t).list())if(P.status==="done"&&!P.delivered)this.deliverRound(t,{record:P,report:He(t).reportFor(P.id)});if(g)await this.refreshActiveSessionGitMetadata(je,A.gitState);if(a.length>0&&!g)try{await this.ensureSessionPersisted(je),await this.invoke("persistSessionMessages",t,a,je.config.systemPrompt)}catch(P){je.config.logger?.error?.("Failed to persist seeded session messages at start",{sessionId:t,error:P}),yr(je.config.telemetry,{component:"core",operation:"session.persist_seeded_messages",error:P,severity:"warn",handled:!0,context:{sessionId:t,providerId:je.config.providerId,modelId:je.config.modelId}})}this.emitStatus(t,je.status);let eu;try{if(s.prompt?.trim())if(eu=await this.executeTurn(je,{prompt:s.prompt,userImages:s.userImages,userFiles:s.userFiles}),!je.interactive)await this.finalizeSingleRun(je,eu.finishReason);else await this.completeInteractiveTurn(je,eu.finishReason)}catch(P){if(je.interactive&&je.aborting)eu=await this.completeAbortedInteractiveTurn(je);else{yr(je.config.telemetry,{component:"core",operation:"session.start",error:P,severity:"error",handled:!1,context:{sessionId:je.sessionId,providerId:je.config.providerId,modelId:je.config.modelId}});try{await this.failSession(je)}catch(ye){je.config.logger?.error?.("Session failure cleanup threw",{sessionId:je.sessionId,error:ye})}throw P}}return{sessionId:t,manifest:m,manifestPath:h,messagesPath:u,result:eu,resolvedConfig:A.resolvedConfig}}async restoreSession(e){return this.sessionVersioning.restoreCheckpoint({...e,telemetry:this.defaultTelemetry,getSession:(t)=>this.getSession(t),readMessages:(t)=>this.readSessionMessages(t),buildStartInput:(t,n)=>{let r=t.restoredCheckpointMetadata?{...n.sessionMetadata??{},checkpoint:t.restoredCheckpointMetadata}:n.sessionMetadata;return{...n,...r?{sessionMetadata:r}:{},initialMessages:t.initialMessages}},startSession:(t)=>this.startSession(t),getStartedSessionId:(t)=>t.sessionId,cleanupStartedSession:async(t)=>{if(!await this.deleteSession(t.sessionId))throw Error(`Failed to clean up restored session ${t.sessionId}`)},readRestoredSession:(t)=>this.getSession(t)})}answerSteerInSideTurn(e,t,n="user"){let r=e.sessionId,o=this.sideTurnConfigs.get(r);if(!o)return;let s=(this.sideTurns.get(r)??Promise.resolve()).then(async()=>{e.config.logger?.log?.(`[Agents] steer while ${pt.runningIn(r).length} agent(s) run: answering in a side turn`);let d=await LV({sessionId:r,message:t,source:n,messages:e.agent.getMessages(),leadTools:(o.tools??[]).filter((l)=>dP.has(l.name)),createRunner:(l)=>{let c=this.createAgentInstance({...o,tools:l,modelTools:void 0,prepareTurn:void 0,hooks:void 0,extensions:void 0,onEvent:void 0,initialMessages:void 0,consumePendingUserMessage:void 0,requestToolApproval:void 0,toolPolicies:void 0,maxIterations:Bc});return{restore:(u)=>c.restore(u),continue:async(u)=>{let h=await c.continue(u);return{text:h.text,finishReason:h.finishReason}}}}});this.eventBridge.dispatchAgentEvent(r,e.config,{type:"notice",noticeType:"status",displayRole:"status",message:[...n==="system"?[`Agents stuck for a long time:
1481
+ ${P.brief}`,metadata:{kind:"escalation_started",index:P.index,of:P.of,brief:P.brief}});return}if(P.type==="expert_said"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.text,metadata:{kind:P.kind==="thinking"?"expert_thinking":"expert_message",index:P.index,of:P.of}});return}if(P.type==="expert_progress"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:`The expert is working: ${P.toolCalls} tool call${P.toolCalls===1?"":"s"} so far.`,metadata:{kind:"expert_progress",index:P.index,of:P.of,toolCalls:P.toolCalls,...P.lastTool?{lastTool:P.lastTool}:{},usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}});return}if(P.type==="expert_asked"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.message,metadata:{kind:"escalation_message"}});return}if(P.type==="escalation_failed"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.limitReached?`The expert stopped: its account reached its usage limit. ${P.reason}`:`The expert's run failed: ${P.reason}`,metadata:{kind:"escalation_failed",index:P.index,of:P.of,reason:P.reason,changed:P.changed,limitReached:P.limitReached,...P.usage?{usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}:{}}});return}if(P.type==="expert_replied"){this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.reply,metadata:{kind:"expert_reply",changed:P.changed,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}});return}this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:P.held?"The expert conversation is on hold. It keeps its context, so a second escalation costs a message rather than the whole exchange again.":"The expert conversation is closed and its slot released.",metadata:{kind:"escalation_ended",held:P.held,usage:{inputTokens:P.usage.inputTokens,outputTokens:P.usage.outputTokens,generateTokens:P.usage.generateTokens,generateMs:P.usage.generateMs,wallMs:P.usage.wallMs,requests:P.usage.requests}}})}}),wi=et?et.decorateTools([...Ue,...et.tools]):G?j.decorate([...Ue,...j.tools]):Ue.some((P)=>YDe.test(P.name))?j.decorateReads([...Ue,...j.tools]):Ue;Zc=Ue.filter((P)=>!Ew.has(P.name));let Vr=me.tools.length>0?L6({remaining:()=>me.remaining,stop:(P)=>{M.logger?.log?.(`[Escalation] ${P}`),this.sessions.get(t)?.agent.abort(Error(P))},logger:{log:(P)=>M.logger?.log?.(P)}}):void 0;ee=()=>{let P=me.remaining;return P>0?dA({diagnosis:"This is the last transaction this task gets. Whatever it ends as is what the run ends as.",remaining:P}):void 0};let gs=Cw(),ae=M.enableSpawnAgent!==!1&&ns({maxConcurrentAgents:M.maxConcurrentAgents,nodes:cs(M)}),Fe=me.tools.length>0||ae;Q=Fe?new Yi(M.escalation?.struggleThresholds):void 0;let Te=Q?wa(Q,(P)=>{let ye=me.remaining;if(!P.message)return;if(P.kind==="nudge"){FV(P.files,M.workspaceRoot??M.cwd).then(({lines:lt,high:Wt,broken:Dn})=>{gs.hold(oj({diagnosis:P.message,complexity:lt,high:Wt,broken:Dn,...P.reason?{reason:P.reason}:{},canDelegate:ae,remaining:ye})),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:"the run has the shape of a stuck one",metadata:{kind:"struggle",phase:"nudge",...P.reason?{reason:P.reason}:{},remaining:ye,high:Wt,broken:Dn}})});return}if(ye<=0)return;let nt=dA({diagnosis:P.message,remaining:ye});M.logger?.debug?.(`[Escalation] ${P.message}`),this.eventBridge.dispatchAgentEvent(t,M,{type:"notice",noticeType:"status",displayRole:"status",message:"the run has the shape of a stuck one — the expert was offered",metadata:{kind:"struggle",phase:"offer",...P.reason?{reason:P.reason}:{},remaining:ye}}),gs.hold(nt)}):void 0,gt=Fe?Pw(me.tools.length>0?[...wi,...me.tools]:wi,gs):wi,Qt=Ee?v6(gt,Ee):gt,ys=et?{...Tr,onCompletionAttempt:(P)=>et.onCompletionAttempt(P),describeUnstartedWork:()=>et.describeUnstartedWork()}:Tr,dk=re.extensions??A.extensions,lk=s.initialCompactionState,ck,uk=lk??y,Y0=w?M3(m.metadata):void 0,_J=Y0?jN({config:M,importedFrom:Y0.tool,next:oe}):oe,EJ=uk?{...uk,conversation_id:uk.conversation_id?.trim()||t}:void 0,X0=0,AJ=yT(UT({compact:_J,getState:()=>ck?.compactionState,logger:M.logger,saveState:async(P,ye)=>{let nt=ck;if(!nt)return;let lt={...P,conversation_id:nt.sessionId},Wt=VDe(lt);if(Wt>X0)X0=Wt,Q?.noteCompaction();try{if(!(await this.persistActiveSessionCompactionState(nt,lt,ye)).updated)M.logger?.debug?.("Skipped stale session compaction state",{sessionId:nt.sessionId,sourceMessageCount:lt.source_message_count})}catch(Dn){M.logger?.error?.("Failed to persist session compaction state",{sessionId:nt.sessionId,error:Dn}),yr(M.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:Dn,context:{sessionId:nt.sessionId,providerId:M.providerId,modelId:M.modelId}})}}}),he),rd={distinctId:this.distinctId,sessionId:t,providerId:X.providerId,modelId:X.modelId,apiKey:X.apiKey,baseUrl:X.baseUrl,headers:X.headers,onAuthError:Ge,knownModels:X.knownModels,providerConfig:X,thinking:M.thinking,reasoningEffort:M.reasoningEffort??X.reasoningEffort,thinkingBudgetTokens:M.thinkingBudgetTokens,maxTokensPerTurn:M.maxTokensPerTurn,maxToolResultChars:M.maxToolResultChars,toolResultFormat:M.toolResultFormat,staleReadRewrites:M.staleReadRewrites,temperature:M.temperature,systemPrompt:M.systemPrompt,maxIterations:M.maxIterations,execution:M.execution,prepareTurn:AJ,condenseDiscardedReasoning:se,recoverTurnFault:ur({label:"lead",baseUrl:()=>X.baseUrl,headers:()=>X.headers,...M.logger?{logger:M.logger}:{}}),recoverTurnFaultKinds:["refusal"],tools:Qt,modelTools:re.modelTools,hooks:A.hooks,extensions:dk,hookErrorMode:M.hookErrorMode,initialMessages:A.effectiveInput.initialMessages,userFileContentLoader:PV,toolPolicies:A.toolPolicies,...re.unavailableToolReasons?{unavailableToolReasons:re.unavailableToolReasons}:{},requestToolApproval:A.requestToolApproval?async(P)=>{let ye=A.requestToolApproval,nt=this.sessions.get(t);if(nt)await this.markTurnPending(nt);try{if(!ye)return{approved:!1,reason:"Tool approval callback is not configured."};return await ye(P)}finally{let lt=this.sessions.get(t);if(lt?.status==="pending")await this.markTurnRunning(lt)}}:void 0,telemetry:M.telemetry,onConsecutiveMistakeLimitReached:Vr?async(P)=>Vr.decide({guard:P.forced?"The repeated-call loop guard":"The consecutive-mistake limit",...P.details?{diagnosis:P.details}:{}})??await M.onConsecutiveMistakeLimitReached?.(P)??{action:"stop"}:M.onConsecutiveMistakeLimitReached,onLoopCut:(P)=>iP(yi(c,`${t}.cuts.jsonl`),P),onReasoningLoopLimitReached:Vr?async(P)=>Vr.decide({guard:"The reasoning-loop guard",diagnosis:P.diagnosis})??await M.onReasoningLoopLimitReached?.(P)??{action:"stop"}:M.onReasoningLoopLimitReached,completionPolicy:ys,consumePendingUserMessage:async()=>{if(this.pendingAtomicDisengage.delete(t)){let ye=await this.sessions.get(t)?.atomicProtocol?.disengage();if(ye)return _c(ye,M.mode)}let P=this.pendingPromptsController.consumeSteer(t);return P?_c(P.prompt,P.mode??M.mode):void 0},describeImages:M.describeImages,alwaysDescribeImages:M.alwaysDescribeImages,logger:re.logger??M.logger,extensionContext:M.extensionContext,onEvent:(P)=>{if(P.type==="iteration_start")be=P.iteration;Te?.observe(P),Vr?.observe(P),this.eventBridge.dispatchAgentEvent(t,M,P)}};rd.hooks={...rd.hooks,onEvent:async(P)=>{if(await A.hooks?.onEvent?.(P),P.type!=="assistant-message")return;let ye=this.sessions.get(t);if(!ye)return;let nt=ye.agent.getMessages();try{await this.invoke("persistSessionMessages",t,nt,M.systemPrompt)}catch(lt){M.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:t,error:lt}),yr(M.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:lt,severity:"warn",handled:!0,context:{sessionId:t,providerId:M.providerId,modelId:M.modelId}})}}};let od=this.createAgentInstance(rd);if(rd.onEvent)od.subscribeEvents(rd.onEvent);this.sideTurnConfigs.set(t,rd),He(t).messageWaiting=()=>this.sessions.get(t)?.pendingPrompts.some((P)=>P.delivery==="steer"&&P.noteKind!=="queued")===!0,this.leadNudgeUnsubscribes.get(t)?.(),this.leadNudgeUnsubscribes.set(t,o2(t,(P,ye)=>this.nudgeLead(t,P,ye))),this.roundUnsubscribes.get(t)?.();let RJ=He(t);this.roundUnsubscribes.set(t,RJ.onSettled((P)=>this.deliverRound(t,P))),re.registerLeadAgent?.(od);let hk=ui({agentId:od.getAgentId(),conversationId:od.getConversationId(),teamId:re.teamRuntime?.getTeamId(),teamName:re.teamRuntime?.getTeamName(),teamRole:re.teamRuntime?"lead":void 0});if(O3(M,t,n,p,hk),hk)ld(M.telemetry,{ulid:t,modelId:M.modelId,provider:M.providerId,...hk});if(re.teamRuntime)RM(M.telemetry,{ulid:t,teamId:re.teamRuntime.getTeamId(),teamName:re.teamRuntime.getTeamName(),leadAgentId:od.getAgentId(),restoredFromPersistence:re.teamRestoredFromPersistence===!0});let je={sessionId:t,config:M,sessionMetadata:B,...g?{artifacts:g}:{},source:o,startedAt:g?.manifest.started_at??i,updatedAt:g?.manifest.ended_at??g?.manifest.started_at??i,pendingPrompt:m.prompt,runtime:re,revisionLog:j.log,agent:od,started:!1,status:g?.manifest.status??(f?"idle":"running"),aborting:!1,interactive:e.interactive===!0,persistedMessages:a,compactionState:EJ,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,...et?{atomicProtocol:et}:{},...me.tools.length>0?{escalation:me}:{},...Y?{pendingAtomicStatus:Y}:{},pluginSandboxShutdown:A.pluginSandboxShutdown,delegatedSandboxesShutdown:async()=>{await C?.closeAll()},submitAndExitObserved:!1,taskCompletedEmitted:!1,lastInteractiveTurnFinishReason:void 0};if(ck=je,je.compactionState&&!this.isCompactionStateForSession(je.sessionId,je.compactionState,je))je.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:je.sessionId,conversationId:je.compactionState.conversation_id}),je.compactionState=void 0;this.sessions.set(t,je);for(let P of He(t).list())if(P.status==="done"&&!P.delivered)this.deliverRound(t,{record:P,report:He(t).reportFor(P.id)});if(g)await this.refreshActiveSessionGitMetadata(je,A.gitState);if(a.length>0&&!g)try{await this.ensureSessionPersisted(je),await this.invoke("persistSessionMessages",t,a,je.config.systemPrompt)}catch(P){je.config.logger?.error?.("Failed to persist seeded session messages at start",{sessionId:t,error:P}),yr(je.config.telemetry,{component:"core",operation:"session.persist_seeded_messages",error:P,severity:"warn",handled:!0,context:{sessionId:t,providerId:je.config.providerId,modelId:je.config.modelId}})}this.emitStatus(t,je.status);let eu;try{if(s.prompt?.trim())if(eu=await this.executeTurn(je,{prompt:s.prompt,userImages:s.userImages,userFiles:s.userFiles}),!je.interactive)await this.finalizeSingleRun(je,eu.finishReason);else await this.completeInteractiveTurn(je,eu.finishReason)}catch(P){if(je.interactive&&je.aborting)eu=await this.completeAbortedInteractiveTurn(je);else{yr(je.config.telemetry,{component:"core",operation:"session.start",error:P,severity:"error",handled:!1,context:{sessionId:je.sessionId,providerId:je.config.providerId,modelId:je.config.modelId}});try{await this.failSession(je)}catch(ye){je.config.logger?.error?.("Session failure cleanup threw",{sessionId:je.sessionId,error:ye})}throw P}}return{sessionId:t,manifest:m,manifestPath:h,messagesPath:u,result:eu,resolvedConfig:A.resolvedConfig}}async restoreSession(e){return this.sessionVersioning.restoreCheckpoint({...e,telemetry:this.defaultTelemetry,getSession:(t)=>this.getSession(t),readMessages:(t)=>this.readSessionMessages(t),buildStartInput:(t,n)=>{let r=t.restoredCheckpointMetadata?{...n.sessionMetadata??{},checkpoint:t.restoredCheckpointMetadata}:n.sessionMetadata;return{...n,...r?{sessionMetadata:r}:{},initialMessages:t.initialMessages}},startSession:(t)=>this.startSession(t),getStartedSessionId:(t)=>t.sessionId,cleanupStartedSession:async(t)=>{if(!await this.deleteSession(t.sessionId))throw Error(`Failed to clean up restored session ${t.sessionId}`)},readRestoredSession:(t)=>this.getSession(t)})}answerSteerInSideTurn(e,t,n="user"){let r=e.sessionId,o=this.sideTurnConfigs.get(r);if(!o)return;let s=(this.sideTurns.get(r)??Promise.resolve()).then(async()=>{e.config.logger?.log?.(`[Agents] steer while ${pt.runningIn(r).length} agent(s) run: answering in a side turn`);let d=await LV({sessionId:r,message:t,source:n,messages:e.agent.getMessages(),leadTools:(o.tools??[]).filter((l)=>dP.has(l.name)),createRunner:(l)=>{let c=this.createAgentInstance({...o,tools:l,modelTools:void 0,prepareTurn:void 0,hooks:void 0,extensions:void 0,onEvent:void 0,initialMessages:void 0,consumePendingUserMessage:void 0,requestToolApproval:void 0,toolPolicies:void 0,maxIterations:Bc});return{restore:(u)=>c.restore(u),continue:async(u)=>{let h=await c.continue(u);return{text:h.text,finishReason:h.finishReason}}}}});this.eventBridge.dispatchAgentEvent(r,e.config,{type:"notice",noticeType:"status",displayRole:"status",message:[...n==="system"?[`Agents stuck for a long time:
1482
1482
  ${t}`]:[],`While the agents run: ${d.reply||"(no reply)"}`,...d.actions].join(`
1483
1483
 
1484
1484
  `),metadata:{kind:n==="system"?"lead_nudge_reply":"steer_reply",actions:d.actions}}),this.pendingPromptsController.enqueue(r,{prompt:NV(t,d,n),delivery:"steer",origin:"harness",noteKind:"recap"})});this.sideTurns.set(r,s.catch(()=>{return}))}nudgeLead(e,t,n){let r=this.sessions.get(e);if(!r)return;let o={prompt:t,delivery:"steer",origin:"harness",noteKind:n?.noteKind??"status",...n?.refresh?{refresh:n.refresh}:{}};if(He(e).leadAwaiting){if(this.pendingPromptsController.enqueue(e,o),!n?.quiet)He(e).wakeAwaits();return}if(!n?.quiet&&!r.agent.canStartRun()&&this.sideTurnConfigs.has(e)&&He(e).leadBlocked&&pt.runningIn(e).length>0){this.answerSteerInSideTurn(r,t,"system");return}this.pendingPromptsController.enqueue(e,o)}async runTurn(e){let t=this.getSessionOrThrow(e.sessionId),n=t.agent.canStartRun(),r=e.delivery??(t.interactive&&!n?"queue":void 0);if(t.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:e.sessionId,promptLength:e.prompt.length,userImageCount:e.userImages?.length??0,userFileCount:e.userFiles?.length??0,delivery:r??"immediate"}}),(r==="queue"||r==="steer")&&e.prompt.trim()===""&&!e.userImages?.length&&!e.userFiles?.length)return;if(r==="steer"&&!n&&He(e.sessionId).leadAwaiting){this.pendingPromptsController.enqueue(e.sessionId,{prompt:e.prompt,mode:e.mode,delivery:r,userImages:e.userImages,userFiles:e.userFiles}),He(e.sessionId).wakeAwaits();return}if(r==="steer"&&!n&&!e.userImages?.length&&!e.userFiles?.length&&this.sideTurnConfigs.has(e.sessionId)&&He(e.sessionId).leadBlocked&&pt.runningIn(e.sessionId).length>0){this.answerSteerInSideTurn(t,e.prompt);return}if(r==="queue"||r==="steer"){this.pendingPromptsController.enqueue(e.sessionId,{prompt:e.prompt,mode:e.mode,delivery:r,userImages:e.userImages,userFiles:e.userFiles});return}try{let o=await this.executeTurn(t,{prompt:e.prompt,mode:e.mode,userImages:e.userImages,userFiles:e.userFiles});if(!t.interactive)await this.finalizeSingleRun(t,o.finishReason);else await this.completeInteractiveTurn(t,o.finishReason);if(o.finishReason!=="error")queueMicrotask(()=>{this.pendingPromptsController.drain(e.sessionId)});return o}catch(o){if(t.interactive&&t.aborting)return await this.completeAbortedInteractiveTurn(t);throw yr(t.config.telemetry,{component:"core",operation:"session.submit",error:o,severity:"error",handled:!1,context:{sessionId:t.sessionId,providerId:t.config.providerId,modelId:t.config.modelId}}),await this.failSession(t),o}}async getAccumulatedUsage(e){let t=ZC(this.usageBySession.get(e)),n=ZC(this.aggregateUsageBySession.get(e));return t||n?{usage:t,aggregateUsage:n}:void 0}async abort(e,t){let n=this.sessions.get(e);if(!n)return;if(n.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:e}}),n.aborting=!0,n.drainingPendingPrompts)this.pendingPromptsController.discardQueue(n);else this.pendingPromptsController.dropHarnessNotes(n);let r=n.runtime.teamRuntime;try{r?.cancelOutstandingWork(t)}finally{if(r)n.activeTeamRunIds.clear(),n.pendingTeamRunUpdates.length=0,Bp(n);n.agent.abort(t)}}async proceedWhileRunning(e,t){return this.runCommandExecutionController.proceedWhileRunning(e,t)}async stopSession(e){let t=this.sessions.get(e);if(!t)return;if(t.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:e}}),t.interactive&&!Kt(t.status)){await this.releaseSessionRuntime(t,"session_stop");return}if(t.interactive&&t.agent.canStartRun()){await this.shutdownSession(t,{status:this.resolveInteractiveStopStatus(t),exitCode:this.resolveInteractiveStopExitCode(t),shutdownReason:"session_stop",endReason:"stopped"});return}t.aborting=!0,t.agent.abort(Error("session_stop")),await this.shutdownSession(t,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose(e="session_manager_dispose"){let t=[...this.sessions.values()];if(t.length===0)return;await Promise.allSettled(t.map((n)=>n.interactive&&!Kt(n.status)?this.releaseSessionRuntime(n,e):n.interactive&&n.agent.canStartRun()?this.shutdownSession(n,{status:this.resolveInteractiveStopStatus(n),exitCode:this.resolveInteractiveStopExitCode(n),shutdownReason:e,endReason:"disposed"}):this.shutdownSession(n,{status:"cancelled",exitCode:0,shutdownReason:e,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession(e){let t=this.sessions.get(e);if(t)return tP(t);let n=e.trim();if(!n)return;let r=await this.getRow(n);if(r)return ub(r);let o=await this.readManifest(n);return o?xV(o):void 0}async listSessions(e=200,t={}){let r=(await this.listRows(e,t)).map(ub),o=new Set(r.map((i)=>i.sessionId));for(let i of this.sessions.values()){if(o.has(i.sessionId))continue;r.unshift(tP(i))}return r.slice(0,e)}async deleteSession(e){if(this.sessions.has(e))await this.stopSession(e);let t=await this.invoke("deleteSession",e);if(t.deleted)this.usageBySession.delete(e),this.aggregateUsageBySession.delete(e);return t.deleted}async updateSession(e,t){let n=await this.invokeOptionalValue("updateSession",{sessionId:e,prompt:t.prompt,metadata:t.metadata,title:t.title}),r=n?.updated===!0;if(r&&n.metadata!==void 0){let o=this.sessions.get(e.trim());if(o){if(o.sessionMetadata=n.metadata??void 0,o.artifacts)o.artifacts.manifest.metadata=o.sessionMetadata}}return{updated:r}}async updateSessionCompactionState(e,t){let n=e.trim();if(!n)return{updated:!1};let r=this.sessions.get(n),o=r?void 0:await this.getSession(n);if(!(r??o))return{updated:!1};if(r){let a=await this.readSessionMessages(n),d=t.source_message_count>0&&a.length>=t.source_message_count,l=d?a:void 0;if(d){if(!await this.canPersistCompactionState(n,t,r,void 0,a))return{updated:!1};r.agent.restore(a)}return await this.persistActiveSessionCompactionState(r,t,l)}if(!await this.canPersistCompactionState(n,t,void 0,o))return{updated:!1};let s=await this.invokeOptionalValue("readSessionCompactionState",n);if(UV(t,s))return{updated:!1};return await this.invoke("persistSessionCompactionState",n,t),{updated:!0}}async readSessionCompactionState(e){let t=e.trim();if(!t)return;let n=this.sessions.get(t);if(n)for(;;){let r=n.compactionStateWriteQueue;if(!r)return n.compactionState;await r.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",t)}isCompactionStateForSession(e,t,n,r){let o=t.conversation_id?.trim();if(!o)return!0;if(o===e)return!0;let i=n?.agent.getConversationId()?.trim()||r?.conversationId?.trim();return i?o===i:!1}async canPersistCompactionState(e,t,n,r,o){if(!t.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession(e,t,n,r))return!1;let i=o??n?.agent.getMessages()??await this.readSessionMessages(e);return wu(t,i)!==void 0}async persistActiveSessionCompactionState(e,t,n){if(!await this.canPersistCompactionState(e.sessionId,t,e,void 0,n))return{updated:!1};return await this.enqueueCompactionStateWrite(e,async()=>{let r=e.compactionState,o=r!==void 0&&wu(r,n??e.agent.getMessages())!==void 0;if(r&&(o?UV(t,r):Date.parse(t.updated_at)<Date.parse(r.updated_at)))return{updated:!1};return await this.invoke("persistSessionCompactionState",e.sessionId,t),e.compactionState=t,{updated:!0}})}async enqueueCompactionStateWrite(e,t){let r=(e.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(t),o=r.then(()=>{return},()=>{return});e.compactionStateWriteQueue=o;try{return await r}finally{if(e.compactionStateWriteQueue===o)e.compactionStateWriteQueue=void 0}}async listConfiguredAgents(e){let t=this.sessions.get(e.trim());return Ra(t?.runtime.configuredAgents)}async delegateToConfiguredAgent(e){let t=e.sessionId.trim(),n=this.sessions.get(t);if(!n)throw Error("There is no running session to delegate from. Start a task first.");if(!n.agent.canStartRun())throw Error("Cannot delegate while a response is in progress. Wait for the current turn to finish, or abort it.");let r=await pp({agents:n.runtime.configuredAgents,tools:n.runtime.tools,agentName:e.agentName,prompt:e.prompt,sessionId:t,parentAgentId:n.agent.getAgentId(),conversationId:n.agent.getConversationId(),signal:e.signal}),o=n.agent.getMessages();return n.agent.restore([...o,{role:"user",content:sb(r,e.prompt)}]),r}async startBackgroundDelegation(e){let t=e.sessionId.trim(),n=this.sessions.get(t);if(!n)throw Error("There is no running session to delegate from. Start a task first.");return bR(this.backgroundDelegationsFor(t),{agents:n.runtime.configuredAgents,tools:n.runtime.tools,agentName:e.agentName,prompt:e.prompt,sessionId:t,parentAgentId:n.agent.getAgentId(),conversationId:n.agent.getConversationId(),onSettled:(r)=>{this.deliverBackgroundDelegation(t,r)}})}async listBackgroundDelegations(e){return this.backgroundDelegations.get(e.trim())?.list()??[]}async controlBackgroundDelegation(e){let t=this.backgroundDelegations.get(e.sessionId.trim());if(!t)return!1;if(e.action==="pause")return t.pause(e.id);if(e.action==="resume")return t.resume(e.id);return t.stop(e.id)}backgroundDelegationsFor(e){let t=this.backgroundDelegations.get(e);if(t)return t;let n=wR();return this.backgroundDelegations.set(e,n),n}async disengageAtomicProtocol(e){let t=this.sessions.get(e),n=t?.atomicProtocol;if(!t||!n||n.disengaged)return!1;if(t.agent.canStartRun()){let r=await n.disengage();if(r)t.agent.restore([...t.agent.getMessages(),{role:"user",content:r}]);return!0}return this.pendingAtomicDisengage.add(e),!0}deliverRound(e,t){let n=this.sessions.get(e);if(!n)return;He(e).markDelivered(t.record.id);let r=R2(t);if(n.agent.canStartRun()){n.agent.restore([...n.agent.getMessages(),{role:"user",content:r}]);return}this.pendingPromptsController.enqueue(e,{prompt:r,delivery:"steer",origin:"harness"})}deliverBackgroundDelegation(e,t){let n=t.result?sb(t.result,t.prompt):`The background delegation to "${t.agentName}" failed: ${t.error??"no reason given"}
@@ -1551,7 +1551,7 @@ ${d}`:d,t.mode??e.config.mode),c=this.resolveAbsoluteFilePaths(e.config.cwd,t.us
1551
1551
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
1552
1552
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
1553
1553
  metadata_json, transcript_path, hook_path, messages_path, updated_at
1554
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.sessionId,e.source,e.pid,e.startedAt,null,null,"running",0,e.interactive?1:0,e.provider,e.model,e.cwd,e.workspaceRoot,e.teamName??null,e.enableTools?1:0,e.enableSpawn?1:0,e.enableTeams?1:0,null,null,null,null,0,e.prompt??null,e.metadata?JSON.stringify(e.metadata):null,"","",e.messagesPath,ft()])}}function A$e(e){return{text:e.text,usage:e.usage,inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,iterations:e.iterations,finishReason:e.finishReason,toolCalls:e.toolCalls.map((t)=>({name:t.name,input:t.input,output:t.output,error:t.error,durationMs:t.durationMs}))}}function R$e(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function YV(e={}){let t=async(r)=>r,n=new um({sessionService:new fm(new mm),capabilities:{toolExecutors:{submit:t}},fetch:e.fetch,telemetry:e.telemetry});return{async startSession(r,o){let i=(r.cwd?.trim()||r.workspaceRoot).trim(),s=await n.startSession({source:Gt.CORE,mode:"automation",sessionMetadata:Gn(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:E$e(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:i,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:R$e(r),maxIterations:r.maxIterations,enableTools:r.enableTools!==!1,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},toolPolicies:r.toolPolicies??{"*":{autoApprove:r.autoApproveTools!==!1}},localRuntime:{configExtensions:r.configExtensions}});return{sessionId:s.sessionId,startResult:{sessionId:s.sessionId,manifestPath:s.manifestPath,messagesPath:s.messagesPath}}},async sendSession(r,o){let i=await n.runTurn({sessionId:r,prompt:o.prompt,userImages:o.attachments?.userImages,userFiles:o.attachments?.userFiles?.map((s)=>s.content)});if(!i)throw Error("local hub schedule runtime returned no turn result");return{result:A$e(i)}},async abortSession(r){return await n.abort(r,Error("hub schedule abort")),{applied:!0}},async stopSession(r){return await n.stopSession(r),{applied:!0}}}}import{CLINE_HUB_DEV_PORT as I$e,CLINE_HUB_PORT as C$e,resolveClineBuildEnv as P$e}from"@cerebriline/shared";var M$e="CLINE_HUB_HOST",O$e="CLINE_HUB_PORT",L$e="CLINE_HUB_PATHNAME",N$e="127.0.0.1",D$e=C$e,$$e="/hub";function XV(e){return P$e(e)==="development"?I$e:D$e}function F$e(e={}){return(e.env??process.env)[M$e]?.trim()||N$e}function fP(e={}){let n=(e.env??process.env)[O$e]?.trim();if(!n)return XV(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return XV(e);return r}function U$e(e={}){return(e.env??process.env)[L$e]?.trim()||$$e}function gP(e={},t={}){return{host:e.host??F$e(t),port:e.port??fP(t),pathname:e.pathname??U$e(t)}}import{chmodSync as B$e,existsSync as H$e,mkdirSync as W$e}from"node:fs";import{dirname as j$e}from"node:path";import{loadSqliteDb as q$e}from"@cerebriline/shared/db";var JV=3;class QV extends Error{lockFile;constructor(e){super(`Hub instance lock is held by a live Hub: ${e}. Connect to the running Hub or diagnose it; never replace it.`);this.name="HubLockHeldError",this.lockFile=e}}function gm(e){return e instanceof Error&&e.name==="HubLockHeldError"}function ZV(e){return`${e}.instance.lock`}class Hc{db;lockFile;constructor(e,t){this.lockFile=e,this.db=t}get held(){return this.db!==void 0}release(){let e=this.db;if(!e)return;this.db=void 0;try{e.exec("ROLLBACK;")}catch{}e.close?.()}static acquire(e){let t=!1,n;try{W$e(j$e(e),{recursive:!0}),t=H$e(e),n=q$e(e)}catch{return new Hc(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),z$e(r))throw new QV(e);return new Hc(e,void 0)}if(!t)try{B$e(e,384)}catch{}return new Hc(e,n)}}function z$e(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return n==="SQLITE_BUSY"||n==="SQLITE_LOCKED"||t.includes("SQLITE_BUSY")||t.includes("SQLITE_LOCKED")||t.includes("database is locked")}import{join as dFe}from"node:path";import{createHash as K$e,randomBytes as r5}from"node:crypto";import{mkdir as wP,open as e5,readFile as o5,rename as G$e,rm as bP,writeFile as V$e}from"node:fs/promises";import{dirname as i5,join as vP}from"node:path";import{ensureLoopbackProxyBypass as Y$e,isHubProtocolCompatible as yyt}from"@cerebriline/shared";import{resolveClineDataDir as Ov,resolveClineDir as byt}from"@cerebriline/shared/storage";var X$e="CLINE_HUB_DISCOVERY_PATH",J$e="CLINE_HUB_BUILD_ID",Q$e="CLINE_HUB_BUILD_EPOCH_MS",Z$e=30000,eFe=15000,t5=100;function tFe(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function nFe(e){return K$e("sha256").update(e).digest("hex").slice(0,12)}function rFe(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function s5(){return r5(32).toString("hex")}function n5(e){return new Promise((t)=>setTimeout(t,e))}function oFe(e){return`${e}.lock`}async function iFe(e){try{let t=JSON.parse(await o5(vP(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function yP(e){await bP(e,{recursive:!0,force:!0}).catch(()=>{return})}function ym(){let e=process.env[J$e]?.trim();if(e)return e;return"sdk-v1-1388275e3a296765a1ef7bd2a590950ed311d2f3a4681d8e7aa53c448139ee24".trim()||`source-${String(nc.version)}`}function a5(){let e=Number(process.env[Q$e]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1793299183934)?1793299183934:void 0}function Lv(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${nFe(e)}`,n=process.env[X$e]?.trim()||vP(Ov(),"locks","hub","owners",`${tFe(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Nv(e){try{let t=JSON.parse(await o5(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function kP(e,t,n){await l5(e,async()=>{let r=i5(e);await wP(r,{recursive:!0});let o=`${e}.${process.pid}.${r5(6).toString("hex")}.tmp`,i;try{i=await e5(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
1554
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.sessionId,e.source,e.pid,e.startedAt,null,null,"running",0,e.interactive?1:0,e.provider,e.model,e.cwd,e.workspaceRoot,e.teamName??null,e.enableTools?1:0,e.enableSpawn?1:0,e.enableTeams?1:0,null,null,null,null,0,e.prompt??null,e.metadata?JSON.stringify(e.metadata):null,"","",e.messagesPath,ft()])}}function A$e(e){return{text:e.text,usage:e.usage,inputTokens:e.usage.inputTokens,outputTokens:e.usage.outputTokens,iterations:e.iterations,finishReason:e.finishReason,toolCalls:e.toolCalls.map((t)=>({name:t.name,input:t.input,output:t.output,error:t.error,durationMs:t.durationMs}))}}function R$e(e){return e.mode==="plan"?"plan":e.mode==="yolo"?"yolo":"act"}function YV(e={}){let t=async(r)=>r,n=new um({sessionService:new fm(new mm),capabilities:{toolExecutors:{submit:t}},fetch:e.fetch,telemetry:e.telemetry});return{async startSession(r,o){let i=(r.cwd?.trim()||r.workspaceRoot).trim(),s=await n.startSession({source:Gt.CORE,mode:"automation",sessionMetadata:Gn(o?.sessionMetadata,{mode:"automation",trigger:r.source}),interactive:!1,config:{providerId:E$e(r.provider),modelId:r.model,apiKey:r.apiKey?.trim()||void 0,cwd:i,workspaceRoot:r.workspaceRoot,systemPrompt:r.systemPrompt??"",mode:R$e(r),maxIterations:r.maxIterations,enableTools:r.enableTools!==!1,enableSpawnAgent:r.enableSpawn!==!1,enableAgentTeams:r.enableTeams!==!1,disableMcpSettingsTools:r.disableMcpSettingsTools,agentPluginPaths:r.agentPluginPaths,missionLogIntervalSteps:r.missionStepInterval,missionLogIntervalMs:r.missionTimeIntervalMs},toolPolicies:r.toolPolicies??{"*":{autoApprove:r.autoApproveTools!==!1}},localRuntime:{configExtensions:r.configExtensions}});return{sessionId:s.sessionId,startResult:{sessionId:s.sessionId,manifestPath:s.manifestPath,messagesPath:s.messagesPath}}},async sendSession(r,o){let i=await n.runTurn({sessionId:r,prompt:o.prompt,userImages:o.attachments?.userImages,userFiles:o.attachments?.userFiles?.map((s)=>s.content)});if(!i)throw Error("local hub schedule runtime returned no turn result");return{result:A$e(i)}},async abortSession(r){return await n.abort(r,Error("hub schedule abort")),{applied:!0}},async stopSession(r){return await n.stopSession(r),{applied:!0}}}}import{CLINE_HUB_DEV_PORT as I$e,CLINE_HUB_PORT as C$e,resolveClineBuildEnv as P$e}from"@cerebriline/shared";var M$e="CLINE_HUB_HOST",O$e="CLINE_HUB_PORT",L$e="CLINE_HUB_PATHNAME",N$e="127.0.0.1",D$e=C$e,$$e="/hub";function XV(e){return P$e(e)==="development"?I$e:D$e}function F$e(e={}){return(e.env??process.env)[M$e]?.trim()||N$e}function fP(e={}){let n=(e.env??process.env)[O$e]?.trim();if(!n)return XV(e);let r=Number.parseInt(n,10);if(!Number.isInteger(r)||r<1||r>65535)return XV(e);return r}function U$e(e={}){return(e.env??process.env)[L$e]?.trim()||$$e}function gP(e={},t={}){return{host:e.host??F$e(t),port:e.port??fP(t),pathname:e.pathname??U$e(t)}}import{chmodSync as B$e,existsSync as H$e,mkdirSync as W$e}from"node:fs";import{dirname as j$e}from"node:path";import{loadSqliteDb as q$e}from"@cerebriline/shared/db";var JV=3;class QV extends Error{lockFile;constructor(e){super(`Hub instance lock is held by a live Hub: ${e}. Connect to the running Hub or diagnose it; never replace it.`);this.name="HubLockHeldError",this.lockFile=e}}function gm(e){return e instanceof Error&&e.name==="HubLockHeldError"}function ZV(e){return`${e}.instance.lock`}class Hc{db;lockFile;constructor(e,t){this.lockFile=e,this.db=t}get held(){return this.db!==void 0}release(){let e=this.db;if(!e)return;this.db=void 0;try{e.exec("ROLLBACK;")}catch{}e.close?.()}static acquire(e){let t=!1,n;try{W$e(j$e(e),{recursive:!0}),t=H$e(e),n=q$e(e)}catch{return new Hc(e,void 0)}try{n.exec("PRAGMA busy_timeout = 0;"),n.exec("BEGIN EXCLUSIVE;")}catch(r){if(n.close?.(),z$e(r))throw new QV(e);return new Hc(e,void 0)}if(!t)try{B$e(e,384)}catch{}return new Hc(e,n)}}function z$e(e){let t=e instanceof Error?e.message:String(e),n=e?.code;return n==="SQLITE_BUSY"||n==="SQLITE_LOCKED"||t.includes("SQLITE_BUSY")||t.includes("SQLITE_LOCKED")||t.includes("database is locked")}import{join as dFe}from"node:path";import{createHash as K$e,randomBytes as r5}from"node:crypto";import{mkdir as wP,open as e5,readFile as o5,rename as G$e,rm as bP,writeFile as V$e}from"node:fs/promises";import{dirname as i5,join as vP}from"node:path";import{ensureLoopbackProxyBypass as Y$e,isHubProtocolCompatible as byt}from"@cerebriline/shared";import{resolveClineDataDir as Ov,resolveClineDir as kyt}from"@cerebriline/shared/storage";var X$e="CLINE_HUB_DISCOVERY_PATH",J$e="CLINE_HUB_BUILD_ID",Q$e="CLINE_HUB_BUILD_EPOCH_MS",Z$e=30000,eFe=15000,t5=100;function tFe(e){return e.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function nFe(e){return K$e("sha256").update(e).digest("hex").slice(0,12)}function rFe(e){if(!Number.isInteger(e)||!e||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t instanceof Error&&"code"in t?String(t.code)==="EPERM":!1}}function s5(){return r5(32).toString("hex")}function n5(e){return new Promise((t)=>setTimeout(t,e))}function oFe(e){return`${e}.lock`}async function iFe(e){try{let t=JSON.parse(await o5(vP(e,"owner.json"),"utf8"));if(typeof t.pid!=="number"||typeof t.acquiredAt!=="string")return;return{pid:t.pid,acquiredAt:t.acquiredAt}}catch{return}}async function yP(e){await bP(e,{recursive:!0,force:!0}).catch(()=>{return})}function ym(){let e=process.env[J$e]?.trim();if(e)return e;return"sdk-v1-ae0398ec8aafc784b621c159c759e7880762e2aea04c797ef2d90837a45894e8".trim()||`source-${String(nc.version)}`}function a5(){let e=Number(process.env[Q$e]);if(Number.isFinite(e)&&e>0)return e;return Number.isFinite(1793518707834)?1793518707834:void 0}function Lv(e=process.argv[1]?.trim()||process.cwd()){let t=`hub-${nFe(e)}`,n=process.env[X$e]?.trim()||vP(Ov(),"locks","hub","owners",`${tFe(t)}.json`);return{ownerId:t,discoveryPath:n}}async function Nv(e){try{let t=JSON.parse(await o5(e,"utf8"));if(typeof t.hubId!=="string"||typeof t.protocolVersion!=="string"||typeof t.authToken!=="string"||typeof t.host!=="string"||typeof t.port!=="number"||typeof t.url!=="string"||typeof t.startedAt!=="string"||typeof t.updatedAt!=="string")return;return{hubId:t.hubId,protocolVersion:t.protocolVersion,minClientProtocolVersion:typeof t.minClientProtocolVersion==="string"?t.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof t.maxClientProtocolVersion==="string"?t.maxClientProtocolVersion:void 0,capabilities:Array.isArray(t.capabilities)?t.capabilities.filter((n)=>typeof n==="string"):void 0,coreVersion:typeof t.coreVersion==="string"?t.coreVersion:void 0,buildId:typeof t.buildId==="string"?t.buildId:void 0,buildEpochMs:typeof t.buildEpochMs==="number"?t.buildEpochMs:void 0,authToken:t.authToken,host:t.host,port:t.port,url:t.url,pid:typeof t.pid==="number"?t.pid:void 0,startedAt:t.startedAt,updatedAt:t.updatedAt}}catch{return}}async function kP(e,t,n){await l5(e,async()=>{let r=i5(e);await wP(r,{recursive:!0});let o=`${e}.${process.pid}.${r5(6).toString("hex")}.tmp`,i;try{i=await e5(o,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
1555
1555
  `,{encoding:"utf8"}),await i.sync(),await i.close(),i=void 0,n?.beforePublish?.(),await G$e(o,e);let s;try{s=await e5(r,"r"),await s.sync()}catch{}finally{await s?.close().catch(()=>{return})}}catch(s){throw await i?.close().catch(()=>{return}),await bP(o,{force:!0}).catch(()=>{return}),s}})}async function d5(e,t){return await l5(e,async()=>{if((await Nv(e))?.hubId!==t)return!1;return await bP(e,{force:!0}),!0})}async function sFe(e,t,n){let r=oFe(e);await wP(i5(r),{recursive:!0});let o=Date.now()+eFe;while(!0){try{await wP(r,{recursive:!1})}catch(i){if((i instanceof Error&&"code"in i?String(i.code):"")!=="EEXIST")throw i;let a=await iFe(r);if(!a){if(Date.now()>=o){await yP(r);continue}await n5(t5);continue}let d=Date.now()-Date.parse(a.acquiredAt);if(!rFe(a.pid)||d>Z$e){await yP(r);continue}if(Date.now()>=o)throw Error(`Timed out waiting for hub ${t} lock ${r}`);await n5(t5);continue}try{return await V$e(vP(r,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
1556
1556
  `,"utf8"),await n()}finally{await yP(r)}}}function l5(e,t){return sFe(`${e}.mutation`,"discovery mutation",t)}async function wm(e,t){Y$e();try{let n=await fetch(t?.authToken?aFe(e):c5(e),{headers:t?.authToken?{authorization:`Bearer ${t.authToken}`}:void 0,signal:t?.signal});if(!n.ok)return;let r=await n.json();if(typeof r.protocolVersion!=="string"||typeof r.host!=="string"||typeof r.port!=="number"||typeof r.url!=="string")return;return{protocolVersion:r.protocolVersion,minClientProtocolVersion:typeof r.minClientProtocolVersion==="string"?r.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof r.maxClientProtocolVersion==="string"?r.maxClientProtocolVersion:void 0,capabilities:Array.isArray(r.capabilities)?r.capabilities.filter((o)=>typeof o==="string"):void 0,coreVersion:typeof r.coreVersion==="string"?r.coreVersion:void 0,buildId:typeof r.buildId==="string"?r.buildId:void 0,buildEpochMs:typeof r.buildEpochMs==="number"?r.buildEpochMs:void 0,host:r.host,port:r.port,url:r.url,hubId:typeof r.hubId==="string"?r.hubId:void 0,authToken:typeof r.authToken==="string"?r.authToken:void 0,pid:typeof r.pid==="number"?r.pid:void 0,startedAt:typeof r.startedAt==="string"?r.startedAt:void 0,updatedAt:typeof r.updatedAt==="string"?r.updatedAt:void 0}}catch{return}}function Wc(e,t,n="/hub"){return new URL(`ws://${e}:${t}${n}`).toString()}function c5(e){let t=new URL(e);return t.protocol=t.protocol==="wss:"?"https:":"http:",t.pathname="/health",t.search="",t.toString()}function aFe(e){let t=new URL(c5(e));return t.pathname="/status",t.toString()}var lFe="shared:cline",cFe="CLINE_HUB_DISCOVERY_PATH",uFe="hub-production";function Dv(e=lFe){return Lv(`${e}@${ym()}`)}function $v(){return{ownerId:uFe,discoveryPath:process.env[cFe]?.trim()||dFe(Ov(),"locks","hub","production.json")}}function hFe(e){if(typeof e==="string")return e.trim()||void 0;if(!Array.isArray(e))return;return e.map((n)=>{if(n&&typeof n==="object"&&"type"in n&&n.type==="text"&&"text"in n&&typeof n.text==="string")return n.text.trim();return""}).filter(Boolean).join(`
1557
1557
  `).trim()||void 0}var u5=120,TP="...";function SP(e){let t=e.trim();if(!t)return"";if(Buffer.byteLength(t,"utf8")<=u5)return t;let n=u5-Buffer.byteLength(TP,"utf8");if(n<=0)return TP;let r="";for(let o of t){if(Buffer.byteLength(r+o,"utf8")>n)break;r+=o}return`${r}${TP}`}async function h5(e){let t=e?.sessionId?.trim()||"unknown",n=typeof e?.metadata?.messagesPath==="string"?e.metadata.messagesPath:void 0,o=[...await Uc(n)].reverse().find((d)=>d.role==="assistant"),i=o?hFe(o.content):void 0,s=e?.workspaceRoot?.trim()||"workspace",a=typeof e?.metadata?.prompt==="string"?e.metadata.prompt.trim():s;return{title:`Task completed (${t})`,body:SP(i&&i.length>0?i:a.length>0?a:s),severity:"info"}}import{resolve as $He}from"node:path";import{CLINE_DEFAULT_MODEL_ID as FHe,captureSdkError as rk,createSessionId as P0,HUB_CLIENT_TOOL_APPROVAL_CAPABILITY as UHe}from"@cerebriline/shared";import{isChatWorkspacePath as BHe}from"@cerebriline/shared/storage";function bm(e){return!!e&&typeof e==="object"&&!Array.isArray(e)}function xP(e){let t=e?.trim();return t?t:void 0}function pFe(e,t){let n=e?.trim();if(!n)return t;let r=Date.parse(n);if(!Number.isFinite(r))return t;return new Date(r).toISOString()}function p5(e,t){return new Date(new Date(e).getTime()+Math.max(0,Math.floor(t))*1000).toISOString()}function m5(e,t){return new Date(new Date(e).getTime()-Math.max(0,Math.floor(t))*1000).toISOString()}function mFe(e,t){if(!e)return t;return new Date(e).getTime()>=new Date(t).getTime()?e:t}function fFe(e,t){let n=e.eventId.trim(),r=e.eventType.trim(),o=e.source.trim(),i=xP(e.subject),s=xP(e.dedupeKey)??`${r}:${o}:${i??n}`;return{eventId:n,eventType:r,source:o,subject:i,occurredAt:pFe(e.occurredAt,t),workspaceRoot:xP(e.workspaceRoot),payload:bm(e.payload)?e.payload:void 0,attributes:bm(e.attributes)?e.attributes:void 0,dedupeKey:s}}function _P(e,t){if(!t)return;let n=t.split("."),r=e;for(let o of n){if(!bm(r))return;r=r[o]}return r}function gFe(e,t){if(e.attributes&&Object.hasOwn(e.attributes,t))return e.attributes[t];if(e.payload&&Object.hasOwn(e.payload,t))return e.payload[t];let n={eventId:e.eventId,eventType:e.eventType,source:e.source,subject:e.subject,occurredAt:e.occurredAt,workspaceRoot:e.workspaceRoot,dedupeKey:e.dedupeKey,attributes:e.attributes,payload:e.payload},r=_P(n,t);if(r!==void 0)return r;if(e.attributes){let o=_P(e.attributes,t);if(o!==void 0)return o}if(e.payload)return _P(e.payload,t);return}function Fv(e,t){if(Array.isArray(t))return t.some((n)=>Fv(e,n));if(Array.isArray(e))return e.some((n)=>Fv(n,t));if(bm(t)){if(!bm(e))return!1;return Object.entries(t).every(([n,r])=>Fv(e[n],r))}return Object.is(e,t)}function yFe(e,t){if(!t||Object.keys(t).length===0)return!0;return Object.entries(t).every(([n,r])=>Fv(gFe(e,n),r))}class EP{store;nowFn;logger;constructor(e){this.store=e.store,this.nowFn=e.now??(()=>Date.now()),this.logger=e.logger}ingestEvent(e){let t=new Date(this.nowFn()).toISOString(),n=fFe(e,t);try{let r=this.store.eventTransaction(()=>this.materializeEvent(n,t));return this.logger?.debug(r.duplicate?"cron.event.duplicate":"cron.event.processed",{eventId:r.event.eventId,eventType:r.event.eventType,source:r.event.source,status:r.event.processingStatus,matchedSpecCount:r.event.matchedSpecCount,queuedRunCount:r.event.queuedRunCount}),r}catch(r){throw this.logger?.error?.("cron.event.failed",{eventId:n.eventId,eventType:n.eventType,error:r}),r}}materializeEvent(e,t){let n=this.store.insertEventLog(e,{receivedAtIso:t});if(!n.created)return{event:n.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:n.record.dedupeKey}]};let r=this.store.listEventSpecsForType(e.eventType),o=[],i=[],s=[];for(let l of r){if(!yFe(e,l.filters)){o.push({specId:l.specId,externalId:l.externalId,reason:"filter_mismatch",dedupeKey:e.dedupeKey});continue}i.push(l);let c=this.materializeForSpec(l,e,n.record.receivedAt);if(c.run)s.push(c.run);else o.push({specId:l.specId,externalId:l.externalId,reason:c.reason,dedupeKey:e.dedupeKey})}let a=i.length===0?"unmatched":s.length>0?"queued":"suppressed";return this.store.updateEventLogProcessing(n.record.eventId,{status:a,matchedSpecCount:i.length,queuedRunCount:s.length,suppressedCount:o.filter((l)=>l.reason!=="filter_mismatch").length}),{event:this.store.getEventLog(n.record.eventId)??n.record,duplicate:!1,matchedSpecs:i,queuedRuns:s,suppressions:o}}materializeForSpec(e,t,n){let r=t.dedupeKey??t.eventId,o=e.debounceSeconds??0;if(o>0){let d=this.store.findQueuedEventRunForDedupe({specId:e.specId,dedupeKey:r});if(d){let l=mFe(d.scheduledFor,p5(n,o)),c=this.store.updateQueuedEventRunForDebounce({runId:d.runId,triggerEventId:t.eventId,scheduledFor:l});if(c)return{run:c,reason:"dedupe_window"}}}let i=e.dedupeWindowSeconds??0;if(i>0&&this.store.hasRecentEventRunForDedupe({specId:e.specId,dedupeKey:r,sinceIso:m5(n,i)}))return{reason:"dedupe_window"};let s=e.cooldownSeconds??0;if(s>0&&this.store.hasRecentEventRunForSpec({specId:e.specId,sinceIso:m5(n,s)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:e.specId,specRevision:e.revision,triggerKind:"event",triggerEventId:t.eventId,scheduledFor:o>0?p5(n,o):n}),reason:"dedupe_window"}}}class vm{store;nowFn;constructor(e){this.store=e.store,this.nowFn=e.now??(()=>Date.now())}materializeAll(){let e={oneOffQueued:0,scheduleQueued:0},t=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let r of t)if(this.materializeOneOff(r))e.oneOffQueued+=1;let n=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let r of n)try{if(this.materializeSchedule(r))e.scheduleQueued+=1}catch{}return e}materializeOneOff(e){if(e.triggerKind!=="one_off")return!1;if(!e.enabled||e.removed)return!1;if(this.store.hasConsumedOneOffRevision(e.specId,e.revision))return!1;return this.store.enqueueRun({specId:e.specId,specRevision:e.revision,triggerKind:"one_off",scheduledFor:e.nextRunAt??new Date(this.nowFn()).toISOString()}),!0}materializeSchedule(e){if(e.triggerKind!=="schedule")return!1;if(!e.enabled||e.removed)return!1;if(!e.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:e.specId,nowMs:this.nowFn()}).queued}}import{basename as RFe}from"node:path";import{buildClineSystemPrompt as IFe}from"@cerebriline/shared";import{nowIso as b5}from"@cerebriline/shared/db";import{mkdirSync as wFe,writeFileSync as bFe}from"node:fs";import{isAbsolute as vFe,join as g5}from"node:path";import{resolveCronReportsDir as kFe,resolveCronSpecsDir as TFe}from"@cerebriline/shared/storage";function us(e){if(/[:#\n]/.test(e)||e.includes('"'))return JSON.stringify(e);return e}function wr(e,t){if(t===void 0||t===null)return;return`${e}: ${us(t)}`}function y5(e){let t=0;for(let r of e.matchAll(/`+/g))t=Math.max(t,r[0].length);let n="`".repeat(Math.max(3,t+1));return`${n}
@@ -2080,7 +2080,7 @@ ${e.instructions.trim()}
2080
2080
  ${t.length?`WHERE ${t.join(" AND ")}`:""}
2081
2081
  ORDER BY accepted_seq DESC LIMIT ?;`).all(...n).map(Fm)}recoverOnStartup(){let e=this.db.prepare("SELECT * FROM hub_runs WHERE state = 'running' ORDER BY accepted_seq;").all().map(Fm);this.db.prepare(`UPDATE hub_runs SET state = 'interrupted', ended_at = ?,
2082
2082
  error = 'Hub daemon exited before the run finished.'
2083
- WHERE state = 'running';`).run(Date.now());let t=this.db.prepare("SELECT * FROM hub_runs WHERE state = 'queued' ORDER BY accepted_seq;").all().map(Fm);return this.db.prepare("DELETE FROM hub_runs WHERE ended_at IS NOT NULL AND ended_at < ?;").run(Date.now()-iHe),{interrupted:e.map((n)=>({...n,state:"interrupted"})),requeued:t}}close(){if(this.closed)return;this.closed=!0,this.db.close?.()}}function Fm(e){let t={};try{let n=JSON.parse(String(e.input_json));if(n&&typeof n==="object"&&!Array.isArray(n))t=n}catch{}return{runId:String(e.run_id),sessionId:String(e.session_id),state:String(e.state),input:t,clientId:typeof e.client_id==="string"?e.client_id:void 0,acceptedAt:Number(e.accepted_at),startedAt:e.started_at===null?void 0:Number(e.started_at),endedAt:e.ended_at===null?void 0:Number(e.ended_at),error:typeof e.error==="string"?e.error:void 0}}var aHe="hub_draining",dHe=new Set(["session.create","session.restore","session.fork","run.start","session.send_input","run.enqueue"]);function wX(e){return dHe.has(e)}function bX(e){return{version:e.version,requestId:e.requestId,ok:!1,error:{code:aHe,message:"Hub is draining and refuses new mutating work; retry once a hub is serving again.",details:{retryable:!0}}}}class S0{ctx;queue;activeSessions=new Set;constructor(e,t){this.ctx=e;this.queue=t}pump(e){if(this.activeSessions.has(e))return;this.activeSessions.add(e),this.drainSession(e).catch((t)=>{ke("error","run.queue.pump_failed",{sessionId:e,error:t})}).finally(()=>{if(this.activeSessions.delete(e),this.queue.nextQueued(e))this.pump(e)})}async drainSession(e){for(;;){let t=this.queue.nextQueued(e);if(!t)return;this.queue.markRunning(t.runId),await this.execute(t)}}async execute(e){let t={version:"v1",command:"run.start",requestId:e.runId,clientId:e.clientId,sessionId:e.sessionId,payload:{...e.input,sessionId:e.sessionId}};try{let n=await $m(this.ctx,t);if(n.ok){let r=n.payload?.result?.finishReason;this.queue.markTerminal(e.runId,r==="aborted"?"aborted":r==="error"||r==="failed"?"failed":"completed",r==="error"?"Run finished with an error.":void 0)}else this.queue.markTerminal(e.runId,"failed",n.error?.message??"Run failed.")}catch(n){this.queue.markTerminal(e.runId,"failed",n instanceof Error?n.message:String(n))}}}function vX(e,t,n,r){let o=Rt(t);if(!o)return pe(t,"invalid_session_id","run.enqueue requires a sessionId");let i=t.payload&&typeof t.payload==="object"?t.payload:{};if(!(typeof i.prompt==="string"?i.prompt:typeof i.input==="string"?i.input:"").trim())return pe(t,"invalid_session_input","run.enqueue requires a prompt string");let a;try{a=n.admit(o,i,t.clientId?.trim()||void 0)}catch(d){if(d instanceof ek)return{version:t.version,requestId:t.requestId,ok:!1,error:{code:"run_admission_rejected",message:d.message,details:{retryable:!0}}};throw d}return e.publish(e.buildEvent("run.enqueued",{runId:a.runId,acceptedAt:a.acceptedAt,queuePosition:a.queuePosition,...t.clientId?{clientId:t.clientId}:{}},o)),r.pump(o),ie(t,{...a})}function kX(e,t){let n=Rt(e)||void 0,r=typeof e.payload?.limit==="number"&&Number.isFinite(e.payload.limit)&&e.payload.limit>0?Math.floor(e.payload.limit):void 0;return ie(e,{runs:t.list({sessionId:n,limit:r}).map((o)=>({runId:o.runId,sessionId:o.sessionId,state:o.state,acceptedAt:o.acceptedAt,startedAt:o.startedAt,endedAt:o.endedAt,error:o.error}))})}async function TX(e,t){switch(t.type){case"chunk":return;case"agent_event":await lHe(e,t);return;case"hook":if(t.payload.hookEventName==="tool_call")e.publish(e.buildEvent("tool.started",{toolName:t.payload.toolName},t.payload.sessionId));else if(t.payload.hookEventName==="tool_result")e.publish(e.buildEvent("tool.finished",{toolName:t.payload.toolName},t.payload.sessionId));return;case"team_progress":{let n={type:"team_progress_projection",version:1,sessionId:t.payload.sessionId,summary:t.payload.summary,lastEvent:t.payload.lifecycle};e.publish(e.buildEvent("team.progress",n,t.payload.sessionId));return}case"pending_prompts":e.publish(e.buildEvent("session.pending_prompts",{sessionId:t.payload.sessionId,prompts:t.payload.prompts},t.payload.sessionId));return;case"pending_prompt_submitted":{let n={id:t.payload.id,prompt:t.payload.prompt,delivery:t.payload.delivery,attachmentCount:t.payload.attachmentCount,userImages:t.payload.userImages,userFiles:t.payload.userFiles,...t.payload.origin?{origin:t.payload.origin}:{}};e.publish(e.buildEvent("session.pending_prompt_submitted",{sessionId:t.payload.sessionId,prompt:n},t.payload.sessionId));return}case"session_snapshot":e.publish(e.buildEvent("session.updated",{sessionId:t.payload.sessionId,snapshot:t.payload.snapshot},t.payload.sessionId));return;case"status":{let[n,r]=await Promise.all([kn(e,t.payload.sessionId),Nn(e,t.payload.sessionId)]);if(n)e.publish(e.buildEvent("session.updated",{session:n,...r?{snapshot:r}:{}},t.payload.sessionId));return}case"ended":await uHe(e,t);return;default:return}}async function lHe(e,t){let{sessionId:n,event:r}=t.payload;if(r.type==="iteration_start"){e.publish(e.buildEvent("iteration.started",{iteration:r.iteration},n));return}if(r.type==="iteration_end"){e.publish(e.buildEvent("iteration.finished",{iteration:r.iteration,hadToolCalls:r.hadToolCalls,toolCallCount:r.toolCallCount},n));return}if(r.type==="content_start"){if(r.contentType==="text"&&typeof r.text==="string"&&r.text.length>0){e.publish(e.buildEvent("assistant.delta",{text:r.text},n));return}if(r.contentType==="reasoning"){if(r.redacted&&!r.reasoning){e.publish(e.buildEvent("reasoning.delta",{text:"",redacted:!0},n));return}if(typeof r.reasoning==="string"&&r.reasoning.length>0)e.publish(e.buildEvent("reasoning.delta",{text:r.reasoning,redacted:r.redacted===!0},n));return}if(r.contentType==="tool"){e.publish(e.buildEvent("tool.started",{toolCallId:r.toolCallId,toolName:r.toolName,input:r.input},n));return}}if(r.type==="content_update"&&r.contentType==="tool"){e.publish(e.buildEvent("tool.updated",{toolCallId:r.toolCallId,toolName:r.toolName,update:r.update},n));return}if(r.type==="content_end"){switch(r.contentType){case"text":e.publish(e.buildEvent("assistant.finished",{text:r.text},n));break;case"media":if(r.media)e.publish(e.buildEvent("assistant.media",{media:r.media},n));break;case"reasoning":e.publish(e.buildEvent("reasoning.finished",{reasoning:r.reasoning},n));break;case"tool":e.publish(e.buildEvent("tool.finished",{toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,error:r.error},n));break}return}if(r.type==="notice"){e.publish(e.buildEvent("session.notice",{sessionId:n,message:r.message,noticeType:r.noticeType,...r.displayRole?{displayRole:r.displayRole}:{},...r.reason?{reason:r.reason}:{},...r.metadata?{metadata:r.metadata}:{},agent:{kind:t.payload.teamRole==="teammate"?"teammate":r.parentAgentId?"subagent":"lead",agentId:r.agentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamAgentId:t.payload.teamAgentId,teamRole:t.payload.teamRole}},n));return}if(r.type==="usage"){let o;try{o=await e.sessionHost.getAccumulatedUsage?.(n)}catch{o=void 0}e.publish(e.buildEvent("usage.updated",{sessionId:n,delta:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens??0,cacheWriteTokens:r.cacheWriteTokens??0,reasoningTokenCount:r.reasoningTokenCount,totalCost:r.cost??0,...r.reasoningTokens!==void 0?{reasoningTokens:r.reasoningTokens}:{},...r.timings?{timings:r.timings}:{},...r.outputSplit?{outputSplit:r.outputSplit}:{},...r.auxiliary?{auxiliary:!0}:{}},totals:{inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens,cacheReadTokens:r.totalCacheReadTokens??0,cacheWriteTokens:r.totalCacheWriteTokens??0,totalCost:r.totalCost??0},usage:o?.usage,aggregateUsage:o?.aggregateUsage,agent:{kind:t.payload.teamRole==="teammate"?"teammate":r.parentAgentId?"subagent":"lead",agentId:r.agentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamAgentId:t.payload.teamAgentId,teamRole:t.payload.teamRole}},n));return}if(r.type==="done"){e.publish(e.buildEvent("agent.done",{reason:r.reason,text:r.text,iterations:r.iterations,usage:r.usage},n));return}if(r.type==="error")await cHe(e,t)}async function cHe(e,t){let{sessionId:n,event:r}=t.payload;if(r.type!=="error"||r.recoverable)return;if(r.parentAgentId||t.payload.teamRole==="teammate")return;if((e.activeRpcTurnCountBySession.get(n)??0)>0)return;let o=r.error instanceof Error?r.error.message:String(r.error),i=await Nn(e,n);e.publish(e.buildEvent("run.failed",{reason:"error",...o?{error:o,text:o}:{},...i?{snapshot:i}:{}},n))}async function uHe(e,t){let n=e.suppressNextTerminalEventBySession.get(t.payload.sessionId),r=n===t.payload.reason||n==="run.start.reply";if(r)e.suppressNextTerminalEventBySession.delete(t.payload.sessionId);let[o,i]=await Promise.all([kn(e,t.payload.sessionId),Nn(e,t.payload.sessionId)]);if(t.payload.reason==="completed"){let s=await h5(o);e.publish(e.buildEvent("ui.notify",s,t.payload.sessionId))}if(r)return;e.publish(e.buildEvent(t.payload.reason==="aborted"?"run.aborted":t.payload.reason==="error"||t.payload.reason==="failed"?"run.failed":"run.completed",{reason:t.payload.reason,...i?{snapshot:i}:{}},t.payload.sessionId))}import{createSessionId as RX,parseRuntimeConfigExtensions as IX,ReasoningEffortSchema as THe}from"@cerebriline/shared";import{HUB_CHECKPOINT_CAPABILITY as skt,HUB_COMPACTION_CAPABILITY as akt,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as dkt,HUB_HOOK_CAPABILITY_PREFIX as lkt,HUB_MISTAKE_LIMIT_CAPABILITY as ckt,HUB_REASONING_LOOP_LIMIT_CAPABILITY as ukt,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as hkt,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as pkt,isHubToolExecutorName as hHe}from"@cerebriline/shared";import{HUB_CHECKPOINT_CAPABILITY as vkt,HUB_COMPACTION_CAPABILITY as kkt,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Tkt,HUB_HOOK_CAPABILITY_PREFIX as Skt,HUB_MISTAKE_LIMIT_CAPABILITY as xkt,HUB_REASONING_LOOP_LIMIT_CAPABILITY as _kt,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Ekt,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Akt}from"@cerebriline/shared";var pHe=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function td(e){return e&&typeof e==="object"&&!Array.isArray(e)?JSON.parse(JSON.stringify(e)):void 0}function mHe(e,t){let n=typeof e.name==="string"?e.name.trim():"",r=typeof e.description==="string"?e.description:"",o=typeof e.capabilityName==="string"?e.capabilityName.trim():"",i=td(e.inputSchema);if(!n||!r||!i||!o||t.has(o))return;return t.add(o),{kind:"tool",capabilityName:o,name:n,description:r,inputSchema:i,...td(e.lifecycle)?{lifecycle:td(e.lifecycle)}:{}}}function _0(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!r||typeof r!=="object"||Array.isArray(r))continue;let o=r,i=o.kind,s=typeof o.capabilityName==="string"?o.capabilityName.trim():"";if(!s||n.has(s))continue;if(i==="tool"){let a=mHe(o,n);if(a)t.push(a);continue}if(i==="toolExecutor"){let a=o.executor;if(!hHe(a))continue;n.add(s),t.push({kind:"toolExecutor",capabilityName:s,executor:a});continue}if(i==="hook"){let a=typeof o.name==="string"?o.name.trim():"";if(!a)continue;n.add(s),t.push({kind:"hook",capabilityName:s,name:a});continue}if(i==="compaction"){n.add(s),t.push({kind:"compaction",capabilityName:s,...td(o.config)?{config:td(o.config)}:{}});continue}if(i==="checkpoint"){n.add(s),t.push({kind:"checkpoint",capabilityName:s,...td(o.config)?{config:td(o.config)}:{}});continue}if(i==="mistakeLimit"){n.add(s),t.push({kind:"mistakeLimit",capabilityName:s});continue}if(i==="reasoningLoopLimit"){n.add(s),t.push({kind:"reasoningLoopLimit",capabilityName:s});continue}if(i==="userInstructionService")n.add(s),t.push({kind:"userInstructionService",capabilityName:s})}return t}function xX(e){let t=e.metadata?{...e.metadata}:void 0;return{sessionId:e.sessionId,agentId:e.agentId,conversationId:e.conversationId,runId:e.runId,iteration:e.iteration,toolCallId:e.toolCallId,metadata:t&&Object.keys(t).length>0?t:void 0}}function _X(e){return Object.hasOwn(e,"update")?e.update:e}function Um(e){return e.trim().replace(/^\/+/,"").toLowerCase()}function fHe(e){let t=(e??[]).map(Um).filter(Boolean);return t.length>0?new Set(t):void 0}function gHe(e,t,n){if(!n)return!0;let r=Um(e),o=Um(t),i=r.includes(":")?r.split(":").at(-1)??r:r,s=o.includes(":")?o.split(":").at(-1)??o:o;return n.has(r)||n.has(o)||n.has(i)||n.has(s)}function x0(e,t){let n=fHe(t);return e.records.skill.map((r)=>({id:r.id,name:r.item.name,description:"description"in r.item&&typeof r.item.description==="string"?r.item.description:void 0,disabled:r.item.disabled===!0,skill:r.item})).filter((r)=>gHe(r.id,r.name,n))}function SX(e,t){let n=async(r,o)=>{let i=Um(r),a=x0(e,t).filter((l)=>l.id===i||Um(l.name)===i||l.id.endsWith(`:${i}`)).filter((l)=>!l.disabled);if(a.length!==1)return a.length>1?`Skill "${r}" is ambiguous. Use one of: ${a.map((l)=>l.id).join(", ")}`:`Skill "${r}" not found.`;let d=a[0].skill;return wC(d,o)};return Object.defineProperty(n,"configuredSkills",{get:()=>x0(e,t).map(({skill:r,...o})=>o),enumerable:!0}),n}function yHe(e,t,n,r){let o={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},i=async()=>{let s=await r(e,n.capabilityName,{},t);if(s?.snapshot)o=s.snapshot};return{start:i,stop:()=>{},refreshType:async()=>{await i()},listRecords:(s)=>[...o.records[s]],listRuntimeCommands:()=>[...o.runtimeCommands],resolveRuntimeSlashCommand:(s,a)=>{if(!s.startsWith("/")||s.length<2)return s;let l=s.match(/^\/(\S+)/)?.[1];if(!l)return s;let c=ls(l),u=o.runtimeCommands.find((h)=>ls(h.name)===c);if(!u)return s;if(u.kind==="skill"&&a?.expandSkillCommands===!1)return s;return`${u.instructions}${s.slice(l.length+1)}`},hasConfiguredSkills:(s)=>x0(o,s).some((a)=>!a.disabled),createSkillsExecutor:(s)=>SX(o,s),createExtension:(s)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[s.includeRules?"rules":void 0,s.registerSkillsTool?"tools":void 0,s.includeSkills||s.includeWorkflows?"commands":void 0].filter((a)=>Boolean(a))},setup(a){if(s.includeRules)a.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>sv(o.records.rule)});if(s.registerSkillsTool)a.registerTool(Ho(SX(o,s.allowedSkillNames)));for(let d of o.runtimeCommands.filter((l)=>l.kind==="skill"&&s.includeSkills||l.kind==="workflow"&&s.includeWorkflows))a.registerCommand({name:d.name,description:d.description,handler:(l)=>{let c=l.trim();return c?`${d.instructions}
2083
+ WHERE state = 'running';`).run(Date.now());let t=this.db.prepare("SELECT * FROM hub_runs WHERE state = 'queued' ORDER BY accepted_seq;").all().map(Fm);return this.db.prepare("DELETE FROM hub_runs WHERE ended_at IS NOT NULL AND ended_at < ?;").run(Date.now()-iHe),{interrupted:e.map((n)=>({...n,state:"interrupted"})),requeued:t}}close(){if(this.closed)return;this.closed=!0,this.db.close?.()}}function Fm(e){let t={};try{let n=JSON.parse(String(e.input_json));if(n&&typeof n==="object"&&!Array.isArray(n))t=n}catch{}return{runId:String(e.run_id),sessionId:String(e.session_id),state:String(e.state),input:t,clientId:typeof e.client_id==="string"?e.client_id:void 0,acceptedAt:Number(e.accepted_at),startedAt:e.started_at===null?void 0:Number(e.started_at),endedAt:e.ended_at===null?void 0:Number(e.ended_at),error:typeof e.error==="string"?e.error:void 0}}var aHe="hub_draining",dHe=new Set(["session.create","session.restore","session.fork","run.start","session.send_input","run.enqueue"]);function wX(e){return dHe.has(e)}function bX(e){return{version:e.version,requestId:e.requestId,ok:!1,error:{code:aHe,message:"Hub is draining and refuses new mutating work; retry once a hub is serving again.",details:{retryable:!0}}}}class S0{ctx;queue;activeSessions=new Set;constructor(e,t){this.ctx=e;this.queue=t}pump(e){if(this.activeSessions.has(e))return;this.activeSessions.add(e),this.drainSession(e).catch((t)=>{ke("error","run.queue.pump_failed",{sessionId:e,error:t})}).finally(()=>{if(this.activeSessions.delete(e),this.queue.nextQueued(e))this.pump(e)})}async drainSession(e){for(;;){let t=this.queue.nextQueued(e);if(!t)return;this.queue.markRunning(t.runId),await this.execute(t)}}async execute(e){let t={version:"v1",command:"run.start",requestId:e.runId,clientId:e.clientId,sessionId:e.sessionId,payload:{...e.input,sessionId:e.sessionId}};try{let n=await $m(this.ctx,t);if(n.ok){let r=n.payload?.result?.finishReason;this.queue.markTerminal(e.runId,r==="aborted"?"aborted":r==="error"||r==="failed"?"failed":"completed",r==="error"?"Run finished with an error.":void 0)}else this.queue.markTerminal(e.runId,"failed",n.error?.message??"Run failed.")}catch(n){this.queue.markTerminal(e.runId,"failed",n instanceof Error?n.message:String(n))}}}function vX(e,t,n,r){let o=Rt(t);if(!o)return pe(t,"invalid_session_id","run.enqueue requires a sessionId");let i=t.payload&&typeof t.payload==="object"?t.payload:{};if(!(typeof i.prompt==="string"?i.prompt:typeof i.input==="string"?i.input:"").trim())return pe(t,"invalid_session_input","run.enqueue requires a prompt string");let a;try{a=n.admit(o,i,t.clientId?.trim()||void 0)}catch(d){if(d instanceof ek)return{version:t.version,requestId:t.requestId,ok:!1,error:{code:"run_admission_rejected",message:d.message,details:{retryable:!0}}};throw d}return e.publish(e.buildEvent("run.enqueued",{runId:a.runId,acceptedAt:a.acceptedAt,queuePosition:a.queuePosition,...t.clientId?{clientId:t.clientId}:{}},o)),r.pump(o),ie(t,{...a})}function kX(e,t){let n=Rt(e)||void 0,r=typeof e.payload?.limit==="number"&&Number.isFinite(e.payload.limit)&&e.payload.limit>0?Math.floor(e.payload.limit):void 0;return ie(e,{runs:t.list({sessionId:n,limit:r}).map((o)=>({runId:o.runId,sessionId:o.sessionId,state:o.state,acceptedAt:o.acceptedAt,startedAt:o.startedAt,endedAt:o.endedAt,error:o.error}))})}async function TX(e,t){switch(t.type){case"chunk":return;case"agent_event":await lHe(e,t);return;case"hook":if(t.payload.hookEventName==="tool_call")e.publish(e.buildEvent("tool.started",{toolName:t.payload.toolName},t.payload.sessionId));else if(t.payload.hookEventName==="tool_result")e.publish(e.buildEvent("tool.finished",{toolName:t.payload.toolName},t.payload.sessionId));return;case"team_progress":{let n={type:"team_progress_projection",version:1,sessionId:t.payload.sessionId,summary:t.payload.summary,lastEvent:t.payload.lifecycle};e.publish(e.buildEvent("team.progress",n,t.payload.sessionId));return}case"pending_prompts":e.publish(e.buildEvent("session.pending_prompts",{sessionId:t.payload.sessionId,prompts:t.payload.prompts},t.payload.sessionId));return;case"pending_prompt_submitted":{let n={id:t.payload.id,prompt:t.payload.prompt,delivery:t.payload.delivery,attachmentCount:t.payload.attachmentCount,userImages:t.payload.userImages,userFiles:t.payload.userFiles,...t.payload.origin?{origin:t.payload.origin}:{}};e.publish(e.buildEvent("session.pending_prompt_submitted",{sessionId:t.payload.sessionId,prompt:n},t.payload.sessionId));return}case"session_snapshot":e.publish(e.buildEvent("session.updated",{sessionId:t.payload.sessionId,snapshot:t.payload.snapshot},t.payload.sessionId));return;case"status":{let[n,r]=await Promise.all([kn(e,t.payload.sessionId),Nn(e,t.payload.sessionId)]);if(n)e.publish(e.buildEvent("session.updated",{session:n,...r?{snapshot:r}:{}},t.payload.sessionId));return}case"ended":await uHe(e,t);return;default:return}}async function lHe(e,t){let{sessionId:n,event:r}=t.payload;if(r.type==="iteration_start"){e.publish(e.buildEvent("iteration.started",{iteration:r.iteration},n));return}if(r.type==="iteration_end"){e.publish(e.buildEvent("iteration.finished",{iteration:r.iteration,hadToolCalls:r.hadToolCalls,toolCallCount:r.toolCallCount},n));return}if(r.type==="content_start"){if(r.contentType==="text"&&typeof r.text==="string"&&r.text.length>0){e.publish(e.buildEvent("assistant.delta",{text:r.text},n));return}if(r.contentType==="reasoning"){if(r.redacted&&!r.reasoning){e.publish(e.buildEvent("reasoning.delta",{text:"",redacted:!0},n));return}if(typeof r.reasoning==="string"&&r.reasoning.length>0)e.publish(e.buildEvent("reasoning.delta",{text:r.reasoning,redacted:r.redacted===!0},n));return}if(r.contentType==="tool"){e.publish(e.buildEvent("tool.started",{toolCallId:r.toolCallId,toolName:r.toolName,input:r.input},n));return}}if(r.type==="content_update"&&r.contentType==="tool"){e.publish(e.buildEvent("tool.updated",{toolCallId:r.toolCallId,toolName:r.toolName,update:r.update},n));return}if(r.type==="content_end"){switch(r.contentType){case"text":e.publish(e.buildEvent("assistant.finished",{text:r.text},n));break;case"media":if(r.media)e.publish(e.buildEvent("assistant.media",{media:r.media},n));break;case"reasoning":e.publish(e.buildEvent("reasoning.finished",{reasoning:r.reasoning},n));break;case"tool":e.publish(e.buildEvent("tool.finished",{toolCallId:r.toolCallId,toolName:r.toolName,output:r.output,error:r.error},n));break}return}if(r.type==="notice"){e.publish(e.buildEvent("session.notice",{sessionId:n,message:r.message,noticeType:r.noticeType,...r.displayRole?{displayRole:r.displayRole}:{},...r.reason?{reason:r.reason}:{},...r.metadata?{metadata:r.metadata}:{},agent:{kind:t.payload.teamRole==="teammate"?"teammate":r.parentAgentId?"subagent":"lead",agentId:r.agentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamAgentId:t.payload.teamAgentId,teamRole:t.payload.teamRole}},n));return}if(r.type==="usage"){let o;try{o=await e.sessionHost.getAccumulatedUsage?.(n)}catch{o=void 0}e.publish(e.buildEvent("usage.updated",{sessionId:n,delta:{inputTokens:r.inputTokens,outputTokens:r.outputTokens,cacheReadTokens:r.cacheReadTokens??0,cacheWriteTokens:r.cacheWriteTokens??0,reasoningTokenCount:r.reasoningTokenCount,totalCost:r.cost??0,...r.reasoningTokens!==void 0?{reasoningTokens:r.reasoningTokens}:{},...r.timings?{timings:r.timings}:{},...r.outputSplit?{outputSplit:r.outputSplit}:{},...r.auxiliary?{auxiliary:!0}:{}},totals:{inputTokens:r.totalInputTokens,outputTokens:r.totalOutputTokens,cacheReadTokens:r.totalCacheReadTokens??0,cacheWriteTokens:r.totalCacheWriteTokens??0,totalCost:r.totalCost??0},usage:o?.usage,aggregateUsage:o?.aggregateUsage,agent:{kind:t.payload.teamRole==="teammate"?"teammate":r.parentAgentId?"subagent":"lead",agentId:r.agentId,conversationId:r.conversationId,parentAgentId:r.parentAgentId,teamAgentId:t.payload.teamAgentId,teamRole:t.payload.teamRole}},n));return}if(r.type==="done"){e.publish(e.buildEvent("agent.done",{reason:r.reason,text:r.text,iterations:r.iterations,usage:r.usage},n));return}if(r.type==="error")await cHe(e,t)}async function cHe(e,t){let{sessionId:n,event:r}=t.payload;if(r.type!=="error"||r.recoverable)return;if(r.parentAgentId||t.payload.teamRole==="teammate")return;if((e.activeRpcTurnCountBySession.get(n)??0)>0)return;let o=r.error instanceof Error?r.error.message:String(r.error),i=await Nn(e,n);e.publish(e.buildEvent("run.failed",{reason:"error",...o?{error:o,text:o}:{},...i?{snapshot:i}:{}},n))}async function uHe(e,t){let n=e.suppressNextTerminalEventBySession.get(t.payload.sessionId),r=n===t.payload.reason||n==="run.start.reply";if(r)e.suppressNextTerminalEventBySession.delete(t.payload.sessionId);let[o,i]=await Promise.all([kn(e,t.payload.sessionId),Nn(e,t.payload.sessionId)]);if(t.payload.reason==="completed"){let s=await h5(o);e.publish(e.buildEvent("ui.notify",s,t.payload.sessionId))}if(r)return;e.publish(e.buildEvent(t.payload.reason==="aborted"?"run.aborted":t.payload.reason==="error"||t.payload.reason==="failed"?"run.failed":"run.completed",{reason:t.payload.reason,...i?{snapshot:i}:{}},t.payload.sessionId))}import{createSessionId as RX,parseRuntimeConfigExtensions as IX,ReasoningEffortSchema as THe}from"@cerebriline/shared";import{HUB_CHECKPOINT_CAPABILITY as dkt,HUB_COMPACTION_CAPABILITY as lkt,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ckt,HUB_HOOK_CAPABILITY_PREFIX as ukt,HUB_MISTAKE_LIMIT_CAPABILITY as hkt,HUB_REASONING_LOOP_LIMIT_CAPABILITY as pkt,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as mkt,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as fkt,isHubToolExecutorName as hHe}from"@cerebriline/shared";import{HUB_CHECKPOINT_CAPABILITY as Tkt,HUB_COMPACTION_CAPABILITY as Skt,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as xkt,HUB_HOOK_CAPABILITY_PREFIX as _kt,HUB_MISTAKE_LIMIT_CAPABILITY as Ekt,HUB_REASONING_LOOP_LIMIT_CAPABILITY as Akt,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Rkt,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Ikt}from"@cerebriline/shared";var pHe=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function td(e){return e&&typeof e==="object"&&!Array.isArray(e)?JSON.parse(JSON.stringify(e)):void 0}function mHe(e,t){let n=typeof e.name==="string"?e.name.trim():"",r=typeof e.description==="string"?e.description:"",o=typeof e.capabilityName==="string"?e.capabilityName.trim():"",i=td(e.inputSchema);if(!n||!r||!i||!o||t.has(o))return;return t.add(o),{kind:"tool",capabilityName:o,name:n,description:r,inputSchema:i,...td(e.lifecycle)?{lifecycle:td(e.lifecycle)}:{}}}function _0(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e){if(!r||typeof r!=="object"||Array.isArray(r))continue;let o=r,i=o.kind,s=typeof o.capabilityName==="string"?o.capabilityName.trim():"";if(!s||n.has(s))continue;if(i==="tool"){let a=mHe(o,n);if(a)t.push(a);continue}if(i==="toolExecutor"){let a=o.executor;if(!hHe(a))continue;n.add(s),t.push({kind:"toolExecutor",capabilityName:s,executor:a});continue}if(i==="hook"){let a=typeof o.name==="string"?o.name.trim():"";if(!a)continue;n.add(s),t.push({kind:"hook",capabilityName:s,name:a});continue}if(i==="compaction"){n.add(s),t.push({kind:"compaction",capabilityName:s,...td(o.config)?{config:td(o.config)}:{}});continue}if(i==="checkpoint"){n.add(s),t.push({kind:"checkpoint",capabilityName:s,...td(o.config)?{config:td(o.config)}:{}});continue}if(i==="mistakeLimit"){n.add(s),t.push({kind:"mistakeLimit",capabilityName:s});continue}if(i==="reasoningLoopLimit"){n.add(s),t.push({kind:"reasoningLoopLimit",capabilityName:s});continue}if(i==="userInstructionService")n.add(s),t.push({kind:"userInstructionService",capabilityName:s})}return t}function xX(e){let t=e.metadata?{...e.metadata}:void 0;return{sessionId:e.sessionId,agentId:e.agentId,conversationId:e.conversationId,runId:e.runId,iteration:e.iteration,toolCallId:e.toolCallId,metadata:t&&Object.keys(t).length>0?t:void 0}}function _X(e){return Object.hasOwn(e,"update")?e.update:e}function Um(e){return e.trim().replace(/^\/+/,"").toLowerCase()}function fHe(e){let t=(e??[]).map(Um).filter(Boolean);return t.length>0?new Set(t):void 0}function gHe(e,t,n){if(!n)return!0;let r=Um(e),o=Um(t),i=r.includes(":")?r.split(":").at(-1)??r:r,s=o.includes(":")?o.split(":").at(-1)??o:o;return n.has(r)||n.has(o)||n.has(i)||n.has(s)}function x0(e,t){let n=fHe(t);return e.records.skill.map((r)=>({id:r.id,name:r.item.name,description:"description"in r.item&&typeof r.item.description==="string"?r.item.description:void 0,disabled:r.item.disabled===!0,skill:r.item})).filter((r)=>gHe(r.id,r.name,n))}function SX(e,t){let n=async(r,o)=>{let i=Um(r),a=x0(e,t).filter((l)=>l.id===i||Um(l.name)===i||l.id.endsWith(`:${i}`)).filter((l)=>!l.disabled);if(a.length!==1)return a.length>1?`Skill "${r}" is ambiguous. Use one of: ${a.map((l)=>l.id).join(", ")}`:`Skill "${r}" not found.`;let d=a[0].skill;return wC(d,o)};return Object.defineProperty(n,"configuredSkills",{get:()=>x0(e,t).map(({skill:r,...o})=>o),enumerable:!0}),n}function yHe(e,t,n,r){let o={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},i=async()=>{let s=await r(e,n.capabilityName,{},t);if(s?.snapshot)o=s.snapshot};return{start:i,stop:()=>{},refreshType:async()=>{await i()},listRecords:(s)=>[...o.records[s]],listRuntimeCommands:()=>[...o.runtimeCommands],resolveRuntimeSlashCommand:(s,a)=>{if(!s.startsWith("/")||s.length<2)return s;let l=s.match(/^\/(\S+)/)?.[1];if(!l)return s;let c=ls(l),u=o.runtimeCommands.find((h)=>ls(h.name)===c);if(!u)return s;if(u.kind==="skill"&&a?.expandSkillCommands===!1)return s;return`${u.instructions}${s.slice(l.length+1)}`},hasConfiguredSkills:(s)=>x0(o,s).some((a)=>!a.disabled),createSkillsExecutor:(s)=>SX(o,s),createExtension:(s)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[s.includeRules?"rules":void 0,s.registerSkillsTool?"tools":void 0,s.includeSkills||s.includeWorkflows?"commands":void 0].filter((a)=>Boolean(a))},setup(a){if(s.includeRules)a.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>sv(o.records.rule)});if(s.registerSkillsTool)a.registerTool(Ho(SX(o,s.allowedSkillNames)));for(let d of o.runtimeCommands.filter((l)=>l.kind==="skill"&&s.includeSkills||l.kind==="workflow"&&s.includeWorkflows))a.registerCommand({name:d.name,description:d.description,handler:(l)=>{let c=l.trim();return c?`${d.instructions}
2084
2084
 
2085
2085
  ${c}`:d.instructions}})}})}}function wHe(e,t,n,r){let o=n.map((i)=>[i.executor,async(...s)=>{let a=s.at(-1),d=s.slice(0,-1);return(await r(e,i.capabilityName,{executor:i.executor,args:d,context:xX(a)},t,a.emitUpdate?(c)=>{a.emitUpdate?.(_X(c))}:void 0))?.result}]);return o.length>0?Object.fromEntries(o):void 0}function bHe(e,t,n,r){if(n.length===0)return;return n.map((o)=>({name:o.name,description:o.description,inputSchema:o.inputSchema,lifecycle:o.lifecycle,async execute(i,s){return(await r(e,o.capabilityName,{toolName:o.name,input:i,context:xX(s)},t,s.emitUpdate?(d)=>{s.emitUpdate?.(_X(d))}:void 0))?.result}}))}var vHe=new Set(["assistant-text-delta","assistant-reasoning-delta","tool-updated"]);function kHe(e,t,n,r){let o=new Map(n.map((s)=>[s.name,s])),i={};for(let s of pHe){let a=o.get(s);if(!a)continue;i[s]=async(d)=>{if(s==="onEvent"&&vHe.has(d.type))return;return(await r(e,a.capabilityName,{context:d},t))?.control}}return Object.keys(i).length>0?i:void 0}function E0(e){let t=e.contributions.filter((l)=>l.kind==="toolExecutor"),n=e.contributions.filter((l)=>l.kind==="tool"),r=e.contributions.filter((l)=>l.kind==="hook"),o=e.contributions.find((l)=>l.kind==="compaction"),i=e.contributions.find((l)=>l.kind==="checkpoint"),s=e.contributions.find((l)=>l.kind==="mistakeLimit"),a=e.contributions.find((l)=>l.kind==="reasoningLoopLimit"),d=e.contributions.find((l)=>l.kind==="userInstructionService");return{hasClientContributions:e.contributions.length>0,toolExecutors:wHe(e.sessionId,e.targetClientId,t,e.requestCapability),localRuntime:{...r.length>0?{hooks:kHe(e.sessionId,e.targetClientId,r,e.requestCapability)}:{},...n.length>0?{extraTools:bHe(e.sessionId,e.targetClientId,n,e.requestCapability)}:{},...o?{compaction:{...e.sessionConfig?.compaction??{},...o.config,compact:async(l)=>(await e.requestCapability(e.sessionId,o.capabilityName,{context:l},e.targetClientId))?.result}}:{},...i?{checkpoint:{...e.sessionConfig?.checkpoint??{},...i.config,createCheckpoint:async(l)=>(await e.requestCapability(e.sessionId,i.capabilityName,{context:l},e.targetClientId))?.result}}:{},...s?{onConsecutiveMistakeLimitReached:async(l)=>(await e.requestCapability(e.sessionId,s.capabilityName,{context:l},e.targetClientId))?.result}:{},...a?{onReasoningLoopLimitReached:async(l)=>(await e.requestCapability(e.sessionId,a.capabilityName,{context:l},e.targetClientId))?.result}:{},...d?{userInstructionService:yHe(e.sessionId,e.targetClientId,d,e.requestCapability)}:{}}}}var EX="hubCapabilityOwnerClientId";function nd(e,t){let n=e?.[t];return typeof n==="string"&&n.trim()?n.trim():void 0}function CX(e){let t=No(e),n=typeof t?.name==="string"?t.name.trim():"";if(!n)return;let r=nd(t,"version"),o=nd(t,"platform"),i=nd(t,"platformVersion");return{name:n,...r?{version:r}:{},...o?{platform:o}:{},...i?{platformVersion:i}:{},...typeof t?.isMultiRoot==="boolean"?{isMultiRoot:t.isMultiRoot}:{}}}function PX(e){let t=No(e),n=nd(t,"distinctId"),o=t?.accountId===null?null:nd(t,"accountId"),i=nd(t,"email"),s=nd(t,"organizationId");if(!n&&o===void 0&&!i&&!s)return;return{...n?{distinctId:n}:{},...o!==void 0?{accountId:o}:{},...i?{email:i}:{},...s?{organizationId:s}:{}}}async function MX(e,t){let n=await e.sessionHost.deleteSession(t);e.sessionState.delete(t);try{e.sessionSearch.removeSession(t)}catch(r){ke("warn","session search eviction failed",{error:r,sessionId:t})}return n}function OX(e,t,n){let r=ZA(n);return e.filter((o)=>(t!=="yolo"||o.name!==Xv)&&eR(o.name,r))}function tk(e){return typeof e==="string"&&e.trim().length>0?e.trim():void 0}function SHe(e){if(e===null)return null;let t=THe.safeParse(e);return t.success?t.data:void 0}function xHe(e){let t=No(e)??{},n={},r=tk(t.providerId);if(r)n.providerId=r;let o=tk(t.modelId);if(o)n.modelId=o;let i=tk(t.apiKey);if(i!==void 0)n.apiKey=i;let s=tk(t.baseUrl);if(s!==void 0)n.baseUrl=s;if(t.headers&&typeof t.headers==="object")n.headers=t.headers;if(t.providerConfig&&typeof t.providerConfig==="object")n.providerConfig=t.providerConfig;if(Object.hasOwn(t,"thinking")){if(typeof t.thinking==="boolean"||t.thinking===null)n.thinking=t.thinking}if(Object.hasOwn(t,"reasoningEffort")){let a=SHe(t.reasoningEffort);if(a!==void 0)n.reasoningEffort=a}if(Object.hasOwn(t,"thinkingBudgetTokens")){if(typeof t.thinkingBudgetTokens==="number"&&Number.isFinite(t.thinkingBudgetTokens)&&t.thinkingBudgetTokens>0)n.thinkingBudgetTokens=Math.trunc(t.thinkingBudgetTokens);else if(t.thinkingBudgetTokens===null)n.thinkingBudgetTokens=null}return rc(n)}function _He(e,t){return e.sessionState.get(t)?.createdByClientId}function AX(e){return typeof e==="string"||e===null?e:void 0}function EHe(e){if(!e||!("autoApproveTools"in e)&&!(EX in e))return e;let t={...e};return delete t[EX],delete t.autoApproveTools,t}function LX(e,t){let n=No(e),r=No(n?.["*"]);if(typeof r?.autoApprove==="boolean")return r.autoApprove;return t.autoApproveTools===!0}function NX(e){let t=_He(e.ctx,e.sessionId);if(!t)return pe(e.envelope,"session_wrong_client",`Session ${e.sessionId} has no owner`);if(t!==e.clientId)return pe(e.envelope,"session_wrong_client",`Session ${e.sessionId} is owned by ${t}`);return}async function A0(e,t,n){let r=performance.now(),o={command:t.command,requestId:t.requestId,clientId:t.clientId,sessionId:t.sessionId};ke("info","session.create.begin",o);let i=t.payload&&typeof t.payload==="object"?t.payload:{},s=i.metadata&&typeof i.metadata==="object"?JSON.parse(JSON.stringify(i.metadata)):{},a=i.sessionConfig&&typeof i.sessionConfig==="object"?JSON.parse(JSON.stringify(i.sessionConfig)):void 0,d=i.runtimeOptions&&typeof i.runtimeOptions==="object"?i.runtimeOptions:{},l=CX(d.clientContext),c=PX(d.userContext),u=Ed(i.initialCompactionState);if(typeof a?.mode==="string")s.mode=a.mode;else if(typeof d.mode==="string")s.mode=d.mode;if(typeof a?.systemPrompt==="string")s.systemPrompt=a.systemPrompt;else if(typeof d.systemPrompt==="string")s.systemPrompt=d.systemPrompt;if((a?.checkpoint?.enabled??d.checkpointEnabled)!==!1)s.checkpointEnabled=!0;s.autoApproveTools=LX(i.toolPolicies,d);let h=i.modelSelection&&typeof i.modelSelection==="object"?i.modelSelection:{},p=typeof i.workspaceRoot==="string"&&i.workspaceRoot.trim()?i.workspaceRoot.trim():typeof i.cwd==="string"&&i.cwd.trim()?i.cwd.trim():void 0,f=t.clientId?.trim()||"hub-client",m=_0(d.clientContributions);ke("info","session.create.contributions_parsed",{...o,clientId:f,workspaceRoot:p,cwd:typeof i.cwd==="string"?i.cwd:void 0,contributionCount:m.length});let y=(typeof a?.sessionId==="string"?a.sessionId.trim():"")||RX(),w=IX(d.configExtensions);ke("info","session.create.runtime_build.begin",{...o,sessionId:y,configExtensionCount:w?.length??0});let k=E0({sessionId:y,targetClientId:f,contributions:m,sessionConfig:a,requestCapability:e.requestCapability});ke("info","session.create.start_session.begin",{...o,sessionId:y,provider:a?.providerId??(typeof h.provider==="string"?h.provider:typeof s.provider==="string"?s.provider:"hub"),model:a?.modelId??(typeof h.model==="string"?h.model:typeof s.model==="string"?s.model:"hub")});let b=a?.mode??(d.mode==="plan"||d.mode==="yolo"?d.mode:"act"),v=await e.sessionHost.startSession({source:typeof s.source==="string"?s.source:void 0,interactive:s.interactive!==!1,sessionMetadata:Object.keys(s).length>0?s:void 0,initialMessages:Array.isArray(i.initialMessages)?i.initialMessages:void 0,initialCompactionState:u,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:w,...k.localRuntime,...l||c?{extensionContext:{...k.localRuntime.extensionContext,...l?{client:l}:{},...c?{user:c}:{}}}:{},extensions:[...e.sessionExtensions??[],...k.localRuntime.extensions??[]],extraTools:OX([...e.sessionTools??[],...k.localRuntime.extraTools??[]],b,typeof s.source==="string"?s.source:void 0)},capabilities:{toolExecutors:k.toolExecutors,requestToolApproval:n},config:{...a??{},sessionId:y,providerId:a?.providerId??(typeof h.provider==="string"?h.provider:typeof s.provider==="string"?s.provider:"hub"),modelId:a?.modelId??(typeof h.model==="string"?h.model:typeof s.model==="string"?s.model:"hub"),apiKey:a?.apiKey??(typeof h.apiKey==="string"?h.apiKey:void 0),cwd:a?.cwd??(typeof i.cwd==="string"&&i.cwd.trim()?i.cwd.trim():p),workspaceRoot:a?.workspaceRoot??p,systemPrompt:a?.systemPrompt??(typeof d.systemPrompt==="string"?d.systemPrompt:""),mode:b,maxIterations:a?.maxIterations??(typeof d.maxIterations==="number"?d.maxIterations:void 0),enableTools:a?.enableTools??d.enableTools!==!1,enableSpawnAgent:a?.enableSpawnAgent??d.enableSpawn!==!1,enableAgentTeams:a?.enableAgentTeams??d.enableTeams===!0,checkpoint:a?.checkpoint??{enabled:d.checkpointEnabled!==!1},teamName:a?.teamName??(typeof s.teamName==="string"?s.teamName:void 0)},toolPolicies:i.toolPolicies&&typeof i.toolPolicies==="object"&&!Array.isArray(i.toolPolicies)?JSON.parse(JSON.stringify(i.toolPolicies)):d.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});ke("info","session.create.start_session.end",{...o,sessionId:v.sessionId,elapsedMs:Math.round(performance.now()-r),hasImmediateResult:!!v.result}),g0(e,v.sessionId,f,"creator",{interactive:s.interactive!==!1}),ke("info","session.create.read_records.begin",{...o,sessionId:v.sessionId});let[E,S]=await Promise.all([kn(e,v.sessionId),Nn(e,v.sessionId)]);if(ke("info","session.create.read_records.end",{...o,sessionId:v.sessionId,hasSession:!!E,hasSnapshot:!!S,elapsedMs:Math.round(performance.now()-r)}),E)e.publish(e.buildEvent("session.created",{session:E,...S?{snapshot:S}:{}},v.sessionId));return ke("info","session.create.reply",{...o,sessionId:v.sessionId,elapsedMs:Math.round(performance.now()-r)}),ie(t,{session:E,...S?{snapshot:S}:{}})}async function DX(e,t,n){let r=t.payload&&typeof t.payload==="object"?t.payload:{},o=typeof r.sessionId==="string"?r.sessionId.trim():t.sessionId?.trim()||"",i=r.checkpointRunCount;if(!o)return pe(t,"invalid_restore","session.restore requires a session id");let s=r.restore&&typeof r.restore==="object"?r.restore:{},a=s.messages!==!1;if(typeof i!=="number")return pe(t,"invalid_restore","checkpointRunCount must be a positive integer");try{let d=r.sessionConfig&&typeof r.sessionConfig==="object"?JSON.parse(JSON.stringify(r.sessionConfig)):void 0;if(a&&!d)return pe(t,"invalid_restore","sessionConfig is required when restore.messages is true");let l=r.runtimeOptions&&typeof r.runtimeOptions==="object"?r.runtimeOptions:{},c=CX(l.clientContext),u=PX(l.userContext),h=Ed(r.initialCompactionState),p=r.metadata&&typeof r.metadata==="object"?JSON.parse(JSON.stringify(r.metadata)):{};if(typeof d?.mode==="string")p.mode=d.mode;else if(typeof l.mode==="string")p.mode=l.mode;if(typeof d?.systemPrompt==="string")p.systemPrompt=d.systemPrompt;else if(typeof l.systemPrompt==="string")p.systemPrompt=l.systemPrompt;if((d?.checkpoint?.enabled??l.checkpointEnabled)!==!1)p.checkpointEnabled=!0;p.autoApproveTools=LX(r.toolPolicies,l);let f=r.modelSelection&&typeof r.modelSelection==="object"?r.modelSelection:{},m=t.clientId?.trim()||"hub-client",g=_0(l.clientContributions),w=(typeof d?.sessionId==="string"?d.sessionId.trim():"")||RX(),k=IX(l.configExtensions),b=E0({sessionId:w,targetClientId:m,contributions:g,sessionConfig:d,requestCapability:e.requestCapability}),E=await new Dp().restoreCheckpoint({sessionId:o,checkpointRunCount:i,telemetry:e.telemetry,restore:{messages:s.messages,workspace:s.workspace,omitCheckpointMessageFromSession:s.omitCheckpointMessageFromSession===!0},start:d,cwd:typeof d?.cwd==="string"&&d.cwd.trim()||typeof d?.workspaceRoot==="string"&&d.workspaceRoot.trim()||void 0,getSession:(A)=>e.sessionHost.getSession(A),readMessages:(A)=>e.sessionHost.readSessionMessages(A),buildStartInput:(A)=>{if(A.restoredCheckpointMetadata)p.checkpoint=A.restoredCheckpointMetadata;let R=typeof r.workspaceRoot==="string"&&r.workspaceRoot.trim()?r.workspaceRoot.trim():typeof r.cwd==="string"&&r.cwd.trim()?r.cwd.trim():A.sourceSession.workspaceRoot||A.sourceSession.cwd,C=d?.mode??(l.mode==="plan"||l.mode==="yolo"?l.mode:"act");return{source:typeof p.source==="string"?p.source:void 0,interactive:p.interactive!==!1,sessionMetadata:{...p,restoredFromSessionId:o,restoredCheckpointRunCount:i},initialMessages:A.initialMessages,initialCompactionState:h,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:k,...b.localRuntime,...c||u?{extensionContext:{...b.localRuntime.extensionContext,...c?{client:c}:{},...u?{user:u}:{}}}:{},extensions:[...e.sessionExtensions??[],...b.localRuntime.extensions??[]],extraTools:OX([...e.sessionTools??[],...b.localRuntime.extraTools??[]],C,typeof p.source==="string"?p.source:void 0)},capabilities:{toolExecutors:b.toolExecutors,requestToolApproval:n},config:{...d??{},sessionId:w,providerId:d?.providerId??(typeof f.provider==="string"?f.provider:A.sourceSession.provider),modelId:d?.modelId??(typeof f.model==="string"?f.model:A.sourceSession.model),apiKey:d?.apiKey??(typeof f.apiKey==="string"?f.apiKey:""),cwd:d?.cwd??A.plan.cwd,workspaceRoot:d?.workspaceRoot??R,systemPrompt:d?.systemPrompt??(typeof l.systemPrompt==="string"?l.systemPrompt:""),mode:C,maxIterations:d?.maxIterations??(typeof l.maxIterations==="number"?l.maxIterations:void 0),enableTools:d?.enableTools??l.enableTools!==!1,enableSpawnAgent:d?.enableSpawnAgent??l.enableSpawn!==!1,enableAgentTeams:d?.enableAgentTeams??l.enableTeams===!0,checkpoint:d?.checkpoint??{enabled:l.checkpointEnabled!==!1},teamName:d?.teamName??(typeof p.teamName==="string"?p.teamName:void 0)},toolPolicies:r.toolPolicies&&typeof r.toolPolicies==="object"&&!Array.isArray(r.toolPolicies)?JSON.parse(JSON.stringify(r.toolPolicies)):l.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(A)=>e.sessionHost.startSession(A),getStartedSessionId:(A)=>A.sessionId,cleanupStartedSession:async(A)=>{if(!await MX(e,A.sessionId))throw Error(`Failed to clean up restored session ${A.sessionId}`)},readRestoredSession:(A)=>e.sessionHost.getSession(A)});if(!a)return ie(t,{checkpoint:E.checkpoint});let S=E.startResult;if(!S)return pe(t,"restore_failed","Checkpoint restore did not start a session");g0(e,S.sessionId,m,"creator",{interactive:p.interactive!==!1});let[x,T]=await Promise.all([kn(e,S.sessionId),Nn(e,S.sessionId)]);if(x)e.publish(e.buildEvent("session.created",{session:x,...T?{snapshot:T}:{}},S.sessionId));return ie(t,{session:x,...T?{snapshot:T}:{},messages:E.messages??[],checkpoint:E.checkpoint})}catch(d){if(d instanceof Fr)return pe(t,d.code,d.code==="session_not_found"?`Unknown session: ${o}`:d.message);return pe(t,"restore_failed",d instanceof Error?d.message:String(d))}}async function $X(e,t){let n=Rt(t);if(!n)return pe(t,"invalid_session_attach","session.attach requires a session id");let r=await kn(e,n);if(!r)return pe(t,"session_not_found",`Unknown session: ${n}`);ZY(e,n,t.clientId?.trim()||"hub-client","participant");let o=await kn(e,n);return e.publish(e.buildEvent("session.attached",{session:o??r},n)),ie(t,{session:o??r})}async function FX(e,t){let n=Rt(t);if(!n)return pe(t,"invalid_session_detach","session.detach requires a session id");let r=t.clientId?.trim()||"hub-client",o=e.sessionState.get(n);if(o){if(o.participants.delete(r),o.createdByClientId===r)o.createdByClientId=void 0;if(o.participants.size===0)e.sessionState.delete(n)}fs(e,(a)=>a.sessionId===n&&a.targetClientId===r,`Capability owner client ${r} detached before request was resolved.`);let[i,s]=await Promise.all([kn(e,n),Nn(e,n)]);return e.publish(e.buildEvent("session.detached",i?{session:i,...s?{snapshot:s}:{},clientId:r}:{clientId:r},n)),ie(t)}async function UX(e,t){let n=Rt(t),r=t.payload?.includeSnapshot===!0,[o,i]=await Promise.all([kn(e,n),r?Nn(e,n):Promise.resolve(void 0)]);return o?ie(t,{session:o,...i?{snapshot:i}:{}}):pe(t,"session_not_found",`Unknown session: ${n}`)}async function BX(e,t){let n=Rt(t);if(!n)return pe(t,"invalid_session_id","session.messages requires a session id");if(!await kn(e,n))return pe(t,"session_not_found",`Unknown session: ${n}`);let o=await e.sessionHost.readSessionMessages(n);return ie(t,{sessionId:n,messages:o})}async function HX(e,t){let n=Rt(t);if(!n)return pe(t,"invalid_session_id","session.compaction.get requires a session id");if(!await kn(e,n))return pe(t,"session_not_found",`Unknown session: ${n}`);let o=t.clientId?.trim()||"hub-client",i=NX({sessionId:n,ctx:e,clientId:o,envelope:t});if(i)return i;let s=await e.sessionHost.readSessionCompactionState(n);return ie(t,{sessionId:n,state:s})}async function WX(e,t){let n=typeof t.payload?.limit==="number"?t.payload.limit:200,o=(await e.sessionHost.listSessions(n,{rootOnly:t.payload?.rootOnly===!0})).map((i)=>Jv(i,e.sessionState.get(i.sessionId)));return ie(t,{sessions:o})}async function jX(e,t){let n=t.payload??{};if(typeof n.query!=="string"||!n.query.trim())return pe(t,"invalid_search_query","session.search requires a non-empty query");return ie(t,{hits:e.sessionSearch.search({query:n.query,limit:n.limit,workspaceRoot:n.workspaceRoot})})}async function qX(e,t){let n=Rt(t),r=EHe(No(t.payload?.metadata)),o=AX(t.payload?.prompt),i=AX(t.payload?.title),s=await e.sessionHost.updateSession(n,{metadata:r,...o!==void 0?{prompt:o}:{},...i!==void 0?{title:i}:{}}),[a,d]=await Promise.all([kn(e,n),Nn(e,n)]);if(a)e.publish(e.buildEvent("session.updated",{session:a,...d?{snapshot:d}:{}},n));return{version:t.version,requestId:t.requestId,ok:s.updated,payload:{updated:s.updated,session:a,...d?{snapshot:d}:{}}}}async function zX(e,t){let n=Rt(t);if(!n)return pe(t,"invalid_session_update_connection","session.update_connection requires a session id");let r=e.sessionHost.updateSessionConnection;if(!r)return pe(t,"unsupported_session_update_connection","runtime host does not support session connection updates");let o=No(t.payload),i=xHe(o?.updates);return await r.call(e.sessionHost,n,i),ie(t,{sessionId:n,updated:!0})}async function KX(e,t){let n=Rt(t);if(!n)return pe(t,"invalid_session_id","session.compaction.update requires a session id");let r=t.clientId?.trim()||"hub-client",o=await kn(e,n);if(!o)return pe(t,"session_not_found",`Unknown session: ${n}`);let i=NX({sessionId:n,ctx:e,clientId:r,envelope:t});if(i)return i;let s=t.payload&&typeof t.payload==="object"?t.payload:{},a=Ed(s.state);if(!a)return pe(t,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let d=await e.sessionHost.updateSessionCompactionState(n,a),[l,c]=d.updated?await Promise.all([kn(e,n),Nn(e,n)]):[o,void 0];if(d.updated)e.publish(e.buildEvent("session.updated",{session:l??o,...c?{snapshot:c}:{}},n));return{version:t.version,requestId:t.requestId,ok:!0,payload:{updated:d.updated,session:l??o,...c?{snapshot:c}:{}}}}async function GX(e,t){let n=Rt(t),r=await MX(e,n);return ie(t,{deleted:r})}async function VX(e,t){let n=Rt(t),r=e.sessionHost.pendingPrompts;if(!r)return pe(t,"pending_prompts_unavailable","Pending prompt service is not available.");let o=await r.list({sessionId:n});return ie(t,{sessionId:n,prompts:o})}async function YX(e,t){let n=Rt(t),r=e.sessionHost.pendingPrompts;if(!r)return pe(t,"pending_prompts_unavailable","Pending prompt service is not available.");let o=await r.steerFirst({sessionId:n});return ie(t,o)}async function XX(e,t){let n=Rt(t),r=typeof t.payload?.promptId==="string"?t.payload.promptId.trim():"",o=typeof t.payload?.prompt==="string"?t.payload.prompt:void 0,i=t.payload?.delivery==="queue"||t.payload?.delivery==="steer"?t.payload.delivery:void 0,s=e.sessionHost.pendingPrompts;if(!s)return pe(t,"pending_prompts_unavailable","Pending prompt service is not available.");let a=await s.update({sessionId:n,promptId:r,prompt:o,delivery:i});return ie(t,a)}async function JX(e,t){let n=Rt(t),r=typeof t.payload?.promptId==="string"?t.payload.promptId.trim():"",o=e.sessionHost.pendingPrompts;if(!o)return pe(t,"pending_prompts_unavailable","Pending prompt service is not available.");let i=await o.delete({sessionId:n,promptId:r});return ie(t,i)}import{join as AHe}from"node:path";import{loadSqliteDb as RHe}from"@cerebriline/shared/db";import{resolveDbDataDir as IHe}from"@cerebriline/shared/storage";var CHe=604800000,PHe=200000,MHe=67108864,OHe=16777216;function LHe(e){let t=e?.replace(/[^a-zA-Z0-9_-]/g,"-");return AHe(IHe(),t?`hub-events-${t}.db`:"hub-events.db")}class R0{db;retentionMs;maxRows;maxTotalBytes;appendedBytesSincePrune=0;closed=!1;constructor(e={}){this.db=RHe(e.dbPath??LHe(e.ownerId)),this.retentionMs=e.retentionMs??CHe,this.maxRows=e.maxRows??PHe,this.maxTotalBytes=e.maxTotalBytes??MHe,this.db.exec("PRAGMA journal_mode = WAL;"),this.db.exec("PRAGMA synchronous = NORMAL;"),this.db.exec("PRAGMA busy_timeout = 5000;"),this.db.exec(`
2086
2086
  CREATE TABLE IF NOT EXISTS hub_events (
@@ -2118,7 +2118,7 @@ Title: ${t.title}
2118
2118
  Type: ${t.type}
2119
2119
  Priority: P${t.priority}${o}
2120
2120
 
2121
- ${t.instructions}${r}`,s=await $m(this.ctx,{version:"v1",command:"run.start",requestId:P0("task_run_"),clientId:n.requestedByClientId??"agenda-task-manager",sessionId:e,payload:{sessionId:e,input:i,mode:t.mode??"act",timeoutSeconds:t.timeoutSeconds}});if(!s.ok)return{status:"failed",error:s.error?.message??"task session run failed"};let a=s.payload?.result,d=typeof a?.finishReason==="string"?a.finishReason:void 0,l=typeof a?.text==="string"&&a.text.trim()?a.text.trim():void 0;if(d==="completed")return{status:"completed",summary:l};if(d==="aborted")return{status:"cancelled",summary:l};return{status:"failed",summary:l,error:l??(d?`Task session ended with ${d}`:"Task session did not return a completion result")}}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(this.sessionSearch.start(),await this.tasks.start(),await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(e){console.error("[hub] cron service start failed",e)}this.startEventLog(),this.startRunQueue()}startEventLog(){if(this.options.eventLog===!1||this.eventLog)return;try{let e=new R0({ownerId:this.options.owner?.ownerId,...this.options.eventLog??{}});e.prune(),this.eventLog=e,this.eventLogPruneTimer=setInterval(()=>{try{e.prune()}catch{}},3600000),this.eventLogPruneTimer.unref?.()}catch(e){ke("error","event_log.start_failed",{error:e})}}startRunQueue(){if(this.options.runQueue===!1||this.runQueue)return;try{this.runQueue=new T0({ownerId:this.options.owner?.ownerId,...this.options.runQueue??{}}),this.runExecutor=new S0(this.ctx,this.runQueue);let e=this.runQueue.recoverOnStartup();for(let n of e.interrupted)this.publish(Kr("run.interrupted",{runId:n.runId,error:n.error,reason:"hub_restart"},n.sessionId));let t=new Set(e.requeued.map((n)=>n.sessionId));for(let n of t)this.runExecutor.pump(n);if(e.interrupted.length>0||e.requeued.length>0)ke("info","run.queue.recovered",{interrupted:e.interrupted.length,requeued:e.requeued.length})}catch(e){ke("error","run.queue.start_failed",{error:e})}}async stop(){if(this.eventLogPruneTimer)clearInterval(this.eventLogPruneTimer),this.eventLogPruneTimer=void 0;for(let e of this.pendingApprovals.keys())y0(this.ctx,e,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(fs(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionSearch.dispose(),await this.tasks.dispose(),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(e){console.error("[hub] cron service stop failed",e)}this.eventLog?.close(),this.eventLog=void 0,this.runQueue?.close(),this.runQueue=void 0,this.runExecutor=void 0}async handleCommand(e,t){try{let n=e.clientId?.trim(),r=t===void 0?this.options.workspaceRoot?.trim()&&n?{clientId:n,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.workspaceRoot}}:void 0:t??void 0,o=await this.dispatchCommand(e,r);return this.captureFailedReply(e,o),o}catch(n){throw rk(this.options.telemetry,{component:"core",operation:"hub.command",error:n,severity:"error",handled:!1,context:this.commandTelemetryContext(e)}),n}}async dispatchCommand(e,t){if(this.draining&&wX(e.command))return bX(e);if(eJ(e.command))return await this.taskCommands.handleCommand(e,t);switch(e.command){case"client.register":{let n=aX(this.ctx,e);return this.tasks.notifyAutomationReadinessChanged(),n}case"client.update":{let n=dX(this.ctx,e);return this.tasks.notifyAutomationReadinessChanged(),n}case"client.unregister":{let n=lX(this.ctx,e,(r)=>{this.listeners.delete(r),this.detachClientFromSessions(r)});return this.tasks.notifyAutomationReadinessChanged(),n}case"client.list":return cX(this.ctx,e);case"session.create":return await A0(this.ctx,e,(n)=>Qv(this.ctx,n));case"session.restore":return await DX(this.ctx,e,(n)=>Qv(this.ctx,n));case"session.attach":return await $X(this.ctx,e);case"session.detach":return await FX(this.ctx,e);case"session.get":return await UX(this.ctx,e);case"session.messages":return await BX(this.ctx,e);case"session.compaction.get":return await HX(this.ctx,e);case"session.list":return await WX(this.ctx,e);case"session.search":return await jX(this.ctx,e);case"session.update":return await qX(this.ctx,e);case"session.update_connection":return await zX(this.ctx,e);case"session.compaction.update":return await KX(this.ctx,e);case"session.pending_prompts":return await VX(this.ctx,e);case"session.steer_first_pending_prompt":return await YX(this.ctx,e);case"session.update_pending_prompt":return await XX(this.ctx,e);case"session.remove_pending_prompt":return await JX(this.ctx,e);case"session.delete":return await GX(this.ctx,e);case"session.hook":return await yX(this.ctx,e);case"run.start":case"session.send_input":return await $m(this.ctx,e);case"run.enqueue":{if(!this.runQueue||!this.runExecutor)return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"run_queue_unavailable",message:"This hub has no durable run queue; use run.start instead."}};return vX(this.ctx,e,this.runQueue,this.runExecutor)}case"run.list":{if(!this.runQueue)return ie(e,{runs:[]});return kX(e,this.runQueue)}case"hub.drain":return this.handleHubDrain(e);case"hub.status":return this.handleHubStatus(e);case"run.abort":return await fX(this.ctx,e);case"run.proceed_while_running":return await gX(this.ctx,e);case"capability.request":return await iX(this.ctx,e);case"approval.respond":return await tX(this.ctx,e);case"capability.respond":return sX(this.ctx,e);case"capability.progress":return oX(this.ctx,e);case"ui.notify":return this.publish(Kr("ui.notify",e.payload??{})),ie(e);case"ui.show_window":return this.publish(Kr("ui.show_window",e.payload??{})),ie(e);case"settings.list":return await this.handleSettingsList(e);case"settings.toggle":return await this.handleSettingsToggle(e);case"connector.channels":case"connector.configure":case"connector.delete_config":case"connector.start":case"connector.stop":case"connector.supervised":return await pX(this.ctx,e);case"settings.get":case"settings.patch":return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"not_implemented",message:`${e.command} is not implemented yet.`}};default:{let n=await this.scheduleCommands.handleCommand(e,t);if(n.ok){let r=QX(e.command);if(r)this.publish(Kr(r,n.payload))}return n}}}captureFailedReply(e,t){if(t.ok||!t.error||!qHe(t.error.code))return;rk(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(t.error.message),severity:t.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext(e),errorCode:t.error.code}})}commandTelemetryContext(e){return{command:e.command,requestId:e.requestId,clientId:e.clientId,sessionId:typeof e.payload?.sessionId==="string"?e.payload.sessionId:e.sessionId}}async handleSettingsList(e){try{let t=await this.settings.list(nJ(e.payload));return{version:e.version,requestId:e.requestId,ok:!0,payload:{snapshot:t}}}catch(t){return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"settings_list_failed",message:t instanceof Error?t.message:String(t)}}}}async handleSettingsToggle(e){try{let t=await this.settings.toggle(jHe(e.payload));return this.publish(Kr("settings.changed",{types:t.changedTypes,snapshot:t.snapshot})),{version:e.version,requestId:e.requestId,ok:!0,payload:{snapshot:t.snapshot,changedTypes:t.changedTypes}}}catch(t){return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"settings_toggle_failed",message:t instanceof Error?t.message:String(t)}}}}handleHubDrain(e){let t=e.payload?.draining!==!1,n=typeof e.payload?.reason==="string"?e.payload.reason:void 0;if(this.draining!==t)this.draining=t,this.publish(Kr("hub.drain_changed",{draining:this.draining,...n?{reason:n}:{}})),ke("info","hub.drain_changed",{draining:this.draining,reason:n});return ie(e,this.describeStatus())}handleHubStatus(e){return ie(e,this.describeStatus())}describeStatus(){let e=0;for(let t of this.activeRpcTurnCountBySession.values())e+=t;return{hubId:this.hubId,draining:this.draining,activeRpcTurns:e,pendingRuns:this.runQueue?.countPending()??0,eventLog:this.eventLog?{lastSequence:this.eventLog.lastSequence()}:void 0,idle:e===0&&(this.runQueue?.countPending()??0)===0}}isDraining(){return this.draining}replayEventsAfter(e,t){if(!this.eventLog)return[];return this.eventLog.listAfter(e,{sessionId:t.sessionId},t.limit)}lastEventSequence(){return this.eventLog?.lastSequence()??0}subscribe(e,t,n){let r=this.listeners.get(e)??new Set,o={sessionId:n?.sessionId,listener:t};r.add(o),this.listeners.set(e,r);let i=eX(this.ctx,n?.sessionId);if(i.length>0)queueMicrotask(()=>{if(!this.listeners.get(e)?.has(o))return;for(let a of i)try{o.listener(a)}catch(d){Za("listener threw while re-issuing pending approval",d)}});return()=>{let s=this.listeners.get(e);if(!s)return;if(s.delete(o),s.size===0)this.listeners.delete(e)}}detachClientFromSessions(e){for(let[t,n]of this.sessionState.entries()){if(n.participants.delete(e),n.createdByClientId===e)n.createdByClientId=void 0;if(n.participants.size===0)this.sessionState.delete(t)}fs(this.ctx,(t)=>t.targetClientId===e,`Capability owner client ${e} disconnected before request was resolved.`)}publish(e){if(this.eventLog)try{e=this.eventLog.append(e)}catch(t){Za(`event log append failed for ${e.event}`,t)}for(let t of this.listeners.values())for(let n of t){if(n.sessionId&&n.sessionId!==e.sessionId)continue;try{n.listener(e)}catch(r){Za(`listener threw while publishing ${e.event}`,r),rk(this.options.telemetry,{component:"core",operation:"hub.publish",error:r,severity:"warn",handled:!0,context:{event:e.event,sessionId:e.sessionId}})}}}}function qHe(e){return e==="session_not_found"||e==="session_messages_not_found"||e==="hub_command_timeout"||e.endsWith("_failed")}import{timingSafeEqual as oWe}from"node:crypto";import iWe from"node:http";import{URL as B0}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as $0,HUB_CAPABILITIES as sWe,MAX_CLIENT_HUB_PROTOCOL_VERSION as sJ,MIN_CLIENT_HUB_PROTOCOL_VERSION as aJ}from"@cerebriline/shared";import{WebSocketServer as aWe}from"ws";import{createSessionId as jTt,ensureLoopbackProxyBypass as qTt,isHubProtocolCompatible as zTt,resolveClineBuildEnv as KTt,resolveHubCommandTimeoutMs as GTt}from"@cerebriline/shared";import YTt from"ws";import{CLINE_RUN_AS_HUB_DAEMON_ENV as ATt,isBunEmbeddedModulePath as RTt,isHubDaemonProcess as ITt,resolveClineBuildEnv as CTt,withResolvedClineBuildEnv as PTt}from"@cerebriline/shared";import{isAbsolute as YHe,relative as XHe,resolve as O0,sep as JHe}from"node:path";import{captureSdkError as iJ,HUB_COMMAND_SLOW_LOG_MS as QHe,resolveHubCommandTimeoutMs as ZHe,safeJsonParse as eWe}from"@cerebriline/shared";var tWe=200,nWe=1000;function L0(e){return{command:e.envelope.command,requestId:e.envelope.requestId,clientId:e.envelope.clientId,sessionId:e.envelope.sessionId}}function Hm(e,t,n){return{version:e.envelope.version,requestId:e.envelope.requestId,ok:!1,error:{code:t,message:n}}}function rWe(e,t,n=!1){let r=e.envelope.payload??{},o=e.envelope.clientId?.trim(),i=r.clientId?.trim()||o;if(!i||o&&i!==o)throw Error("Registration clientId must match the command connection");let s=r.workspaceContext?.workspaceRoot?.trim(),a=n?s||t?.trim():t?.trim();if(!a)return{clientId:i};let d=O0(a);if(!n&&s&&O0(s)!==d)throw Error("Registration workspace must match the Hub-authorized workspace");let l=O0(r.workspaceContext?.cwd?.trim()||d),c=XHe(d,l);if(c===".."||c.startsWith(`..${JHe}`)||YHe(c))throw Error("Registration cwd must be inside its workspace");return{clientId:i,workspaceContext:{workspaceRoot:d,cwd:l},...n?{crossWorkspace:!0}:{}}}class N0{transport;telemetry;workspaceRoot;constructor(e,t,n){this.transport=e;this.telemetry=t;this.workspaceRoot=n}attach(e,t={}){let n=new Map,r=new Set,o,i=!1,s=(c)=>{try{e.send(JSON.stringify(c))}catch(u){console.error(`[hub] failed to send websocket frame: ${u instanceof Error?u.stack||u.message:String(u)}`)}},a=(c)=>{s({kind:"event",envelope:c})},d=async(c)=>{try{let u=JSON.parse(c.data);switch(u.kind){case"command":{let h;if(o&&u.envelope.command==="client.register"){s({kind:"reply",envelope:Hm(u,"client_already_registered","This connection already owns a registered client.")});break}if(o&&u.envelope.clientId?.trim()!==o.clientId){s({kind:"reply",envelope:Hm(u,"client_authority_mismatch","Command clientId does not belong to this connection.")});break}if(u.envelope.command==="client.register")try{h=rWe(u,this.workspaceRoot,t.allowRegisteredWorkspace)}catch(S){s({kind:"reply",envelope:Hm(u,"invalid_client_registration",S instanceof Error?S.message:String(S))});break}let p=performance.now(),f=!1,m=L0(u);ke("info","command.start",m);let g=setTimeout(()=>{if(f)return;ke("warn","command.slow",{...m,elapsedMs:Math.round(performance.now()-p)})},QHe),y=this.transport.command(u.envelope,o??null);y.then((S)=>{if(!f)return;ke(S.ok?"warn":"error","command.late_end",{...m,elapsedMs:Math.round(performance.now()-p),ok:S.ok,errorCode:S.error?.code,errorMessage:S.error?.message})},(S)=>{if(!f)return;ke("error","command.late_error",{...m,elapsedMs:Math.round(performance.now()-p),error:S})});let w=!1,k,b,v=ZHe(u.envelope.command,u.envelope.timeoutMs);try{b=v===null?await y:await Promise.race([y,new Promise((S)=>{k=setTimeout(()=>{w=!0,iJ(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${u.envelope.command} did not complete within ${v}ms.`),severity:"error",handled:!0,context:{...m,timeoutMs:v}}),S(Hm(u,"hub_command_timeout",`Hub command ${u.envelope.command} did not complete within ${v}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${u.envelope.requestId}.`))},v)})])}catch(S){if(clearTimeout(g),k)clearTimeout(k);throw S}if(f=w,clearTimeout(g),k)clearTimeout(k);let E=Math.round(performance.now()-p);if(w)ke("error","command.timeout",{...m,durationMs:E,timeoutMs:v});else ke(b.ok?"info":"warn","command.end",{...m,durationMs:E,ok:b.ok,errorCode:b.error?.code,errorMessage:b.error?.message});if(u.envelope.command==="client.register"&&b.ok){if(h)r.add(h.clientId),o=h}else if(u.envelope.command==="client.unregister"&&b.ok){let S=u.envelope.clientId?.trim();if(S)r.delete(S),o=void 0}s({kind:"reply",envelope:b});break}case"stream.subscribe":{let h=`${u.clientId}:${u.sessionId??"*"}`;if(n.has(h))break;let p=typeof u.sinceSequence==="number"&&Number.isFinite(u.sinceSequence)&&u.sinceSequence>=0?Math.floor(u.sinceSequence):void 0;if(p===void 0||typeof this.transport.replayEventsAfter!=="function"){let v=await this.transport.subscribe(u.clientId,a,{sessionId:u.sessionId});n.set(h,v);break}let f=!1,m=p,g=[],y=new Set,w=(v)=>{if(typeof v.sequence==="number"){if(v.sequence<=m)return;m=v.sequence}if(v.eventId&&y){if(y.has(v.eventId))return;y.add(v.eventId)}a(v)},k=(v)=>{if(!f){g.push(v);return}w(v)},b=await this.transport.subscribe(u.clientId,k,{sessionId:u.sessionId});n.set(h,b);try{let v=0;while(!i&&v<nWe){let E=m,S=this.transport.replayEventsAfter(m,{sessionId:u.sessionId,limit:tWe});if(S.length===0)break;for(let x of S)w(x);if(m<=E)break;v+=1,await new Promise((x)=>setTimeout(x,0))}}finally{f=!0;for(let v of g)w(v);g.length=0,y=void 0}break}case"stream.unsubscribe":{let h=`${u.clientId}:${u.sessionId??"*"}`;n.get(h)?.(),n.delete(h);break}case"reply":case"event":break}}catch(u){let h=typeof c.data==="string"?eWe(c.data):void 0;if(!h||h.kind!=="command"){ke("error","rejected malformed websocket frame",{error:u});return}ke("error","command.error",{...L0(h),error:u}),iJ(this.telemetry,{component:"core",operation:"hub.websocket_command",error:u,severity:"error",handled:!0,context:L0(h)}),s({kind:"reply",envelope:Hm(h,"command_failed",u instanceof Error?u.message:"Unknown hub error")})}},l=()=>{if(i)return;i=!0;for(let c of n.values())c();n.clear();for(let c of r)this.transport.command({version:"v1",command:"client.unregister",clientId:c});r.clear(),e.removeEventListener("message",d),e.removeEventListener("close",l)};return e.addEventListener("message",d),e.addEventListener("close",l),l}}class D0{transport;constructor(e){this.transport=e}command(e,t){return this.transport.handleCommand(e,t)}subscribe(e,t,n){return this.transport.subscribe(e,t,n)}replayEventsAfter(e,t){return this.transport.replayEventsAfter?.(e,t)??[]}}function pJ(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();return String(e)}function dWe(e){return{send(t){e.send(t)},addEventListener(t,n){if(t==="message"){e.on("message",(r)=>{n({data:pJ(r)})});return}e.on("close",n)},removeEventListener(){}}}function lWe(e){try{e.write(`HTTP/1.1 400 Bad Request\r
2121
+ ${t.instructions}${r}`,s=await $m(this.ctx,{version:"v1",command:"run.start",requestId:P0("task_run_"),clientId:n.requestedByClientId??"agenda-task-manager",sessionId:e,payload:{sessionId:e,input:i,mode:t.mode??"act",timeoutSeconds:t.timeoutSeconds}});if(!s.ok)return{status:"failed",error:s.error?.message??"task session run failed"};let a=s.payload?.result,d=typeof a?.finishReason==="string"?a.finishReason:void 0,l=typeof a?.text==="string"&&a.text.trim()?a.text.trim():void 0;if(d==="completed")return{status:"completed",summary:l};if(d==="aborted")return{status:"cancelled",summary:l};return{status:"failed",summary:l,error:l??(d?`Task session ended with ${d}`:"Task session did not return a completion result")}}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(this.sessionSearch.start(),await this.tasks.start(),await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch(e){console.error("[hub] cron service start failed",e)}this.startEventLog(),this.startRunQueue()}startEventLog(){if(this.options.eventLog===!1||this.eventLog)return;try{let e=new R0({ownerId:this.options.owner?.ownerId,...this.options.eventLog??{}});e.prune(),this.eventLog=e,this.eventLogPruneTimer=setInterval(()=>{try{e.prune()}catch{}},3600000),this.eventLogPruneTimer.unref?.()}catch(e){ke("error","event_log.start_failed",{error:e})}}startRunQueue(){if(this.options.runQueue===!1||this.runQueue)return;try{this.runQueue=new T0({ownerId:this.options.owner?.ownerId,...this.options.runQueue??{}}),this.runExecutor=new S0(this.ctx,this.runQueue);let e=this.runQueue.recoverOnStartup();for(let n of e.interrupted)this.publish(Kr("run.interrupted",{runId:n.runId,error:n.error,reason:"hub_restart"},n.sessionId));let t=new Set(e.requeued.map((n)=>n.sessionId));for(let n of t)this.runExecutor.pump(n);if(e.interrupted.length>0||e.requeued.length>0)ke("info","run.queue.recovered",{interrupted:e.interrupted.length,requeued:e.requeued.length})}catch(e){ke("error","run.queue.start_failed",{error:e})}}async stop(){if(this.eventLogPruneTimer)clearInterval(this.eventLogPruneTimer),this.eventLogPruneTimer=void 0;for(let e of this.pendingApprovals.keys())y0(this.ctx,e,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(fs(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionSearch.dispose(),await this.tasks.dispose(),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch(e){console.error("[hub] cron service stop failed",e)}this.eventLog?.close(),this.eventLog=void 0,this.runQueue?.close(),this.runQueue=void 0,this.runExecutor=void 0}async handleCommand(e,t){try{let n=e.clientId?.trim(),r=t===void 0?this.options.workspaceRoot?.trim()&&n?{clientId:n,workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.workspaceRoot}}:void 0:t??void 0,o=await this.dispatchCommand(e,r);return this.captureFailedReply(e,o),o}catch(n){throw rk(this.options.telemetry,{component:"core",operation:"hub.command",error:n,severity:"error",handled:!1,context:this.commandTelemetryContext(e)}),n}}async dispatchCommand(e,t){if(this.draining&&wX(e.command))return bX(e);if(eJ(e.command))return await this.taskCommands.handleCommand(e,t);switch(e.command){case"client.register":{let n=aX(this.ctx,e);return this.tasks.notifyAutomationReadinessChanged(),n}case"client.update":{let n=dX(this.ctx,e);return this.tasks.notifyAutomationReadinessChanged(),n}case"client.unregister":{let n=lX(this.ctx,e,(r)=>{this.listeners.delete(r),this.detachClientFromSessions(r)});return this.tasks.notifyAutomationReadinessChanged(),n}case"client.list":return cX(this.ctx,e);case"session.create":return await A0(this.ctx,e,(n)=>Qv(this.ctx,n));case"session.restore":return await DX(this.ctx,e,(n)=>Qv(this.ctx,n));case"session.attach":return await $X(this.ctx,e);case"session.detach":return await FX(this.ctx,e);case"session.get":return await UX(this.ctx,e);case"session.messages":return await BX(this.ctx,e);case"session.compaction.get":return await HX(this.ctx,e);case"session.list":return await WX(this.ctx,e);case"session.search":return await jX(this.ctx,e);case"session.update":return await qX(this.ctx,e);case"session.update_connection":return await zX(this.ctx,e);case"session.compaction.update":return await KX(this.ctx,e);case"session.pending_prompts":return await VX(this.ctx,e);case"session.steer_first_pending_prompt":return await YX(this.ctx,e);case"session.update_pending_prompt":return await XX(this.ctx,e);case"session.remove_pending_prompt":return await JX(this.ctx,e);case"session.delete":return await GX(this.ctx,e);case"session.hook":return await yX(this.ctx,e);case"run.start":case"session.send_input":return await $m(this.ctx,e);case"run.enqueue":{if(!this.runQueue||!this.runExecutor)return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"run_queue_unavailable",message:"This hub has no durable run queue; use run.start instead."}};return vX(this.ctx,e,this.runQueue,this.runExecutor)}case"run.list":{if(!this.runQueue)return ie(e,{runs:[]});return kX(e,this.runQueue)}case"hub.drain":return this.handleHubDrain(e);case"hub.status":return this.handleHubStatus(e);case"run.abort":return await fX(this.ctx,e);case"run.proceed_while_running":return await gX(this.ctx,e);case"capability.request":return await iX(this.ctx,e);case"approval.respond":return await tX(this.ctx,e);case"capability.respond":return sX(this.ctx,e);case"capability.progress":return oX(this.ctx,e);case"ui.notify":return this.publish(Kr("ui.notify",e.payload??{})),ie(e);case"ui.show_window":return this.publish(Kr("ui.show_window",e.payload??{})),ie(e);case"settings.list":return await this.handleSettingsList(e);case"settings.toggle":return await this.handleSettingsToggle(e);case"connector.channels":case"connector.configure":case"connector.delete_config":case"connector.start":case"connector.stop":case"connector.supervised":return await pX(this.ctx,e);case"settings.get":case"settings.patch":return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"not_implemented",message:`${e.command} is not implemented yet.`}};default:{let n=await this.scheduleCommands.handleCommand(e,t);if(n.ok){let r=QX(e.command);if(r)this.publish(Kr(r,n.payload))}return n}}}captureFailedReply(e,t){if(t.ok||!t.error||!qHe(t.error.code))return;rk(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(t.error.message),severity:t.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext(e),errorCode:t.error.code}})}commandTelemetryContext(e){return{command:e.command,requestId:e.requestId,clientId:e.clientId,sessionId:typeof e.payload?.sessionId==="string"?e.payload.sessionId:e.sessionId}}async handleSettingsList(e){try{let t=await this.settings.list(nJ(e.payload));return{version:e.version,requestId:e.requestId,ok:!0,payload:{snapshot:t}}}catch(t){return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"settings_list_failed",message:t instanceof Error?t.message:String(t)}}}}async handleSettingsToggle(e){try{let t=await this.settings.toggle(jHe(e.payload));return this.publish(Kr("settings.changed",{types:t.changedTypes,snapshot:t.snapshot})),{version:e.version,requestId:e.requestId,ok:!0,payload:{snapshot:t.snapshot,changedTypes:t.changedTypes}}}catch(t){return{version:e.version,requestId:e.requestId,ok:!1,error:{code:"settings_toggle_failed",message:t instanceof Error?t.message:String(t)}}}}handleHubDrain(e){let t=e.payload?.draining!==!1,n=typeof e.payload?.reason==="string"?e.payload.reason:void 0;if(this.draining!==t)this.draining=t,this.publish(Kr("hub.drain_changed",{draining:this.draining,...n?{reason:n}:{}})),ke("info","hub.drain_changed",{draining:this.draining,reason:n});return ie(e,this.describeStatus())}handleHubStatus(e){return ie(e,this.describeStatus())}describeStatus(){let e=0;for(let t of this.activeRpcTurnCountBySession.values())e+=t;return{hubId:this.hubId,draining:this.draining,activeRpcTurns:e,pendingRuns:this.runQueue?.countPending()??0,eventLog:this.eventLog?{lastSequence:this.eventLog.lastSequence()}:void 0,idle:e===0&&(this.runQueue?.countPending()??0)===0}}isDraining(){return this.draining}replayEventsAfter(e,t){if(!this.eventLog)return[];return this.eventLog.listAfter(e,{sessionId:t.sessionId},t.limit)}lastEventSequence(){return this.eventLog?.lastSequence()??0}subscribe(e,t,n){let r=this.listeners.get(e)??new Set,o={sessionId:n?.sessionId,listener:t};r.add(o),this.listeners.set(e,r);let i=eX(this.ctx,n?.sessionId);if(i.length>0)queueMicrotask(()=>{if(!this.listeners.get(e)?.has(o))return;for(let a of i)try{o.listener(a)}catch(d){Za("listener threw while re-issuing pending approval",d)}});return()=>{let s=this.listeners.get(e);if(!s)return;if(s.delete(o),s.size===0)this.listeners.delete(e)}}detachClientFromSessions(e){for(let[t,n]of this.sessionState.entries()){if(n.participants.delete(e),n.createdByClientId===e)n.createdByClientId=void 0;if(n.participants.size===0)this.sessionState.delete(t)}fs(this.ctx,(t)=>t.targetClientId===e,`Capability owner client ${e} disconnected before request was resolved.`)}publish(e){if(this.eventLog)try{e=this.eventLog.append(e)}catch(t){Za(`event log append failed for ${e.event}`,t)}for(let t of this.listeners.values())for(let n of t){if(n.sessionId&&n.sessionId!==e.sessionId)continue;try{n.listener(e)}catch(r){Za(`listener threw while publishing ${e.event}`,r),rk(this.options.telemetry,{component:"core",operation:"hub.publish",error:r,severity:"warn",handled:!0,context:{event:e.event,sessionId:e.sessionId}})}}}}function qHe(e){return e==="session_not_found"||e==="session_messages_not_found"||e==="hub_command_timeout"||e.endsWith("_failed")}import{timingSafeEqual as oWe}from"node:crypto";import iWe from"node:http";import{URL as B0}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as $0,HUB_CAPABILITIES as sWe,MAX_CLIENT_HUB_PROTOCOL_VERSION as sJ,MIN_CLIENT_HUB_PROTOCOL_VERSION as aJ}from"@cerebriline/shared";import{WebSocketServer as aWe}from"ws";import{createSessionId as zTt,ensureLoopbackProxyBypass as KTt,isHubProtocolCompatible as GTt,resolveClineBuildEnv as VTt,resolveHubCommandTimeoutMs as YTt}from"@cerebriline/shared";import JTt from"ws";import{CLINE_RUN_AS_HUB_DAEMON_ENV as ITt,isBunEmbeddedModulePath as CTt,isHubDaemonProcess as PTt,resolveClineBuildEnv as MTt,withResolvedClineBuildEnv as OTt}from"@cerebriline/shared";import{isAbsolute as YHe,relative as XHe,resolve as O0,sep as JHe}from"node:path";import{captureSdkError as iJ,HUB_COMMAND_SLOW_LOG_MS as QHe,resolveHubCommandTimeoutMs as ZHe,safeJsonParse as eWe}from"@cerebriline/shared";var tWe=200,nWe=1000;function L0(e){return{command:e.envelope.command,requestId:e.envelope.requestId,clientId:e.envelope.clientId,sessionId:e.envelope.sessionId}}function Hm(e,t,n){return{version:e.envelope.version,requestId:e.envelope.requestId,ok:!1,error:{code:t,message:n}}}function rWe(e,t,n=!1){let r=e.envelope.payload??{},o=e.envelope.clientId?.trim(),i=r.clientId?.trim()||o;if(!i||o&&i!==o)throw Error("Registration clientId must match the command connection");let s=r.workspaceContext?.workspaceRoot?.trim(),a=n?s||t?.trim():t?.trim();if(!a)return{clientId:i};let d=O0(a);if(!n&&s&&O0(s)!==d)throw Error("Registration workspace must match the Hub-authorized workspace");let l=O0(r.workspaceContext?.cwd?.trim()||d),c=XHe(d,l);if(c===".."||c.startsWith(`..${JHe}`)||YHe(c))throw Error("Registration cwd must be inside its workspace");return{clientId:i,workspaceContext:{workspaceRoot:d,cwd:l},...n?{crossWorkspace:!0}:{}}}class N0{transport;telemetry;workspaceRoot;constructor(e,t,n){this.transport=e;this.telemetry=t;this.workspaceRoot=n}attach(e,t={}){let n=new Map,r=new Set,o,i=!1,s=(c)=>{try{e.send(JSON.stringify(c))}catch(u){console.error(`[hub] failed to send websocket frame: ${u instanceof Error?u.stack||u.message:String(u)}`)}},a=(c)=>{s({kind:"event",envelope:c})},d=async(c)=>{try{let u=JSON.parse(c.data);switch(u.kind){case"command":{let h;if(o&&u.envelope.command==="client.register"){s({kind:"reply",envelope:Hm(u,"client_already_registered","This connection already owns a registered client.")});break}if(o&&u.envelope.clientId?.trim()!==o.clientId){s({kind:"reply",envelope:Hm(u,"client_authority_mismatch","Command clientId does not belong to this connection.")});break}if(u.envelope.command==="client.register")try{h=rWe(u,this.workspaceRoot,t.allowRegisteredWorkspace)}catch(S){s({kind:"reply",envelope:Hm(u,"invalid_client_registration",S instanceof Error?S.message:String(S))});break}let p=performance.now(),f=!1,m=L0(u);ke("info","command.start",m);let g=setTimeout(()=>{if(f)return;ke("warn","command.slow",{...m,elapsedMs:Math.round(performance.now()-p)})},QHe),y=this.transport.command(u.envelope,o??null);y.then((S)=>{if(!f)return;ke(S.ok?"warn":"error","command.late_end",{...m,elapsedMs:Math.round(performance.now()-p),ok:S.ok,errorCode:S.error?.code,errorMessage:S.error?.message})},(S)=>{if(!f)return;ke("error","command.late_error",{...m,elapsedMs:Math.round(performance.now()-p),error:S})});let w=!1,k,b,v=ZHe(u.envelope.command,u.envelope.timeoutMs);try{b=v===null?await y:await Promise.race([y,new Promise((S)=>{k=setTimeout(()=>{w=!0,iJ(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${u.envelope.command} did not complete within ${v}ms.`),severity:"error",handled:!0,context:{...m,timeoutMs:v}}),S(Hm(u,"hub_command_timeout",`Hub command ${u.envelope.command} did not complete within ${v}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${u.envelope.requestId}.`))},v)})])}catch(S){if(clearTimeout(g),k)clearTimeout(k);throw S}if(f=w,clearTimeout(g),k)clearTimeout(k);let E=Math.round(performance.now()-p);if(w)ke("error","command.timeout",{...m,durationMs:E,timeoutMs:v});else ke(b.ok?"info":"warn","command.end",{...m,durationMs:E,ok:b.ok,errorCode:b.error?.code,errorMessage:b.error?.message});if(u.envelope.command==="client.register"&&b.ok){if(h)r.add(h.clientId),o=h}else if(u.envelope.command==="client.unregister"&&b.ok){let S=u.envelope.clientId?.trim();if(S)r.delete(S),o=void 0}s({kind:"reply",envelope:b});break}case"stream.subscribe":{let h=`${u.clientId}:${u.sessionId??"*"}`;if(n.has(h))break;let p=typeof u.sinceSequence==="number"&&Number.isFinite(u.sinceSequence)&&u.sinceSequence>=0?Math.floor(u.sinceSequence):void 0;if(p===void 0||typeof this.transport.replayEventsAfter!=="function"){let v=await this.transport.subscribe(u.clientId,a,{sessionId:u.sessionId});n.set(h,v);break}let f=!1,m=p,g=[],y=new Set,w=(v)=>{if(typeof v.sequence==="number"){if(v.sequence<=m)return;m=v.sequence}if(v.eventId&&y){if(y.has(v.eventId))return;y.add(v.eventId)}a(v)},k=(v)=>{if(!f){g.push(v);return}w(v)},b=await this.transport.subscribe(u.clientId,k,{sessionId:u.sessionId});n.set(h,b);try{let v=0;while(!i&&v<nWe){let E=m,S=this.transport.replayEventsAfter(m,{sessionId:u.sessionId,limit:tWe});if(S.length===0)break;for(let x of S)w(x);if(m<=E)break;v+=1,await new Promise((x)=>setTimeout(x,0))}}finally{f=!0;for(let v of g)w(v);g.length=0,y=void 0}break}case"stream.unsubscribe":{let h=`${u.clientId}:${u.sessionId??"*"}`;n.get(h)?.(),n.delete(h);break}case"reply":case"event":break}}catch(u){let h=typeof c.data==="string"?eWe(c.data):void 0;if(!h||h.kind!=="command"){ke("error","rejected malformed websocket frame",{error:u});return}ke("error","command.error",{...L0(h),error:u}),iJ(this.telemetry,{component:"core",operation:"hub.websocket_command",error:u,severity:"error",handled:!0,context:L0(h)}),s({kind:"reply",envelope:Hm(h,"command_failed",u instanceof Error?u.message:"Unknown hub error")})}},l=()=>{if(i)return;i=!0;for(let c of n.values())c();n.clear();for(let c of r)this.transport.command({version:"v1",command:"client.unregister",clientId:c});r.clear(),e.removeEventListener("message",d),e.removeEventListener("close",l)};return e.addEventListener("message",d),e.addEventListener("close",l),l}}class D0{transport;constructor(e){this.transport=e}command(e,t){return this.transport.handleCommand(e,t)}subscribe(e,t,n){return this.transport.subscribe(e,t,n)}replayEventsAfter(e,t){return this.transport.replayEventsAfter?.(e,t)??[]}}function pJ(e){if(typeof e==="string")return e;if(e instanceof Uint8Array)return Buffer.from(e).toString();if(e instanceof ArrayBuffer)return Buffer.from(e).toString();if(Array.isArray(e))return Buffer.concat(e.map((t)=>Buffer.from(t))).toString();return String(e)}function dWe(e){return{send(t){e.send(t)},addEventListener(t,n){if(t==="message"){e.on("message",(r)=>{n({data:pJ(r)})});return}e.on("close",n)},removeEventListener(){}}}function lWe(e){try{e.write(`HTTP/1.1 400 Bad Request\r
2122
2122
  Connection: close\r
2123
2123
  Content-Length: 0\r
2124
2124
  \r