@robota-sdk/agent-cli 3.0.5 → 3.0.6

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.
Files changed (28) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/dist/node/bin.js +1 -1
  3. package/dist/node/{cli-core-DDwaU887.js → cli-core-CcG7HrJg.js} +40 -40
  4. package/dist/node/desktop-host.js +1 -1
  5. package/dist/node/headless.js +1 -1
  6. package/dist/node/host.js +1 -1
  7. package/dist/node/index.js +1 -1
  8. package/dist/node/{node-TUI6iwZA.js → node-CrF8rjSF.js} +21 -21
  9. package/dist/node/node-D_40SJP5.js +67 -0
  10. package/dist/node/node-D_40SJP5.js.map +1 -0
  11. package/dist/node/{product-host-D08dCAW1.js → product-host-B2jYVaCe.js} +42 -42
  12. package/dist/node/{product-host-D08dCAW1.js.map → product-host-B2jYVaCe.js.map} +1 -1
  13. package/dist/node/product-host-SaMRTzxB.d.ts.map +1 -1
  14. package/dist/node/{src-B9UMvThT-B2KTGTWN.js → src-B9UMvThT-CH8RbDyz.js} +1 -1
  15. package/dist/node/{src-B9UMvThT-C7tdUtnO.js → src-B9UMvThT-Mipp-Spb.js} +2 -2
  16. package/dist/node/{src-B9UMvThT-C7tdUtnO.js.map → src-B9UMvThT-Mipp-Spb.js.map} +1 -1
  17. package/dist/node/{src-BzaNFPZx-BhNHy6VF.js → src-BzaNFPZx-0zlY87KO.js} +2 -2
  18. package/dist/node/{src-BzaNFPZx-BhNHy6VF.js.map → src-BzaNFPZx-0zlY87KO.js.map} +1 -1
  19. package/dist/node/{src-BzaNFPZx-DElk_FSv.js → src-BzaNFPZx-DdIEi4rg.js} +1 -1
  20. package/dist/node/{src-DwAfU-9z-CONMoS5Y.js → src-DwAfU-9z-B3bEabDl.js} +1 -1
  21. package/dist/node/{src-DwAfU-9z-DeVCAItW.js → src-DwAfU-9z-DDIgZhiP.js} +2 -2
  22. package/dist/node/{src-DwAfU-9z-DeVCAItW.js.map → src-DwAfU-9z-DDIgZhiP.js.map} +1 -1
  23. package/dist/node/{src-UPsd6jNY-DI_aEmty.js → src-UPsd6jNY-CpXUNTpA.js} +1 -1
  24. package/dist/node/{src-UPsd6jNY-DNJ5Z5Eu.js → src-UPsd6jNY-XM9nqZGs.js} +2 -2
  25. package/dist/node/{src-UPsd6jNY-DNJ5Z5Eu.js.map → src-UPsd6jNY-XM9nqZGs.js.map} +1 -1
  26. package/package.json +37 -37
  27. package/dist/node/node-DwQY2ITL.js +0 -67
  28. package/dist/node/node-DwQY2ITL.js.map +0 -1
@@ -1,5 +1,5 @@
1
1
  ;(function(){var v=parseInt(process.versions.node.split('.')[0],10);if(v<22){process.stderr.write('\n✗ Node.js 22+ is required (current: '+process.version+')\n\nUpgrade:\n nvm: nvm install 22 && nvm use 22\n Volta: volta install node@22\n Download: https://nodejs.org/en/download\n\n');process.exit(1);}})();
2
- import{n as e,r as t,t as n}from"./rolldown-runtime-rs7quPpn.js";import{A as r,C as i,D as a,E as o,O as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,h as _,i as v,k as y,l as b,m as x,n as S,o as C,p as w,r as T,s as E,t as ee,u as te,v as ne,w as re,x as ie,y as ae}from"./node-TUI6iwZA.js";import{$ as oe,$t as se,A as ce,At as le,B as ue,C as de,Ct as fe,D,Dt as pe,E as me,F as he,Ft as ge,G as _e,H as ve,Ht as ye,I as be,It as xe,Jt as Se,K as O,Kt as Ce,L as we,Lt as Te,M as Ee,Mt as De,Nt as Oe,O as ke,Ot as Ae,P as je,Pt as Me,Q as Ne,Qt as Pe,R as Fe,S as Ie,St as Le,T as Re,Tt as ze,Ut as Be,V as Ve,Vt as He,W as Ue,Wt as We,X as Ge,Xt as Ke,Y as qe,Yt as Je,Zt as Ye,_ as Xe,_t as Ze,a as Qe,at as $e,bt as et,c as tt,ct as nt,d as rt,dt as it,et as at,f as ot,ft as st,g as ct,gt as lt,h as ut,ht as dt,i as ft,it as pt,j as mt,jt as ht,k as gt,kt as _t,l as eee,lt as vt,m as tee,mt as nee,n as ree,nt as iee,o as yt,ot as aee,p as bt,q as xt,qt as St,r as Ct,rt as wt,s as oee,st as Tt,t as Et,tt as see,u as Dt,ut as Ot,v as cee,vt as kt,w as At,wt as jt,x as Mt,xt as lee,y as uee,yt as Nt,z as Pt,zt as Ft}from"./node-PhNl8kvo.js";import{S as dee,_ as It,a as Lt,c as Rt,h as fee,n as zt,o as pee,p as Bt,r as mee,t as hee,u as Vt,v as Ht,w as Ut,x as Wt}from"./bounded-output-BdWv9SX3-C4ucXwLR.js";import{r as Gt}from"./verdict-decoder-Dz_rjoIZ-qM0jJVsB.js";import{n as Kt}from"./command-executor-D_UBZHxh-D7UrdAlN.js";import{n as qt}from"./http-executor-ADn4locH-uz5KV6N-.js";import{a as Jt,c as gee,i as Yt,l as Xt,n as Zt,o as Qt,r as _ee,s as $t,t as en,u as vee}from"./node-gdZ0H7su.js";import{createRequire as tn}from"node:module";import{execFile as nn,execFileSync as rn,execSync as an,spawn as on,spawnSync as sn}from"node:child_process";import{accessSync as yee,appendFileSync as cn,chmodSync as ln,closeSync as un,constants as k,cpSync as bee,createReadStream as dn,existsSync as fn,fstatSync as pn,fsyncSync as mn,ftruncateSync as hn,linkSync as gn,lstatSync as _n,mkdirSync as vn,mkdtempSync as yn,openSync as bn,readFileSync as A,readSync as xn,readdirSync as Sn,realpathSync as Cn,renameSync as wn,rmSync as Tn,rmdirSync as En,statSync as Dn,unlinkSync as On,utimesSync as xee,writeFileSync as kn,writeSync as An}from"node:fs";import j,{basename as jn,delimiter as See,dirname as Mn,extname as Nn,isAbsolute as Pn,join as M,posix as Fn,relative as In,resolve as Ln,sep as Rn,win32 as zn}from"node:path";import{Cron as Bn}from"croner";import{createHash as Vn,createHmac as Hn,createPublicKey as Un,randomBytes as Wn,randomInt as Gn,randomUUID as N,timingSafeEqual as Kn,verify as qn}from"node:crypto";import{access as Jn,copyFile as Yn,link as Xn,lstat as Zn,mkdir as Qn,open as $n,readFile as er,readdir as tr,realpath as nr,rename as Cee,rm as wee,stat as rr,unlink as ir,writeFile as Tee}from"node:fs/promises";import{constants as ar,homedir as or,hostname as sr,networkInterfaces as cr,tmpdir as lr}from"node:os";import{z as P}from"zod";import{BlockList as ur,createConnection as dr,createServer as fr,isIP as pr,isIPv4 as mr,isIPv6 as Eee}from"node:net";import{createServer as hr}from"node:http";import{Duplex as Dee,PassThrough as Oee,Readable as kee,Writable as Aee}from"node:stream";import{EventEmitter as gr}from"node:events";import{isDeepStrictEqual as _r,parseArgs as vr,parseEnv as jee}from"node:util";import{Worker as Mee}from"node:worker_threads";import{fileURLToPath as Nee,pathToFileURL as yr}from"node:url";import{AsyncLocalStorage as br}from"node:async_hooks";import xr from"koffi";import{existsSync as Sr,readFileSync as Cr,readdirSync as wr,unlinkSync as Tr}from"fs";import{resolve as Er,sep as Dr}from"path";import Or from"string-width";import*as kr from"node:readline";import{createInterface as Ar}from"node:readline";import jr from"@anthropic-ai/sdk";import{FunctionCallingConfigMode as Mr,GoogleGenAI as Nr,Type as Pr}from"@google/genai";import Fr from"openai";import Ir,{WebSocket as Lr,WebSocketServer as Rr}from"ws";import{StringDecoder as Pee}from"node:string_decoder";import{ReadStream as Fee,WriteStream as Iee,isatty as zr}from"node:tty";import Lee from"qrcode";import{createSocket as Ree}from"node:dgram";import{SimplePool as zee}from"nostr-tools/pool";import{finalizeEvent as Bee,getPublicKey as Vee,verifyEvent as Hee}from"nostr-tools/pure";import{ROOT_CONTEXT as Br,SpanKind as Vr,SpanStatusCode as Hr,TraceFlags as Ur,ValueType as Wr,trace as Uee}from"@opentelemetry/api";import{ExportResultCode as Gr}from"@opentelemetry/core";import{ProtobufLogsSerializer as Kr,ProtobufMetricsSerializer as qr,ProtobufTraceSerializer as Jr}from"@opentelemetry/otlp-transformer";import{resourceFromAttributes as Yr}from"@opentelemetry/resources";import{BatchSpanProcessor as Wee,TracerProvider as Gee}from"@opentelemetry/sdk-trace";import{AggregationTemporality as Xr,DataPointType as Zr}from"@opentelemetry/sdk-metrics";import{SeverityNumber as Qr}from"@opentelemetry/api-logs";import{createInterface as $r}from"node:readline/promises";import Kee from"open";import{Client as qee,IssuerMismatchError as Jee,LATEST_PROTOCOL_VERSION as ei,OAuthError as Yee,OAuthErrorCode as Xee,ProtocolError as Zee,ProtocolErrorCode as Qee,SERVER_INFO_META_KEY as $ee,SdkError as ti,SdkErrorCode as ni,SdkHttpError as ete,StreamableHTTPClientTransport as tte,UnauthorizedError as nte,UnsupportedProtocolVersionError as ri,buildDiscoveryUrls as rte,deserializeMessage as ite,discoverAuthorizationServerMetadata as ate,exchangeAuthorization as ote,extractWWWAuthenticateParams as ste,refreshAuthorization as cte,registerClient as lte,selectClientAuthMethod as ute,serializeMessage as dte,startAuthorization as fte}from"@modelcontextprotocol/client";import{OAuthMetadataSchema as pte,OAuthProtectedResourceMetadataSchema as mte}from"@modelcontextprotocol/core";import{DEFAULT_INHERITED_ENV_VARS as hte}from"@modelcontextprotocol/client/stdio";import{getRequestListener as gte}from"@hono/node-server";import{Hono as _te}from"hono";import{bodyLimit as vte}from"hono/body-limit";import{streamSSE as yte}from"hono/streaming";import{Server as bte,createMcpHandler as xte,inputRequired as ii,inputResponse as Ste,specTypeSchemas as Cte}from"@modelcontextprotocol/server";import{StdioServerTransport as wte}from"@modelcontextprotocol/server/stdio";import{toNodeHandler as Tte}from"@modelcontextprotocol/node";import{PROTOCOL_VERSION as Ete,RequestError as ai,agent as Dte,ndJsonStream as Ote}from"@agentclientprotocol/sdk";var oi=class extends Error{category;recoverable;constructor(e,t,n=!0){super(t),this.name=`BackgroundTaskError`,this.category=e,this.recoverable=n}};const kte=new Set([`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`]);function Ate(){let e=()=>{},t=()=>{},n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function si(e){return new oi(`runner`,e)}function jte(e){return e instanceof oi?{category:e.category,message:e.message,recoverable:e.recoverable}:{category:`runner`,message:e instanceof Error?e.message:e,recoverable:!0}}function Mte(e){return e instanceof Error?e.message:e}function Nte(e,t){if(e.kind===`agent`){let n=t.metadata?.worktreePath;typeof n==`string`&&(e.worktreePath=n);let r=t.metadata?.branchName;typeof r==`string`&&(e.branchName=r);let i=t.metadata?.worktreeStatus;typeof i==`string`&&(e.worktreeStatus=i);let a=t.metadata?.worktreeNextAction;typeof a==`string`&&(e.worktreeNextAction=a);let o=t.metadata?.worktreeBaseRevision;typeof o==`string`&&(e.worktreeBaseRevision=o);let s=t.metadata?.parentWorktreeStatus;typeof s==`string`&&(e.parentWorktreeStatus=s)}let n=t.metadata?.logPath;typeof n==`string`&&(e.logPath=n);let r=t.metadata?.transcriptPath;typeof r==`string`&&(e.transcriptPath=r);let i=t.metadata?.timeoutReason;Pte(i)&&(e.timeoutReason=i)}function Pte(e){return typeof e==`string`&&kte.has(e)}function ci(e){e.unref?.()}function li(e){return e.replace(/\s+/g,` `).trim()}function Fte(e,t){return e.length<=t?e:e.slice(e.length-t)}function Ite(e,t){if(t<=1)return!1;let n=li(e);if(!n)return!1;let r=n.split(/(?<=[.!?。!?])\s+/).map(e=>e.trim()).filter(e=>e.length>=12);if(r.length<t)return!1;let i=``,a=0;for(let e of r)if(e===i?a+=1:(i=e,a=1),a>=t)return!0;return!1}function Lte(e){let t=e.metadata?{...e.metadata}:void 0;return e.kind===`tool-invocation`?{...t,toolName:e.toolName,serverId:e.serverId,sourceName:e.sourceName,...e.securityIdentity===void 0?{}:{securityIdentity:e.securityIdentity},permissionMode:e.permissionMode,provenanceOwner:e.provenanceOwner}:t}function Rte(e,t,n,r,i=`queued`){let a=Lte(t),o={id:e,label:t.label,status:i,mode:t.mode,parentSessionId:t.parentSessionId,parentTaskId:t.parentTaskId,depth:t.depth,cwd:t.cwd,updatedAt:n,unread:!1,...a?{metadata:a}:{}};switch(t.kind){case`agent`:return{...o,kind:`agent`,agentType:t.agentType,isolation:t.isolation,promptPreview:t.prompt.slice(0,r),...t.resumeSessionId===void 0?{}:{resumeSessionId:t.resumeSessionId}};case`process`:return{...o,kind:`process`,commandPreview:t.command.slice(0,r)};case`tool-invocation`:return{...o,kind:`tool-invocation`,commandPreview:`${t.toolName} (${t.serverId})`.slice(0,r)};case`scheduled`:{let e=t.command??t.agentInstruction;return{...o,kind:`scheduled`,...e===void 0?{}:{commandPreview:e.slice(0,r)},schedule:{cronExpression:t.cronExpression,...t.agentInstruction===void 0?{}:{agentInstruction:t.agentInstruction},...t.command===void 0?{}:{command:t.command},...t.shell===void 0?{}:{shell:t.shell},...t.env===void 0?{}:{env:{...t.env}}}}}}}function zte(e,t){return!t||!(t.kind&&e.kind!==t.kind||t.status&&e.status!==t.status||t.mode&&e.mode!==t.mode)}function ui(e){if(e)return{...e,metadata:e.metadata?{...e.metadata}:void 0}}function di(e){let t=e.metadata?{...e.metadata}:void 0,n=e.error?{...e.error}:void 0;switch(e.kind){case`agent`:return{...e,metadata:t,error:n,result:ui(e.result)};case`process`:return{...e,metadata:t,error:n,result:ui(e.result)};case`tool-invocation`:return{...e,metadata:t,error:n,result:ui(e.result)};case`scheduled`:return{...e,metadata:t,error:n,result:ui(e.result),schedule:e.schedule?{...e.schedule,env:e.schedule.env?{...e.schedule.env}:void 0}:void 0}}}const Bte=new Set([`completed`,`failed`,`cancelled`]),Vte=[{from:`queued`,event:`START`,to:`running`},{from:`queued`,event:`CANCEL`,to:`cancelled`},{from:`running`,event:`REQUEST_PERMISSION`,to:`waiting_permission`},{from:`running`,event:`COMPLETE`,to:`completed`},{from:`running`,event:`FAIL`,to:`failed`},{from:`running`,event:`CANCEL`,to:`cancelled`},{from:`running`,event:`SLEEP`,to:`sleeping`},{from:`waiting_permission`,event:`PERMISSION_ALLOWED`,to:`running`},{from:`waiting_permission`,event:`PERMISSION_DENIED`,to:`failed`},{from:`waiting_permission`,event:`CANCEL`,to:`cancelled`},{from:`sleeping`,event:`WAKE`,to:`running`},{from:`sleeping`,event:`CANCEL`,to:`cancelled`},{from:`sleeping`,event:`PAUSE`,to:`paused`},{from:`running`,event:`PAUSE`,to:`paused`},{from:`paused`,event:`RESUME`,to:`sleeping`},{from:`paused`,event:`CANCEL`,to:`cancelled`}];function fi(e){return Bte.has(e)}function pi(e,t){let n=Vte.find(n=>n.from===e&&n.event===t);if(n)return n.to;throw new oi(`validation`,`Invalid background task transition: ${e} + ${t} (${fi(e)?`terminal status`:`unsupported event`})`)}function Hte(e,t){return e.state.status=pi(e.state.status,`START`),e.state.startedAt=t,e.state.updatedAt=t,e.state.lastActivityAt=t,di(e.state)}function mi(e,t,n){if(e.depth>n)throw new oi(`validation`,`Background task depth limit exceeded: depth=${e.depth} maxDepth=${n}`);if(!t.has(e.kind))throw si(`No background task runner registered for kind: ${e.kind}`)}function hi(e,t,n){if(e.handle=t,t.pid&&(e.state.pid=t.pid),t.logPath&&(e.state.logPath=t.logPath),t.transcriptPath&&(e.state.transcriptPath=t.transcriptPath),!t.pid&&!t.logPath&&!t.transcriptPath)return;let r=n();return e.state.updatedAt=r,e.state.lastActivityAt=r,di(e.state)}function gi(e,t,n){return e.state.status=pi(e.state.status,`COMPLETE`),e.state.result=t,Nte(e.state,t),e.state.unread=e.state.mode===`background`,e.state.completedAt=n,e.state.updatedAt=n,di(e.state)}function _i(e,t,n){return e.state.status=pi(e.state.status,`FAIL`),e.state.error=jte(t),e.state.completedAt=n,e.state.updatedAt=n,di(e.state)}function vi(e,t,n){return e.state.status=pi(e.state.status,`CANCEL`),e.state.error={category:`runner`,message:t??`Background task cancelled`,recoverable:!0},e.state.completedAt=n,e.state.updatedAt=n,{task:di(e.state)}}function yi(e,t){return e.state.status=pi(e.state.status,`PAUSE`),e.state.kind===`scheduled`&&(e.state.nextFireAt=void 0),e.state.updatedAt=t,di(e.state)}function bi(e,t){return e.state.status=pi(e.state.status,`RESUME`),e.state.updatedAt=t,di(e.state)}function xi(e,t,n){if(e.state.lastActivityAt=n,t.type===`background_task_tool_start`)return e.state.currentAction=t.firstArg??t.toolName,e.state.updatedAt=n,di(e.state);if(t.type===`background_task_tool_end`)return e.state.currentAction=t.success?void 0:t.error??t.toolName,e.state.updatedAt=n,di(e.state);if(t.type===`background_task_sleeping`)return e.state.status!==`sleeping`&&(e.state.status=pi(e.state.status,`SLEEP`)),e.state.kind===`scheduled`&&(e.state.nextFireAt=t.nextFireAt),e.state.updatedAt=n,di(e.state);if(t.type===`background_task_waking`)return e.state.status===`sleeping`&&(e.state.status=pi(e.state.status,`WAKE`)),e.state.kind===`scheduled`&&(e.state.nextFireAt=void 0),e.state.updatedAt=n,di(e.state)}function Si(e){try{if(e.runner.kind!==e.task.request.kind)throw new oi(`runner`,`Runner kind ${e.runner.kind} does not match task kind ${e.task.request.kind}`);let t=e.runner.start({taskId:e.task.state.id,request:e.task.request,emit:e.onEvent}),n=hi(e.task,t,e.now);n&&e.onUpdated(n),e.onStarted(),t.result.then(t=>e.onCompleted(t),t=>e.onFailed(t instanceof Error?t:String(t)))}catch(t){e.onFailed(t instanceof Error?t:String(t))}}var Ci=class{defaults;onTimeout;constructor(e,t){this.defaults=e,this.onTimeout=t}start(e){if(e.request.kind!==`agent`)return;this.resetIdleTimer(e);let t=e.request.maxRuntimeMs??this.defaults.agentMaxRuntimeMs;t>0&&(e.maxRuntimeTimer=setTimeout(()=>{this.onTimeout(e,`max_runtime`,`Background agent exceeded max runtime: ${t}ms`)},t),ci(e.maxRuntimeTimer))}recordActivity(e,t){(e.state.status===`running`||e.state.status===`waiting_permission`)&&(e.state.lastActivityAt=t,this.resetIdleTimer(e))}clear(e){e.idleTimer&&=(clearTimeout(e.idleTimer),void 0),e.maxRuntimeTimer&&=(clearTimeout(e.maxRuntimeTimer),void 0)}applyTextGuards(e,t){if(e.request.kind!==`agent`)return;e.outputBytes+=Buffer.byteLength(t,`utf8`),e.textDeltas+=1,e.recentText=Fte(`${e.recentText}${t}`,e.request.repetitionWindow??this.defaults.repetitionWindow);let n=e.request.outputLimitBytes??this.defaults.agentOutputLimitBytes;if(n>0&&e.outputBytes>n){this.onTimeout(e,`output_limit`,`Background agent exceeded output limit: ${n} bytes`);return}let r=e.request.maxTextDeltas??this.defaults.agentMaxTextDeltas;if(r>0&&e.textDeltas>r){this.onTimeout(e,`output_limit`,`Background agent exceeded text delta limit: ${r}`);return}this.isRepetitiveOutput(e,t)&&this.onTimeout(e,`repetition`,`Background agent produced repetitive output`)}resetIdleTimer(e){if(e.request.kind!==`agent`)return;e.idleTimer&&clearTimeout(e.idleTimer);let t=e.request.idleTimeoutMs??e.request.timeoutMs??this.defaults.agentIdleTimeoutMs;t<=0||(e.idleTimer=setTimeout(()=>{this.onTimeout(e,`idle`,`Background agent produced no activity for ${t}ms`)},t),ci(e.idleTimer))}isRepetitiveOutput(e,t){if(e.request.kind!==`agent`)return!1;let n=e.request.repetitionThreshold??this.defaults.repetitionThreshold;if(n<=1)return!1;let r=li(t);return r&&r===e.lastNormalizedDelta?e.repeatedDeltaCount+=1:(e.lastNormalizedDelta=r,e.repeatedDeltaCount=+!!r),e.repeatedDeltaCount>=n||Ite(e.recentText,n)}};function wi(e,t){return new Ci({agentIdleTimeoutMs:e.agentIdleTimeoutMs??24e4,agentMaxRuntimeMs:e.agentMaxRuntimeMs??0,agentOutputLimitBytes:e.agentOutputLimitBytes??256e3,agentMaxTextDeltas:e.agentMaxTextDeltas??2e4,repetitionWindow:e.repetitionWindow??800,repetitionThreshold:e.repetitionThreshold??8},t)}function Ti(e,t=`BACKGROUND_OBSERVER_FAILURE`){let n=e.error instanceof Error?e.error.message:String(e.error??`unknown`),r=typeof e.event==`object`&&e.event!==null&&`type`in e.event?String(e.event.type):`unknown`;process.emitWarning(`Background lifecycle observer #${e.observerIndex} threw on '${r}': ${n}`,{code:t})}function Ei(e,t,n){let r=0,i=0;for(let a of t){try{a(e)}catch(t){r+=1,n({event:e,error:t,observerIndex:i})}i+=1}return r}const Di=new TextEncoder;function Oi(e){let t=[],n=0,r=!1,i=e.truncationMarker??`
2
+ import{n as e,r as t,t as n}from"./rolldown-runtime-rs7quPpn.js";import{A as r,C as i,D as a,E as o,O as s,S as c,T as l,_ as u,a as d,b as f,c as p,d as m,f as h,g,h as _,i as v,k as y,l as b,m as x,n as S,o as C,p as w,r as T,s as E,t as ee,u as te,v as ne,w as re,x as ie,y as ae}from"./node-CrF8rjSF.js";import{$ as oe,$t as se,A as ce,At as le,B as ue,C as de,Ct as fe,D,Dt as pe,E as me,F as he,Ft as ge,G as _e,H as ve,Ht as ye,I as be,It as xe,Jt as Se,K as O,Kt as Ce,L as we,Lt as Te,M as Ee,Mt as De,Nt as Oe,O as ke,Ot as Ae,P as je,Pt as Me,Q as Ne,Qt as Pe,R as Fe,S as Ie,St as Le,T as Re,Tt as ze,Ut as Be,V as Ve,Vt as He,W as Ue,Wt as We,X as Ge,Xt as Ke,Y as qe,Yt as Je,Zt as Ye,_ as Xe,_t as Ze,a as Qe,at as $e,bt as et,c as tt,ct as nt,d as rt,dt as it,et as at,f as ot,ft as st,g as ct,gt as lt,h as ut,ht as dt,i as ft,it as pt,j as mt,jt as ht,k as gt,kt as _t,l as eee,lt as vt,m as tee,mt as nee,n as ree,nt as iee,o as yt,ot as aee,p as bt,q as xt,qt as St,r as Ct,rt as wt,s as oee,st as Tt,t as Et,tt as see,u as Dt,ut as Ot,v as cee,vt as kt,w as At,wt as jt,x as Mt,xt as lee,y as uee,yt as Nt,z as Pt,zt as Ft}from"./node-PhNl8kvo.js";import{S as dee,_ as It,a as Lt,c as Rt,h as fee,n as zt,o as pee,p as Bt,r as mee,t as hee,u as Vt,v as Ht,w as Ut,x as Wt}from"./bounded-output-BdWv9SX3-C4ucXwLR.js";import{r as Gt}from"./verdict-decoder-Dz_rjoIZ-qM0jJVsB.js";import{n as Kt}from"./command-executor-D_UBZHxh-D7UrdAlN.js";import{n as qt}from"./http-executor-ADn4locH-uz5KV6N-.js";import{a as Jt,c as gee,i as Yt,l as Xt,n as Zt,o as Qt,r as _ee,s as $t,t as en,u as vee}from"./node-gdZ0H7su.js";import{createRequire as tn}from"node:module";import{execFile as nn,execFileSync as rn,execSync as an,spawn as on,spawnSync as sn}from"node:child_process";import{accessSync as yee,appendFileSync as cn,chmodSync as ln,closeSync as un,constants as k,cpSync as bee,createReadStream as dn,existsSync as fn,fstatSync as pn,fsyncSync as mn,ftruncateSync as hn,linkSync as gn,lstatSync as _n,mkdirSync as vn,mkdtempSync as yn,openSync as bn,readFileSync as A,readSync as xn,readdirSync as Sn,realpathSync as Cn,renameSync as wn,rmSync as Tn,rmdirSync as En,statSync as Dn,unlinkSync as On,utimesSync as xee,writeFileSync as kn,writeSync as An}from"node:fs";import j,{basename as jn,delimiter as See,dirname as Mn,extname as Nn,isAbsolute as Pn,join as M,posix as Fn,relative as In,resolve as Ln,sep as Rn,win32 as zn}from"node:path";import{Cron as Bn}from"croner";import{createHash as Vn,createHmac as Hn,createPublicKey as Un,randomBytes as Wn,randomInt as Gn,randomUUID as N,timingSafeEqual as Kn,verify as qn}from"node:crypto";import{access as Jn,copyFile as Yn,link as Xn,lstat as Zn,mkdir as Qn,open as $n,readFile as er,readdir as tr,realpath as nr,rename as Cee,rm as wee,stat as rr,unlink as ir,writeFile as Tee}from"node:fs/promises";import{constants as ar,homedir as or,hostname as sr,networkInterfaces as cr,tmpdir as lr}from"node:os";import{z as P}from"zod";import{BlockList as ur,createConnection as dr,createServer as fr,isIP as pr,isIPv4 as mr,isIPv6 as Eee}from"node:net";import{createServer as hr}from"node:http";import{Duplex as Dee,PassThrough as Oee,Readable as kee,Writable as Aee}from"node:stream";import{EventEmitter as gr}from"node:events";import{isDeepStrictEqual as _r,parseArgs as vr,parseEnv as jee}from"node:util";import{Worker as Mee}from"node:worker_threads";import{fileURLToPath as Nee,pathToFileURL as yr}from"node:url";import{AsyncLocalStorage as br}from"node:async_hooks";import xr from"koffi";import{existsSync as Sr,readFileSync as Cr,readdirSync as wr,unlinkSync as Tr}from"fs";import{resolve as Er,sep as Dr}from"path";import Or from"string-width";import*as kr from"node:readline";import{createInterface as Ar}from"node:readline";import jr from"@anthropic-ai/sdk";import{FunctionCallingConfigMode as Mr,GoogleGenAI as Nr,Type as Pr}from"@google/genai";import Fr from"openai";import Ir,{WebSocket as Lr,WebSocketServer as Rr}from"ws";import{StringDecoder as Pee}from"node:string_decoder";import{ReadStream as Fee,WriteStream as Iee,isatty as zr}from"node:tty";import Lee from"qrcode";import{createSocket as Ree}from"node:dgram";import{SimplePool as zee}from"nostr-tools/pool";import{finalizeEvent as Bee,getPublicKey as Vee,verifyEvent as Hee}from"nostr-tools/pure";import{ROOT_CONTEXT as Br,SpanKind as Vr,SpanStatusCode as Hr,TraceFlags as Ur,ValueType as Wr,trace as Uee}from"@opentelemetry/api";import{ExportResultCode as Gr}from"@opentelemetry/core";import{ProtobufLogsSerializer as Kr,ProtobufMetricsSerializer as qr,ProtobufTraceSerializer as Jr}from"@opentelemetry/otlp-transformer";import{resourceFromAttributes as Yr}from"@opentelemetry/resources";import{BatchSpanProcessor as Wee,TracerProvider as Gee}from"@opentelemetry/sdk-trace";import{AggregationTemporality as Xr,DataPointType as Zr}from"@opentelemetry/sdk-metrics";import{SeverityNumber as Qr}from"@opentelemetry/api-logs";import{createInterface as $r}from"node:readline/promises";import Kee from"open";import{Client as qee,IssuerMismatchError as Jee,LATEST_PROTOCOL_VERSION as ei,OAuthError as Yee,OAuthErrorCode as Xee,ProtocolError as Zee,ProtocolErrorCode as Qee,SERVER_INFO_META_KEY as $ee,SdkError as ti,SdkErrorCode as ni,SdkHttpError as ete,StreamableHTTPClientTransport as tte,UnauthorizedError as nte,UnsupportedProtocolVersionError as ri,buildDiscoveryUrls as rte,deserializeMessage as ite,discoverAuthorizationServerMetadata as ate,exchangeAuthorization as ote,extractWWWAuthenticateParams as ste,refreshAuthorization as cte,registerClient as lte,selectClientAuthMethod as ute,serializeMessage as dte,startAuthorization as fte}from"@modelcontextprotocol/client";import{OAuthMetadataSchema as pte,OAuthProtectedResourceMetadataSchema as mte}from"@modelcontextprotocol/core";import{DEFAULT_INHERITED_ENV_VARS as hte}from"@modelcontextprotocol/client/stdio";import{getRequestListener as gte}from"@hono/node-server";import{Hono as _te}from"hono";import{bodyLimit as vte}from"hono/body-limit";import{streamSSE as yte}from"hono/streaming";import{Server as bte,createMcpHandler as xte,inputRequired as ii,inputResponse as Ste,specTypeSchemas as Cte}from"@modelcontextprotocol/server";import{StdioServerTransport as wte}from"@modelcontextprotocol/server/stdio";import{toNodeHandler as Tte}from"@modelcontextprotocol/node";import{PROTOCOL_VERSION as Ete,RequestError as ai,agent as Dte,ndJsonStream as Ote}from"@agentclientprotocol/sdk";var oi=class extends Error{category;recoverable;constructor(e,t,n=!0){super(t),this.name=`BackgroundTaskError`,this.category=e,this.recoverable=n}};const kte=new Set([`idle`,`max_runtime`,`output_limit`,`repetition`,`stale_worker`]);function Ate(){let e=()=>{},t=()=>{},n=new Promise((n,r)=>{e=n,t=r});return n.catch(()=>{}),{promise:n,resolve:e,reject:t}}function si(e){return new oi(`runner`,e)}function jte(e){return e instanceof oi?{category:e.category,message:e.message,recoverable:e.recoverable}:{category:`runner`,message:e instanceof Error?e.message:e,recoverable:!0}}function Mte(e){return e instanceof Error?e.message:e}function Nte(e,t){if(e.kind===`agent`){let n=t.metadata?.worktreePath;typeof n==`string`&&(e.worktreePath=n);let r=t.metadata?.branchName;typeof r==`string`&&(e.branchName=r);let i=t.metadata?.worktreeStatus;typeof i==`string`&&(e.worktreeStatus=i);let a=t.metadata?.worktreeNextAction;typeof a==`string`&&(e.worktreeNextAction=a);let o=t.metadata?.worktreeBaseRevision;typeof o==`string`&&(e.worktreeBaseRevision=o);let s=t.metadata?.parentWorktreeStatus;typeof s==`string`&&(e.parentWorktreeStatus=s)}let n=t.metadata?.logPath;typeof n==`string`&&(e.logPath=n);let r=t.metadata?.transcriptPath;typeof r==`string`&&(e.transcriptPath=r);let i=t.metadata?.timeoutReason;Pte(i)&&(e.timeoutReason=i)}function Pte(e){return typeof e==`string`&&kte.has(e)}function ci(e){e.unref?.()}function li(e){return e.replace(/\s+/g,` `).trim()}function Fte(e,t){return e.length<=t?e:e.slice(e.length-t)}function Ite(e,t){if(t<=1)return!1;let n=li(e);if(!n)return!1;let r=n.split(/(?<=[.!?。!?])\s+/).map(e=>e.trim()).filter(e=>e.length>=12);if(r.length<t)return!1;let i=``,a=0;for(let e of r)if(e===i?a+=1:(i=e,a=1),a>=t)return!0;return!1}function Lte(e){let t=e.metadata?{...e.metadata}:void 0;return e.kind===`tool-invocation`?{...t,toolName:e.toolName,serverId:e.serverId,sourceName:e.sourceName,...e.securityIdentity===void 0?{}:{securityIdentity:e.securityIdentity},permissionMode:e.permissionMode,provenanceOwner:e.provenanceOwner}:t}function Rte(e,t,n,r,i=`queued`){let a=Lte(t),o={id:e,label:t.label,status:i,mode:t.mode,parentSessionId:t.parentSessionId,parentTaskId:t.parentTaskId,depth:t.depth,cwd:t.cwd,updatedAt:n,unread:!1,...a?{metadata:a}:{}};switch(t.kind){case`agent`:return{...o,kind:`agent`,agentType:t.agentType,isolation:t.isolation,promptPreview:t.prompt.slice(0,r),...t.resumeSessionId===void 0?{}:{resumeSessionId:t.resumeSessionId}};case`process`:return{...o,kind:`process`,commandPreview:t.command.slice(0,r)};case`tool-invocation`:return{...o,kind:`tool-invocation`,commandPreview:`${t.toolName} (${t.serverId})`.slice(0,r)};case`scheduled`:{let e=t.command??t.agentInstruction;return{...o,kind:`scheduled`,...e===void 0?{}:{commandPreview:e.slice(0,r)},schedule:{cronExpression:t.cronExpression,...t.agentInstruction===void 0?{}:{agentInstruction:t.agentInstruction},...t.command===void 0?{}:{command:t.command},...t.shell===void 0?{}:{shell:t.shell},...t.env===void 0?{}:{env:{...t.env}}}}}}}function zte(e,t){return!t||!(t.kind&&e.kind!==t.kind||t.status&&e.status!==t.status||t.mode&&e.mode!==t.mode)}function ui(e){if(e)return{...e,metadata:e.metadata?{...e.metadata}:void 0}}function di(e){let t=e.metadata?{...e.metadata}:void 0,n=e.error?{...e.error}:void 0;switch(e.kind){case`agent`:return{...e,metadata:t,error:n,result:ui(e.result)};case`process`:return{...e,metadata:t,error:n,result:ui(e.result)};case`tool-invocation`:return{...e,metadata:t,error:n,result:ui(e.result)};case`scheduled`:return{...e,metadata:t,error:n,result:ui(e.result),schedule:e.schedule?{...e.schedule,env:e.schedule.env?{...e.schedule.env}:void 0}:void 0}}}const Bte=new Set([`completed`,`failed`,`cancelled`]),Vte=[{from:`queued`,event:`START`,to:`running`},{from:`queued`,event:`CANCEL`,to:`cancelled`},{from:`running`,event:`REQUEST_PERMISSION`,to:`waiting_permission`},{from:`running`,event:`COMPLETE`,to:`completed`},{from:`running`,event:`FAIL`,to:`failed`},{from:`running`,event:`CANCEL`,to:`cancelled`},{from:`running`,event:`SLEEP`,to:`sleeping`},{from:`waiting_permission`,event:`PERMISSION_ALLOWED`,to:`running`},{from:`waiting_permission`,event:`PERMISSION_DENIED`,to:`failed`},{from:`waiting_permission`,event:`CANCEL`,to:`cancelled`},{from:`sleeping`,event:`WAKE`,to:`running`},{from:`sleeping`,event:`CANCEL`,to:`cancelled`},{from:`sleeping`,event:`PAUSE`,to:`paused`},{from:`running`,event:`PAUSE`,to:`paused`},{from:`paused`,event:`RESUME`,to:`sleeping`},{from:`paused`,event:`CANCEL`,to:`cancelled`}];function fi(e){return Bte.has(e)}function pi(e,t){let n=Vte.find(n=>n.from===e&&n.event===t);if(n)return n.to;throw new oi(`validation`,`Invalid background task transition: ${e} + ${t} (${fi(e)?`terminal status`:`unsupported event`})`)}function Hte(e,t){return e.state.status=pi(e.state.status,`START`),e.state.startedAt=t,e.state.updatedAt=t,e.state.lastActivityAt=t,di(e.state)}function mi(e,t,n){if(e.depth>n)throw new oi(`validation`,`Background task depth limit exceeded: depth=${e.depth} maxDepth=${n}`);if(!t.has(e.kind))throw si(`No background task runner registered for kind: ${e.kind}`)}function hi(e,t,n){if(e.handle=t,t.pid&&(e.state.pid=t.pid),t.logPath&&(e.state.logPath=t.logPath),t.transcriptPath&&(e.state.transcriptPath=t.transcriptPath),!t.pid&&!t.logPath&&!t.transcriptPath)return;let r=n();return e.state.updatedAt=r,e.state.lastActivityAt=r,di(e.state)}function gi(e,t,n){return e.state.status=pi(e.state.status,`COMPLETE`),e.state.result=t,Nte(e.state,t),e.state.unread=e.state.mode===`background`,e.state.completedAt=n,e.state.updatedAt=n,di(e.state)}function _i(e,t,n){return e.state.status=pi(e.state.status,`FAIL`),e.state.error=jte(t),e.state.completedAt=n,e.state.updatedAt=n,di(e.state)}function vi(e,t,n){return e.state.status=pi(e.state.status,`CANCEL`),e.state.error={category:`runner`,message:t??`Background task cancelled`,recoverable:!0},e.state.completedAt=n,e.state.updatedAt=n,{task:di(e.state)}}function yi(e,t){return e.state.status=pi(e.state.status,`PAUSE`),e.state.kind===`scheduled`&&(e.state.nextFireAt=void 0),e.state.updatedAt=t,di(e.state)}function bi(e,t){return e.state.status=pi(e.state.status,`RESUME`),e.state.updatedAt=t,di(e.state)}function xi(e,t,n){if(e.state.lastActivityAt=n,t.type===`background_task_tool_start`)return e.state.currentAction=t.firstArg??t.toolName,e.state.updatedAt=n,di(e.state);if(t.type===`background_task_tool_end`)return e.state.currentAction=t.success?void 0:t.error??t.toolName,e.state.updatedAt=n,di(e.state);if(t.type===`background_task_sleeping`)return e.state.status!==`sleeping`&&(e.state.status=pi(e.state.status,`SLEEP`)),e.state.kind===`scheduled`&&(e.state.nextFireAt=t.nextFireAt),e.state.updatedAt=n,di(e.state);if(t.type===`background_task_waking`)return e.state.status===`sleeping`&&(e.state.status=pi(e.state.status,`WAKE`)),e.state.kind===`scheduled`&&(e.state.nextFireAt=void 0),e.state.updatedAt=n,di(e.state)}function Si(e){try{if(e.runner.kind!==e.task.request.kind)throw new oi(`runner`,`Runner kind ${e.runner.kind} does not match task kind ${e.task.request.kind}`);let t=e.runner.start({taskId:e.task.state.id,request:e.task.request,emit:e.onEvent}),n=hi(e.task,t,e.now);n&&e.onUpdated(n),e.onStarted(),t.result.then(t=>e.onCompleted(t),t=>e.onFailed(t instanceof Error?t:String(t)))}catch(t){e.onFailed(t instanceof Error?t:String(t))}}var Ci=class{defaults;onTimeout;constructor(e,t){this.defaults=e,this.onTimeout=t}start(e){if(e.request.kind!==`agent`)return;this.resetIdleTimer(e);let t=e.request.maxRuntimeMs??this.defaults.agentMaxRuntimeMs;t>0&&(e.maxRuntimeTimer=setTimeout(()=>{this.onTimeout(e,`max_runtime`,`Background agent exceeded max runtime: ${t}ms`)},t),ci(e.maxRuntimeTimer))}recordActivity(e,t){(e.state.status===`running`||e.state.status===`waiting_permission`)&&(e.state.lastActivityAt=t,this.resetIdleTimer(e))}clear(e){e.idleTimer&&=(clearTimeout(e.idleTimer),void 0),e.maxRuntimeTimer&&=(clearTimeout(e.maxRuntimeTimer),void 0)}applyTextGuards(e,t){if(e.request.kind!==`agent`)return;e.outputBytes+=Buffer.byteLength(t,`utf8`),e.textDeltas+=1,e.recentText=Fte(`${e.recentText}${t}`,e.request.repetitionWindow??this.defaults.repetitionWindow);let n=e.request.outputLimitBytes??this.defaults.agentOutputLimitBytes;if(n>0&&e.outputBytes>n){this.onTimeout(e,`output_limit`,`Background agent exceeded output limit: ${n} bytes`);return}let r=e.request.maxTextDeltas??this.defaults.agentMaxTextDeltas;if(r>0&&e.textDeltas>r){this.onTimeout(e,`output_limit`,`Background agent exceeded text delta limit: ${r}`);return}this.isRepetitiveOutput(e,t)&&this.onTimeout(e,`repetition`,`Background agent produced repetitive output`)}resetIdleTimer(e){if(e.request.kind!==`agent`)return;e.idleTimer&&clearTimeout(e.idleTimer);let t=e.request.idleTimeoutMs??e.request.timeoutMs??this.defaults.agentIdleTimeoutMs;t<=0||(e.idleTimer=setTimeout(()=>{this.onTimeout(e,`idle`,`Background agent produced no activity for ${t}ms`)},t),ci(e.idleTimer))}isRepetitiveOutput(e,t){if(e.request.kind!==`agent`)return!1;let n=e.request.repetitionThreshold??this.defaults.repetitionThreshold;if(n<=1)return!1;let r=li(t);return r&&r===e.lastNormalizedDelta?e.repeatedDeltaCount+=1:(e.lastNormalizedDelta=r,e.repeatedDeltaCount=+!!r),e.repeatedDeltaCount>=n||Ite(e.recentText,n)}};function wi(e,t){return new Ci({agentIdleTimeoutMs:e.agentIdleTimeoutMs??24e4,agentMaxRuntimeMs:e.agentMaxRuntimeMs??0,agentOutputLimitBytes:e.agentOutputLimitBytes??256e3,agentMaxTextDeltas:e.agentMaxTextDeltas??2e4,repetitionWindow:e.repetitionWindow??800,repetitionThreshold:e.repetitionThreshold??8},t)}function Ti(e,t=`BACKGROUND_OBSERVER_FAILURE`){let n=e.error instanceof Error?e.error.message:String(e.error??`unknown`),r=typeof e.event==`object`&&e.event!==null&&`type`in e.event?String(e.event.type):`unknown`;process.emitWarning(`Background lifecycle observer #${e.observerIndex} threw on '${r}': ${n}`,{code:t})}function Ei(e,t,n){let r=0,i=0;for(let a of t){try{a(e)}catch(t){r+=1,n({event:e,error:t,observerIndex:i})}i+=1}return r}const Di=new TextEncoder;function Oi(e){let t=[],n=0,r=!1,i=e.truncationMarker??`
3
3
  [output truncated]
4
4
  `;return{appendOutput(a){if(r)return;let o=e.limitBytes-n,s=ji(a);if(s<=o){t.push(a),n+=s;return}let c=Mi(a,Math.max(o,0));c.length>0&&t.push(c),t.push(i),r=!0},getOutput(){return t.join(``)}}}function ki(e,t,n){for(let r of n.split(/\r?\n/))r.length>0&&e.push(`[${t}] ${r}`)}function Ai(e,t,n,r=200){let i=n?.offset??0,a=Math.min(i+r,t.length);return{taskId:e,cursor:n,nextCursor:a<t.length?{offset:a}:void 0,lines:t.slice(i,a)}}function ji(e){return Di.encode(e).byteLength}function Mi(e,t){let n=0,r=0;for(let i of e){let e=ji(i);if(n+e>t)break;n+=e,r+=i.length}return e.slice(0,r)}function Ni(e,t={}){let n=Ut({executable:e.shell?.trim()||t.executable,...t.env===void 0?{}:{env:t.env},...t.platform===void 0?{}:{platform:t.platform}});return{executable:n.command,args:n.commandArgs(e.command)}}const Pi=process.platform!==`win32`,Fi=3e4;function Ii(e,t,n={}){let r=new Bn(e,{paused:!0,...n.timezone===void 0?{}:{timezone:n.timezone}});try{return r.nextRun(new Date(t.getTime()-1))}finally{r.stop()}}function Li(e={}){return{kind:`scheduled`,nextScheduledFireOnOrAfter:(t,n)=>Ii(t,n,e),start(t){if(t.request.kind!==`scheduled`)throw new oi(`runner`,`Invalid scheduled task kind: ${t.request.kind}`);return Ri(t.taskId,t.request,t.emit??(()=>void 0),e)}}}function Ri(e,t,n,i){t.command!==void 0&&Ni({...t,command:t.command},{executable:i.shellExecutable});let a,o=new Promise(e=>{a=e}),s=[],c={protect:!0,...i.timezone===void 0?{}:{timezone:i.timezone}},l=()=>{u.cancelled||u.paused||zi(u)},u={taskId:e,request:t,shellExecutable:i.shellExecutable,logs:s,cancelled:!1,paused:!1,fired:!1,emit:n,resolve:a,job:new Bn(t.cronExpression,c,l)};return Bi(u),{taskId:e,result:o,cancel:async()=>{u.cancelled=!0,u.job.stop(),u.currentChild&&await r(u.currentChild,{processGroup:Pi}),a({taskId:e,kind:`scheduled`,output:Oi({limitBytes:Fi}).getOutput()})},pause:()=>(u.paused=!0,u.job.pause(),Promise.resolve()),resume:()=>(u.paused=!1,u.job.resume(),Bi(u),Promise.resolve()),editSchedule:e=>(u.request={...u.request,...e},e.cronExpression!==void 0&&(u.job.stop(),u.job=new Bn(e.cronExpression,c,l),u.paused&&u.job.pause()),u.paused||Bi(u),Promise.resolve()),readLog:t=>Promise.resolve(Ai(e,s,t))}}function zi(e){if(e.cancelled||e.paused)return;e.fired=!0,e.emit(e.request.agentInstruction===void 0?{type:`background_task_waking`}:{type:`background_task_waking`,instruction:e.request.agentInstruction});let t=e.request.command;if(t===void 0){e.cancelled||Bi(e);return}let n=Oi({limitBytes:e.request.outputLimitBytes??Fi}),i=Ni({...e.request,command:t},{executable:e.shellExecutable}),a=on(i.executable,i.args,{cwd:e.request.cwd,env:{...process.env,...e.request.env??{}},stdio:[`ignore`,`pipe`,`pipe`],detached:Pi});e.currentChild=a;let o=e.request.timeoutMs===void 0?void 0:setTimeout(()=>{ki(e.logs,`system`,`fire timed out after ${e.request.timeoutMs}ms — killing`),r(a,{processGroup:Pi})},e.request.timeoutMs),s=()=>{o&&clearTimeout(o)};a.stdout?.on(`data`,t=>{let r=t.toString(`utf8`);n.appendOutput(r),ki(e.logs,`stdout`,r)}),a.stderr?.on(`data`,t=>{let r=t.toString(`utf8`);n.appendOutput(r),ki(e.logs,`stderr`,r)}),a.on(`close`,()=>{s(),e.currentChild===a&&(e.currentChild=void 0),!e.cancelled&&!e.paused&&Bi(e)}),a.on(`error`,t=>{s(),e.currentChild===a&&(e.currentChild=void 0),ki(e.logs,`system`,t.message),!e.cancelled&&!e.paused&&Bi(e)})}function Bi(e){let t=e.job.nextRun();if(t===null){!e.cancelled&&!e.paused&&e.fired&&Vi(e);return}e.emit({type:`background_task_sleeping`,nextFireAt:t.toISOString()})}function Vi(e){e.job.stop(),e.resolve({taskId:e.taskId,kind:`scheduled`,output:e.logs.join(`
5
5
  `)})}var Hi=class{runners=new Map;maxConcurrent;maxDepth;now;idFactory;watchdogs;listeners=new Set;eventSink;onObserverFailure;tasks=new Map;queue=[];slotHolders=new Set;sequence=0;shuttingDown=!1;shutdownPromise;constructor(e){for(let t of e.runners)this.runners.set(t.kind,t);this.maxConcurrent=e.maxConcurrent??4,this.maxDepth=e.maxDepth??1,this.eventSink=e.eventSink,this.onObserverFailure=e.onObserverFailure??(t=>Ti(t,e.observerFailureWarningCode)),this.now=e.now??(()=>new Date().toISOString()),this.watchdogs=wi(e,(e,t,n)=>{this.failForTimeout(e,t,n)}),this.idFactory=e.idFactory??(()=>(this.sequence+=1,`task_${this.sequence}`))}async spawn(e){if(this.shuttingDown)throw new oi(`validation`,`Background task manager is shutting down`);mi(e,this.runners,this.maxDepth);let t=this.idFactory(e),n=Ate();n.promise.catch(()=>void 0);let r=this.runners.get(e.kind),i=r?.admission===`already-running`?r:void 0,a=Rte(t,e,this.now(),120,i?`running`:`queued`),o={state:a,request:e,completion:n.promise,resolve:n.resolve,reject:n.reject,recentText:``,outputBytes:0,textDeltas:0,repeatedDeltaCount:0};return this.tasks.set(t,o),i?(this.emit({type:`background_task_created`,task:di(a)}),this.startAdmittedTask(o,i)):(this.queue.push(t),this.emit({type:`background_task_created`,task:di(a)}),this.drainQueue()),di(a)}wait(e){return this.requireTask(e).completion}list(e){return[...this.tasks.values()].map(e=>e.state).filter(t=>zte(t,e)).map(e=>di(e))}get(e){let t=this.tasks.get(e);return t?di(t.state):void 0}nextScheduledFireOnOrAfter(e,t){let n=this.runners.get(`scheduled`);return n?.nextScheduledFireOnOrAfter?n.nextScheduledFireOnOrAfter(e,t):Ii(e,t)}async cancel(e,t){let n=this.requireTask(e);if(fi(n.state.status))return;if(n.state.status===`queued`){this.removeFromQueue(e),this.cancelTask(n,t);return}let r=n.handle;this.cancelTask(n,t),await r?.cancel(t).catch(()=>void 0)}async close(e){if(!fi(this.requireTask(e).state.status))throw si(`Cannot close active background task: ${e}`);this.tasks.delete(e),this.emit({type:`background_task_closed`,taskId:e})}async pauseScheduledTask(e){let t=this.requireScheduledTask(e);if(t.state.status===`paused`)return;let n=t.handle;if(!n?.pause)throw si(`Background task runner does not support pause: ${e}`);let r=yi(t,this.now());this.releaseSlot(e),this.emit({type:`background_task_updated`,task:r}),await n.pause(),this.shuttingDown||this.drainQueue()}async resumeScheduledTask(e){let t=this.requireScheduledTask(e);if(t.state.status!==`paused`)return;let n=t.handle;if(!n?.resume)throw si(`Background task runner does not support resume: ${e}`);let r=bi(t,this.now());this.emit({type:`background_task_updated`,task:r}),await n.resume()}async editScheduledTask(e,t){let n=this.requireScheduledTask(e),r=n.handle;if(!r?.editSchedule)throw si(`Background task runner does not support edit: ${e}`);await r.editSchedule(t);let{label:i,...a}=t;n.state.kind===`scheduled`&&n.state.schedule&&(n.state.schedule={...n.state.schedule,...a}),i!==void 0&&(n.state.label=i),n.state.updatedAt=this.now(),this.emit({type:`background_task_updated`,task:di(n.state)})}requireScheduledTask(e){let t=this.requireTask(e);if(t.state.kind!==`scheduled`)throw si(`Not a scheduled task: ${e}`);if(fi(t.state.status))throw si(`Cannot change lifecycle of a ${t.state.status} task: ${e}`);if(t.state.status===`queued`)throw si(`Cannot change lifecycle of a not-yet-started (queued) schedule: ${e}`);return t}shutdown(e=`Background task manager shutdown`){return this.shutdownPromise?this.shutdownPromise:(this.shuttingDown=!0,this.shutdownPromise=Promise.all([...this.tasks.values()].filter(e=>!fi(e.state.status)).map(t=>this.cancel(t.state.id,e))).then(()=>void 0),this.shutdownPromise)}async send(e,t){let n=this.requireTask(e);if(!n.handle?.send)throw si(`Background task runner does not support input: ${e}`);await n.handle.send(t)}async readLog(e,t){let n=this.requireTask(e);if(!n.handle?.readLog)throw si(`Background task runner does not support log reads: ${e}`);return n.handle.readLog(t)}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}acquireSlot(e){this.slotHolders.add(e)}releaseSlot(e){this.slotHolders.delete(e)}drainQueue(){for(;this.slotHolders.size<this.maxConcurrent;){let e=this.queue.shift();if(!e)return;let t=this.tasks.get(e);!t||t.state.status!==`queued`||this.startTask(t)}}startTask(e){let t=this.runners.get(e.request.kind);if(!t){this.failTask(e,si(`No runner for task kind: ${e.request.kind}`));return}let n=Hte(e,this.now());this.acquireSlot(e.state.id),this.emit({type:`background_task_started`,task:n}),Si({task:e,runner:t,now:this.now,onEvent:t=>this.handleRunnerEvent(e,t),onStarted:()=>this.watchdogs.start(e),onUpdated:e=>this.emit({type:`background_task_updated`,task:e}),onCompleted:t=>this.completeTask(e,t),onFailed:t=>this.failTask(e,t)})}startAdmittedTask(e,t){let n=this.now();e.state.startedAt=n,e.state.updatedAt=n,e.state.lastActivityAt=n,this.emit({type:`background_task_started`,task:di(e.state)}),Si({task:e,runner:t,now:this.now,onEvent:t=>this.handleRunnerEvent(e,t),onStarted:()=>this.watchdogs.start(e),onUpdated:e=>this.emit({type:`background_task_updated`,task:e}),onCompleted:t=>this.completeTask(e,t),onFailed:t=>this.failTask(e,t)})}completeTask(e,t){if(fi(e.state.status))return;if(t.taskId!==e.state.id||t.kind!==e.state.kind){this.failTask(e,si(`Background task result identity mismatch: expected ${e.state.id} (${e.state.kind}), received ${t.taskId} (${t.kind})`));return}this.watchdogs.clear(e);let n=gi(e,t,this.now());this.releaseSlot(e.state.id),e.resolve(t),this.emit({type:`background_task_completed`,task:n}),this.shuttingDown||this.drainQueue()}failTask(e,t){if(fi(e.state.status))return;this.watchdogs.clear(e);let n=_i(e,t,this.now());this.releaseSlot(e.state.id),e.reject(si(Mte(t))),this.emit({type:`background_task_failed`,task:n}),this.shuttingDown||this.drainQueue()}cancelTask(e,t){if(fi(e.state.status))return;this.watchdogs.clear(e);let n=vi(e,t,this.now());this.releaseSlot(e.state.id),e.reject(si(e.state.error?.message??`Background task cancelled`)),this.emit({type:`background_task_cancelled`,task:n.task}),this.shuttingDown||this.drainQueue()}handleRunnerEvent(e,t){if(!fi(e.state.status)){if(this.applyRunnerEventToState(e,t),t.type===`background_task_sleeping`){this.releaseSlot(e.state.id),this.shuttingDown||this.drainQueue();return}if(t.type===`background_task_waking`){this.acquireSlot(e.state.id),this.emit({type:`background_task_waking`,taskId:e.state.id,...t.instruction===void 0?{}:{instruction:t.instruction}});return}this.emit({...t,taskId:e.state.id}),t.type===`background_task_text_delta`&&this.watchdogs.applyTextGuards(e,t.delta)}}applyRunnerEventToState(e,t){let n=this.now();this.watchdogs.recordActivity(e,n);let r=xi(e,t,n);r&&this.emit({type:`background_task_updated`,task:r})}async failForTimeout(e,t,n){if(fi(e.state.status))return;e.state.timeoutReason=t;let r=e.handle;this.failTask(e,new oi(`timeout`,n));try{await r?.cancel(n)}catch{}}removeFromQueue(e){let t=this.queue.indexOf(e);t>=0&&this.queue.splice(t,1)}requireTask(e){let t=this.tasks.get(e);if(!t)throw si(`Unknown background task: ${e}`);return t}emit(e){Ei(e,this.eventSink?[this.eventSink,...this.listeners]:[...this.listeners],this.onObserverFailure)}};function Ui(e){let t=new RegExp(e.matchPattern),n=e.cooldownMs??1e3,r=e.now??(()=>Date.now()),i=``,a=-1/0;return{push(o){i+=o;let s=i.split(`
@@ -123,10 +123,10 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
123
123
  `);return[this.basePrompt??ms,r,``,`Conversation:`,i].join(`
124
124
  `)}};const gs=.835;var _s=class{contextUsedTokens=0;contextMaxTokens;contextMaxTokensOverride;autoCompactThreshold;constructor(e,t,n){this.contextMaxTokensOverride=t,this.contextMaxTokens=t??mt(e),this.autoCompactThreshold=vs(n)}getContextState(){let e=Math.min(100,this.contextUsedTokens/this.contextMaxTokens*100);return{maxTokens:this.contextMaxTokens,usedTokens:this.contextUsedTokens,usedPercentage:Math.round(e*100)/100,remainingPercentage:Math.round((100-e)*100)/100}}shouldAutoCompact(e){return this.autoCompactThreshold!==!1&&(e?Mt(e).usedTokens:this.contextUsedTokens)>=this.contextMaxTokens*this.autoCompactThreshold}setModel(e){this.contextMaxTokens=this.contextMaxTokensOverride??mt(e)}getAutoCompactThreshold(){return this.autoCompactThreshold}setAutoCompactThreshold(e){this.autoCompactThreshold=vs(e)}updateFromHistory(e){this.contextUsedTokens=Mt(e).usedTokens}reset(){this.contextUsedTokens=0}};function vs(e){if(e===void 0)return gs;if(e===!1)return!1;if(!Number.isFinite(e)||e<=0||e>1)throw RangeError(`autoCompactThreshold must be a number greater than 0 and at most 1.`);return e}async function ys(e,t){if(t===void 0)return e;if(t.aborted)return!1;let n;try{return await Promise.race([e,new Promise(e=>{n=()=>e(!1),t.addEventListener(`abort`,n,{once:!0})})])}finally{n!==void 0&&t.removeEventListener(`abort`,n)}}function bs(e){return e===`allow-session`?{allowed:!0,rememberForSession:!0,rememberForProject:!1}:e===`allow-project`?{allowed:!0,rememberForSession:!0,rememberForProject:!0}:{allowed:e===!0,rememberForSession:!1,rememberForProject:!1}}async function xs(e){let t={allowed:!1,rememberForSession:!1,rememberForProject:!1};if(e.alreadyAllowed)return{allowed:!0,rememberForSession:!1,rememberForProject:!1};if(e.signal?.aborted===!0)return t;let n={...e.signal?{signal:e.signal}:{},...e.executionId===void 0?{}:{executionId:e.executionId}},r=e.signal!==void 0||e.executionId!==void 0,i=e.handler?()=>r?e.handler(e.toolName,e.toolArgs,n):e.handler(e.toolName,e.toolArgs):e.injectedPrompt&&e.terminal?()=>e.injectedPrompt(e.terminal,e.toolName,e.toolArgs):void 0;return i===void 0?t:bs(await ys(i(),e.signal))}const Ss=`robota-session/approval`;function Cs(e){return e?.waits.some(e=>e.request.kind===Ss)??!1}async function ws(e,t,n){let r=t?.waits.filter(e=>e.request.kind===Ss)??[];if(!n&&!r.length)return;if(!t||t.action.toolName!==e.toolName)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Checkpointed approval requires the current journaled action`);let i=Cn(e.cwd);for(let{request:t}of r)if(t.data.version!==1||t.data.sessionId!==e.sessionId||t.data.cwd!==i||t.data.toolName!==e.toolName)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Saved approval belongs to a different Session or tool`);let a=await t.request({kind:Ss,data:{version:1,sessionId:e.sessionId,cwd:i,toolName:e.toolName,arguments:structuredClone(e.toolArgs)}});if(Object.keys(a).length!==1||typeof a.approved!=`boolean`)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Approval response must contain only a boolean approved decision`);return a.approved}function Ts(e,t){return`${e}\u0000${JSON.stringify(t)}`}var Es=class{classifier;consecutive=0;total=0;paused=!1;retries=new Set;constructor(e){this.classifier=e}isPaused(){return this.paused}resume(){this.paused=!1,this.consecutive=0}grantRetry(e,t){this.retries.add(Ts(e,t))}takeRetry(e,t){return this.retries.delete(Ts(e,t))}async judge(e,t){let n;try{n=await this.classifier.classify(e,t)}catch{n=void 0}if(n===void 0){t?.aborted!==!0&&(this.consecutive+=1);let e=this.consecutive>=3;return e&&(this.paused=!0),{kind:`unusable`,reason:`no usable verdict`,message:`The auto-mode classifier gave no usable verdict, so the call was not run. Try again, or ask the user to approve it.`+(e?` Auto mode is paused: the next calls ask the user.`:``)}}if(n.decision===`allow`)return this.consecutive=0,{kind:`allow`};this.consecutive+=1,this.total+=1;let r=this.consecutive>=3||this.total>=20;return this.total>=20&&(this.total=0),r&&(this.paused=!0),{kind:`block`,reason:n.reason,message:`Blocked by the auto-mode classifier: ${n.reason}. Do not retry the same action; take another approach or ask the user.`+(r?` Auto mode is paused after repeated blocks: the next calls ask the user.`:``)}}};function Ds(e){let t=e.replace(/\\/g,`/`),n=t.lastIndexOf(`/`);return n<0?`.`:n===0?`/`:t.slice(0,n)}function Os(e,t){switch(e){case`path`:{let e=Ds(t);return e===`/`?`/**`:`${e}/**`}case`url`:try{let e=new URL(t);return`${e.protocol}//${e.host}/**`}catch{return t}case`command`:{let e=t.trim().split(/\s+/)[0];return e?`${e} *`:void 0}default:return}}function ks(e,t){let n=Ge(e).argument;if(n===void 0)return e;let r=t[n.key];if(typeof r!=`string`||r===``)return e;let i=Os(n.kind,r);return i===void 0?e:`${e}(${i})`}function As(e,t,n){let r=Ge(e).argument;if(r===void 0||r.kind!==`path`)return t;let i=t[r.key];return typeof i!=`string`||i===``||Pn(i)?t:{...t,[r.key]:Ln(n,i)}}function js(e,t,n){return{success:!1,outcome:e,error:t,data:JSON.stringify(n??{success:!1,output:``,error:t}),metadata:{}}}function Ms(e,t,n){let r=e instanceof Error?e.message:String(e);return t?.({type:`end`,toolName:n.toolName,toolArgs:n.toolArgs,success:!1,executionId:n.executionId}),js(`threw`,r)}const Ns=js(`denied`,`Permission denied. The user did not approve this action.`),Ps=Qe(`ToolHookHelpers`);function Fs(e){if(ye(e)||typeof e.data!=`string`||e.data.length<=3e4)return e;let t=15e3,n=e.data.substring(0,t),r=e.data.substring(e.data.length-t),i=`${n}\n\n[... output truncated: ${e.data.length.toLocaleString()} chars total, showing first and last ${t.toLocaleString()} chars ...]\n\n${r}`;return{...e,data:i}}function Is(e,t,n,r,i,a){return{session_id:e,cwd:t,hook_event_name:`PreToolUse`,tool_name:n,tool_input:r,...i!==void 0&&{permission_mode:i},...a!==void 0&&{transcript_path:a}}}async function Ls(e,t,n,r){let i=t,a,o=new Set([JSON.stringify(i.tool_input)]);for(let t=0;t<8;t++){let t=await Rs(e,i,n,r);if(t.result!==null)return{refusal:t.result};let{permissionDecision:s,updatedInput:c}=t.hookResult;if(c!==void 0){if(typeof c!=`object`||!c||Array.isArray(c))return{refusal:js(`hook-blocked`,`PreToolUse updatedInput must be an object.`)};let e=As(i.tool_name??``,c,i.cwd),t=JSON.stringify(e);if(t!==JSON.stringify(i.tool_input)){if(o.has(t))break;o.add(t),a=e,i={...i,tool_input:e};continue}}return{refusal:null,...a===void 0?{}:{parameters:a},...s===`allow`||s===`ask`?{decision:s}:{}}}let s=`PreToolUse input rewriting did not stabilize; no tool call was executed.`;return{refusal:js(`hook-blocked`,s,{blocked:!0,reason:s})}}async function Rs(e,t,n,r){let i=await ue(e,`PreToolUse`,t,n,r);if(i.blocked){let e=i.reason??`Blocked by hook`;return{result:js(`hook-blocked`,e,{blocked:!0,reason:e}),hookResult:i}}if(Me(`PreToolUse`)){let e=i.errors,t=e?.[0],n=i.unknownHookTypes??[],r=n.length>0?`Hook type(s) with no registered executor: ${n.join(`, `)}. Nothing evaluated this gate, so the tool call is denied rather than silently allowed. Remove the hook from the PreToolUse configuration, or supply an executor for its type.`:``;if(e!==void 0&&t!==void 0){let n=e.length-1,a=`Hook could not evaluate (${t.kind}, source: ${t.source}): ${t.reason}.`+(n>0?` (+${n} more hook failure(s))`:``)+(r===``?``:` Also unevaluated — ${r}`);return{result:js(`hook-blocked`,a,{blocked:!0,reason:a}),hookResult:i}}if(r!==``)return{result:js(`hook-blocked`,r,{blocked:!0,reason:r}),hookResult:i}}return{result:null,hookResult:i}}function zs(e,t,n,r,i){ue(e,`PostToolUse`,{...t,hook_event_name:`PostToolUse`,tool_output:typeof n.data==`string`?n.data:JSON.stringify(n.data)},r,i).catch(e=>Ps.warn(`hook failed`,{error:e}))}function Bs(e,t){let n=Ge(e).argument?.key;if(n===void 0)return;let r=t[n];if(typeof r==`string`)return r.length>200?`${r.slice(0,200)}…`:r}var Vs=class{capacity;now;entries=[];calls=[];constructor(e=20,t=Date.now){this.capacity=e,this.now=t}record(e,t,n,r){let i=Bs(e,t);this.entries.unshift({toolName:e,...i===void 0?{}:{argument:i},reason:n,...r===void 0?{}:{detail:r},at:this.now()}),this.calls.unshift({toolName:e,toolArgs:t}),this.calls.length>this.capacity&&(this.calls.length=this.capacity),this.entries.length>this.capacity&&(this.entries.length=this.capacity)}list(){return[...this.entries]}callAt(e){return this.calls[e]}};const Hs=Qe(`ToolBodyTrace`);var Us=class extends Error{result;constructor(e){super(`Effective tool arguments were not authorized`),this.result=e}};function Ws(e,t){try{e?.eventService?.emit(Ze.DECIDED,{timestamp:new Date,executionId:e.executionId,decidedAt:new Date().toISOString(),decision:t})}catch(e){Hs.warn(`tool permission observation failed`,e instanceof Error?e:Error(String(e)))}}function Gs(e,t){let n=e.execute.bind(e),r=e.executeWithAdmission?.bind(e),i=cee(e.provenance),a=e=>{if(e.type!==`end`||!i)return t.onToolExecution?.(e);let n=we({success:e.success??!1,parts:e.toolResultParts},i);t.onToolExecution?.({...e,toolResultParts:n.parts})},o=Pt,s=Object.create(e);Object.defineProperty(s,"provenance",{value:i,enumerable:!0});let c=async(i,s,c)=>{let l=i,u=`(unknown)`;try{u=e.getName(),l=As(u,i,t.cwd),t.log(`tool_call`,{tool:u,args:l});let d=Is(t.sessionId,t.cwd,u,l,t.getPermissionMode(),t.transcriptPath),f=await Ls(t.config.hooks,d,t.hookTypeExecutors,s?.hookTraceEnv);if(f.refusal)return t.log(`tool_blocked`,{tool:u,reason:`hook`}),Ws(s,`hook-blocked`),f.refusal;f.parameters!==void 0&&(l=f.parameters,d={...d,tool_input:l});let p=await t.checkPermission(u,l,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation,f.decision,s?.executionId);if(p!==!0)return t.log(`tool_denied`,{tool:u,reason:`permission`}),Ws(s,`denied`),a({type:`end`,toolName:u,toolArgs:l,success:!1,denied:!0,executionId:s?.executionId}),typeof p==`object`?js(`denied`,p.message):Ns;Ws(s,`allowed`),s?.signal?.throwIfAborted(),a({type:`start`,toolName:u,toolArgs:structuredClone(l),executionId:s?.executionId}),s?.signal?.throwIfAborted();let m,h=async e=>{s?.signal?.throwIfAborted();let n=As(u,e,t.cwd);if(JSON.stringify(n)!==JSON.stringify(e))throw new Us(js(`denied`,`Tool admission requires final canonical arguments; relative paths must be resolved before admission.`));if(JSON.stringify(n)!==JSON.stringify(l)){let e=Is(t.sessionId,t.cwd,u,n,t.getPermissionMode(),t.transcriptPath),r=await Ls(t.config.hooks,e,t.hookTypeExecutors,s?.hookTraceEnv);if(r.refusal)throw new Us(r.refusal);if(r.parameters!==void 0&&JSON.stringify(r.parameters)!==JSON.stringify(n))throw new Us(js(`hook-blocked`,`A hook cannot replace arguments already settled by the tool; retry as a new call.`));let i=await t.checkPermission(u,n,s?.signal,s?.permissionInteraction,s?.hookTraceEnv,s?.continuation,r.decision,s?.executionId);if(i!==!0)throw new Us(typeof i==`object`?js(`denied`,i.message):Ns);d=e}l=structuredClone(e),s?.signal?.throwIfAborted(),await c?.(l),s?.signal?.throwIfAborted(),m=Date.now()},g=`failure`,_;try{let e=s===void 0?void 0:{...s,parameters:l,instanceEventService:o};c&&r?_=await r(l,e,h):(c?await h(l):m=Date.now(),s?.signal?.throwIfAborted(),_=await n(l,e)),g=s?.signal?.aborted?`interrupted`:_.success?`success`:`failure`}catch(e){throw g=s?.signal?.aborted||Ee(e)?`interrupted`:`failure`,e}finally{try{m!==void 0&&s?.eventService?.emit(De.COMPLETED,{timestamp:new Date,executionId:s.executionId,startedAt:new Date(m).toISOString(),endedAt:new Date(Math.max(Date.now(),m)).toISOString(),outcome:g,toolName:u,...typeof s.toolBodyId==`string`?{toolBodyId:s.toolBodyId}:{}})}catch(e){Hs.warn(`tool body observation failed`,e instanceof Error?e:Error(String(e)))}}let v=Fs(_);v!==_&&typeof _.data==`string`&&t.terminal.writeLine(` ⚠ Output truncated: ${_.data.length.toLocaleString()} chars total — model sees first and last 15,000 chars`),a({type:`end`,toolName:u,toolArgs:l,success:v.success,toolResultData:typeof v.data==`string`?v.data:JSON.stringify(v.data),toolResultParts:v.parts,executionId:s?.executionId,...v.view?{view:v.view}:{}});let y=typeof v.data==`string`?v.data.length:JSON.stringify(v.data)?.length??0;return t.log(`tool_result`,{tool:u,success:v.success,dataChars:y,truncated:v!==_}),zs(t.config.hooks,d,v,t.hookTypeExecutors,s?.hookTraceEnv),v}catch(e){if(uee(e))throw e;return e instanceof Us?e.result:Ms(e,a,{toolName:u,toolArgs:l,executionId:s?.executionId})}},l=async(...e)=>we(await c(...e),i);return s.execute=l,s.executeWithAdmission=l,s.setEventService=t=>{o=t??Pt,e.setEventService(t)},s}function Ks(e){let t=e,n=[];for(;;)try{let e=Cn(t);return n.length===0?e:Ln(e,...n.reverse())}catch{let r=Mn(t);if(r===t)return e;n.push(t.slice(r.length).replace(/^[\\/]/,``)),t=r}}function qs(e,t){let n=In(e,t);return n===``||!n.startsWith(`..`)&&!Pn(n)}function Js(e){return(t,n)=>{let r=Ks(e),i=Ks(Ln(t??r,n));return qs(r,i)?i:void 0}}function Ys(e){let t=[...gt(e.allow,`allow`),...gt(e.restrictive,`deny`)];if(t.length===0)return;let n=t.map(({pattern:e,reason:t})=>`"${e}" ${t}`).join(`; `);throw Error(`Invalid permission pattern(s) in permissions.allow/deny/ask: ${n}. Fix the pattern where it is configured (issue #2428).`)}var Xs=class{sessionId;cwd;getPermissionMode;config;terminal;permissionHandler;promptForApprovalFn;sessionLogger;onToolExecution;hookTypeExecutors;transcriptPath;sessionAllowedTools=new Set;presetFreeRules;onProjectAllowTool;permissionPolicy;taskPermissions;pathProtection;homeDirectory;resolveInWorkspace;commandSandbox;denials=new Vs;peerTurn=!1;checkpointedApprovals=!1;autoMode;constructor(e){this.sessionId=e.sessionId,this.cwd=e.cwd,this.getPermissionMode=e.getPermissionMode,this.config=e.config,this.presetFreeRules=e.presetFreePermissions??{allow:[...e.config.permissions.allow],deny:[...e.config.permissions.deny]},Ys(this.configuredRules(e)),this.terminal=e.terminal,this.permissionHandler=e.permissionHandler,this.promptForApprovalFn=e.promptForApprovalFn,this.sessionLogger=e.sessionLogger,this.onToolExecution=e.onToolExecution,this.hookTypeExecutors=e.hookTypeExecutors,this.transcriptPath=e.transcriptPath,this.onProjectAllowTool=e.onProjectAllowTool,this.permissionPolicy=e.permissionPolicy,this.taskPermissions=e.taskPermissions,this.homeDirectory=e.homeDirectory??or(),this.pathProtection=e.pathProtection,this.resolveInWorkspace=Js(e.cwd),this.commandSandbox=e.commandSandbox,e.permissionClassifier!==void 0&&(this.autoMode=new Es(e.permissionClassifier))}beginTurn(e,t=!1){this.peerTurn=e,this.checkpointedApprovals=t}endTurn(){this.peerTurn=!1,this.checkpointedApprovals=!1}hasPermissionClassifier(){return this.autoMode!==void 0}allowRetryOfDenial(e){let t=this.denials.list()[e],n=this.denials.callAt(e);if(t?.reason===`classifier`&&n!==void 0&&this.autoMode!==void 0)return this.autoMode.grantRetry(n.toolName,n.toolArgs),t}configuredRules(e={config:this.config,...this.taskPermissions===void 0?{}:{taskPermissions:this.taskPermissions}}){return{allow:[...e.config.permissions.allow,...e.taskPermissions?.allow??[]],restrictive:[...e.config.permissions.deny,...e.config.permissions.ask??[],...e.taskPermissions?.deny??[]]}}isToolVisible(e){let t=Ge(e);return!this.peerTurn&&t.repliesToPeer===!0||this.peerTurn&&t.notInPeerTurn===!0?!1:!Nt(e,[...this.config.permissions.deny,...this.taskPermissions?.deny??[]])}registerToolParameters(e){for(let t of e){let e=t.schema;if(e===void 0)continue;let n=e.parameters?.properties??{};ht(e.name,{parameters:Object.keys(n)})}let t=this.configuredRules();Ys(t);for(let{pattern:e,reason:n}of rt(t.restrictive))this.terminal.writeLine(` ⚠ Permission rule "${e}" ${n}.`)}wrapTools(e){this.registerToolParameters(e);let t={sessionId:this.sessionId,cwd:this.cwd,config:this.config,terminal:this.terminal,transcriptPath:this.transcriptPath,onToolExecution:this.onToolExecution,hookTypeExecutors:this.hookTypeExecutors,getPermissionMode:this.getPermissionMode,log:(e,t)=>this.log(e,t),checkPermission:(e,t,n,r,i,a,o,s)=>this.decidePermission(e,t,n,r,i,{continuation:a,...o===void 0?{}:{hookDecision:o},...s===void 0?{}:{executionId:s}})};return e.map(e=>Gs(e,t))}getSessionAllowedTools(){return[...this.sessionAllowedTools]}getRecentDenials(){return this.denials.list()}clearSessionAllowedTools(){this.sessionAllowedTools.clear()}currentPermissionRules(){return{allow:[...this.config.permissions.allow],deny:[...this.config.permissions.deny],ask:[...this.config.permissions.ask??[]]}}applyPresetToolLists(e){let t=Ie(this.presetFreeRules,e);this.config.permissions.allow=t.allow,this.config.permissions.deny=t.deny}async checkPermission(e,t,n,r=`interactive`,i){return await this.decidePermission(e,t,n,r,i)===!0}async checkDelegatedToolCall(e,t,n){let r=Is(this.sessionId,this.cwd,e,t,this.getPermissionMode(),this.transcriptPath),i=await Ls(this.config.hooks,r,this.hookTypeExecutors);return i.refusal||i.parameters!==void 0?(this.log(`tool_blocked`,{tool:e,reason:`hook`,delegated:!0}),!1):await this.decidePermission(e,t,n,`interactive`,void 0,{sandboxed:!1,...i.decision===void 0?{}:{hookDecision:i.decision}})===!0}async decidePermission(e,t,n,r=`interactive`,i,a={}){let o=await this.evaluateToolPermission(e,t,n,r,i,a);return o===!0?(n?.throwIfAborted(),await ws({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a.continuation,!1)??!0):o}async evaluateToolPermission(e,t,n,r=`interactive`,i,a={}){let o=this.permissionPolicy===void 0?void 0:We(this.permissionPolicy,{taskAllow:this.taskPermissions?.allow,taskDeny:this.taskPermissions?.deny,parentAllow:this.config.permissions.allow}),s=this.getPermissionMode(),c=[...this.config.permissions.allow,...o?.allow??[]],l={allow:s===`auto`?Ke(c):c,deny:[...this.config.permissions.deny,...o?.deny??[]],ask:this.config.permissions.ask??[]},u={cwd:this.cwd,homeDirectory:this.homeDirectory,pathProtection:this.pathProtection},d=oe(e,t,s,l,{...u,resolveInWorkspace:this.resolveInWorkspace,sandboxAutoApproved:a.sandboxed!==!1&&this.sandboxAutoApproves(e,t),...o?.ceiling===void 0?{}:{ceiling:o.ceiling},askAll:o?.askAll??!1,...this.peerTurn?{peerTurn:!0}:{}});if(this.firePermissionDecisionHook(e,t,d,i),d===`deny`)return this.denials.record(e,t,`policy`),!1;if(a.hookDecision===`ask`)return this.promptForApproval(e,t,n,r,!0,a);if(d===`auto`)return!0;let f=O(e,t,l,u);return s===`auto`&&this.autoMode!==void 0&&!f&&o?.askAll!==!0?this.decideInAutoMode(this.autoMode,e,t,n,r,i,a):a.hookDecision===`allow`&&!f&&o?.askAll!==!0||this.promptForApproval(e,t,n,r,f,a)}async decideInAutoMode(e,t,n,r,i,a,o){if(e.takeRetry(t,n)||nt(t,n,Ke([...this.sessionAllowedTools])))return!0;if(e.isPaused()){let a=await this.promptForApproval(t,n,r,i,!0,o);return a&&!this.checkpointedApprovals&&!Cs(o.continuation)&&e.resume(),a}let s=await e.judge({toolName:t,toolArgs:n,cwd:this.cwd},r);return r?.aborted===!0?!1:this.getPermissionMode()===`auto`?s.kind===`allow`?!0:(this.denials.record(t,n,`classifier`,s.reason),{message:s.message}):this.decidePermission(t,n,r,i,a,o)}async promptForApproval(e,t,n,r=`interactive`,i=!1,{continuation:a,executionId:o}={}){let s=!i&&nt(e,t,[...this.sessionAllowedTools]);if(this.checkpointedApprovals&&!s||Cs(a)){if(n?.aborted||r!==`interactive`)return!1;let i=await ws({sessionId:this.sessionId,cwd:this.cwd,toolName:e,toolArgs:t},a,!0);return i!==!0&&this.denials.record(e,t,`user`),i===!0}let c=ks(e,t),l=n?.aborted===!0,u=r===`interactive`&&(this.permissionHandler!==void 0||this.promptForApprovalFn!==void 0),d=await xs({toolName:e,alreadyAllowed:s,...r===`interactive`&&this.permissionHandler?{handler:this.permissionHandler}:{},...r===`interactive`&&this.promptForApprovalFn?{injectedPrompt:this.promptForApprovalFn,terminal:this.terminal}:{},toolArgs:t,...n?{signal:n}:{},...o===void 0?{}:{executionId:o}});if(!d.allowed&&!l&&this.denials.record(e,t,u?`user`:`no-approver`),i)return d.allowed;if(d.rememberForProject){if(this.onProjectAllowTool===void 0)throw Error(`Project-wide permission persistence is unavailable for this session.`);this.onProjectAllowTool(c)}return d.rememberForSession&&this.sessionAllowedTools.add(c),d.allowed}firePermissionDecisionHook(e,t,n,r){let i=this.getPermissionMode();ue(this.config.hooks,`PermissionDecision`,{session_id:this.sessionId,cwd:this.cwd,hook_event_name:`PermissionDecision`,tool_name:e,tool_input:t,permission_decision:n,...i!==void 0&&{permission_mode:i},...this.transcriptPath!==void 0&&{transcript_path:this.transcriptPath},env:{CLAUDE_PROJECT_DIR:this.cwd,CLAUDE_SESSION_ID:this.sessionId}},this.hookTypeExecutors,r).catch(()=>void 0)}sandboxAutoApproves(e,t){if(this.commandSandbox===void 0)return!1;let n=Ge(e).argument;if(n?.kind!==`command`)return!1;let r=t[n.key];return typeof r==`string`&&this.commandSandbox.autoApproves(e,r)}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}};function Zs(e,t,n,r,i){return new Xs({pathProtection:e.pathProtection,sessionId:t,cwd:n,getPermissionMode:r,config:{permissions:e.permissions??{allow:[],deny:[]},hooks:e.hooks},...e.presetFreePermissions===void 0?{}:{presetFreePermissions:e.presetFreePermissions},terminal:e.terminal,permissionHandler:e.permissionHandler,...e.commandSandbox===void 0?{}:{commandSandbox:e.commandSandbox},...e.permissionClassifier===void 0?{}:{permissionClassifier:e.permissionClassifier},promptForApprovalFn:e.promptForApproval,sessionLogger:e.sessionLogger,onToolExecution:e.onToolExecution,hookTypeExecutors:e.hookTypeExecutors,transcriptPath:i,onProjectAllowTool:e.onProjectAllowTool,permissionPolicy:e.permissionPolicy,taskPermissions:e.taskPermissions})}function Qs(e,t,n,r){return{contextTracker:new _s(t,e.contextMaxTokens,e.autoCompactThreshold),compactionOrchestrator:new hs({sessionId:n,cwd:r,model:t,hooks:e.hooks,compactInstructions:e.compactInstructions,basePrompt:e.compactionBasePrompt,hookTypeExecutors:e.hookTypeExecutors})}}function $s(e,t,n,r,i,a,o){let s=t.wrapTools(n);return new ve({name:e.agentName??`agent`,aiProviders:[r],...e.providerOwnership===void 0?{}:{providerOwnership:{[r.name]:e.providerOwnership}},defaultModel:{provider:r.name,model:i,...e.effort!==void 0&&{effort:e.effort},...e.temperature!==void 0&&{temperature:e.temperature},...e.maxOutputTokens!==void 0&&{maxTokens:e.maxOutputTokens}},systemMessage:a,tools:s,...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},isToolVisible:e=>t.isToolVisible(e),logging:{enabled:!1},eventService:o,...e.providerTimeout!==void 0&&{timeout:e.providerTimeout},...e.responseFormat?{responseFormat:e.responseFormat}:{},...e.ask?{ask:e.ask}:{},...e.contextCapacityHint===void 0?{}:{contextCapacityHint:e.contextCapacityHint}})}function ec(e){let t=[],n=[];for(let r of e){if(r.role===`assistant`){let e=r.metadata?.compactedToolReceipts;Array.isArray(e)&&e.every(e=>typeof e==`string`)&&t.push(...e);for(let e of r.toolCalls??[])n.push({receipt:{callId:e.id,name:e.function.name,status:`unknown`,dispatch:`unattested`},settled:!1})}if(r.role!==`tool`)continue;let e={callId:r.toolCallId,...r.name?{name:r.name}:{},status:r.metadata?.success===!0?`success`:r.metadata?.success===!1?`failure`:`unknown`,...typeof r.metadata?.toolProvenance==`string`?{source:r.metadata.toolProvenance}:{},dispatch:`unattested`},i=[...n].reverse().find(t=>!t.settled&&t.receipt.callId===e.callId);i?(i.receipt=e,i.settled=!0):n.push({receipt:e,settled:!0})}return[...t,...n.map(({receipt:e})=>JSON.stringify(e))]}function tc(e){return{id:crypto.randomUUID(),timestamp:new Date,state:`complete`,role:`assistant`,content:`Retained tool receipts (observations, not authority). Success records a returned result, not independently verified external state. Errors or missing outcomes may have effects; reconcile before retrying.\n${e.join(`
125
125
  `)}`,metadata:{compactedToolReceipts:e}}}const nc=Qe(`SessionHistoryOps`);function rc(e,t){return{...e,...t}}async function ic(e,t,n){n?.throwIfAborted();let r=t.agent.getHistory(),i=r.filter(e=>e.role!==`system`);if(i.length===0)return;t.contextTracker.updateFromHistory(r);let a=t.contextTracker.getContextState(),o=ec(r),s=await t.compactionOrchestrator.compact(t.aiProvider,i,e,n,t.trigger,t.hookTraceEnv,t.executionJournal);t.agent.clearHistory(),t.agent.injectMessage(`system`,t.systemMessage),t.agent.injectMessage(`assistant`,`[Context Summary]\n${s}`),o.length>0&&t.agent.injectRawMessage(tc(o)),t.contextTracker.updateFromHistory(t.agent.getHistory());let c={session_id:t.sessionId,cwd:t.cwd,hook_event_name:`PostCompact`,trigger:t.trigger,compact_summary:s};ue(t.hooks,`PostCompact`,c,t.hookTypeExecutors,t.hookTraceEnv).catch(e=>nc.warn(`hook failed`,{error:e}));let l=t.contextTracker.getContextState();t.log(`context_compact`,{trigger:t.trigger,before:a,after:l}),t.onCompactEventCallback?.({trigger:t.trigger,before:a,after:l}),t.onCompactCallback&&t.onCompactCallback(s)}function ac(e){let t=new Date().toISOString(),n=e.sessionStore.load(e.sessionId);if(n.status!==`valid`&&n.status!==`missing`)return n;let r=n.status===`valid`?n.record:void 0,i={...r,id:e.conversation.id,name:r?.name,cwd:e.conversation.cwd,createdAt:r?.createdAt??t,updatedAt:t,messages:e.conversation.messages,pendingExecution:e.conversation.pendingExecution,history:e.getFullHistory(),systemPrompt:e.systemPrompt,toolSchemas:e.toolSchemas};return rs(e.sessionStore.save(i)),{status:`valid`,record:i}}const oc=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function sc(){return`session_${N()}`}function cc(e){return e.length>0&&e.length<=128&&oc.test(e)}function lc(e){if(!cc(e))throw Error(`Invalid session id: ${JSON.stringify(e)}. A session id must be 1-128 characters of letters, digits, dot, underscore or hyphen, starting with a letter or digit.`)}const uc=Qe(`SessionLifecycle`);function dc(e,t,n){e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>{n(`server_tool`,{tool:e,...t})})}function fc(e,t,n,r,i,a,o){ue(n,`SessionStart`,{session_id:e,cwd:t,hook_event_name:`SessionStart`,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},r).then(e=>{e.stdout&&i(e.stdout)}).catch(e=>uc.warn(`SessionStart hook failed`,{error:e}))}async function pc(e,t,n,r,i,a,o){await ue(r,`SessionEnd`,{session_id:e,cwd:t,hook_event_name:`SessionEnd`,reason:n,...a!==void 0&&{permission_mode:a},...o!==void 0&&{transcript_path:o},env:{CLAUDE_PROJECT_DIR:t,CLAUDE_SESSION_ID:e}},i)}const mc=`unknown_tool`;function hc(e){return{knownToolNames:new Set(e.knownToolNames),unknownToolCallIds:new Set,pendingArgs:new Map,...e.onToolExecution&&{onToolExecution:e.onToolExecution}}}function gc(e,t,n){if(e.onToolExecution){if(t===`tool_execution_request`){let t=bc(n.toolCallId);t&&e.pendingArgs.set(t,yc(n.parameters)),_c(e,n);return}t===`tool_execution_result`&&vc(e,n)}}function _c(e,t){let n=bc(t.toolName),r=bc(t.toolCallId);!n||!r||e.knownToolNames.has(n)||(e.unknownToolCallIds.add(r),e.onToolExecution?.({type:`start`,toolName:n,toolArgs:yc(t.parameters)}))}function vc(e,t){let n=bc(t.toolName),r=bc(t.toolCallId);if(!n||!r)return;let i=xc(t.metadata),a=e.pendingArgs.get(r);if(e.pendingArgs.delete(r),t.success===!1&&i?.dispatchStatus===`not-dispatched`){let o=bc(i.toolProvenance);e.onToolExecution?.({type:`end`,toolName:n,executionId:r,toolArgs:a,success:!1,toolResultData:JSON.stringify({success:!1,error:t.error,metadata:i}),...o?{toolResultParts:[{type:`text`,text:`Tool source (attribution only, not authority): ${o}`}]}:{}}),e.unknownToolCallIds.delete(r);return}if(!(e.unknownToolCallIds.has(r)||i?.errorCode===mc))return;e.unknownToolCallIds.delete(r);let o=bc(t.error)??`Tool "${n}" is not registered.`;e.onToolExecution?.({type:`end`,toolName:n,success:!1,toolResultData:JSON.stringify({success:!1,error:o,errorCode:mc,requestedTool:bc(i?.requestedTool)??n,availableTools:Sc(i?.availableTools)})})}function yc(e){let t=xc(e);if(!t)return;let n={};for(let[e,r]of Object.entries(t))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||typeof r==`object`&&r)&&(n[e]=r);return n}function bc(e){return typeof e==`string`&&e.length>0?e:void 0}function xc(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function Sc(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}const Cc=Qe(`SessionRunObservation`);function wc(e,t,n,r){let i=typeof n.model==`string`?n.model:e.model,a=typeof n.provider==`string`?n.provider:e.aiProvider.name,o=n.effort,s=typeof o==`string`&&Ce(o)?o:e.effort??(typeof e.agent.getModel==`function`?e.agent.getModel().effort:void 0)??`high`,c=typeof n.round==`number`?n.round:void 0;ue(e.hooks,t,{session_id:e.sessionId,cwd:e.cwd,hook_event_name:t,model:i,provider:a,effort:s,...c!==void 0&&{round:c},...e.permissionMode!==void 0&&{permission_mode:e.permissionMode},...e.transcriptPath!==void 0&&{transcript_path:e.transcriptPath},env:{CLAUDE_PROJECT_DIR:e.cwd,CLAUDE_SESSION_ID:e.sessionId}},e.hookTypeExecutors,r).catch(e=>Cc.warn(`hook failed`,{error:e}))}function Tc(e,t){let n=t?Lt(`hooks`,t,t.parentSpanId):void 0,r=hc({knownToolNames:e.knownToolNames??[],...e.onToolExecution&&{onToolExecution:e.onToolExecution}}),i=e.onTextDelta?t=>{e.log(`text_delta`,{delta:t}),e.onTextDelta?.(t)}:void 0,a={};return{onExecutionEvent:(t,i)=>{if(t===`history_mutation`&&i.mutation===`append_message`){let t=i.message;(t?.role===`user`||t?.role===`assistant`&&Array.isArray(t.toolCalls)&&t.toolCalls.length>0)&&e.checkpointHistory?.()}if(t!==st.COMPLETED&&e.log(t,i),gc(r,t,i),t===`provider_request`){let t=i;a={model:t.model,provider:t.provider},wc(e,`PreModelCall`,t,n)}else if(t===`provider_response_normalized`)wc(e,`PostModelCall`,{...i,...a},n);else if(t===xt.SWITCHED){let t=Le(i);t!==void 0&&(wc(e,`PostModelCall`,{round:i.round,model:t.from.model,provider:t.from.provider},n),e.emitProviderFallback?.(t))}else if(t===st.COMPLETED&&e.emitProviderCallCompleted){let t=i;Number.isSafeInteger(t.round)&&t.round>0&&typeof t.startedAt==`string`&&typeof t.endedAt==`string`&&(t.outcome===`success`||t.outcome===`failure`||t.outcome===`interrupted`)&&e.emitProviderCallCompleted({round:t.round,startedAt:t.startedAt,endedAt:t.endedAt,outcome:t.outcome,...typeof t.callId==`string`&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t.callId)&&{callId:t.callId},...(t.disposition===`invoked`||t.disposition===`cache-hit`||t.disposition===`preflight-refused`)&&{disposition:t.disposition},...typeof t.providerId==`string`&&t.providerId.length>0&&t.providerId.length<=128&&[...t.providerId].every(e=>e.charCodeAt(0)>=32)&&{providerId:t.providerId},...typeof t.modelId==`string`&&t.modelId.length>0&&t.modelId.length<=128&&[...t.modelId].every(e=>e.charCodeAt(0)>=32)&&{modelId:t.modelId},...(t.usageProvenance===`complete`||t.usageProvenance===`partial`||t.usageProvenance===`absent`)&&{usageProvenance:t.usageProvenance},...t.usageProvenance===`complete`&&typeof t.promptTokens==`number`&&Number.isSafeInteger(t.promptTokens)&&t.promptTokens>=0&&typeof t.completionTokens==`number`&&Number.isSafeInteger(t.completionTokens)&&t.completionTokens>=0&&typeof t.totalTokens==`number`&&Number.isSafeInteger(t.totalTokens)&&t.totalTokens===t.promptTokens+t.completionTokens&&{promptTokens:t.promptTokens,completionTokens:t.completionTokens,totalTokens:t.totalTokens},...t.disposition===`invoked`&&typeof t.providerRequestId==`string`&&{providerRequestId:t.providerRequestId}})}t===`assistant_message_committed`&&(e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()))},...i&&{onTextDelta:i},...e.onThinkingDelta&&{onThinkingDelta:e.onThinkingDelta}}}async function Ec(e,t){let n=await e.agent.resume({...t,...Tc(e,t.traceContext)});return e.contextTracker.updateFromHistory(e.agent.getHistory()),e.onContextUpdate?.(e.contextTracker.getContextState()),n}function Dc(e,t){let n=Cn(t.cwd);return{append:async r=>{if((r.kind===`model-request`||r.kind===`model-cache-hit`)&&r.checkpoint){let i=structuredClone(r);i.checkpoint.owner={kind:`agent-session`,version:1,state:{sessionId:t.sessionId,cwd:n,peerTurn:t.peerTurn,executionId:r.executionId}},await e.append(i)}else await e.append(r)}}}function Oc(e,t,n,r){let i,a=Cn(n);return{read:async o=>{let s=structuredClone(await e.read(o)),c;for(let e of s){if(e.kind!==`model-request`&&e.kind!==`model-cache-hit`)continue;let n=e.checkpoint?.owner,r=n?.state;if(!n||n.kind!==`agent-session`||n.version!==1||!r||r.sessionId!==t||r.cwd!==a||r.executionId!==o||typeof r.peerTurn!=`boolean`||c!==void 0&&c!==r.peerTurn||r.peerTurn&&e.checkpoint?.continuation?.options.withholdHostedTools!==!0)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Session continuation owner or scope is incompatible`);c=r.peerTurn}if(c===void 0)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`No Session owner checkpoint exists`);return i=Dc(e,{sessionId:t,cwd:n,peerTurn:c}),r(c),s},append:async e=>{if(!i)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Session owner has not been restored`);await i.append(e)}}}function kc(e){return{...e?.executionJournal!==void 0&&{executionJournal:e.executionJournal},...e?.ephemeralSystemContext!==void 0&&{ephemeralSystemContext:e.ephemeralSystemContext},...e?.driverId!==void 0&&{driverId:e.driverId},...e?.turnSource!==void 0&&{turnSource:e.turnSource},...e?.toolChoice!==void 0&&{toolChoice:e.toolChoice},...e?.traceContext!==void 0&&{traceContext:e.traceContext},...e?.peerTurn===!0&&{withholdHostedTools:!0}}}const Ac=Qe(`SessionRun`);async function zre(e,t,n,r,i){let a=i?.traceContext,o=a?Lt(`hooks`,a,a.parentSpanId):void 0;n.log(`user`,{content:e});let s=await ue(n.hooks,`UserPromptSubmit`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`UserPromptSubmit`,user_message:t??e,prompt:t??e,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o),c=[n.sessionStartStdout,s.stdout].filter(Boolean).join(`
126
- `),l=c?`<system-reminder>\n${c}\n</system-reminder>\n${e}`:e,u=Ot(l),d=i?.ephemeralSystemContext,f=[u,...d?.trim()?[He(d)]:[]];n.contextTracker.updateFromHistory(n.agent.getHistory()),n.contextTracker.shouldAutoCompact([...n.agent.getHistory(),...f])&&(i?.executionJournal?await n.compact(r,o,i.executionJournal):await(o?n.compact(r,o):n.compact(r))),n.clearSessionStartStdout();let p=n.agent.getHistory(),m=JSON.stringify(p),h=Be(n.aiProvider);n.log(`pre_run`,{historyLength:p.length,historyChars:m.length,historyEstTokens:Math.ceil(m.length/4),input:l,history:p,model:n.model,provider:n.aiProvider.name,maxTokens:n.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:h.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:h.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:h.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:h.nativeWebTools.webFetch.enabled}),n.contextTracker.updateFromHistory([...p,...f]),n.onContextUpdate?.(n.contextTracker.getContextState());let g;try{if(g=await n.agent.run(l,{signal:r,maxExecutionRounds:n.maxTurns??0,...kc(i),...Tc(n,a)}),r.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){if(e instanceof ot)throw e;try{n.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:n.agent.getHistory().length})}catch{}throw ue(n.hooks,`StopFailure`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>Ac.warn(`hook failed`,{error:e})),e}let _=n.agent.getHistory(),v=_.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});n.log(`assistant`,{content:g,historyLength:_.length,estimatedChars:JSON.stringify(_).length,history:_,historyStructure:v}),n.contextTracker.updateFromHistory(_);let y=n.contextTracker.getContextState();return n.onContextUpdate?.(y),n.log(`context`,{maxTokens:y.maxTokens,usedTokens:y.usedTokens,usedPercentage:y.usedPercentage,remainingPercentage:y.remainingPercentage}),ue(n.hooks,`Stop`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`Stop`,response:g.substring(0,500),last_assistant_message:g,stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>Ac.warn(`hook failed`,{error:e})),g}function jc(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function Mc(e){let t=e.findLastIndex(e=>e.role===`assistant`),n=e[t];if(n?.role!==`assistant`)return;let r=new Set(e.slice(t+1).flatMap(e=>e.role===`tool`?[e.toolCallId]:[]));return{assistant:n,open:(n.toolCalls??[]).filter(e=>!r.has(e.id)),ending:e.slice(t+1).every(e=>e.role===`tool`)}}function Nc(e,t,n){let r=Mc(e),i=r?.assistant.metadata?.executionId;if(!r?.ending||!r.open.length||typeof i!=`string`)return;let a=new Set(r.open.map(e=>e.id)),o=t?.executionId===i?t.requests.filter(e=>a.has(e.toolCallId)&&!n.has(e.actionId)):[];return{executionId:i,requests:structuredClone(o)}}function Bre(e,t,n){return{read:t=>e.read(t),append:r=>(r.kind===`tool-effect-start`&&(t.add(r.actionId),n?.()),e.append(r))}}function Vre(e,t,n){let r=Mc(e);if(!r||r.assistant.metadata?.executionId!==t.executionId)return[];let i=new Set((n?t.requests:[]).map(e=>e.toolCallId));return r.open.map(e=>{let t=i.has(e.id)?`Not run: the execution was abandoned while this call awaited a response.`:`Execution abandoned before this call recorded a result; its outcome is unknown.`;return St(`Error: ${t}`,{toolCallId:e.id,name:e.function.name,metadata:{success:!1,error:t,toolName:e.function.name}})})}async function Pc(e,t){if(!t||typeof t.append!=`function`||typeof t.read!=`function`)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await e()}}catch(e){if(e instanceof ot)return{status:`waiting`,requests:structuredClone(e.requests)};throw e}}var Hre=class{agent;claim;sessionId;ask;execution=null;constructor(e,t,n,r){this.agent=e,this.claim=t,this.sessionId=n,this.ask=r}async invoke(e,t,n){let r=this.claim.claim(),i=Fc(r,n?.signal);try{return r.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:n?.executionId??N(),sessionId:this.sessionId,signal:r.signal,permissionInteraction:n?.permissionInteraction??`deny`,...n?.permissionInteraction===`interactive`&&this.ask!==void 0?{ask:this.askUnder(r.signal)}:{}}),await this.execution}finally{this.execution=null,i(),this.claim.release(r)}}askUnder(e){let t=this.ask;if(t===void 0)throw Error(`No ask port`);return(n,r)=>t(n,{signal:r?.signal??e})}async drain(){await this.execution}};function Fc(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var Ic=class extends ss{agent;eventService=new lee;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;checkpointHistoryCallback;hooks;hookTypeExecutors;onTextDeltaCallback;onThinkingDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;recoveryState={kind:`ready`};checkpointing=!1;get pendingExecution(){return this.recoveryState.kind===`ready`?void 0:this.recoveryState.pending}setPending(e,t=!1){this.recoveryState.kind!==`save-required`&&(this.recoveryState=e?{kind:`pending`,pending:e,liveWaits:t}:{kind:`ready`})}shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super(e.cwd);let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.checkpointHistoryCallback=e.checkpointHistory,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.wrapAddedTools=e.wrapAddedTools,this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.onThinkingDeltaCallback=e.onThinkingDelta,this.onContextUpdateCallback=e.onContextUpdate,this.onToolExecutionCallback=e.onToolExecution,this.onCompactCallback=e.onCompact,this.onCompactEventCallback=e.onCompactEvent,this.maxTurns=e.maxTurns,this.model=e.model??`claude-sonnet-4-5`,this.sessionId=e.sessionId??sc(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?At[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,dc(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=Zs(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:i,compactionOrchestrator:a}=Qs(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.agent=$s(e,this.permissionEnforcer,t,n,this.model,r,this.eventService),this.runtimeTools=new Hre(this.agent,this.turnClaim,this.sessionId,e.ask),fc(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){return this.runTurn(e,t,n,!1)}runRecoverable(e,t,n){return Pc(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(e,t,n,r){let i=n?{...n}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);this.assertInputAllowed();let a=this.turnClaim.claim(),o=Fc(a,i?.signal),{signal:s}=a;this.permissionEnforcer.beginTurn(i?.peerTurn===!0,r);try{s.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let n=i?.executionJournal?{...i,executionJournal:Dc(i.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:i.peerTurn===!0})}:i,r=await zre(e,t,this.buildRunContext(i?.executionJournal!==void 0),s,n);return this.setPending(void 0),this.commitConversation(),this.messageCount+=1,r}catch(e){throw e instanceof ot?(this.setPending(jc(e),!0),s.throwIfAborted()):i?.executionJournal&&this.setPending(Nc(this.agent.getHistory(),void 0,new Set)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),o(),this.turnClaim.release(a)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return Pc(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(e,t){let n={...e,toolResponses:structuredClone(e.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution&&this.pendingExecution.executionId!==n.executionId)throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim(),i=Fc(r,n.signal),a=new Set;try{r.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=Oc(Bre(n.journal,a,()=>{this.recoveryState.kind===`pending`&&(this.recoveryState.liveWaits=!1)}),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,t)),i=await Ec(this.buildRunContext(!0),{...n,journal:e,signal:r.signal});return this.setPending(void 0),this.commitConversation(n.executionId),i}catch(e){throw e instanceof ot?(this.setPending(jc(e),!0),r.signal.throwIfAborted()):this.setPending(Nc(this.agent.getHistory(),this.pendingExecution,a)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}getPendingExecution(){return structuredClone(this.pendingExecution)}abandonPendingExecution(e){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.recoveryState.kind===`save-required`){if(this.recoveryState.executionId!==e||this.pendingExecution)throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`Checkpoint the unresolved Session transition first`);this.checkpoint();return}let t=this.pendingExecution;if(!t)return;if(t.executionId!==e)throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let n=this.turnClaim.claim();try{let n=this.recoveryState.kind===`pending`&&this.recoveryState.liveWaits;for(let e of Vre(this.agent.getHistory(),t,n))this.agent.injectRawMessage(e);this.setPending(void 0),this.commitConversation(e)}finally{this.turnClaim.release(n)}}assertInputAllowed(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution)throw new Xe(`EXECUTION_RECOVERY_REQUIRED`,`Resume or abandon the pending Session execution before submitting new input`)}assertCheckpointSettled(){if(this.checkpointing||this.recoveryState.kind===`save-required`)throw new Xe(`EXECUTION_RECOVERY_REQUIRED`,`Call Session.checkpoint() to save the unresolved conversation transition`)}getConversationSnapshot(){return structuredClone({id:this.sessionId,cwd:Cn(this.cwd),messages:this.agent.getHistory(),...this.pendingExecution?{pendingExecution:this.pendingExecution}:{}})}restoreConversation(e){if(this.assertInputAllowed(),this.turnClaim.isRunning()||this.agent.getHistory().some(e=>e.role!==`system`))throw Error(`Conversation restore requires a pristine idle Session`);if(e.id!==this.sessionId||Cn(e.cwd)!==Cn(this.cwd))throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`Conversation owner or workspace differs`);let t=Qo({id:e.id,cwd:e.cwd,messages:e.messages,...e.pendingExecution===void 0?{}:{pendingExecution:e.pendingExecution},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(t.status!==`valid`)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Invalid conversation recovery snapshot`);let n=structuredClone(t.record);this.agent.clearHistory();for(let e of n.messages)this.agent.injectRawMessage(e);this.setPending(n.pendingExecution),this.syncContextFromHistory()}checkpoint(){if(this.turnClaim.isRunning()||this.checkpointing)throw Error(`Cannot checkpoint during a Session transition`);if(!this.checkpointHistoryCallback&&!this.sessionStore)throw Error(`Session checkpoint requires a persistence sink`);this.commitConversation(this.recoveryState.kind===`save-required`?this.recoveryState.executionId:void 0)}commitConversation(e){if(!this.checkpointHistoryCallback&&!this.sessionStore)return;if(this.checkpointing)throw Error(`Reentrant Session checkpoint`);let t=this.pendingExecution,n=this.recoveryState.kind!==`ready`&&this.recoveryState.liveWaits;this.checkpointing=!0;try{this.checkpointHistoryCallback?rs(this.checkpointHistoryCallback()):this.persistSessionInternal(!0),this.recoveryState=t?{kind:`pending`,pending:t,liveWaits:n}:{kind:`ready`}}catch(r){throw this.recoveryState={kind:`save-required`,pending:t,liveWaits:n,executionId:e??t?.executionId},r}finally{this.checkpointing=!1}}saveAfterFailure(e){if(this.recoveryState.kind!==`save-required`)try{this.commitConversation()}catch(t){if(e instanceof ot)throw t;try{this.log(`error`,{message:`Session checkpoint failed while preserving the execution error: ${t instanceof Error?t.message:String(t)}`,stack:t instanceof Error?t.stack??``:``,historyLength:this.agent.getHistory().length})}catch{}}}addTools(e){return this.assertInputAllowed(),this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.assertInputAllowed(),this.runtimeTools.invoke(e,t,n)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(e=!1){if(!this.sessionStore)return;let t=ac({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,conversation:this.getConversationSnapshot(),getFullHistory:()=>this.getFullHistory()});if(e&&t.status!==`valid`)throw Error(`Session history could not be durably checkpointed: ${t.status}`)}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),await n(`drain-turn`,()=>this.turnClaim.drained),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>pc(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.agent.destroy()})})(),this.shutdownPromise}swapProvider(e,t,n){this.assertInputAllowed(),this.agent.swapDefaultProvider(e,t,n),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e,this.setActiveModel(t)}async compact(e,t=`manual`,n,r){this.assertInputAllowed();let i=this.turnClaim.claim(),a=Fc(i,n);try{await this.compactWith(e,t,i.signal,void 0,r)}finally{a(),this.turnClaim.release(i)}}async compactWith(e,t,n,r,i){let a={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{},...i?{executionJournal:i}:{}};await ic(e,rc(this.buildRunContext(),a),n)}buildRunContext(e=!1){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,effort:this.getModelEffort(),agent:this.agent,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:(e,t,n)=>this.compactWith(void 0,`auto`,e,t,n),persistSession:()=>this.persistSessionInternal(),checkpointHistory:this.checkpointHistoryCallback||this.sessionStore?()=>{e&&this.setPending(Nc(this.agent.getHistory(),this.pendingExecution,new Set)),this.commitConversation()}:void 0,getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onThinkingDelta:this.onThinkingDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:e=>this.eventService.emit(st.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(xt.SWITCHED,{timestamp:new Date,fromProvider:e.from.provider,fromModel:e.from.model,toProvider:e.to.provider,toModel:e.to.model,reason:e.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};const Ure=/^(api[-_]?key|authorization|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function Wre(e){return Ure.test(e)}const Gre={sessionInit:`session_init`,sessionShutdown:`session_shutdown`,sessionShutdownStepError:`session_shutdown_step_error`,context:`context`,contextCompact:`context_compact`,error:`error`,historyMutation:`history_mutation`,providerRequest:`provider_request`,providerNativeRawPayload:`provider_native_raw_payload`,providerStreamRawDelta:`provider_stream_raw_delta`,providerResponseRaw:`provider_response_raw`,providerResponseNormalized:`provider_response_normalized`,structuredOutputTransport:`structured_output_transport`,providerFallback:`provider_fallback`,assistantMessageCommitted:`assistant_message_committed`,toolExecutionRequest:`tool_execution_request`,toolExecutionResult:`tool_execution_result`,toolBatchStarted:`tool_batch_started`,toolMessageCommitted:`tool_message_committed`,backgroundTaskEvent:`background_task_event`,backgroundJobGroupEvent:`background_job_group_event`,memoryEvent:`memory_event`,user:`user`,preRun:`pre_run`,textDelta:`text_delta`,assistant:`assistant`,toolCall:`tool_call`,toolResult:`tool_result`,toolBlocked:`tool_blocked`,toolDenied:`tool_denied`,serverTool:`server_tool`};function Kre(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=Lc(e,a,o,n,r);return i}function Lc(e,t,n,r,i){if(Wre(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return Rc(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return Rc(e,n.map(n=>Lc(e,t,n,r,i)),r,i);if(typeof n==`object`){let t=n,a={};for(let[n,o]of Object.entries(t))a[n]=Lc(e,n,o,r,i);return Rc(e,a,r,i)}return String(n)}function Rc(e,t,n,r){let i=JSON.stringify(t);if(i===void 0||Buffer.byteLength(i)<=n.externalPayloadThresholdBytes||r===void 0)return t;let a=Vn(`sha256`).update(i).digest(`hex`);return r.writeJson(e,a,i)}const qre=Qe(`FileSessionLogger`),Jre=new Set([`text_delta`]),zc=new Set;let Bc=!1;function Yre(e){zc.add(e),!Bc&&(typeof process>`u`||typeof process.on!=`function`||(Bc=!0,process.on(`exit`,()=>{for(let e of zc)e.flush()})))}var Vc=class{sink;options;pending=new Map;pendingBytes=0;constructor(e,t={}){this.sink=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`}}log(e,t,n){if(cc(e))try{let r=Kre(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
126
+ `),l=c?`<system-reminder>\n${c}\n</system-reminder>\n${e}`:e,u=Ot(l),d=i?.ephemeralSystemContext,f=[u,...d?.trim()?[He(d)]:[]];n.contextTracker.updateFromHistory(n.agent.getHistory()),n.contextTracker.shouldAutoCompact([...n.agent.getHistory(),...f])&&(i?.executionJournal?await n.compact(r,o,i.executionJournal):await(o?n.compact(r,o):n.compact(r))),n.clearSessionStartStdout();let p=n.agent.getHistory(),m=JSON.stringify(p),h=Be(n.aiProvider);n.log(`pre_run`,{historyLength:p.length,historyChars:m.length,historyEstTokens:Math.ceil(m.length/4),input:l,history:p,model:n.model,provider:n.aiProvider.name,maxTokens:n.contextTracker.getContextState().maxTokens,nativeWebSearchSupported:h.nativeWebTools.webSearch.supported,nativeWebSearchEnabled:h.nativeWebTools.webSearch.enabled,nativeWebFetchSupported:h.nativeWebTools.webFetch.supported,nativeWebFetchEnabled:h.nativeWebTools.webFetch.enabled}),n.contextTracker.updateFromHistory([...p,...f]),n.onContextUpdate?.(n.contextTracker.getContextState());let g;try{if(g=await n.agent.run(l,{signal:r,maxExecutionRounds:n.maxTurns??0,...kc(i),...Tc(n,a)}),r.aborted)throw new DOMException(`Aborted`,`AbortError`)}catch(e){if(e instanceof ot)throw e;try{n.log(`error`,{message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack??``:``,historyLength:n.agent.getHistory().length})}catch{}throw ue(n.hooks,`StopFailure`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`StopFailure`,reason:e instanceof Error?e.message:String(e),stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>Ac.warn(`hook failed`,{error:e})),e}let _=n.agent.getHistory(),v=_.map(e=>{let t=`toolCalls`in e&&Array.isArray(e.toolCalls)&&e.toolCalls.length>0,n=t?e.toolCalls.map(e=>e.function.name):[];return{role:e.role,contentLength:typeof e.content==`string`?e.content.length:0,hasToolCalls:t,toolCallNames:n,...e.metadata?{metadata:e.metadata}:{}}});n.log(`assistant`,{content:g,historyLength:_.length,estimatedChars:JSON.stringify(_).length,history:_,historyStructure:v}),n.contextTracker.updateFromHistory(_);let y=n.contextTracker.getContextState();return n.onContextUpdate?.(y),n.log(`context`,{maxTokens:y.maxTokens,usedTokens:y.usedTokens,usedPercentage:y.usedPercentage,remainingPercentage:y.remainingPercentage}),ue(n.hooks,`Stop`,{session_id:n.sessionId,cwd:n.cwd,hook_event_name:`Stop`,response:g.substring(0,500),last_assistant_message:g,stop_hook_active:!1,...n.permissionMode!==void 0&&{permission_mode:n.permissionMode},...n.transcriptPath!==void 0&&{transcript_path:n.transcriptPath},env:{CLAUDE_PROJECT_DIR:n.cwd,CLAUDE_SESSION_ID:n.sessionId}},n.hookTypeExecutors,o).catch(e=>Ac.warn(`hook failed`,{error:e})),g}function jc(e){let t=e.requests[0]?.executionId;return t?{executionId:t,requests:structuredClone(e.requests)}:void 0}function Mc(e){let t=e.findLastIndex(e=>e.role===`assistant`),n=e[t];if(n?.role!==`assistant`)return;let r=new Set(e.slice(t+1).flatMap(e=>e.role===`tool`?[e.toolCallId]:[]));return{assistant:n,open:(n.toolCalls??[]).filter(e=>!r.has(e.id)),ending:e.slice(t+1).every(e=>e.role===`tool`)}}function Nc(e,t,n){let r=Mc(e),i=r?.assistant.metadata?.executionId;if(!r?.ending||!r.open.length||typeof i!=`string`)return;let a=new Set(r.open.map(e=>e.id)),o=t?.executionId===i?t.requests.filter(e=>a.has(e.toolCallId)&&!n.has(e.actionId)):[];return{executionId:i,requests:structuredClone(o)}}function Bre(e,t,n){return{read:t=>e.read(t),append:r=>(r.kind===`tool-effect-start`&&(t.add(r.actionId),n?.()),e.append(r))}}function Vre(e,t,n){let r=Mc(e);if(!r||r.assistant.metadata?.executionId!==t.executionId)return[];let i=new Set((n?t.requests:[]).map(e=>e.toolCallId));return r.open.map(e=>{let t=i.has(e.id)?`Not run: the execution was abandoned while this call awaited a response.`:`Execution abandoned before this call recorded a result; its outcome is unknown.`;return St(`Error: ${t}`,{toolCallId:e.id,name:e.function.name,metadata:{success:!1,error:t,toolName:e.function.name}})})}async function Pc(e,t){if(!t||typeof t.append!=`function`||typeof t.read!=`function`)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Recoverable Session execution requires a readable journal`);try{return{status:`completed`,response:await e()}}catch(e){if(e instanceof ot)return{status:`waiting`,requests:structuredClone(e.requests)};throw e}}var Hre=class{agent;claim;sessionId;ask;execution=null;constructor(e,t,n,r){this.agent=e,this.claim=t,this.sessionId=n,this.ask=r}async invoke(e,t,n){let r=this.claim.claim(),i=Fc(r,n?.signal);try{return r.signal.throwIfAborted(),this.execution=this.agent.invokeRuntimeTool(e,t,{toolName:e,parameters:t,executionId:n?.executionId??N(),sessionId:this.sessionId,signal:r.signal,permissionInteraction:n?.permissionInteraction??`deny`,...n?.permissionInteraction===`interactive`&&this.ask!==void 0?{ask:this.askUnder(r.signal)}:{}}),await this.execution}finally{this.execution=null,i(),this.claim.release(r)}}askUnder(e){let t=this.ask;if(t===void 0)throw Error(`No ask port`);return(n,r)=>t(n,{signal:r?.signal??e})}async drain(){await this.execution}};function Fc(e,t){let n=()=>e.abort(t?.reason);return t?.aborted?n():t?.addEventListener(`abort`,n,{once:!0}),()=>t?.removeEventListener(`abort`,n)}var Ic=class extends ss{agent;eventService=new lee;permissionEnforcer;contextTracker;permissionMode;activePresetId;parallelSubagentsEnabled;sessionId;aiProvider;toolSchemas;model;systemMessage;messageCount=0;terminal;sessionStore;checkpointHistoryCallback;hooks;hookTypeExecutors;onTextDeltaCallback;onThinkingDeltaCallback;onContextUpdateCallback;onToolExecutionCallback;onCompactCallback;onCompactEventCallback;sessionLogger;maxTurns;compactionOrchestrator;runtimeTools;wrapAddedTools;pendingTools=[];toolChange=Promise.resolve();shuttingDown=!1;recoveryState={kind:`ready`};checkpointing=!1;get pendingExecution(){return this.recoveryState.kind===`ready`?void 0:this.recoveryState.pending}setPending(e,t=!1){this.recoveryState.kind!==`save-required`&&(this.recoveryState=e?{kind:`pending`,pending:e,liveWaits:t}:{kind:`ready`})}shutdownPromise=null;sessionStartStdout=``;transcriptPath;constructor(e){super(e.cwd);let{tools:t,provider:n,systemMessage:r}=e;this.terminal=e.terminal,this.sessionStore=e.sessionStore,this.checkpointHistoryCallback=e.checkpointHistory,this.systemMessage=r,this.toolSchemas=t.map(e=>e.schema),this.wrapAddedTools=e.wrapAddedTools,this.sessionLogger=e.sessionLogger,this.hooks=e.hooks,this.hookTypeExecutors=e.hookTypeExecutors,this.onTextDeltaCallback=e.onTextDelta,this.onThinkingDeltaCallback=e.onThinkingDelta,this.onContextUpdateCallback=e.onContextUpdate,this.onToolExecutionCallback=e.onToolExecution,this.onCompactCallback=e.onCompact,this.onCompactEventCallback=e.onCompactEvent,this.maxTurns=e.maxTurns,this.model=e.model??`claude-sonnet-4-5`,this.sessionId=e.sessionId??sc(),this.permissionMode=e.permissionMode??(e.defaultTrustLevel?At[e.defaultTrustLevel]:void 0)??`default`,this.activePresetId=e.activePresetId??`default`,this.parallelSubagentsEnabled=e.enableParallelSubagents??!0,this.transcriptPath=e.transcriptPath,this.log(`session_init`,{cwd:this.cwd,systemPromptLength:r.length,systemPrompt:r,toolSchemas:this.toolSchemas,model:this.model,provider:n.name}),this.aiProvider=n,dc(n,e,(e,t)=>this.log(e,t)),this.permissionEnforcer=Zs(e,this.sessionId,this.cwd,()=>this.permissionMode,this.transcriptPath),this.requireClassifierFor(this.permissionMode),this.addPermissionModeGuard(e=>this.requireClassifierFor(e));let{contextTracker:i,compactionOrchestrator:a}=Qs(e,this.model,this.sessionId,this.cwd);this.contextTracker=i,this.compactionOrchestrator=a,this.agent=$s(e,this.permissionEnforcer,t,n,this.model,r,this.eventService),this.runtimeTools=new Hre(this.agent,this.turnClaim,this.sessionId,e.ask),fc(this.sessionId,this.cwd,this.hooks,this.hookTypeExecutors,e=>void(this.sessionStartStdout=e),this.permissionMode,this.transcriptPath)}async run(e,t,n){return this.runTurn(e,t,n,!1)}runRecoverable(e,t,n){return Pc(()=>this.runTurn(e,n,t,!0),t.executionJournal)}async runTurn(e,t,n,r){let i=n?{...n}:void 0;if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);this.assertInputAllowed();let a=this.turnClaim.claim(),o=Fc(a,i?.signal),{signal:s}=a;this.permissionEnforcer.beginTurn(i?.peerTurn===!0,r);try{s.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let n=i?.executionJournal?{...i,executionJournal:Dc(i.executionJournal,{sessionId:this.sessionId,cwd:this.cwd,peerTurn:i.peerTurn===!0})}:i,r=await zre(e,t,this.buildRunContext(i?.executionJournal!==void 0),s,n);return this.setPending(void 0),this.commitConversation(),this.messageCount+=1,r}catch(e){throw e instanceof ot?(this.setPending(jc(e),!0),s.throwIfAborted()):i?.executionJournal&&this.setPending(Nc(this.agent.getHistory(),void 0,new Set)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),o(),this.turnClaim.release(a)}}async resume(e){return this.resumeTurn(e,!1)}resumeRecoverable(e){return Pc(()=>this.resumeTurn(e,!0),e.journal)}async resumeTurn(e,t){let n={...e,toolResponses:structuredClone(e.toolResponses)};if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution&&this.pendingExecution.executionId!==n.executionId)throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let r=this.turnClaim.claim(),i=Fc(r,n.signal),a=new Set;try{r.signal.throwIfAborted(),await this.serializeToolChange(()=>this.applyPendingTools());let e=Oc(Bre(n.journal,a,()=>{this.recoveryState.kind===`pending`&&(this.recoveryState.liveWaits=!1)}),this.sessionId,this.cwd,e=>this.permissionEnforcer.beginTurn(e,t)),i=await Ec(this.buildRunContext(!0),{...n,journal:e,signal:r.signal});return this.setPending(void 0),this.commitConversation(n.executionId),i}catch(e){throw e instanceof ot?(this.setPending(jc(e),!0),r.signal.throwIfAborted()):this.setPending(Nc(this.agent.getHistory(),this.pendingExecution,a)),this.saveAfterFailure(e),e}finally{this.permissionEnforcer.endTurn(),i(),this.turnClaim.release(r)}}getPendingExecution(){return structuredClone(this.pendingExecution)}abandonPendingExecution(e){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.recoveryState.kind===`save-required`){if(this.recoveryState.executionId!==e||this.pendingExecution)throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`Checkpoint the unresolved Session transition first`);this.checkpoint();return}let t=this.pendingExecution;if(!t)return;if(t.executionId!==e)throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`A different Session execution is pending`);let n=this.turnClaim.claim();try{let n=this.recoveryState.kind===`pending`&&this.recoveryState.liveWaits;for(let e of Vre(this.agent.getHistory(),t,n))this.agent.injectRawMessage(e);this.setPending(void 0),this.commitConversation(e)}finally{this.turnClaim.release(n)}}assertInputAllowed(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);if(this.assertCheckpointSettled(),this.pendingExecution)throw new Xe(`EXECUTION_RECOVERY_REQUIRED`,`Resume or abandon the pending Session execution before submitting new input`)}assertCheckpointSettled(){if(this.checkpointing||this.recoveryState.kind===`save-required`)throw new Xe(`EXECUTION_RECOVERY_REQUIRED`,`Call Session.checkpoint() to save the unresolved conversation transition`)}getConversationSnapshot(){return structuredClone({id:this.sessionId,cwd:Cn(this.cwd),messages:this.agent.getHistory(),...this.pendingExecution?{pendingExecution:this.pendingExecution}:{}})}restoreConversation(e){if(this.assertInputAllowed(),this.turnClaim.isRunning()||this.agent.getHistory().some(e=>e.role!==`system`))throw Error(`Conversation restore requires a pristine idle Session`);if(e.id!==this.sessionId||Cn(e.cwd)!==Cn(this.cwd))throw new Xe(`EXECUTION_RECOVERY_CONFLICT`,`Conversation owner or workspace differs`);let t=Qo({id:e.id,cwd:e.cwd,messages:e.messages,...e.pendingExecution===void 0?{}:{pendingExecution:e.pendingExecution},createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()});if(t.status!==`valid`)throw new Xe(`EXECUTION_RECOVERY_INVALID`,`Invalid conversation recovery snapshot`);let n=structuredClone(t.record);this.agent.clearHistory();for(let e of n.messages)this.agent.injectRawMessage(e);this.setPending(n.pendingExecution),this.syncContextFromHistory()}checkpoint(){if(this.turnClaim.isRunning()||this.checkpointing)throw Error(`Cannot checkpoint during a Session transition`);if(!this.checkpointHistoryCallback&&!this.sessionStore)throw Error(`Session checkpoint requires a persistence sink`);this.commitConversation(this.recoveryState.kind===`save-required`?this.recoveryState.executionId:void 0)}commitConversation(e){if(!this.checkpointHistoryCallback&&!this.sessionStore)return;if(this.checkpointing)throw Error(`Reentrant Session checkpoint`);let t=this.pendingExecution,n=this.recoveryState.kind!==`ready`&&this.recoveryState.liveWaits;this.checkpointing=!0;try{this.checkpointHistoryCallback?rs(this.checkpointHistoryCallback()):this.persistSessionInternal(!0),this.recoveryState=t?{kind:`pending`,pending:t,liveWaits:n}:{kind:`ready`}}catch(r){throw this.recoveryState={kind:`save-required`,pending:t,liveWaits:n,executionId:e??t?.executionId},r}finally{this.checkpointing=!1}}saveAfterFailure(e){if(this.recoveryState.kind!==`save-required`)try{this.commitConversation()}catch(t){if(e instanceof ot)throw t;try{this.log(`error`,{message:`Session checkpoint failed while preserving the execution error: ${t instanceof Error?t.message:String(t)}`,stack:t instanceof Error?t.stack??``:``,historyLength:this.agent.getHistory().length})}catch{}}}addTools(e){return this.assertInputAllowed(),this.shuttingDown?Promise.reject(Error(`[LIFECYCLE] Session is shutting down`)):this.serializeToolChange(async()=>{let t=new Set([...this.toolSchemas.map(e=>e.name),...this.pendingTools.map(e=>e.schema.name)]),n=[];for(let r of e)t.has(r.schema.name)||(t.add(r.schema.name),n.push(r));return n.length===0?[]:(this.pendingTools.push(...n),this.turnClaim.isRunning()||await this.applyPendingTools(),n.map(e=>e.schema.name))})}serializeToolChange(e){let t=this.toolChange.then(e);return this.toolChange=t.then(()=>void 0,()=>void 0),t}async applyPendingTools(){if(this.pendingTools.length===0)return;let e=this.pendingTools.splice(0);await this.agent.ensureReady();let t=this.permissionEnforcer.wrapTools(this.wrapAddedTools?.(e)??e);await this.agent.updateTools([...this.agent.getConfig().tools??[],...t]),this.toolSchemas.push(...t.map(e=>e.schema))}async listRuntimeTools(){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.agent.listRuntimeTools()}async invokeRuntimeTool(e,t,n){if(this.shuttingDown)throw Error(`[LIFECYCLE] Session is shutting down`);return this.assertInputAllowed(),this.runtimeTools.invoke(e,t,n)}getEventService(){return this.eventService}log(e,t){this.sessionLogger?.log(this.sessionId,e,t)}persistSessionInternal(e=!1){if(!this.sessionStore)return;let t=ac({sessionId:this.sessionId,cwd:this.cwd,systemPrompt:this.systemMessage,toolSchemas:this.toolSchemas,sessionStore:this.sessionStore,conversation:this.getConversationSnapshot(),getFullHistory:()=>this.getFullHistory()});if(e&&t.status!==`valid`)throw Error(`Session history could not be durably checkpointed: ${t.status}`)}shutdown(e={}){if(this.shutdownPromise)return this.shutdownPromise;this.shuttingDown=!0;let t=e.reason??`other`,n=async(e,t)=>{try{await t()}catch(t){this.log(`session_shutdown_step_error`,{step:e,error:t instanceof Error?t.message:String(t)})}};return this.shutdownPromise=(async()=>{await n(`abort`,()=>this.abort()),await n(`drain-direct-tool`,()=>this.runtimeTools.drain()),await n(`drain-turn`,()=>this.turnClaim.drained),this.log(`session_shutdown`,{reason:t}),await n(`persist`,()=>this.persistSessionInternal()),await n(`session-end-hook`,()=>pc(this.sessionId,this.cwd,t,this.hooks,this.hookTypeExecutors,this.permissionMode,this.transcriptPath)),await n(`destroy-agent`,async()=>{await this.agent.destroy()})})(),this.shutdownPromise}swapProvider(e,t,n){this.assertInputAllowed(),this.agent.swapDefaultProvider(e,t,n),e.configureNativeWebTools?.({webSearch:!0}),`onServerToolUse`in e&&(e.onServerToolUse=(e,t)=>this.log(`server_tool`,{tool:e,...t})),this.aiProvider=e,this.setActiveModel(t)}async compact(e,t=`manual`,n,r){this.assertInputAllowed();let i=this.turnClaim.claim(),a=Fc(i,n);try{await this.compactWith(e,t,i.signal,void 0,r)}finally{a(),this.turnClaim.release(i)}}async compactWith(e,t,n,r,i){let a={systemMessage:this.systemMessage,compactionOrchestrator:this.compactionOrchestrator,onCompactCallback:this.onCompactCallback,onCompactEventCallback:this.onCompactEventCallback,trigger:t,...r?{hookTraceEnv:r}:{},...i?{executionJournal:i}:{}};await ic(e,rc(this.buildRunContext(),a),n)}buildRunContext(e=!1){return{sessionId:this.sessionId,cwd:this.cwd,model:this.model,effort:this.getModelEffort(),agent:this.agent,aiProvider:this.aiProvider,contextTracker:this.contextTracker,hooks:this.hooks,hookTypeExecutors:this.hookTypeExecutors,sessionStartStdout:this.sessionStartStdout,log:(e,t)=>this.log(e,t),compact:(e,t,n)=>this.compactWith(void 0,`auto`,e,t,n),persistSession:()=>this.persistSessionInternal(),checkpointHistory:this.checkpointHistoryCallback||this.sessionStore?()=>{e&&this.setPending(Nc(this.agent.getHistory(),this.pendingExecution,new Set)),this.commitConversation()}:void 0,getSessionStore:()=>!!this.sessionStore,clearSessionStartStdout:()=>void(this.sessionStartStdout=``),permissionMode:this.permissionMode,transcriptPath:this.transcriptPath,maxTurns:this.maxTurns,onTextDelta:this.onTextDeltaCallback,onThinkingDelta:this.onThinkingDeltaCallback,onContextUpdate:this.onContextUpdateCallback,onToolExecution:this.onToolExecutionCallback,emitProviderCallCompleted:e=>this.eventService.emit(st.COMPLETED,{timestamp:new Date,...e},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),emitProviderFallback:e=>this.eventService.emit(xt.SWITCHED,{timestamp:new Date,fromProvider:e.from.provider,fromModel:e.from.model,toProvider:e.to.provider,toModel:e.to.model,reason:e.reason},{ownerType:`session`,ownerId:this.sessionId,ownerPath:[{type:`session`,id:this.sessionId}]}),knownToolNames:this.toolSchemas.map(e=>e.name)}}};const Ure=/^(api[-_]?key|authorization|auth[-_]?token|access[-_]?token|refresh[-_]?token|secret|password|x[-_]?api[-_]?key)$/i;function Wre(e){return Ure.test(e)}const Gre={sessionInit:`session_init`,sessionShutdown:`session_shutdown`,sessionShutdownStepError:`session_shutdown_step_error`,context:`context`,contextCompact:`context_compact`,error:`error`,historyMutation:`history_mutation`,providerRequest:`provider_request`,providerNativeRawPayload:`provider_native_raw_payload`,providerStreamRawDelta:`provider_stream_raw_delta`,providerResponseRaw:`provider_response_raw`,providerResponseNormalized:`provider_response_normalized`,structuredOutputTransport:`structured_output_transport`,providerFallback:`provider_fallback`,assistantMessageCommitted:`assistant_message_committed`,toolExecutionRequest:`tool_execution_request`,toolExecutionResult:`tool_execution_result`,toolBatchStarted:`tool_batch_started`,toolMessageCommitted:`tool_message_committed`,backgroundTaskEvent:`background_task_event`,backgroundJobGroupEvent:`background_job_group_event`,memoryEvent:`memory_event`,user:`user`,preRun:`pre_run`,textDelta:`text_delta`,assistant:`assistant`,toolCall:`tool_call`,toolResult:`tool_result`,toolBlocked:`tool_blocked`,toolDenied:`tool_denied`,serverTool:`server_tool`};function Kre(e,t,n,r){let i={};for(let[a,o]of Object.entries(t))i[a]=Lc(e,a,o,n,r);return i}function Lc(e,t,n,r,i){if(Wre(t))return r.redactedValue;if(n==null||typeof n==`string`||typeof n==`number`)return Rc(e,n,r,i);if(typeof n==`boolean`)return n;if(n instanceof Date)return n.toISOString();if(Array.isArray(n))return Rc(e,n.map(n=>Lc(e,t,n,r,i)),r,i);if(typeof n==`object`){let t=n,a={};for(let[n,o]of Object.entries(t))a[n]=Lc(e,n,o,r,i);return Rc(e,a,r,i)}return String(n)}function Rc(e,t,n,r){let i=JSON.stringify(t);if(i===void 0||Buffer.byteLength(i)<=n.externalPayloadThresholdBytes||r===void 0)return t;let a=Vn(`sha256`).update(i).digest(`hex`);return r.writeJson(e,a,i)}const qre=Qe(`FileSessionLogger`),Jre=new Set([`text_delta`]),zc=new Set;let Bc=!1;function Yre(e){zc.add(e),!Bc&&(typeof process>`u`||typeof process.on!=`function`||(Bc=!0,process.on(`exit`,()=>{for(let e of zc)e.flush()})))}var Vc=class{sink;options;pending=new Map;pendingBytes=0;constructor(e,t={}){this.sink=e,this.options={externalPayloadThresholdBytes:t.externalPayloadThresholdBytes??32768,redactedValue:t.redactedValue??`[REDACTED]`}}log(e,t,n){if(cc(e))try{let r=Kre(e,n,this.options,this.sink.externalPayloadSink),i=JSON.stringify({...r,schemaVersion:1,timestamp:new Date().toISOString(),sessionId:e,event:t})+`
127
127
  `;if(Jre.has(t)){this.buffer(e,i);return}this.flush(),this.write(e,i)}catch(n){this.report(e,t,n)}}flush(){if(this.pending.size===0){zc.delete(this);return}let e=[...this.pending.entries()];this.pending.clear(),this.pendingBytes=0,zc.delete(this);for(let[t,n]of e)try{this.write(t,n.join(``))}catch(e){this.report(t,`flush`,e)}}buffer(e,t){Yre(this);let n=this.pending.get(e)??[];n.push(t),this.pending.set(e,n),this.pendingBytes+=t.length,this.pendingBytes>=65536&&this.flush()}write(e,t){this.sink.append(e,t)}report(e,t,n){qre.warn(`session log write failed`,{sessionId:e,event:t,error:n instanceof Error?n.message:String(n)})}},Xre=class{log(){}};const Zre=Qe(`NodeSessionLogSink`),Qre=/^[0-9a-f]{64}$/;function $re(e,t){let n=Vn(`sha256`).update(t).digest(`hex`);if(!Qre.test(e)||e!==n)throw Error(`Invalid sha256: external JSON payloads require their exact content digest.`)}function eie(e,t,n){return lc(e),$re(t,n),{kind:`external-payload`,encoding:`json`,sha256:t,byteLength:Buffer.byteLength(n),relativePath:M(`${e}.payloads`,`${t}.json`)}}var tie=class{logDirectory;externalPayloadSink=this;enabled;constructor(e){this.logDirectory=e;try{Yt(e),this.enabled=!0}catch(t){this.enabled=!1,Zre.warn(`session log directory could not be created — session logging is disabled`,{logDirectory:e,error:t instanceof Error?t.message:String(t)})}}append(e,t){if(lc(e),!this.enabled)return;let n=M(this.logDirectory,`${e}.jsonl`);Qt(n),cn(n,t,{mode:384})}writeJson(e,t,n){let r=eie(e,t,n),i=`${e}.payloads`;if(this.enabled){Yt(M(this.logDirectory,i));let e=M(this.logDirectory,r.relativePath);try{kn(e,n,{encoding:`utf8`,mode:384,flag:`wx`})}catch(t){if(t.code!==`EEXIST`)throw t;Qt(e)}}return r}};const V=e=>({decode:e}),H=e=>({decode:e,optional:!0}),Hc=(e,t,n)=>ho(e,t,n,z),Uc=(e,t,n)=>ho(e,t,n,Co),Wc=(e,t,n)=>ho(e,t,n,Jo),nie=(e,t,n)=>typeof e==`string`?e:Co(e,t,n),Gc=(e,t,n)=>{let r=lo(e,t,n);return r!==void 0&&r<0&&n.push({path:t,message:`expected a non-negative integer`}),r};function Kc(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qc(e,t,n){if(!Kc(e)){n.push({path:t,message:`expected an object, received ${so(e)}`});return}for(let[r,i]of Object.entries(e))Yc(i,F(t,r),n);return e}const rie=[`maxTokens`,`usedTokens`,`usedPercentage`,`remainingPercentage`];function Jc(e,t,n){let r=B(e,t,n,rie);if(r===void 0)return;let i=co(r.maxTokens,F(t,`maxTokens`),n),a=co(r.usedTokens,F(t,`usedTokens`),n),o=co(r.usedPercentage,F(t,`usedPercentage`),n),s=co(r.remainingPercentage,F(t,`remainingPercentage`),n);if(i!==void 0&&a!==void 0&&o!==void 0&&s!==void 0)return{maxTokens:i,usedTokens:a,usedPercentage:o,remainingPercentage:s}}const iie=(e,t,n)=>ho(e,t,n,(e,t,n)=>{let r=B(e,t,n,[`type`,`id`]);if(r===void 0)return;let i=z(r.type,F(t,`type`),n),a=z(r.id,F(t,`id`),n);return i===void 0||a===void 0?void 0:{type:i,id:a}});function Yc(e,t,n,r=new WeakSet){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`object`||e instanceof Date){n.push({path:t,message:`expected a JSON-compatible value, received ${so(e)}`});return}if(!Array.isArray(e)&&!Kc(e)){n.push({path:t,message:`expected a JSON-compatible object, received ${so(e)}`});return}if(r.has(e)){n.push({path:t,message:`expected an acyclic JSON-compatible value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)Yc(e[i],oo(t,i),n,r);else for(let[i,a]of Object.entries(e))Yc(a,F(t,i),n,r);return r.delete(e),e}function Xc(e,t,n,r=new WeakSet){if(!(typeof e!=`object`||!e||e instanceof Date)){if(r.has(e)){n.push({path:t,message:`expected an acyclic value`});return}if(r.add(e),Array.isArray(e))for(let i=0;i<e.length;i++)Object.hasOwn(e,i)?Xc(e[i],oo(t,i),n,r):n.push({path:oo(t,i),message:`expected an array element, received nothing`});else for(let[i,a]of Object.entries(e))Xc(a,F(t,i),n,r);r.delete(e)}}const Zc=(...e)=>(t,n,r)=>fo(t,e,n,r),aie={session_init:{cwd:V(z),systemPromptLength:V(Gc),systemPrompt:V(z),toolSchemas:V(Wc),model:V(z),provider:V(z)},session_shutdown:{reason:V(z)},session_shutdown_step_error:{step:V(z),error:V(z)},context:{maxTokens:V(co),usedTokens:V(co),usedPercentage:V(co),remainingPercentage:V(co)},context_compact:{trigger:V(z),before:V(Jc),after:V(Jc)},error:{message:V(z),stack:V(z),historyLength:V(Gc)},history_mutation:{executionId:H(z),conversationId:H(z),round:H(Gc),batchId:H(z),usageObservationId:H(z),providerId:H(z),modelId:H(z),providerError:H(uo),contextOverflow:H(uo),mutation:V(Zc(`append_message`)),index:V(Gc),message:V(Co)},provider_request:{executionId:V(z),conversationId:H(z),round:V(Gc),provider:V(z),model:V(z),effort:H(z),forcedSummary:H(uo),messages:V(Uc),tools:H(Wc)},provider_native_raw_payload:{executionId:V(z),conversationId:H(z),round:V(Gc),provider:V(z),apiSurface:H(z),payloadKind:V(Zc(`request`,`response`,`stream_event`)),sequence:V(Gc),payload:H(Yc),metadata:H(qc)},provider_stream_raw_delta:{executionId:V(z),conversationId:H(z),round:V(Gc),sequence:V(Gc),delta:V(z)},provider_response_raw:{executionId:V(z),conversationId:H(z),round:V(Gc),effort:H(z),response:V(Co),responseKind:V(z)},provider_response_normalized:{executionId:V(z),conversationId:H(z),round:V(Gc),response:V(Co),toolCallsCount:H(Gc)},structured_output_transport:{executionId:V(z),conversationId:H(z),round:V(Gc),provider:V(z),model:V(z),mechanism:V(Zc(`response_schema`,`json_object`,`none`)),provenance:V(Zc(`catalog`,`vendor-default`,`undeclared`,`unverified-endpoint`)),sent:V(uo),schemaInPrompt:V(uo),reason:H(z)},provider_fallback:{executionId:V(z),conversationId:H(z),round:V(Gc),fromProvider:V(z),fromModel:V(z),toProvider:V(z),toModel:V(z),reason:V(z)},assistant_message_committed:{executionId:V(z),conversationId:H(z),round:V(Gc),message:V(nie)},tool_execution_request:{executionId:V(z),conversationId:H(z),round:V(Gc),batchId:H(z),index:H(Gc),toolName:V(z),toolCallId:V(z),parameters:V(qc),ownerPath:H(iie)},tool_execution_result:{executionId:V(z),conversationId:H(z),round:V(Gc),batchId:H(z),index:H(Gc),toolName:H(z),toolCallId:H(z),success:V(uo),result:H(Yc),error:H(z),metadata:H(qc)},tool_batch_started:{executionId:V(z),conversationId:H(z),round:V(Gc),batchId:H(z),mode:V(Zc(`parallel`,`sequential`)),maxConcurrency:V(Gc),requestCount:V(Gc),tools:V(Hc)},tool_message_committed:{executionId:V(z),conversationId:H(z),round:V(Gc),batchId:H(z),index:H(Gc),message:V(Co)},background_task_event:{backgroundEventType:H(z),backgroundEvent:H(Io),data:H(Io),taskId:H(z),originToolCallId:H(z)},background_job_group_event:{backgroundJobGroupEvent:H(Ao),data:H(Ao)},memory_event:{memoryEvent:H(Lo),data:H(Lo)},user:{content:V(z)},pre_run:{historyLength:V(Gc),historyChars:V(Gc),historyEstTokens:V(Gc),input:V(z),history:V(Uc),model:V(z),provider:V(z),maxTokens:V(co),nativeWebSearchSupported:V(uo),nativeWebSearchEnabled:V(uo),nativeWebFetchSupported:V(uo),nativeWebFetchEnabled:V(uo)},text_delta:{delta:V(z)},assistant:{content:V(z),historyLength:V(Gc),estimatedChars:V(Gc),history:V(Uc),historyStructure:V((e,t,n)=>ho(e,t,n,(e,t,n)=>{if(typeof e!=`object`||!e||Array.isArray(e)){n.push({path:t,message:`expected an object, received ${so(e)}`});return}let r=e;fo(r.role,[`user`,`assistant`,`system`,`tool`],F(t,`role`),n),Gc(r.contentLength,F(t,`contentLength`),n),uo(r.hasToolCalls,F(t,`hasToolCalls`),n),Hc(r.toolCallNames,F(t,`toolCallNames`),n),r.metadata!==void 0&&qc(r.metadata,F(t,`metadata`),n);for(let e of Object.keys(r))[`role`,`contentLength`,`hasToolCalls`,`toolCallNames`,`metadata`].includes(e)||n.push({path:F(t,e),message:`unknown history structure field`});return r}))},tool_call:{tool:V(z),args:V(qc)},tool_result:{tool:V(z),success:V(uo),dataChars:V(Gc),truncated:V(uo)},tool_blocked:{tool:V(z),reason:V(z)},tool_denied:{tool:V(z),reason:V(z)},server_tool:{tool:V(z)}};var Qc=class extends Error{code;issues;schemaVersion;constructor(e,t,n={}){super(`Session log decode failed: ${e}${t[0]?` at ${t[0].path}: ${t[0].message}`:``}`,{cause:n.cause}),this.name=`SessionLogDecodeError`,this.code=e,this.issues=t,n.schemaVersion!==void 0&&(this.schemaVersion=n.schemaVersion)}};const oie=new Set(Object.values(Gre));function $c(e,t={}){if(!Array.isArray(e))throw new Qc(`INVALID_EVENT`,[{path:`entries`,message:`expected an array, received ${so(e)}`}]);let n=[],r=[],i;for(let[a,o]of e.entries()){let e=sie(o,t.lineNumbers?.[a]===void 0?`[${a}]`:`line ${t.lineNumbers[a]}`,n);e.entry!==void 0&&r.push(e.entry),i??=e.unsupported}if(n.length>0)throw new Qc(i===void 0?`INVALID_EVENT`:`UNSUPPORTED_VERSION`,n,{schemaVersion:i});return r}function sie(e,t,n){if(!Kc(e))return n.push({path:t,message:`expected an object, received ${so(e)}`}),{};let r=n.length;if(Xc(e,t,n),n.length!==r)return{};let i=cie(e,t,n);return i.event===void 0?{unsupported:i.unsupported}:(lie(e,i.event,t,i.output,n),{entry:i.output,unsupported:i.unsupported})}function cie(e,t,n){let r={schemaVersion:1},i;if(e.schemaVersion!==1){let r=e.schemaVersion;typeof r==`number`&&Number.isSafeInteger(r)&&r>=0?(i=r,n.push({path:F(t,`schemaVersion`),message:`unsupported schema version`})):n.push({path:F(t,`schemaVersion`),message:`expected schema version 1, received ${so(r)}`})}let a=po(e.timestamp,F(t,`timestamp`),n);a!==void 0&&(r.timestamp=a);let o=z(e.sessionId,F(t,`sessionId`),n);o===``&&n.push({path:F(t,`sessionId`),message:`expected a non-empty session ID`}),o!==void 0&&(r.sessionId=o);let s=e.event;return typeof s!=`string`||!oie.has(s)?(n.push({path:F(t,`event`),message:`expected a declared event name, received ${so(s)}`}),{output:r,unsupported:i}):(r.event=s,{output:r,event:s,unsupported:i})}function lie(e,t,n,r,i){let a=aie[t];for(let[t,o]of Object.entries(a)){if(!Object.hasOwn(e,t)&&o.optional)continue;let a=o.decode(e[t],F(n,t),i);a!==void 0&&(r[t]=a)}for(let o of Object.keys(e)){if([`schemaVersion`,`timestamp`,`sessionId`,`event`,...Object.keys(a)].includes(o))continue;if(t!==`server_tool`){i.push({path:F(n,o),message:`unknown event payload field`});continue}let s=Yc(e[o],F(n,o),i);s!==void 0&&(r[o]=s)}uie(e,t,n,i)}function uie(e,t,n,r){t===`background_task_event`&&e.backgroundEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a background task event payload`}),t===`background_job_group_event`&&e.backgroundJobGroupEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a background job group event payload`}),t===`memory_event`&&e.memoryEvent===void 0&&e.data===void 0&&r.push({path:n,message:`expected a memory event payload`})}var el=class extends Error{code;metadata;constructor(e,t,n={},r){super(t,r===void 0?void 0:{cause:r}),this.name=`SessionLogPayloadResolutionError`,this.code=e,this.metadata=n}};function die(e){if(e.trim().length===0||e.includes(`\0`)||Pn(e)||zn.isAbsolute(e))throw tl(e);let t=e.split(/[\\/]+/u);if(t.some(e=>e===`.`||e===`..`))throw tl(e);return t}function fie(e){if(!Number.isFinite(e)||!Number.isSafeInteger(e)||e<0)throw new el(`INVALID_LIMIT`,`External-payload maxBytes must be a finite, non-negative safe integer.`,{actual:String(e)})}function tl(e,t){return new el(`OUTSIDE_ROOT`,`External payload path escapes its base directory or contains a link: ${e}.`,{relativePath:e},t)}function pie(e,t,n){return e.code===`INVALID_PATH`||e.code===`UNSAFE_ENTRY`?tl(t,e):e.code===`UNSUPPORTED_BACKEND`?new el(`STABLE_PAYLOAD_READ_UNAVAILABLE`,`Stable root-relative external-payload reads are unavailable on this host.`,{relativePath:t},e):e.code===`OVER_BUDGET`?new el(`MAX_TOTAL_BYTES_EXCEEDED`,`External payload exceeds the remaining byte budget of ${n}.`,{relativePath:t,expected:n},e):new el(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${t}.`,{relativePath:t},e)}var mie=class{baseDirectory;constructor(e){if(e.trim().length===0)throw Error(`External-payload base directory must not be empty.`);this.baseDirectory=Ln(e)}readBytes(e,t){fie(t);let n=die(e);try{let e=a(this.baseDirectory);try{return e.readBytes(n,t)}finally{e.close()}}catch(n){throw n instanceof el?n:n instanceof y?pie(n,e,t):new el(`PAYLOAD_UNREADABLE`,`External payload could not be read: ${e}.`,{relativePath:e},n)}}};const hie=/^tool-result:([A-Za-z0-9_-]{22,64})$/u,nl=8*1024*1024,gie=k.O_WRONLY|k.O_CREAT|k.O_EXCL|(k.O_NOFOLLOW??0);var rl=class extends Error{code;constructor(e){super(`Tool result spill failed (${e})`),this.code=e,this.name=`ToolResultSpillError`}},_ie=class{directory;retentionMs;now;onCleanupFailure;entries=new Map;expiryTimer;closed=!1;constructor(e={}){let t=e.parentDirectory??lr();if(this.retentionMs=e.retentionMs??36e5,this.now=e.now??Date.now,this.onCleanupFailure=e.onCleanupFailure,!Number.isSafeInteger(this.retentionMs)||this.retentionMs<=0)throw new rl(`invalid-options`);try{let e=_n(t);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe parent`);this.directory=yn(M(t,`agent-tool-results-`)),process.platform!==`win32`&&ln(this.directory,448),this.assertRoot()}catch{throw new rl(`unsafe-root`)}}assertRoot(){try{let e=_n(this.directory);if(!e.isDirectory()||e.isSymbolicLink())throw Error(`unsafe directory`);if(process.platform!==`win32`&&e.mode&63)throw Error(`directory is not owner-only`)}catch{throw new rl(`unsafe-root`)}}scheduleExpiry(e=1){if(this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0,this.closed||this.entries.size===0)return;let t=1/0;for(let e of this.entries.values())e.expiresAt<t&&(t=e.expiresAt);let n=Math.min(2147483647,Math.max(e,t-this.now()));this.expiryTimer=setTimeout(()=>{this.expiryTimer=void 0,this.cleanupExpired().catch(()=>{try{this.onCleanupFailure?this.onCleanupFailure(`cleanup-failed`):process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}catch{process.emitWarning(`Tool result spill expiry cleanup failed (cleanup-failed)`)}this.scheduleExpiry(6e4)})},n),this.expiryTimer.unref?.()}async write(e){if(this.closed)throw new rl(`closed`);if(await this.cleanupExpired(),this.assertRoot(),Buffer.byteLength(e,`utf8`)>nl)throw new rl(`write-failed`);let t=Wn(18).toString(`base64url`),n=`${Wn(18).toString(`base64url`)}.partial`,r=`${t}.txt`,i=M(this.directory,n),a=M(this.directory,r),o,s=!1;try{o=bn(i,gie,384),kn(o,e,`utf8`),mn(o),un(o),o=void 0,gn(i,a),s=!0,On(i);let n=`tool-result:${t}`;return this.entries.set(n,{fileName:r,expiresAt:this.now()+this.retentionMs}),this.scheduleExpiry(),{reference:n}}catch{let e=!1;if(o!==void 0)try{un(o)}catch{e=!0}try{On(i)}catch(t){t.code!==`ENOENT`&&(e=!0)}if(s)try{On(a)}catch{e=!0}throw new rl(e?`cleanup-failed`:`write-failed`)}}async read(e){if(this.closed)throw new rl(`closed`);if(!hie.test(e))throw new rl(`invalid-reference`);let t=this.entries.get(e);if(!t)throw new rl(`missing`);if(this.now()>=t.expiresAt)throw this.removeEntry(e,t),this.scheduleExpiry(),new rl(`expired`);this.assertRoot();try{let e=new mie(this.directory).readBytes(t.fileName,nl);if(e===void 0)throw new rl(`missing`);return Buffer.from(e).toString(`utf8`)}catch(e){throw e instanceof rl?e:new rl(`read-failed`)}}removeEntry(e,t){this.assertRoot();try{On(M(this.directory,t.fileName)),this.entries.delete(e)}catch{throw new rl(`cleanup-failed`)}}async cleanupExpired(){if(this.closed)throw new rl(`closed`);for(let[e,t]of this.entries)this.now()>=t.expiresAt&&this.removeEntry(e,t);this.scheduleExpiry()}async shutdown(){if(!this.closed){this.expiryTimer!==void 0&&clearTimeout(this.expiryTimer),this.expiryTimer=void 0;for(let[e,t]of this.entries)this.removeEntry(e,t);this.assertRoot();try{if(Sn(this.directory).length!==0)throw Error(`unexpected files`);En(this.directory),this.closed=!0}catch{throw new rl(`cleanup-failed`)}}}};function vie(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return typeof t.at==`string`&&typeof t.sessionId==`string`&&typeof t.project==`string`&&typeof t.text==`string`}function yie(e){if(e.trim().length===0)return;let t;try{t=JSON.parse(e)}catch{return}if(vie(t))return{at:t.at,sessionId:t.sessionId,project:t.project,text:t.text}}function bie(e){let t=[],n=0;for(let r of e){if(r.length===0)continue;let e=yie(r);e===void 0?n+=1:t.push(e)}return{entries:t,skippedLines:n}}function xie(e){return e.code===`ENOENT`}var Sie=class{path;blockBytes;ownedRoot;constructor(e,t={}){this.path=e,this.blockBytes=t.blockBytes??65536,this.ownedRoot=t.ownedRoot}append(e){Yt(Mn(this.path),this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot}),Qt(this.path),cn(this.path,`${JSON.stringify(e)}\n`,{mode:384})}async*read(e){let t;try{t=bn(this.path,k.O_RDONLY|(k.O_NOFOLLOW??0))}catch(e){if(e instanceof Error&&xie(e))return;throw e}try{let n=pn(t).size,r=Buffer.alloc(0);for(;n>0&&!e.signal.aborted;){let e=Math.min(this.blockBytes,n);n-=e;let i=Buffer.alloc(e),a=xn(t,i,0,e,n),o=Buffer.concat([i.subarray(0,a),r]),s=n===0?-1:o.indexOf(10);r=s===-1&&n>0?o:o.subarray(0,s+1);let c=n===0?o:s===-1?Buffer.alloc(0):o.subarray(s+1);n>0&&s===-1||(yield bie(c.toString(`utf8`).split(`
128
128
  `).reverse()))}}finally{un(t)}}};const Cie=/^[0-9a-f]{64}$/i;function wie(e){if(!il(e))throw new el(`INVALID_REFERENCE`,`External payload reference has an invalid shape.`);return{kind:`external-payload`,encoding:`json`,sha256:String(e.sha256).toLowerCase(),byteLength:Number(e.byteLength),relativePath:String(e.relativePath)}}function il(e){let t=Object.keys(e).sort(),n=[`byteLength`,`encoding`,`kind`,`relativePath`,`sha256`];return t.length===n.length&&t.every((e,t)=>e===n[t])&&e.kind===`external-payload`&&e.encoding===`json`&&typeof e.sha256==`string`&&Cie.test(e.sha256)&&typeof e.byteLength==`number`&&Number.isSafeInteger(e.byteLength)&&e.byteLength>=0&&typeof e.relativePath==`string`&&e.relativePath.trim().length>0}function Tie(e,t){return ol(e,Eie(t),0)}function Eie(e){let t=al(`maxDepth`,e.maxDepth??32),n=al(`maxTotalBytes`,e.maxTotalBytes??67108864);return{source:e.source,maxDepth:t,maxTotalBytes:n,totalBytes:0,activePayloadPaths:new Set,activeObjects:new WeakSet}}function al(e,t){if(!Number.isFinite(t)||!Number.isSafeInteger(t)||t<0)throw new el(`INVALID_LIMIT`,`${e} must be a finite, non-negative safe integer.`,{actual:String(t)});return t}function ol(e,t,n){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`number`)throw sl(`Non-finite numbers are not valid session-log JSON values.`);if(typeof e!=`object`)throw sl(`Unsupported session-log JSON value type: ${typeof e}.`);if(t.activeObjects.has(e))throw new el(`CIRCULAR_REFERENCE`,`Circular in-memory value encountered while resolving external payloads.`,{depth:n});if(kie(e))return Die(e,t,n);if(Array.isArray(e)){t.activeObjects.add(e);try{return e.map(e=>ol(e,t,n))}finally{t.activeObjects.delete(e)}}if(!Aie(e))throw sl(`Session-log payload objects must be plain JSON records.`);t.activeObjects.add(e);try{return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,ol(r,t,n)]))}finally{t.activeObjects.delete(e)}}function Die(e,t,n){let r=wie(e);if(n>=t.maxDepth)throw new el(`MAX_DEPTH_EXCEEDED`,`External-payload reference depth exceeds the configured maximum of ${t.maxDepth}.`,{relativePath:r.relativePath,depth:n});if(t.source===void 0)throw new el(`UNRESOLVED_REFERENCE`,`An external session-log payload requires an explicit payload source.`,{relativePath:r.relativePath,depth:n});if(t.activePayloadPaths.has(r.relativePath))throw new el(`CIRCULAR_REFERENCE`,`External payload ${r.relativePath} recursively references an active payload.`,{relativePath:r.relativePath,depth:n});let i=Oie(r,t);t.activePayloadPaths.add(r.relativePath);try{return ol(i,t,n+1)}finally{t.activePayloadPaths.delete(r.relativePath)}}function Oie(e,t){let n=t.maxTotalBytes-t.totalBytes,r=t.source?.readBytes(e.relativePath,n);if(r===void 0)throw new el(`PAYLOAD_NOT_FOUND`,`External payload was not found: ${e.relativePath}.`,{relativePath:e.relativePath});let i=t.totalBytes+r.byteLength;if(!Number.isSafeInteger(i)||i>t.maxTotalBytes)throw new el(`MAX_TOTAL_BYTES_EXCEEDED`,`External-payload bytes exceed the configured maximum of ${t.maxTotalBytes}.`,{expected:t.maxTotalBytes,actual:i});if(t.totalBytes=i,r.byteLength!==e.byteLength)throw new el(`BYTE_LENGTH_MISMATCH`,`External payload byte length does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.byteLength,actual:r.byteLength});let a=Vn(`sha256`).update(r).digest(`hex`);if(a!==e.sha256)throw new el(`SHA256_MISMATCH`,`External payload sha256 does not match its reference: ${e.relativePath}.`,{relativePath:e.relativePath,expected:e.sha256,actual:a});try{return JSON.parse(Buffer.from(r).toString(`utf8`))}catch(t){throw new el(`INVALID_JSON`,`External payload is not valid JSON: ${e.relativePath}.`,{relativePath:e.relativePath},t)}}function sl(e){return new el(`INVALID_JSON`,e)}function kie(e){return!Array.isArray(e)&&`kind`in e&&e.kind===`external-payload`}function Aie(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function jie(e){let t=[],n=Mie(),r=Nie();return $c(e).forEach((e,i)=>{cl(e,i,t),Fie(e,i,t),Pie(n,e,i),Iie(r,e,i)}),Lie(n,t),Rie(r,t),{ok:t.length===0,issues:t}}function Mie(){return{requests:new Map,nativeRawPayloads:new Set,rawResponses:new Set,normalizedResponses:new Set}}function Nie(){return{requests:new Map,results:new Set}}function Pie(e,t,n){let r=zie(t);r&&(t.event===`provider_request`&&e.requests.set(r.key,{executionId:r.executionId,round:r.round,index:n}),t.event===`provider_response_raw`&&e.rawResponses.add(r.key),t.event===`provider_native_raw_payload`&&(t.payloadKind===`response`||t.payloadKind===`stream_event`)&&e.nativeRawPayloads.add(r.key),t.event===`provider_response_normalized`&&!ll(t.response)&&e.normalizedResponses.add(r.key))}function Fie(e,t,n){ll(e.event===`history_mutation`?e.message:e.event===`provider_response_normalized`?e.response:void 0)&&n.push({code:`UNRESOLVED_REPLAY_PAYLOAD`,message:`Replay substrate ${e.event} contains an unresolved external payload.`,eventIndex:t,executionId:typeof e.executionId==`string`?e.executionId:void 0,round:typeof e.round==`number`?e.round:void 0})}function Iie(e,t,n){let r=Bie(t);r&&(t.event===`tool_execution_request`&&e.requests.set(r.key,{executionId:r.executionId,toolCallId:r.toolCallId,index:n}),t.event===`tool_execution_result`&&e.results.add(r.key))}function Lie(e,t){for(let[n,r]of e.requests)e.nativeRawPayloads.has(n)||t.push({code:`PROVIDER_NATIVE_RAW_PAYLOAD_MISSING`,message:`Provider request ${n} has no provider-native raw response or stream payload event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.rawResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_RAW_MISSING`,message:`Provider request ${n} has no raw response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round}),e.normalizedResponses.has(n)||t.push({code:`PROVIDER_RESPONSE_NORMALIZED_MISSING`,message:`Provider request ${n} has no normalized response event.`,eventIndex:r.index,executionId:r.executionId,round:r.round})}function Rie(e,t){for(let[n,r]of e.requests)e.results.has(n)||t.push({code:`TOOL_RESULT_MISSING`,message:`Tool request ${n} has no terminal result event.`,eventIndex:r.index,executionId:r.executionId,toolCallId:r.toolCallId})}function zie(e){if(typeof e.executionId!=`string`)return;let t=typeof e.round==`number`?e.round:Number(e.round);if(Number.isFinite(t))return{key:`${e.executionId}:${t}`,executionId:e.executionId,round:t}}function Bie(e){if(typeof e.executionId!=`string`)return;let t=typeof e.toolCallId==`string`?e.toolCallId:typeof e.toolExecutionId==`string`?e.toolExecutionId:void 0;if(t)return{key:`${e.executionId}:${t}`,executionId:e.executionId,toolCallId:t}}function cl(e,t,n){if(Array.isArray(e)){e.forEach(e=>cl(e,t,n));return}if(ul(e)){if(e.kind===`external-payload`){il(e)||n.push({code:`PAYLOAD_REFERENCE_INVALID`,message:`External payload reference is missing required replay fields.`,eventIndex:t});return}Object.values(e).forEach(e=>cl(e,t,n))}}function ll(e){return Array.isArray(e)?e.some(e=>ll(e)):ul(e)?e.kind===`external-payload`||Object.values(e).some(e=>ll(e)):!1}function ul(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function dl(e,t={}){let n=e.readText(),r=[];return n!==void 0&&n.split(`
129
- `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new Qc(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),$c(Tie(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Vie(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of $c(e))i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`&&(t.push(c.message),n.push(qe(c.message))),Hie(c,r);return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function Hie(e,t){if(e.event===`background_task_event`){pl(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){pl(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&pl(t.memoryEvents,e,`memoryEvent`,`data`)}function fl(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function pl(e,t,n,r){let i=fl(t,n)??fl(t,r);i&&e.push(i)}function Uie(e){return e instanceof Error?e.message:`unknown error`}function Wie(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=ts(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion,...n.cwd===void 0?{}:{cwd:n.cwd}}:{status:`corrupt`,issues:n.issues,...n.cwd===void 0?{}:{cwd:n.cwd}}}function Gie(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Kie=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){Yt(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){lc(e);let t=Er(this.baseDir),n=Er(t,`${e}.json`);if(!n.startsWith(t+Dr))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),Jt(this.filePath(e.id),JSON.stringify({schemaVersion:2,record:e},null,2))}load(e){let t=this.filePath(e);if(!Sr(t))return{status:`missing`};let n;try{n=Cr(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${Uie(e)}`}]}}return Wie(n)}list(){return Sr(this.baseDir)?wr(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(Gie):[]}outcomeForListedId(e){return cc(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);Sr(t)&&Tr(t)}},qie=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};function Jie(e){return e.admitted&&e.trust===`same-user-same-host`&&e.origin!==void 0}const Yie={presence:`never`,message:`never`,delegate:`every-request`,file:`every-request`,handoff:`every-request`,observe:`every-connection`,drive:`every-connection`};function Xie(e){return Yie[e]}const ml={allowed:!1,reason:`declined`};function hl(e){return e?.aborted===!0}function Zie(e,t){return new Promise(n=>{let r=e=>{t.removeEventListener(`abort`,i),n(e&&!t.aborted)},i=()=>r(!1);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>r(e===!0),()=>r(!1)),t.aborted&&i()})}var gl=class{approver;connectionAnswers=new Map;lifetime=new AbortController;peer;constructor(e,t){this.approver=t,this.peer=Object.freeze({...e,capabilities:Object.freeze([...e.capabilities])})}close(){this.lifetime.abort(),this.connectionAnswers.clear()}authorize(e,t={}){if(this.lifetime.signal.aborted||hl(t.signal))return Promise.resolve(ml);if(!this.peer.capabilities.includes(e))return Promise.resolve({allowed:!1,reason:`not-granted`});let n=Xie(e);if(n===`never`)return Promise.resolve({allowed:!0});if(n===`every-request`)return this.ask(e,`request`,t);let r=this.connectionAnswers.get(e);r===void 0&&(r={result:this.ask(e,`connection`,{...t.signal?{signal:t.signal}:{}}),...t.signal?{signal:t.signal}:{}},this.connectionAnswers.set(e,r));let i=r;return i.result.then(e=>this.lifetime.signal.aborted||hl(i.signal)||hl(t.signal)?ml:e)}async authorizeDelegation(e,t){let{requestId:n,task:r}=e,i=this.peer.sessionId;if(i===void 0)return{allowed:!1,reason:`not-granted`};let a=await this.authorize(`delegate`,{summary:r,...t?{signal:t}:{}});return a.allowed?{allowed:!0,turn:{input:r,options:{turnSource:`peer`,driverId:`peer:${this.peer.deviceId??i}`,peer:{messageId:n,replyTo:i}}}}:a}authorizeFile(e,t){return this.authorize(`file`,{summary:`${e.name} (${e.size} bytes, sha256 ${e.sha256})`,...t?{signal:t}:{}})}async ask(e,t,{summary:n,signal:r}){if(this.approver===void 0)return{allowed:!1,reason:`no-approver`};let i=r===void 0?this.lifetime.signal:AbortSignal.any([this.lifetime.signal,r]);if(i.aborted)return ml;let a={capability:e,scope:t,...this.peer.deviceId===void 0?{}:{deviceId:this.peer.deviceId},locality:this.peer.locality,...n===void 0?{}:{summary:n}};try{return await Zie(this.approver.approve(a,i),i)&&!i.aborted?{allowed:!0}:ml}catch{return ml}}};function Qie(e){return e!==`committed`}function $ie(e){return{handoffId:e.handoffId,sessionId:e.sessionId,phase:`offered`}}const eae={offered:[`transferring`,`abandoned`],transferring:[`staged`,`abandoned`],staged:[`committed`,`abandoned`],committed:[],abandoned:[]};function _l(e,t,n){return eae[e.phase].includes(t)?(e.phase=t,n?.refusal!==void 0&&(e.refusal=n.refusal),n?.detail!==void 0&&(e.detail=n.detail),{accepted:!0,transaction:e}):{accepted:!1,transaction:e,reason:`a hand-off in phase '${e.phase}' cannot move to '${t}'. Refused rather than ignored: an ignored transition leaves the caller believing it happened, and in an ownership protocol that means two machines can each believe they are authoritative.`}}function tae(e,t){if(t.handoffId!==e.handoffId)return{accepted:!1,transaction:e,reason:`acknowledgement is for hand-off '${t.handoffId}', not '${e.handoffId}'. An ack from another transfer must never move this one.`};if(e.phase===`committed`)return{accepted:!0,transaction:e,duplicate:!0};if(t.persisted!==!0)return{accepted:!1,transaction:e,reason:`the acknowledgement does not assert durable persistence. Receipt is not persistence — a destination that crashed before writing would leave the session owned by nobody.`};let n=_l(e,`committed`);return n.accepted?(e.ack=t,{accepted:!0,transaction:e}):n}function nae(e){return Qie(e.phase)}function vl(e){let t=e.toolCallsInFlight??0;return e.modelCallInFlight!==!0&&t<=0?{ready:!0}:{ready:!1,refusal:`in-flight-work`,detail:`A turn is still running, and its outcome belongs in the history being transferred. Snapshotting now would produce a manifest whose digest is correct for a session state that never settled. Wait for it, or cancel it.`}}function rae(e,t){let n=[{kind:`conversation`,disposition:`transferred`},{kind:`session-metadata`,disposition:`transferred`},{kind:`provider-credentials`,disposition:`never-transferred`,note:`The destination resolves its own credential. A hand-off to a machine without one fails at commit, loudly, rather than silently later.`},{kind:`working-directory`,disposition:`rehydrated`,note:`The path '${e.cwd}' is meaningless on the destination; it is carried so the destination can locate or ask for the corresponding checkout. A mismatch is surfaced, not guessed.`}];return(e.goal!==void 0||e.plan!==void 0)&&n.push({kind:`goal-and-plan`,disposition:`transferred`}),(e.backgroundTasks?.length||e.backgroundJobGroups?.length)&&n.push({kind:`background-work`,disposition:`transferred`}),e.sandboxSnapshotId!==void 0&&n.push({kind:`sandbox-snapshot`,disposition:`rehydrated`,note:`Carried as a reference. Its validity on the destination is checked, not assumed.`}),t.uncommittedChanges===!0&&n.push({kind:`uncommitted-changes`,disposition:`source-local`,note:`Moving these would make the hand-off a file-sync product. Their existence is reported at both ends so the choice is yours.`}),(t.subprocesses??0)>0&&n.push({kind:`subprocesses`,disposition:`source-local`,note:`${t.subprocesses} running process(es) stay here. A process cannot migrate, and pretending otherwise would resume a session whose tools point at dead pids.`}),n}function iae(e){let t=vl(e.runtime);return t.ready?{built:!0,manifest:{handoffId:e.handoffId,sessionId:e.sessionId,sourceDeviceId:e.sourceDeviceId,destinationDeviceId:e.destinationDeviceId,inventory:rae(e.record,e.runtime),integrity:e.integrity,offeredAt:e.offeredAt}}:{built:!1,refusal:t.refusal,detail:t.detail}}function aae(e){return{get state(){return e},advance:(t,n)=>_l(e,t,n),commit:t=>tae(e,t),sourceStillOwns:()=>nae(e)}}var oae=class{options;transaction=null;manifestValue=null;serialized=null;readOnlyAnnounced=!1;constructor(e){this.options=e}offer(e){let t=vl(e.runtime);if(!t.ready)return{started:!1,outcome:{handoffId:e.handoffId,phase:`abandoned`,refusal:t.refusal,detail:t.detail}};let n=this.options.composition.sealRecord(e.record),r=iae({...e,integrity:n.integrity});return r.built?(this.transaction=aae($ie(r.manifest)),this.manifestValue=r.manifest,this.serialized=n.serialized,{started:!0}):{started:!1,outcome:{handoffId:e.handoffId,phase:`abandoned`,refusal:r.refusal,detail:r.detail}}}async transfer(){let e=this.requireTransaction(),t=e.advance(`transferring`);if(!t.accepted)return this.outcomeOf(e,`cancelled`,t.reason);let n=this.serialized;if(n===null)throw Error(`handoff: transfer() called with no sealed payload — offer() must run first.`);let r=this.options.carrier;if(await r.sendManifest(this.manifest()),r.sendPayload!==void 0)return await r.sendPayload(e.state.handoffId,n),this.outcome(e);for(let t of this.options.composition.chunk(e.state.handoffId,n))await r.sendChunk(t);return this.outcome(e)}applyAck(e){let t=this.requireTransaction();t.state.phase===`transferring`&&t.advance(`staged`);let n=t.commit(e);return n.accepted?(this.readOnlyAnnounced||(this.readOnlyAnnounced=!0,this.options.onReadOnly()),this.outcome(t)):this.outcomeOf(t,void 0,n.reason)}abandon(e,t){let n=this.requireTransaction();return n.advance(`abandoned`,{refusal:e,...t!==void 0&&{detail:t}}),this.outcome(n)}status(){return this.outcome(this.requireTransaction())}isAuthoritative(){return this.transaction===null||this.transaction.sourceStillOwns()}manifest(){if(this.manifestValue===null)throw Error(`handoff: no manifest — offer() must run first.`);return this.manifestValue}requireTransaction(){if(this.transaction===null)throw Error(`handoff: no transfer is open — offer() must run first.`);return this.transaction}outcome(e){return this.outcomeOf(e)}outcomeOf(e,t,n){let r=e.state;return{handoffId:r.handoffId,phase:r.phase,...(t??r.refusal)!==void 0&&{refusal:t??r.refusal},...(n??r.detail)!==void 0&&{detail:n??r.detail}}}},sae=class{options;state=`idle`;manifest=null;assembler=null;record=null;ack=null;report_={state:`idle`};constructor(e){this.options=e}receiveManifest(e){return this.manifest=e,this.assembler=this.options.composition.createAssembler(e.handoffId),this.state=`receiving`,this.settle({state:this.state})}receiveChunk(e){let t=this.requireManifest();if(this.assembler===null)throw Error(`handoff: no staging area — receiveManifest first.`);let n=this.assembler.accept(e);return n.outcome===`refused`?this.discard(`integrity-failed`,`chunk refused: ${n.rejection??`unknown`}`):n.outcome===`complete`?this.stage(t,n.serialized??``):this.settle({state:this.state})}receivePayload(e){let t=this.requireManifest();return this.state===`receiving`?this.stage(t,e):this.settle({state:this.state,detail:`a payload arrived for a transfer in state '${this.state}'`})}stage(e,t){let n=this.options.composition.verifyPayload(t,e.integrity);if(!n.intact)return this.discard(`integrity-failed`,`payload ${n.failure??`failed verification`}: manifest declared ${n.expectedBytes??e.integrity.byteLength} byte(s), ${n.actualBytes??0} arrived`);let r=this.decodePayload(t);return r.status===`valid`?(this.record=r.record,this.state=`staged`,this.settle({state:this.state})):this.discard(`payload-undecodable`,r.detail)}async commit(){return this.state===`staged`?await this.options.resolveCredential()?await this.options.persist(this.requireRecord())?(this.state=`committed`,this.ack={handoffId:this.requireManifest().handoffId,destinationDeviceId:this.options.deviceId,persisted:!0,committedAt:(this.options.now??Date.now)()},this.settle({state:this.state})):this.discard(`destination-cannot-resume`,`the transferred session could not be written durably. No acknowledgement is produced: receipt is not persistence, and a source that moved on this would hand off to nothing.`):this.discard(`destination-cannot-resume`,`this machine resolved no provider credential. Credentials are never transferred (SEC-009), so the destination must supply its own — the session stays on the source.`):this.settle({state:this.state,detail:`commit refused: a transfer in state '${this.state}' has nothing verified to commit`})}acknowledgement(){return this.ack}decodePayload(e){let t;try{t=JSON.parse(e)}catch{return{status:`invalid`,detail:`payload verified intact but is not JSON`}}let n=this.options.composition.decodeRecord(t);if(n.status===`valid`)return{status:`valid`,record:n.record};if(n.status===`unsupported`)return{status:`invalid`,detail:`payload declares session-record schema version ${n.schemaVersion??`(absent)`}, which this build does not read`};let r=n.issues.slice(0,5);return{status:`invalid`,detail:`payload verified intact but did not decode as a session record — ${r.map(e=>`${e.path===``?`(root)`:e.path}: ${e.message}`).join(`; `)}${n.issues.length>r.length?` (+${n.issues.length-r.length} more)`:``}`}}discard(e,t){return this.state===`committed`?this.settle({state:this.state,detail:`a committed transfer cannot be discarded — this machine is already live for it`}):(this.state=`discarded`,this.record=null,this.settle({state:this.state,refusal:e,detail:t}))}liveRecord(){return this.state===`committed`?this.record:null}report(){return this.report_}settle(e){return this.report_=e,e}requireManifest(){if(this.manifest===null)throw Error(`handoff: no manifest — receiveManifest first.`);return this.manifest}requireRecord(){if(this.record===null)throw Error(`handoff: nothing staged to commit.`);return this.record}};function yl(e,t){let n=e.indexOf(`
129
+ `).forEach((e,t)=>{if(e.trim().length!==0)try{r.push({value:JSON.parse(e),lineNumber:t+1})}catch(e){throw new Qc(`INVALID_JSON`,[{path:`line ${t+1}`,message:`expected valid JSON`}],{cause:e})}}),$c(Tie(r.map(({value:e})=>e),{source:t.externalPayloadSource??e.externalPayloadSource,...t}),{lineNumbers:r.map(({lineNumber:e})=>e)})}function Vie(e){let t=[],n=[],r={backgroundTaskEvents:[],backgroundJobGroupEvents:[],memoryEvents:[]},i,a,o,s;for(let c of $c(e))i??=c.sessionId,o??=c.timestamp,s=c.timestamp,c.event===`session_init`&&(a=typeof c.cwd==`string`?c.cwd:a),c.event===`history_mutation`&&c.mutation===`append_message`&&(t.push(c.message),n.push(qe(c.message))),Hie(c,r);return{sessionId:i,cwd:a,createdAt:o,updatedAt:s,messages:t,history:n,backgroundTaskEvents:r.backgroundTaskEvents,backgroundJobGroupEvents:r.backgroundJobGroupEvents,memoryEvents:r.memoryEvents}}function Hie(e,t){if(e.event===`background_task_event`){pl(t.backgroundTaskEvents,e,`backgroundEvent`,`data`);return}if(e.event===`background_job_group_event`){pl(t.backgroundJobGroupEvents,e,`backgroundJobGroupEvent`,`data`);return}e.event===`memory_event`&&pl(t.memoryEvents,e,`memoryEvent`,`data`)}function fl(e,t){let n=e[t];if(!(typeof n!=`object`||!n||Array.isArray(n)||n instanceof Date))return n}function pl(e,t,n,r){let i=fl(t,n)??fl(t,r);i&&e.push(i)}function Uie(e){return e instanceof Error?e.message:`unknown error`}function Wie(e){let t;try{t=JSON.parse(e)}catch{return{status:`corrupt`,issues:[{path:``,message:`the session file is not JSON`}]}}let n=ts(t);return n.status===`valid`?{status:`valid`,record:n.record}:n.status===`unsupported`?{status:`unsupported`,schemaVersion:n.schemaVersion,...n.cwd===void 0?{}:{cwd:n.cwd}}:{status:`corrupt`,issues:n.issues,...n.cwd===void 0?{}:{cwd:n.cwd}}}function Gie(e,t){let n=e=>e.outcome.status===`valid`?new Date(e.outcome.record.updatedAt).getTime():0;return n(t)-n(e)}var Kie=class{baseDir;ownedRoot;constructor(e,t){this.baseDir=e,this.ownedRoot=t}ensureDir(){Yt(this.baseDir,this.ownedRoot===void 0?{}:{withinRoot:this.ownedRoot})}filePath(e){lc(e);let t=Er(this.baseDir),n=Er(t,`${e}.json`);if(!n.startsWith(t+Dr))throw Error(`Invalid session id: ${JSON.stringify(e)} resolves outside the session store.`);return n}save(e){this.ensureDir(),Jt(this.filePath(e.id),JSON.stringify({schemaVersion:2,record:e},null,2))}load(e){let t=this.filePath(e);if(!Sr(t))return{status:`missing`};let n;try{n=Cr(t,`utf-8`)}catch(e){return{status:`corrupt`,issues:[{path:``,message:`could not read the session file: ${Uie(e)}`}]}}try{Qt(t)}catch{}return Wie(n)}list(){return Sr(this.baseDir)?wr(this.baseDir).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5)).map(e=>({id:e,outcome:this.outcomeForListedId(e)})).sort(Gie):[]}outcomeForListedId(e){return cc(e)?this.load(e):{status:`corrupt`,issues:[{path:``,message:`the file name is not a usable session id`}]}}delete(e){let t=this.filePath(e);Sr(t)&&Tr(t)}},qie=class e{nodes=new Map;children=new Map;activeId;static fromNodes(t,n){let r=new e;for(let e of t){if(r.nodes.has(e.id))throw Error(`CheckpointTree: duplicate node "${e.id}"`);r.nodes.set(e.id,e.parentId===void 0?{id:e.id}:{...e})}for(let e of t)if(e.parentId!==void 0){let t=r.children.get(e.parentId)??[];t.push(e.id),r.children.set(e.parentId,t)}return r.activeId=n,r}addCheckpoint(e){if(this.nodes.has(e))throw Error(`CheckpointTree: duplicate checkpoint id "${e}"`);let t=this.activeId;if(this.nodes.set(e,t===void 0?{id:e}:{id:e,parentId:t}),t!==void 0){let n=this.children.get(t)??[];n.push(e),this.children.set(t,n)}this.activeId=e}fork(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);return this.activeId=e,e}switch(e){if(!this.nodes.has(e))throw Error(`CheckpointTree: unknown checkpoint "${e}"`);this.activeId=e}activeLeaf(){return this.activeId}listBranches(){let e=[];for(let t of this.nodes.keys())(this.children.get(t)?.length??0)===0&&e.push(t);return e}ancestors(e){let t=[],n=e;for(;n!==void 0&&this.nodes.has(n);)t.push(n),n=this.nodes.get(n).parentId;return t}has(e){return this.nodes.has(e)}get size(){return this.nodes.size}};function Jie(e){return e.admitted&&e.trust===`same-user-same-host`&&e.origin!==void 0}const Yie={presence:`never`,message:`never`,delegate:`every-request`,file:`every-request`,handoff:`every-request`,observe:`every-connection`,drive:`every-connection`};function Xie(e){return Yie[e]}const ml={allowed:!1,reason:`declined`};function hl(e){return e?.aborted===!0}function Zie(e,t){return new Promise(n=>{let r=e=>{t.removeEventListener(`abort`,i),n(e&&!t.aborted)},i=()=>r(!1);t.addEventListener(`abort`,i,{once:!0}),e.then(e=>r(e===!0),()=>r(!1)),t.aborted&&i()})}var gl=class{approver;connectionAnswers=new Map;lifetime=new AbortController;peer;constructor(e,t){this.approver=t,this.peer=Object.freeze({...e,capabilities:Object.freeze([...e.capabilities])})}close(){this.lifetime.abort(),this.connectionAnswers.clear()}authorize(e,t={}){if(this.lifetime.signal.aborted||hl(t.signal))return Promise.resolve(ml);if(!this.peer.capabilities.includes(e))return Promise.resolve({allowed:!1,reason:`not-granted`});let n=Xie(e);if(n===`never`)return Promise.resolve({allowed:!0});if(n===`every-request`)return this.ask(e,`request`,t);let r=this.connectionAnswers.get(e);r===void 0&&(r={result:this.ask(e,`connection`,{...t.signal?{signal:t.signal}:{}}),...t.signal?{signal:t.signal}:{}},this.connectionAnswers.set(e,r));let i=r;return i.result.then(e=>this.lifetime.signal.aborted||hl(i.signal)||hl(t.signal)?ml:e)}async authorizeDelegation(e,t){let{requestId:n,task:r}=e,i=this.peer.sessionId;if(i===void 0)return{allowed:!1,reason:`not-granted`};let a=await this.authorize(`delegate`,{summary:r,...t?{signal:t}:{}});return a.allowed?{allowed:!0,turn:{input:r,options:{turnSource:`peer`,driverId:`peer:${this.peer.deviceId??i}`,peer:{messageId:n,replyTo:i}}}}:a}authorizeFile(e,t){return this.authorize(`file`,{summary:`${e.name} (${e.size} bytes, sha256 ${e.sha256})`,...t?{signal:t}:{}})}async ask(e,t,{summary:n,signal:r}){if(this.approver===void 0)return{allowed:!1,reason:`no-approver`};let i=r===void 0?this.lifetime.signal:AbortSignal.any([this.lifetime.signal,r]);if(i.aborted)return ml;let a={capability:e,scope:t,...this.peer.deviceId===void 0?{}:{deviceId:this.peer.deviceId},locality:this.peer.locality,...n===void 0?{}:{summary:n}};try{return await Zie(this.approver.approve(a,i),i)&&!i.aborted?{allowed:!0}:ml}catch{return ml}}};function Qie(e){return e!==`committed`}function $ie(e){return{handoffId:e.handoffId,sessionId:e.sessionId,phase:`offered`}}const eae={offered:[`transferring`,`abandoned`],transferring:[`staged`,`abandoned`],staged:[`committed`,`abandoned`],committed:[],abandoned:[]};function _l(e,t,n){return eae[e.phase].includes(t)?(e.phase=t,n?.refusal!==void 0&&(e.refusal=n.refusal),n?.detail!==void 0&&(e.detail=n.detail),{accepted:!0,transaction:e}):{accepted:!1,transaction:e,reason:`a hand-off in phase '${e.phase}' cannot move to '${t}'. Refused rather than ignored: an ignored transition leaves the caller believing it happened, and in an ownership protocol that means two machines can each believe they are authoritative.`}}function tae(e,t){if(t.handoffId!==e.handoffId)return{accepted:!1,transaction:e,reason:`acknowledgement is for hand-off '${t.handoffId}', not '${e.handoffId}'. An ack from another transfer must never move this one.`};if(e.phase===`committed`)return{accepted:!0,transaction:e,duplicate:!0};if(t.persisted!==!0)return{accepted:!1,transaction:e,reason:`the acknowledgement does not assert durable persistence. Receipt is not persistence — a destination that crashed before writing would leave the session owned by nobody.`};let n=_l(e,`committed`);return n.accepted?(e.ack=t,{accepted:!0,transaction:e}):n}function nae(e){return Qie(e.phase)}function vl(e){let t=e.toolCallsInFlight??0;return e.modelCallInFlight!==!0&&t<=0?{ready:!0}:{ready:!1,refusal:`in-flight-work`,detail:`A turn is still running, and its outcome belongs in the history being transferred. Snapshotting now would produce a manifest whose digest is correct for a session state that never settled. Wait for it, or cancel it.`}}function rae(e,t){let n=[{kind:`conversation`,disposition:`transferred`},{kind:`session-metadata`,disposition:`transferred`},{kind:`provider-credentials`,disposition:`never-transferred`,note:`The destination resolves its own credential. A hand-off to a machine without one fails at commit, loudly, rather than silently later.`},{kind:`working-directory`,disposition:`rehydrated`,note:`The path '${e.cwd}' is meaningless on the destination; it is carried so the destination can locate or ask for the corresponding checkout. A mismatch is surfaced, not guessed.`}];return(e.goal!==void 0||e.plan!==void 0)&&n.push({kind:`goal-and-plan`,disposition:`transferred`}),(e.backgroundTasks?.length||e.backgroundJobGroups?.length)&&n.push({kind:`background-work`,disposition:`transferred`}),e.sandboxSnapshotId!==void 0&&n.push({kind:`sandbox-snapshot`,disposition:`rehydrated`,note:`Carried as a reference. Its validity on the destination is checked, not assumed.`}),t.uncommittedChanges===!0&&n.push({kind:`uncommitted-changes`,disposition:`source-local`,note:`Moving these would make the hand-off a file-sync product. Their existence is reported at both ends so the choice is yours.`}),(t.subprocesses??0)>0&&n.push({kind:`subprocesses`,disposition:`source-local`,note:`${t.subprocesses} running process(es) stay here. A process cannot migrate, and pretending otherwise would resume a session whose tools point at dead pids.`}),n}function iae(e){let t=vl(e.runtime);return t.ready?{built:!0,manifest:{handoffId:e.handoffId,sessionId:e.sessionId,sourceDeviceId:e.sourceDeviceId,destinationDeviceId:e.destinationDeviceId,inventory:rae(e.record,e.runtime),integrity:e.integrity,offeredAt:e.offeredAt}}:{built:!1,refusal:t.refusal,detail:t.detail}}function aae(e){return{get state(){return e},advance:(t,n)=>_l(e,t,n),commit:t=>tae(e,t),sourceStillOwns:()=>nae(e)}}var oae=class{options;transaction=null;manifestValue=null;serialized=null;readOnlyAnnounced=!1;constructor(e){this.options=e}offer(e){let t=vl(e.runtime);if(!t.ready)return{started:!1,outcome:{handoffId:e.handoffId,phase:`abandoned`,refusal:t.refusal,detail:t.detail}};let n=this.options.composition.sealRecord(e.record),r=iae({...e,integrity:n.integrity});return r.built?(this.transaction=aae($ie(r.manifest)),this.manifestValue=r.manifest,this.serialized=n.serialized,{started:!0}):{started:!1,outcome:{handoffId:e.handoffId,phase:`abandoned`,refusal:r.refusal,detail:r.detail}}}async transfer(){let e=this.requireTransaction(),t=e.advance(`transferring`);if(!t.accepted)return this.outcomeOf(e,`cancelled`,t.reason);let n=this.serialized;if(n===null)throw Error(`handoff: transfer() called with no sealed payload — offer() must run first.`);let r=this.options.carrier;if(await r.sendManifest(this.manifest()),r.sendPayload!==void 0)return await r.sendPayload(e.state.handoffId,n),this.outcome(e);for(let t of this.options.composition.chunk(e.state.handoffId,n))await r.sendChunk(t);return this.outcome(e)}applyAck(e){let t=this.requireTransaction();t.state.phase===`transferring`&&t.advance(`staged`);let n=t.commit(e);return n.accepted?(this.readOnlyAnnounced||(this.readOnlyAnnounced=!0,this.options.onReadOnly()),this.outcome(t)):this.outcomeOf(t,void 0,n.reason)}abandon(e,t){let n=this.requireTransaction();return n.advance(`abandoned`,{refusal:e,...t!==void 0&&{detail:t}}),this.outcome(n)}status(){return this.outcome(this.requireTransaction())}isAuthoritative(){return this.transaction===null||this.transaction.sourceStillOwns()}manifest(){if(this.manifestValue===null)throw Error(`handoff: no manifest — offer() must run first.`);return this.manifestValue}requireTransaction(){if(this.transaction===null)throw Error(`handoff: no transfer is open — offer() must run first.`);return this.transaction}outcome(e){return this.outcomeOf(e)}outcomeOf(e,t,n){let r=e.state;return{handoffId:r.handoffId,phase:r.phase,...(t??r.refusal)!==void 0&&{refusal:t??r.refusal},...(n??r.detail)!==void 0&&{detail:n??r.detail}}}},sae=class{options;state=`idle`;manifest=null;assembler=null;record=null;ack=null;report_={state:`idle`};constructor(e){this.options=e}receiveManifest(e){return this.manifest=e,this.assembler=this.options.composition.createAssembler(e.handoffId),this.state=`receiving`,this.settle({state:this.state})}receiveChunk(e){let t=this.requireManifest();if(this.assembler===null)throw Error(`handoff: no staging area — receiveManifest first.`);let n=this.assembler.accept(e);return n.outcome===`refused`?this.discard(`integrity-failed`,`chunk refused: ${n.rejection??`unknown`}`):n.outcome===`complete`?this.stage(t,n.serialized??``):this.settle({state:this.state})}receivePayload(e){let t=this.requireManifest();return this.state===`receiving`?this.stage(t,e):this.settle({state:this.state,detail:`a payload arrived for a transfer in state '${this.state}'`})}stage(e,t){let n=this.options.composition.verifyPayload(t,e.integrity);if(!n.intact)return this.discard(`integrity-failed`,`payload ${n.failure??`failed verification`}: manifest declared ${n.expectedBytes??e.integrity.byteLength} byte(s), ${n.actualBytes??0} arrived`);let r=this.decodePayload(t);return r.status===`valid`?(this.record=r.record,this.state=`staged`,this.settle({state:this.state})):this.discard(`payload-undecodable`,r.detail)}async commit(){return this.state===`staged`?await this.options.resolveCredential()?await this.options.persist(this.requireRecord())?(this.state=`committed`,this.ack={handoffId:this.requireManifest().handoffId,destinationDeviceId:this.options.deviceId,persisted:!0,committedAt:(this.options.now??Date.now)()},this.settle({state:this.state})):this.discard(`destination-cannot-resume`,`the transferred session could not be written durably. No acknowledgement is produced: receipt is not persistence, and a source that moved on this would hand off to nothing.`):this.discard(`destination-cannot-resume`,`this machine resolved no provider credential. Credentials are never transferred (SEC-009), so the destination must supply its own — the session stays on the source.`):this.settle({state:this.state,detail:`commit refused: a transfer in state '${this.state}' has nothing verified to commit`})}acknowledgement(){return this.ack}decodePayload(e){let t;try{t=JSON.parse(e)}catch{return{status:`invalid`,detail:`payload verified intact but is not JSON`}}let n=this.options.composition.decodeRecord(t);if(n.status===`valid`)return{status:`valid`,record:n.record};if(n.status===`unsupported`)return{status:`invalid`,detail:`payload declares session-record schema version ${n.schemaVersion??`(absent)`}, which this build does not read`};let r=n.issues.slice(0,5);return{status:`invalid`,detail:`payload verified intact but did not decode as a session record — ${r.map(e=>`${e.path===``?`(root)`:e.path}: ${e.message}`).join(`; `)}${n.issues.length>r.length?` (+${n.issues.length-r.length} more)`:``}`}}discard(e,t){return this.state===`committed`?this.settle({state:this.state,detail:`a committed transfer cannot be discarded — this machine is already live for it`}):(this.state=`discarded`,this.record=null,this.settle({state:this.state,refusal:e,detail:t}))}liveRecord(){return this.state===`committed`?this.record:null}report(){return this.report_}settle(e){return this.report_=e,e}requireManifest(){if(this.manifest===null)throw Error(`handoff: no manifest — receiveManifest first.`);return this.manifest}requireRecord(){if(this.record===null)throw Error(`handoff: nothing staged to commit.`);return this.record}};function yl(e,t){let n=e.indexOf(`
130
130
  `,t),r=n===-1?e.length:n,i=r>t&&e[r-1]===`\r`?r-1:r;return{text:e.slice(t,i),start:t,end:i,next:n===-1?e.length:n+1}}function bl(e,t){let n=yl(t,0);if(n.text!==`---`)return;let r=n.next;for(;r<t.length;){let e=yl(t,r);if(e.text===`---`)return{header:t.slice(n.next,e.start),body:t.slice(e.next)};if(e.next===r)break;r=e.next}return xl([{code:`unterminated`,source:e,line:1,column:1,expected:`a closing delimiter line (---)`,received:`end of file`}])}function xl(e){let[t,...n]=e;if(t===void 0)throw Error(`frontmatter failure requires at least one diagnostic`);return{ok:!1,diagnostics:[t,...n]}}function Sl(e,t){let n=e.header.length===0?0:Math.max(0,Math.min(t,e.header.length-1)),{line:r,col:i}=e.lineCounter.linePos(n);return{line:r+1,column:i}}function cae(e,t){let n=t?.range?.[0];return n===void 0?void 0:Sl(e,n)}function lae(e){return(0,to.isAlias)(e)?`alias`:(0,to.isMap)(e)?`mapping`:(0,to.isSeq)(e)?`sequence`:(0,to.isScalar)(e)?e.value===null?`null`:typeof e.value==`string`?JSON.stringify(e.value):typeof e.value==`number`&&Number.isNaN(e.value)?`NaN`:String(e.value):`missing value`}function Cl(e,t,n){let r=cae(e,t);return{...n,source:e.source,...r===void 0?{}:r,received:n.received??lae(t)}}function wl(e){return(0,to.isScalar)(e)&&typeof e.value==`string`?e.value:void 0}function uae(e,t){if((0,to.isMap)(e))for(let n of e.items){let e=wl(n.key),r=(0,to.isScalar)(n.key)?n.key.range?.[0]:void 0,i=(0,to.isScalar)(n.key)?n.key.range?.[1]:void 0;if(e===void 0)continue;if(r!==void 0&&i!==void 0&&t>=r&&t<=i)return e;let a=n.value?.range?.[0],o=n.value?.range?.[2];if(a!==void 0&&o!==void 0&&t>=a&&t<=o)return e}}function dae(e,t,n){let r=Sl(e,t.pos[0]),i=t.code===`DUPLICATE_KEY`;return{code:i?`duplicate-key`:`yaml-syntax`,source:e.source,...r,...i?{field:uae(n,t.pos[0])}:{},expected:i?`unique mapping keys`:`valid YAML frontmatter`,received:`${t.code}: ${t.message}`}}function Tl(e,t){if((0,to.isAlias)(e))return{node:e,field:t};if((0,to.isSeq)(e)){for(let n of e.items){let e=Tl(n,t);if(e!==void 0)return e}return}if((0,to.isMap)(e))for(let n of e.items){let e=wl(n.key),r=t??e;if(e===`<<`)return{node:n.key,field:t};let i=Tl(n.key,r);if(i!==void 0)return i;let a=Tl(n.value,r);if(a!==void 0)return a}}function El(e,t){let n=new to.LineCounter,r=(0,to.parseDocument)(t,{lineCounter:n,merge:!1,prettyErrors:!1,schema:`core`,strict:!0,stringKeys:!1,uniqueKeys:!0}),i={source:e,lineCounter:n,header:t},a=[...r.errors,...r.warnings];if(a.length>0)return xl(a.map(e=>dae(i,e,r.contents)));let o=Tl(r.contents);return o===void 0?{context:i,contents:r.contents}:xl([Cl(i,o.node,{code:`alias-or-merge-forbidden`,...o.field===void 0?{}:{field:o.field},expected:`frontmatter without aliases or merge keys`})])}function Dl(e,t,n,r){return{ok:!1,diagnostic:Cl(e,t,{code:`invalid-type`,field:n,expected:r})}}function Ol(e,t,n,r){return{ok:!1,diagnostic:Cl(e,t,{code:`invalid-value`,field:n,expected:r})}}function kl(e,t,n){return!(0,to.isScalar)(t)||typeof t.value!=`string`?Dl(e,t,n,`a non-empty string`):t.value.length===0?Ol(e,t,n,`a non-empty string`):{ok:!0,value:t.value}}function Al(e,t,n){return!(0,to.isScalar)(t)||typeof t.value!=`boolean`?Dl(e,t,n,`a YAML boolean`):{ok:!0,value:t.value}}function jl(e,t,n){if((0,to.isSeq)(t)){if(t.items.length===0)return Ol(e,t,n,`a non-empty string list`);let r=[];for(let i of t.items){if(!(0,to.isScalar)(i)||typeof i.value!=`string`)return Dl(e,i,n,`a list containing only non-empty strings`);if(i.value.length===0)return Ol(e,i,n,`a list containing only non-empty strings`);r.push(i.value)}return{ok:!0,value:r}}if(!(0,to.isScalar)(t)||typeof t.value!=`string`)return Dl(e,t,n,`a string list or delimited string`);let r=t.value.includes(`,`)?t.value.split(`,`).map(e=>e.trim()):t.value.trim().split(/\s+/);return r.length===0||r.some(e=>e.length===0)?Ol(e,t,n,`a non-empty comma- or whitespace-delimited string list`):{ok:!0,value:r}}function fae(e,t,n){return!(0,to.isScalar)(t)||typeof t.value!=`string`?Dl(e,t,n,`one of ${Ft.join(`, `)}`):Ce(t.value)?{ok:!0,value:t.value}:Ol(e,t,n,`one of ${Ft.join(`, `)}`)}function pae(e,t,n){return!(0,to.isScalar)(t)||typeof t.value!=`string`?Dl(e,t,n,`fork`):t.value===`fork`?{ok:!0,value:`fork`}:Ol(e,t,n,`fork`)}function mae(e,t,n){return!(0,to.isScalar)(t)||typeof t.value!=`number`?Dl(e,t,n,`a positive safe integer`):!Number.isSafeInteger(t.value)||t.value<=0?Ol(e,t,n,`a positive safe integer`):{ok:!0,value:t.value}}function hae(e,t,n){if(!(0,to.isMap)(t))return Dl(e,t,n,`a scalar metadata mapping`);let r=Object.create(null);for(let i of t.items){let t=wl(i.key);if(t===void 0||t.length===0)return Dl(e,i.key,n,`metadata with non-empty string keys`);if(!(0,to.isScalar)(i.value)||i.value.value===null)continue;let a=i.value.value;if(typeof a!=`string`&&typeof a!=`number`&&typeof a!=`boolean`||typeof a==`number`&&!Number.isFinite(a))return Dl(e,i.value,n,`metadata with string, finite-number, or boolean values`);r[t]=a}return{ok:!0,value:r}}function Ml(e,t){return(n,r,i,a)=>{let o=e(n,r,i);if(!o.ok)return o.diagnostic;t(a,o.value)}}const Nl={name:Ml(kl,(e,t)=>Object.assign(e,{name:t})),description:Ml(kl,(e,t)=>Object.assign(e,{description:t})),model:Ml(kl,(e,t)=>Object.assign(e,{model:t})),"argument-hint":(e,t,n,r)=>{if(!(t===null||(0,to.isScalar)(t)&&(t.value===``||t.value===null)))return Ml(kl,(e,t)=>Object.assign(e,{argumentHint:t}))(e,t,n,r)},"disable-model-invocation":Ml(Al,(e,t)=>Object.assign(e,{disableModelInvocation:t})),"user-invocable":Ml(Al,(e,t)=>Object.assign(e,{userInvocable:t})),"allowed-tools":Ml(jl,(e,t)=>Object.assign(e,{allowedTools:t})),effort:Ml(fae,(e,t)=>Object.assign(e,{effort:t})),context:Ml(pae,(e,t)=>Object.assign(e,{context:t})),agent:Ml(kl,(e,t)=>Object.assign(e,{agent:t})),loop:Ml(kl,(e,t)=>Object.assign(e,{loop:t})),invocable:Ml(Al,(e,t)=>Object.assign(e,{invocable:t})),license:Ml(kl,(e,t)=>Object.assign(e,{license:t})),metadata:Ml(hae,(e,t)=>Object.assign(e,{metadata:t}))},gae={...Nl,tags:Ml(jl,(e,t)=>Object.assign(e,{tags:t}))},_ae={name:Ml(kl,(e,t)=>Object.assign(e,{name:t})),description:Ml(kl,(e,t)=>Object.assign(e,{description:t})),model:Ml(kl,(e,t)=>Object.assign(e,{model:t})),maxTurns:Ml(mae,(e,t)=>Object.assign(e,{maxTurns:t})),tools:Ml(jl,(e,t)=>Object.assign(e,{tools:t})),disallowedTools:Ml(jl,(e,t)=>Object.assign(e,{disallowedTools:t})),signal:Ml(kl,(e,t)=>Object.assign(e,{signal:t}))};function Pl(e,t,n,r){if(!(0,to.isMap)(t))return xl([Cl(e,t,{code:`root-type`,expected:`a frontmatter mapping`})]);let i=r(),a=[];for(let r of t.items){let t=wl(r.key);if(t===void 0){a.push(Cl(e,r.key,{code:`invalid-type`,expected:`a string field name`}));continue}let o=Object.hasOwn(n,t)?n[t]:void 0;if(o===void 0)continue;let s=o(e,r.value,t,i);s!==void 0&&a.push(s)}return a.length>0?xl(a):{ok:!0,value:i}}function Fl(e,t,n,r){let i=Pl(e,t,n,r);return!i.ok||i.value.model===void 0||i.value.context===`fork`?i:xl([Cl(e,((0,to.isMap)(t)?t.items.find(e=>wl(e.key)===`model`):void 0)?.value??t,{code:`invalid-value`,field:`model`,expected:`context: fork when model is set`})])}function vae(e,t){return Fl(e,t,Nl,()=>({}))}function yae(e,t){return Fl(e,t,gae,()=>({}))}function bae(e,t){return Pl(e,t,_ae,()=>({}))}const xae={skill:{empty:()=>({}),decode:vae},"bundle-skill":{empty:()=>({}),decode:yae},agent:{empty:()=>({}),decode:bae}};function Il(e){let t=xae[e.profile],n=bl(e.source,e.content);if(n===void 0)return{ok:!0,metadata:t.empty(),body:e.content};if(`ok`in n)return n;if(n.header.trim().length===0)return{ok:!0,metadata:t.empty(),body:n.body};let r=El(e.source,n.header);if(`ok`in r)return r;if(r.contents===null)return{ok:!0,metadata:t.empty(),body:n.body};let i=t.decode(r.context,r.contents);return i.ok?{ok:!0,metadata:i.value,body:n.body}:i}const Ll={auto:`Auto`,none:`None`,minimal:`Minimal`,low:`Low`,medium:`Medium`,high:`High`,xhigh:`Extra high`,max:`Maximum`};function Rl(e,t=`--effort`){if(e!==void 0){if(e===`auto`||Ce(e))return e;throw Error(`Invalid ${t} "${String(e)}". Valid: auto | ${Ft.join(` | `)}`)}}function zl(e){let t=[[`command`,e.command],[`flag`,e.flag],[`environment`,e.environment],[`settings`,e.settings],[`preset`,e.preset]].find(([,e])=>e!==void 0),n=t?.[0]??`model-default`,r=t?.[1]??`auto`;return{requested:r,effective:r===`auto`?e.modelDefault:r,source:n,disposition:r===`auto`?`model-default`:`applied`,modelDefault:e.modelDefault}}const Sae=[{pattern:/\b401\b|invalid.*api.?key|authentication.*fail|unauthorized/i,message:`Invalid API key.`,category:`authentication`},{pattern:/\b403\b|permission.*denied|forbidden/i,message:`Access denied. Your API key may lack permission for this model. Check your provider plan.`,category:`forbidden`},{pattern:/\b429\b|rate.?limit|too many requests|quota.*exceeded/i,message:`Rate limit reached. Wait a moment and try again.`,category:`rateLimit`},{pattern:/\b500\b|internal server error/i,message:`The AI provider returned an internal error. This is usually temporary — try again.`},{pattern:/\b503\b|service.*unavailable|overloaded/i,message:`The AI provider is temporarily unavailable or overloaded. Try again in a few seconds.`},{pattern:/\b502\b|bad gateway/i,message:`The AI provider gateway is unreachable. Check your network or try again shortly.`},{pattern:/\btimeout\b|timed.?out|ETIMEDOUT/i,message:`The request timed out. Check your internet connection, or try a shorter prompt to reduce response time.`},{pattern:/ENOTFOUND|ECONNREFUSED|ECONNRESET|network.*error|fetch.*fail/i,message:`Network connection failed. Check your internet connection.`,category:`network`}];function Bl(e,t,n){let r=n?.[t]?.trim();return r?`${e} ${r}`:e}function Vl(e,t){if(e instanceof Rt)return Bl(`Invalid API key.`,`authentication`,t);if(e instanceof Ht)return Bl(`Rate limit reached${e.retryAfter?` (retry after ${e.retryAfter}s)`:``}. Wait a moment and try again.`,`rateLimit`,t);if(e instanceof Wt)return Bl(`Network connection failed. Check your internet connection.`,`network`,t);if(e instanceof Vt)return Bl(`The model${e.model===void 0?``:` "${e.model}"`} is not available for ${e.provider}.`,`modelUnavailable`,t);if(e instanceof Bt&&e.originalError)return Vl(e.originalError,t);let n=e.message;for(let{pattern:e,message:r,category:i}of Sae)if(e.test(n))return i?Bl(r,i,t):r;return n}var Cae=class{seen=!1;durationMs=0;samples=0;invalid=0;admissionStarted=0;notDispatched=0;observe(e){this.seen=!0;let t=typeof e.queuedAt==`string`?Date.parse(e.queuedAt):NaN,n=typeof e.endedAt==`string`?Date.parse(e.endedAt):NaN;if(typeof e.executionId!=`string`||!/^[A-Za-z0-9_-]{1,128}$/u.test(e.executionId)||!Number.isSafeInteger(t)||t<0||!Number.isSafeInteger(n)||n<t||new Date(t).toISOString()!==e.queuedAt||new Date(n).toISOString()!==e.endedAt||e.disposition!==`admission-started`&&e.disposition!==`not-dispatched`||!Number.isSafeInteger(this.durationMs+n-t)||!Number.isSafeInteger(this.samples+1)){this.invalid++;return}this.durationMs+=n-t,this.samples++,e.disposition===`admission-started`?this.admissionStarted++:this.notDispatched++}finish(){return this.seen?{durationMs:this.durationMs,samples:this.samples,invalid:this.invalid,admissionStarted:this.admissionStarted,notDispatched:this.notDispatched}:void 0}};function wae(e){return e===`app`?`desktop-app`:e?.includes(`browser`)||e?.includes(`web`)?`browser`:e?.startsWith(`peer:`)||e?.startsWith(`remote`)?`remote`:e===void 0||e===`owner`?`cli`:`unknown`}function Hl(e){return{id:`usage-observation_${e.turnId}`,timestamp:new Date,category:`event`,type:`usage-observation`,data:{usageObservationId:e.turnId,turnId:e.turnId,outcome:e.outcome,...e.promptExecutionStartedAt?{promptExecutionStartedAt:e.promptExecutionStartedAt}:{},...e.promptExecutionEndedAt?{promptExecutionEndedAt:e.promptExecutionEndedAt}:{},...e.promptExecutionOutcome?{promptExecutionOutcome:e.promptExecutionOutcome}:{},...e.promptExecutionTraceId?{promptExecutionTraceId:e.promptExecutionTraceId}:{},...e.promptExecutionSpanId?{promptExecutionSpanId:e.promptExecutionSpanId}:{},surface:e.surface??wae(e.driverId),...e.providerId?{providerId:e.providerId}:{},...e.modelId?{modelId:e.modelId}:{},...e.modelShares?{modelShares:e.modelShares}:{},...e.usage?{usage:e.usage}:{},...e.usage?.source?{source:e.usage.source}:{}}}}function Tae(e,t,n){let{attribution:r,...i}=n,a=r?.modelShares,o=a===void 0?r?.answeredBy?.providerId??t.getProviderId?.():void 0,s=a===void 0?r?.answeredBy?.modelId??t.getModelId?.():void 0;e.push(Hl({...i,...o?{providerId:o}:{},...s?{modelId:s}:{},...a===void 0?{}:{modelShares:a}}))}function Eae(e){let t=new Map;for(let n of e){if(n.outcome!==`success`||n.disposition!==`invoked`||n.providerId===void 0||n.modelId===void 0)continue;let e=`${n.providerId}\u0000${n.modelId}`,r=t.get(e)??{providerId:n.providerId,modelId:n.modelId,calls:[]};r.calls.push(n),t.set(e,r)}let n=[...t.values()];return n.length===0?{}:n.length===1?{answeredBy:{providerId:n[0].providerId,modelId:n[0].modelId}}:{modelShares:n.map(({providerId:e,modelId:t,calls:n})=>{let r=0,i=0,a=!0;for(let e of n){if(e.usageProvenance!==`complete`||e.promptTokens===void 0||e.completionTokens===void 0){a=!1;continue}r+=e.promptTokens,i+=e.completionTokens}let o=a?be(t,r,i):void 0,s=o!==void 0&&Number.isFinite(o)&&o>=0;return{providerId:e,modelId:t,promptTokens:r,completionTokens:i,totalTokens:r+i,costStatus:s?`estimated`:`unknown`,...s?{costUsd:o}:{}}})}}function Dae(e){return Ee(e)}function Ul(e,t){let n=[];for(let r=t;r<e.length;r++){let t=e[r];if(t?.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)n.push({name:e.function.name,args:e.function.arguments})}return n}function Oae(e,t,n,r,i,a,o,s=[]){let c=Ul(t,r),l=Kl(t,r,i,s);return{response:e,history:n,toolSummaries:c,contextState:i,...l&&{usage:l},...a&&a.length>0?{promptFileReferences:[...a]}:{}}}function kae(e,t,n,r,i,a=[]){let o=Ul(e,n),s=[];for(let t=n;t<e.length;t++){let n=e[t];n?.role===`assistant`&&n.content&&s.push(n.content)}let c=Kl(e,n,r,a);return{response:s.join(`
131
131
 
132
132
  `),interrupted:!0,history:t,toolSummaries:o,contextState:r,...c&&{usage:c}}}function Wl(e){return{id:`usage_${N()}`,timestamp:new Date,category:`event`,type:`usage-summary`,data:e}}function Aae(e,t){return Wl({kind:`exact`,scope:`turn`,totalTokens:e.totalTokens,promptTokens:e.promptTokens,completionTokens:e.completionTokens,contextUsedTokens:0,contextMaxTokens:0,contextUsedPercentage:0,costStatus:`unknown`,source:t})}function jae(e){return{id:`span_${N()}`,timestamp:new Date,category:`event`,type:`span`,data:{spanId:e.spanId,op:e.op,durationMs:e.durationMs}}}function Gl(e,t,n){if(!(typeof t!=`string`||!e.onToolCallObserved)&&(n===`allowed`||n===`denied`||n===`hook-blocked`||n===`body-completed`))try{e.onToolCallObserved(t,n)}catch{}}function Mae(e,t={}){let n=[],r=[],i=[],a=[],o={provider:0,tool:0,permission:0},s=new Cae,c=(e,c)=>{if(e===`tool.${at.COMPLETED}`){s.observe(c);return}if(e===xt.SWITCHED){let e=Le(c);e!==void 0&&t.onProviderFallback?.(e);return}if(e===`tool.${Ze.DECIDED}`){if(Gl(t,c.executionId,c.decision),typeof c.decidedAt==`string`&&(c.decision===`allowed`||c.decision===`denied`||c.decision===`hook-blocked`)){let e={...c.executionId===void 0?{}:{toolCallId:c.executionId},decidedAt:c.decidedAt,decision:c.decision};a.push({kind:`permission`,observation:e})}else o.permission+=1;return}if(e===`tool.${De.COMPLETED}`){if(Gl(t,c.executionId,`body-completed`),typeof c.startedAt==`string`&&typeof c.endedAt==`string`&&(c.outcome===`success`||c.outcome===`failure`||c.outcome===`interrupted`)){let e={...c.executionId===void 0?{}:{toolCallId:c.executionId},...typeof c.toolBodyId==`string`?{toolBodyId:c.toolBodyId}:{},...c.toolName===void 0?{}:{toolName:c.toolName},startedAt:c.startedAt,endedAt:c.endedAt,outcome:c.outcome};i.push(e),a.push({kind:`tool`,observation:e})}else o.tool+=1;return}if(e===st.COMPLETED){if(typeof c.round==`number`&&Number.isSafeInteger(c.round)&&c.round>0&&typeof c.startedAt==`string`&&typeof c.endedAt==`string`&&(c.outcome===`success`||c.outcome===`failure`||c.outcome===`interrupted`)){let e={round:c.round,startedAt:c.startedAt,endedAt:c.endedAt,outcome:c.outcome,...typeof c.callId==`string`&&{callId:c.callId},...(c.disposition===`invoked`||c.disposition===`cache-hit`||c.disposition===`preflight-refused`)&&{disposition:c.disposition},...typeof c.providerId==`string`&&{providerId:c.providerId},...typeof c.modelId==`string`&&{modelId:c.modelId},...(c.usageProvenance===`complete`||c.usageProvenance===`partial`||c.usageProvenance===`absent`)&&{usageProvenance:c.usageProvenance},...typeof c.promptTokens==`number`&&typeof c.completionTokens==`number`&&typeof c.totalTokens==`number`&&{promptTokens:c.promptTokens,completionTokens:c.completionTokens,totalTokens:c.totalTokens},...c.providerRequestId!==void 0&&{providerRequestId:c.providerRequestId}},{providerRequestId:t,...n}=e;r.push(n),a.push({kind:`provider`,observation:e})}else o.provider+=1;return}e===_t.COMPLETED&&n.push(jae(c))};return e.subscribe(c),{get queueSummary(){return s.finish()},entries:n,providerCalls:r,toolBodies:i,completions:a,omittedCompletions:o,dispose:()=>e.unsubscribe(c)}}function Kl(e,t,n,r=[]){let i=e.slice(t),a=0,o=0,s=!1,c=new Set;for(let e of i){if(e.role!==`assistant`)continue;let t=e.metadata?.usageObservationId,n=e.metadata?.round,r=typeof t==`string`?`${t}:${Number.isSafeInteger(n)?n:`legacy`}`:e.id;if(c.has(r))continue;let i=Fe(e);i&&(c.add(r),s=!0,a+=i.inputTokens,o+=i.outputTokens)}if(!s)return;let l=Nae(r,a,o),u=l.costUsd;return{kind:l.tokensMatch?`exact`:`estimated`,scope:`turn`,promptTokens:a,completionTokens:o,totalTokens:a+o,contextUsedTokens:n.usedTokens,contextMaxTokens:n.maxTokens,contextUsedPercentage:n.usedPercentage,costStatus:u===void 0?`unknown`:`estimated`,...u===void 0?{}:{costUsd:u}}}function Nae(e,t,n){let r=new Map,i=0,a=0,o=0,s=!0,c=0;for(let t of e){if(t.disposition!==`invoked`)continue;if(!t.callId)return{tokensMatch:!1};let e=r.get(t.callId);if(e){if(JSON.stringify(e)!==JSON.stringify(t))return{tokensMatch:!1};continue}if(r.set(t.callId,t),c+=1,t.usageProvenance!==`complete`||!Number.isSafeInteger(t.promptTokens)||(t.promptTokens??-1)<0||!Number.isSafeInteger(t.completionTokens)||(t.completionTokens??-1)<0||t.totalTokens!==(t.promptTokens??0)+(t.completionTokens??0))return{tokensMatch:!1};i+=t.promptTokens,a+=t.completionTokens;let n=t.modelId?be(t.modelId,t.promptTokens,t.completionTokens):void 0;n===void 0||!Number.isFinite(n)||n<0?s=!1:o+=n}let l=c>0&&i===t&&a===n;return{tokensMatch:l,...l&&s&&{costUsd:o}}}const Pae={write:()=>{},writeLine:()=>{},writeMarkdown:()=>{},writeError:()=>{},prompt:()=>Promise.resolve(``),select:()=>Promise.resolve(0),spinner:()=>({stop:()=>{},update:()=>{}})},ql=10080*6e4;function Jl(e){if(e.metadata?.sessionLoop!==!0)return;let t=e.metadata.sessionLoopExpiresAt;return t===void 0?e.startedAt?Date.parse(e.startedAt)+ql:NaN:typeof t==`string`?Date.parse(t):NaN}function Yl(e,t,n){if(e?.metadata?.sessionLoop!==!0)return null;let r=Jl(e);return r===void 0||!Number.isFinite(r)||r<=t?`expired`:n?`disabled`:null}function Xl(e,t){if(e?.metadata?.sessionLoop!==!0)return`eligible`;let n=e.metadata.sessionLoopFirstAllowedAt;if(n===void 0)return`eligible`;let r=typeof n==`string`?Date.parse(n):NaN;return Number.isFinite(r)?t<r?`early`:`eligible`:`invalid`}function Fae(e,t){if(e===void 0)return new Date(t+ql).toISOString();let n=Date.parse(e);if(!Number.isFinite(n)||n<=t||n>t+ql)throw Error(`Session loop expiry is invalid, expired, or later than seven days.`);return new Date(n).toISOString()}function Zl(e){return e.kind===`scheduled`&&(e.status===`sleeping`||e.status===`paused`)&&e.schedule!==void 0}function Ql(e,t,n){return!Zl(e)||e.metadata?.sessionLoopSelfPaced===!0?`ignore`:Yl(e,t,n)||(e.status===`paused`?`rearm-paused`:`rearm`)}const $l=1e3;var Iae=class{manager;now;idFactory;unsubscribeManager;listeners=new Set;onObserverFailure;groups=new Map;sequence=0;constructor(e){this.manager=e.manager,this.now=e.now??(()=>new Date().toISOString()),this.idFactory=e.idFactory??(()=>this.nextGroupId()),this.onObserverFailure=e.onObserverFailure??(t=>Ti(t,e.observerFailureWarningCode)),this.sequence=e.initialGroups?.length??0;for(let t of e.initialGroups??[])this.restoreGroup(t);this.unsubscribeManager=this.manager.subscribe(e=>this.handleTaskEvent(e))}createGroup(e){let t=this.now(),n={id:this.idFactory(e),parentSessionId:e.parentSessionId,waitPolicy:e.waitPolicy,taskIds:[...e.taskIds],status:`running`,createdAt:t,updatedAt:t,results:[],...e.label?{label:e.label}:{}},r=this.createRecord(n);return this.groups.set(n.id,r),this.captureExistingTerminalTasks(r),this.emit({type:`background_job_group_created`,group:nu(r.state)}),this.evaluateCompletion(r),nu(r.state)}listGroups(){return[...this.groups.values()].map(e=>nu(e.state))}getGroup(e){let t=this.groups.get(e);return t?nu(t.state):void 0}waitGroup(e){let t=this.groups.get(e);return t?t.completion:Promise.reject(Error(`Unknown background job group: ${e}`))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}dispose(){this.unsubscribeManager(),this.listeners.clear()}nextGroupId(){return this.sequence+=1,`group_${this.sequence}`}restoreGroup(e){let t=this.createRecord(nu(e));this.groups.set(e.id,t),e.status===`completed`&&t.resolve(nu(e))}createRecord(e){let t=()=>{};return{state:e,completion:new Promise(e=>{t=e}),resolve:t}}captureExistingTerminalTasks(e){for(let t of e.state.taskIds){let n=this.manager.get(t);n&&fi(n.status)&&this.captureTask(e,n)}}handleTaskEvent(e){let t=Lae(e);if(t)for(let e of this.groups.values())e.state.taskIds.includes(t.id)&&this.captureTask(e,t)&&(e.state.status===`running`?this.evaluateCompletion(e):this.emit({type:`background_job_group_updated`,group:nu(e.state)}))}captureTask(e,t){return e.state.results.some(e=>e.taskId===t.id)?!1:(e.state.results=[...e.state.results,zae(t)],e.state.updatedAt=this.now(),!0)}evaluateCompletion(e){if(e.state.status===`completed`)return;if(!Rae(e.state)){this.emit({type:`background_job_group_updated`,group:nu(e.state)});return}let t=this.now();e.state.status=`completed`,e.state.completedAt=t,e.state.updatedAt=t;let n=nu(e.state);e.resolve(n),this.emit({type:`background_job_group_completed`,group:n})}emit(e){Ei(e,this.listeners,this.onObserverFailure)}};function Lae(e){if(e.type===`background_task_completed`||e.type===`background_task_failed`||e.type===`background_task_cancelled`)return e.task}function Rae(e){return e.waitPolicy===`manual`?!1:e.waitPolicy===`wait_any`?e.results.length>0:e.taskIds.every(t=>e.results.some(e=>e.taskId===t))}function zae(e){return{taskId:e.id,label:e.label,status:e.status,...e.result?.output?{summary:Bae(e.result.output)}:{},...e.transcriptPath||e.logPath?{outputRef:e.transcriptPath??e.logPath}:{},...e.error?{error:{...e.error}}:{},...e.startedAt?{startedAt:e.startedAt}:{},...e.completedAt?{completedAt:e.completedAt}:{}}}function Bae(e){let t=e.trim();return t.length<=$l?t:`${t.slice(0,$l)}...`}function eu(e){let t=tu(e,`completed`),n=tu(e,`failed`),r=tu(e,`cancelled`);return{groupId:e.id,status:e.status,total:e.taskIds.length,completed:t,failed:n,cancelled:r,pending:Math.max(e.taskIds.length-e.results.length,0),lines:e.results.map(e=>Vae(e))}}function tu(e,t){return e.results.filter(e=>e.status===t).length}function Vae(e){let t=Hae(e),n=e.outputRef&&e.summary?` (output: ${e.outputRef})`:``;return`[${e.status}] ${e.label} ${e.taskId}: ${t}${n}`}function Hae(e){let t=(e.error?.message??e.summary??``).replace(/\s+/g,` `).trim();return t.length>0?t:`(no summary)`}function nu(e){return{...e,taskIds:[...e.taskIds],results:e.results.map(e=>({...e,...e.error?{error:{...e.error}}:{}}))}}const Uae={queued:`working`,running:`working`,sleeping:`working`,waiting_permission:`needs-input`,paused:`stopped`,completed:`completed`,failed:`failed`,cancelled:`stopped`};function Wae(e){return Uae[e.status]}function Gae(e){return e.pendingRequest===void 0?e.isExecuting?`working`:`completed`:`needs-input`}function Kae(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`working`}function ru(e){let t=e?.trim().replace(/\s+/g,` `);if(t)return t.length>120?`${t.slice(0,120)}...`:t}function iu(e,t){let n=ru(t);return n?{kind:e,text:n}:void 0}function qae(e){switch(e.status){case`failed`:return iu(`result`,e.error?.message);case`completed`:return iu(`result`,e.result?.output);case`cancelled`:case`paused`:return iu(`result`,e.status);case`waiting_permission`:return iu(`question`,e.currentAction??`waiting for permission`);default:return iu(`activity`,e.currentAction??Jae(e))}}function Jae(e){switch(e.kind){case`agent`:return e.promptPreview;case`scheduled`:return e.schedule?.agentInstruction??e.commandPreview;case`process`:case`tool-invocation`:return e.commandPreview}}function Yae(e){return e.pendingRequest===void 0?iu(e.isExecuting?`activity`:`result`,e.preview):iu(`question`,e.pendingRequest.text)}function Xae(e){return iu(e.status===`completed`?`result`:`activity`,e.results.map(e=>e.summary??e.error?.message).join(` `).trim()||`${e.results.length}/${e.taskIds.length} tasks`)}const au={kind:`executionOriginKind`,sessionId:`executionOriginSessionId`,turnId:`executionOriginTurnId`,commandName:`executionOriginCommandName`,toolCallId:`executionOriginToolCallId`,skillId:`executionOriginSkillId`,label:`executionOriginLabel`};function ou(e){return[`main`,e].join(`:`)}function su(e){return[`task`,e].join(`:`)}function cu(e){return[`group`,e].join(`:`)}function Zae(e){let[t,n]=e.split(`:`,2);if(n){if(t===`main`)return{kind:`main_thread`,sourceId:n};if(t===`task`)return{kind:`background_task`,sourceId:n};if(t===`group`)return{kind:`background_group`,sourceId:n}}}function lu(e){return{[au.kind]:e.kind,[au.sessionId]:e.sessionId,...e.turnId?{[au.turnId]:e.turnId}:{},...e.commandName?{[au.commandName]:e.commandName}:{},...e.toolCallId?{[au.toolCallId]:e.toolCallId}:{},...e.skillId?{[au.skillId]:e.skillId}:{},...e.label?{[au.label]:e.label}:{}}}function Qae(e){return e?.kind!==`process`||(e.exitCode??0)===0&&!e.signalCode}function $ae(e){let t=loe(e.groups),n=[eoe(e.mainThread),...yoe(e.groups).map(e=>soe(e)),...voe(e.tasks).filter(e=>!ioe(e)).map(e=>toe(e,t.get(e.id))),...ooe(e.selfPacedLoops??[]).filter(e=>e.phase===`pending`||e.phase===`running`).map(t=>aoe(t,e.sessionId))].filter(t=>_oe(t,e.filter));return{sessionId:e.sessionId,selectedEntryId:e.selectedEntryId??n.find(e=>e.kind===`main_thread`)?.id??ou(e.sessionId),updatedAt:n[0]?.updatedAt??e.mainThread.updatedAt,entries:n}}function eoe(e){return{id:ou(e.sessionId),sourceId:e.sessionId,kind:`main_thread`,origin:{kind:`user_prompt`,sessionId:e.sessionId},status:e.isExecuting?`active`:`idle`,title:`Main thread`,subtitle:e.hasPendingPrompt?`prompt queued`:`${e.historyLength} history entries`,preview:ru(e.preview),unread:!1,attention:e.pendingRequest===void 0?`none`:`permission`,visibility:`default`,updatedAt:e.updatedAt,controls:[`select`],state:Gae(e),...uu(Yae(e))}}function toe(e,t){return{id:su(e.id),sourceId:e.id,kind:`background_task`,parentId:e.parentTaskId?su(e.parentTaskId):ou(e.parentSessionId),...t?{groupId:cu(t)}:{},origin:coe(e.metadata,{kind:`system`,sessionId:e.parentSessionId}),taskKind:e.kind,status:e.status,title:e.label,subtitle:doe(e),preview:poe(e),currentAction:e.currentAction,unread:e.unread,attention:moe(e),visibility:hoe(e),updatedAt:e.lastActivityAt??e.updatedAt,controls:uoe(e),...e.kind===`agent`&&e.resumeSessionId!==void 0?{resumeSessionId:e.resumeSessionId}:{},state:Wae(e),...uu(qae(e)),...e.kind===`scheduled`&&e.status===`sleeping`&&e.nextFireAt!==void 0?{nextFireAt:e.nextFireAt}:{},...(()=>{let t=roe(e);return t===void 0?{}:{loopId:t}})(),...(()=>{let t=noe(e);return t===void 0?{}:{deniedToolCalls:t}})()}}function noe(e){if(e.kind!==`agent`||e.result?.kind!==`agent`)return;let t=e.result.deniedToolCalls;return t&&t.total>0?t.total:void 0}function roe(e){if(e.metadata?.sessionLoop!==!0)return;let t=e.metadata.sessionLoopId;return typeof t==`string`&&t.length>0?t:e.id}function ioe(e){return e.metadata?.sessionLoop===!0&&(e.status===`cancelled`||e.status===`completed`)}function aoe(e,t){let n=e.phase===`running`?`running`:`queued`;return{id:su(e.loopId),sourceId:e.loopId,kind:`background_task`,parentId:ou(t),origin:{kind:`slash_command`,sessionId:t,commandName:`loop`},taskKind:`scheduled`,status:n,title:`Loop: ${e.instruction.slice(0,48)}`,subtitle:`self-paced`,preview:ru(e.instruction),unread:!1,attention:`none`,visibility:`default`,updatedAt:e.createdAt,controls:[`select`,`cancel`],state:`working`,loopId:e.loopId}}function ooe(e){return[...e].sort((e,t)=>e.loopId.localeCompare(t.loopId))}function soe(e){let t=ru(e.results.map(e=>e.summary??e.error?.message).join(` `));return{id:cu(e.id),sourceId:e.id,kind:`background_group`,parentId:ou(e.parentSessionId),origin:{kind:`system`,sessionId:e.parentSessionId,label:e.label},status:e.status,title:e.label??e.id,subtitle:`${e.results.length}/${e.taskIds.length} tasks`,preview:t,unread:!1,attention:goe(e),visibility:e.status===`completed`?`collapsed`:`default`,updatedAt:e.updatedAt,controls:e.status===`running`?[`select`,`wait`]:[`select`],state:Kae(e),...uu(Xae(e))}}function coe(e,t){let n=boe(e?.[au.kind]),r=du(e?.[au.sessionId]);return{kind:n??t.kind,sessionId:r??t.sessionId,turnId:du(e?.[au.turnId])??t.turnId,commandName:du(e?.[au.commandName])??t.commandName,toolCallId:du(e?.[au.toolCallId])??t.toolCallId,skillId:du(e?.[au.skillId])??t.skillId,label:du(e?.[au.label])??t.label}}function loe(e){return new Map(e.flatMap(e=>e.taskIds.map(t=>[t,e.id])))}function uoe(e){let t=[`select`];return fi(e.status)?t.push(`close`):t.push(`cancel`),e.kind===`agent`&&e.status===`running`&&t.push(`send`),(e.logPath||e.transcriptPath)&&t.push(`read_log`),e.kind===`agent`&&e.resumeSessionId!==void 0&&t.push(`attach`),t}function doe(e){if(e.kind===`agent`)return e.agentType??e.cwd;let t=e.kind===`scheduled`?e.schedule?.agentInstruction:void 0;return e.status===`sleeping`&&t!==void 0?`↻ wake "${foe(t)}"`:e.cwd}function uu(e){return e===void 0?{}:{headline:e}}function foe(e){let t=e.trim();return t.length>32?`${t.slice(0,32)}…`:t}function poe(e){return e.status===`failed`?ru(e.error?.message):e.status===`completed`?ru(e.result?.output):ru(e.kind===`agent`?e.promptPreview:e.commandPreview)}function moe(e){return e.status===`failed`?`failed`:e.status===`waiting_permission`?`permission`:e.unread?`unread`:e.status===`completed`?`completed`:`none`}function hoe(e){return e.status===`completed`&&!e.unread&&!e.error&&Qae(e.result)&&!(e.kind===`agent`&&e.worktreePath)&&!(e.kind===`agent`&&e.branchName)?`collapsed`:`default`}function goe(e){return e.results.some(e=>e.status===`failed`)?`failed`:e.status===`completed`?`completed`:`none`}function _oe(e,t){return!t||!(t.includeMainThread===!1&&e.kind===`main_thread`||t.kinds&&!t.kinds.includes(e.kind)||t.visibility&&!t.visibility.includes(e.visibility))}function voe(e){return[...e].sort((e,t)=>{let n=e.startedAt??e.updatedAt,r=t.startedAt??t.updatedAt,i=n.localeCompare(r);return i===0?e.id.localeCompare(t.id):i})}function yoe(e){return[...e].sort((e,t)=>e.id.localeCompare(t.id))}function du(e){return typeof e==`string`?e:void 0}function boe(e){if(e===`user_prompt`||e===`slash_command`||e===`model_command`||e===`tool_call`||e===`skill`||e===`transport`||e===`system`)return e}function xoe(e){return e===`active`||e===`idle`?!1:fi(e)}function Soe(e,t){let n=e.resumeSessionId;return n===void 0?{type:`refused`,reason:`${e.title} is not a forked session; nothing to attach to.`}:xoe(e.status)?{type:`refused`,reason:`${e.title} is ${e.status}; attach follows a fork that is still running. Its record is still there; resume session ${n} through your host.`,resumeSessionId:n}:t.hasSessionRecord(n)?{type:`switch-session`,sessionId:n}:{type:`refused`,reason:`The forked session ${n} is no longer in the session store (${e.status}).`}}function Coe(e){let t=woe(e.cursor?.offset),n=e.history.slice(t,t+80),r=n.map(e=>({id:e.id,kind:e.category===`chat`?`message`:`progress`,text:Toe(e),timestamp:e.timestamp.toISOString(),sourceId:e.type}));return e.pendingRequest!==void 0&&t===0&&r.unshift({id:`${e.entryId}:pending`,kind:`message`,text:`Waiting for ${e.pendingRequest.kind}: ${e.pendingRequest.text}`,timestamp:new Date().toISOString(),sourceId:`pending_request`}),{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...t+n.length<e.history.length?{nextCursor:{offset:t+n.length}}:{},records:r}}function fu(e){let t=e.cursor?.offset??0,n=e.lines.map((n,r)=>({id:`${e.entryId}:${t}:${r}`,kind:e.kind??`process_output`,text:n}));return{entryId:e.entryId,...e.cursor?{cursor:e.cursor}:{},...e.nextCursor?{nextCursor:e.nextCursor}:{},records:n}}function woe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Toe(e){return typeof e.data==`string`?e.data:e.type}function Eoe(e){return{spawnAgent:t=>e.manager.spawn(Doe(e,t)),spawnProcess:t=>e.manager.spawn(Ooe(e,t)),createGroup:t=>e.groupOrchestrator.createGroup({parentSessionId:e.sessionId,waitPolicy:t.waitPolicy,taskIds:[...t.taskIds],label:t.label})}}function Doe(e,t){let{mode:n,depth:r,cwd:i,allowedTools:a,disallowedTools:o,...s}=t;return{...s,kind:`agent`,mode:n??`background`,depth:r??1,cwd:i??e.cwd,allowedTools:a?[...a]:void 0,disallowedTools:o?[...o]:void 0,parentSessionId:e.sessionId,metadata:lu(e.origin)}}function Ooe(e,t){return{kind:`process`,label:t.label??t.command,mode:t.mode??`background`,parentSessionId:e.sessionId,parentTaskId:t.parentTaskId,depth:t.depth??0,cwd:t.cwd??e.cwd,command:t.command,shell:t.shell,env:t.env,stdin:t.stdin,timeoutMs:t.timeoutMs,idleTimeoutMs:t.idleTimeoutMs,maxRuntimeMs:t.maxRuntimeMs,outputLimitBytes:t.outputLimitBytes,metadata:lu(e.origin)}}const pu=new WeakMap;function koe(e,t){pu.set(e,t)}function mu(e){return pu.get(e)}const Aoe={BackgroundProcess:{argument:{key:`command`,kind:`command`},riskClass:`execute`},ExecuteCommand:{argument:{key:`command`,kind:`command`},riskClass:`execute`},Agent:{riskClass:`execute`},Advisor:{riskClass:`inspect`},Cd:{argument:{key:`path`,kind:`path`},riskClass:`inspect`},peer_reply:{argument:{key:`text`,kind:`text`},repliesToPeer:!0},peer_send_file:{argument:{key:`path`,kind:`path`},riskClass:`inspect`,notInPeerTurn:!0},report_goal_status:{riskClass:`inspect`},report_loop_decision:{riskClass:`inspect`}};function joe(){for(let[e,t]of Object.entries(Aoe))ht(e,t)}joe();function Moe(e,t){if(e===void 0)throw Error(`${t} tool has no execution root: it was constructed without a \`cwd\`. This is an assembly bug — the child would otherwise run wherever the host process was started.`);return e}const hu=[{name:`general-purpose`,description:`General-purpose task execution agent with full tool access.`,systemPrompt:`You are a general-purpose task execution agent. You have access to all tools available in the parent session and can perform any task delegated to you.
@@ -2744,7 +2744,7 @@ Options:
2744
2744
  `);return}let u=l.at(-1);u||(process.stderr.write(`No sessions found.
2745
2745
  `),process.exit(1)),process.stdout.write(GJ(BJ(u))+`
2746
2746
  `)}function nPe(e){let t,n,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(a===`--threshold`){let t=e[i+1],a=t===void 0?NaN:Number.parseFloat(t);Number.isFinite(a)?n=a:r=!0,i++}else a&&!a.startsWith(`-`)&&t===void 0&&(t=a)}return{definitionPath:t,threshold:n,thresholdInvalid:r}}async function rPe(e){let t=await import(yr(e).href),n=t.default??t.evalDefinition;if(!n)throw Error(`eval definition module '${e}' has no default (or 'evalDefinition') export`);return n}async function iPe(e,t){let n=t.settingsSources??(()=>{throw Error(`Eval startup requires explicit host settings sources.`)})(),r=t.providerDefinitions??Sz(),i=vy(n,{providerDefinitions:r,...t.environment===void 0?{}:{env:t.environment}});return Lme(ihe({cwd:e,provider:Tt(t.resolveProviderCredential===void 0?i:await t.resolveProviderCredential(i),r),userSettingsSources:n.filter(e=>e.kind===`host`),...t.projectAccess===void 0?{}:{projectAccess:t.projectAccess}}))}async function P1(e,t=process.cwd(),n={}){let r=nPe(e);if(!r.definitionPath||r.thresholdInvalid)return process.stderr.write(`Usage: eval <definition-file> [--threshold <0..1>]
2747
- `),1;let i=j.resolve(t,r.definitionPath),a;try{let e=await(n.loadDefinition??rPe)(i);a=r.threshold===void 0?e:{...e,threshold:r.threshold},TS(a)}catch(e){return process.stderr.write(`Failed to load eval definition: ${e instanceof Error?e.message:String(e)}\n`),1}let o;try{let e=n.runFn??await iPe(t,n);o=await Pme(a,e)}catch(e){return process.stderr.write(`Eval run failed: ${e instanceof Error?e.message:String(e)}\n`),1}return process.stdout.write(Bme(o)),+!o.passed}const F1=()=>`3.0.5`,aPe=()=>`3.0.5`,oPe=()=>null,I1=e=>e.artifact?.version??F1(),sPe=e=>e.artifact===void 0?aPe():e.artifact.sourceVersion??e.artifact.version,cPe=e=>e.artifact===void 0?oPe():e.artifact.buildMetadata??null;async function lPe(e){let t=$r({input:process.stdin,output:process.stdout});try{let n=(await t.question(e)).trim().toLowerCase();return n===`y`||n===`yes`}finally{t.close()}}async function uPe(e,t){let n=rC(t.productRuntime);if(!fn(n))return e.writeLine(`No user settings found.`),0;if(!t.yes){if(!t.isTTY)return e.writeError(`--reset deletes ${n}. Refusing without confirmation in non-interactive mode — pass --yes to proceed.`),1;if(!await(t.confirm??lPe)(`Delete ${n}? [y/N] `))return e.writeLine(`Reset cancelled.`),1}let r=Yme(n);return r.deleted?e.writeLine(`Deleted ${r.path}`):e.writeLine(`No user settings found.`),0}function dPe(e){return!fn(e)}function fPe(e){vn(Mn(e),{recursive:!0}),kn(e,new Date().toISOString())}function pPe(e){return[`Welcome to ${e.vocabulary.cliName}! — AI coding assistant`,``,`Try asking:`,` "Explain this project structure"`,` "Find files with TODO comments"`,` "Run tests and analyze failures"`,` "What changed recently in git?"`,``,`Useful commands:`,` /help show all slash commands`,` /cost show token usage and estimated cost`,` /clear clear conversation history`,``,`${e.vocabulary.cliName} diagnose — check your setup`]}function mPe(e){let t=Math.max(...e.map(e=>Or(e)))+4,n=e.map(e=>{let n=t-2-Or(e);return`│${` `.repeat(2)}${e}${` `.repeat(n)}│`});return[`╭${`─`.repeat(t)}╮`,...n,`╰${`─`.repeat(t)}╯`].join(`
2747
+ `),1;let i=j.resolve(t,r.definitionPath),a;try{let e=await(n.loadDefinition??rPe)(i);a=r.threshold===void 0?e:{...e,threshold:r.threshold},TS(a)}catch(e){return process.stderr.write(`Failed to load eval definition: ${e instanceof Error?e.message:String(e)}\n`),1}let o;try{let e=n.runFn??await iPe(t,n);o=await Pme(a,e)}catch(e){return process.stderr.write(`Eval run failed: ${e instanceof Error?e.message:String(e)}\n`),1}return process.stdout.write(Bme(o)),+!o.passed}const F1=()=>`3.0.6`,aPe=()=>`3.0.6`,oPe=()=>null,I1=e=>e.artifact?.version??F1(),sPe=e=>e.artifact===void 0?aPe():e.artifact.sourceVersion??e.artifact.version,cPe=e=>e.artifact===void 0?oPe():e.artifact.buildMetadata??null;async function lPe(e){let t=$r({input:process.stdin,output:process.stdout});try{let n=(await t.question(e)).trim().toLowerCase();return n===`y`||n===`yes`}finally{t.close()}}async function uPe(e,t){let n=rC(t.productRuntime);if(!fn(n))return e.writeLine(`No user settings found.`),0;if(!t.yes){if(!t.isTTY)return e.writeError(`--reset deletes ${n}. Refusing without confirmation in non-interactive mode — pass --yes to proceed.`),1;if(!await(t.confirm??lPe)(`Delete ${n}? [y/N] `))return e.writeLine(`Reset cancelled.`),1}let r=Yme(n);return r.deleted?e.writeLine(`Deleted ${r.path}`):e.writeLine(`No user settings found.`),0}function dPe(e){return!fn(e)}function fPe(e){vn(Mn(e),{recursive:!0}),kn(e,new Date().toISOString())}function pPe(e){return[`Welcome to ${e.vocabulary.cliName}! — AI coding assistant`,``,`Try asking:`,` "Explain this project structure"`,` "Find files with TODO comments"`,` "Run tests and analyze failures"`,` "What changed recently in git?"`,``,`Useful commands:`,` /help show all slash commands`,` /cost show token usage and estimated cost`,` /clear clear conversation history`,``,`${e.vocabulary.cliName} diagnose — check your setup`]}function mPe(e){let t=Math.max(...e.map(e=>Or(e)))+4,n=e.map(e=>{let n=t-2-Or(e);return`│${` `.repeat(2)}${e}${` `.repeat(n)}│`});return[`╭${`─`.repeat(t)}╮`,...n,`╰${`─`.repeat(t)}╯`].join(`
2748
2748
  `)}function hPe(e,t,n={}){let r=pPe(t);e.writeLine(`\n${n.screenReader===!0?r.join(`
2749
2749
  `):mPe(r)}\n`)}function gPe(e,t){process.platform===`darwin`&&t.TERM_PROGRAM===`Apple_Terminal`&&e.writeError(`
2750
2750
  ⚠ macOS Terminal.app detected: CJK/IME input may be unstable.
@@ -2756,7 +2756,7 @@ Options:
2756
2756
  `,0,1)||!r(e,o,s)?!1:(i=!0,!0)};if(t===``){for(let t=0;t<e.length;t++)if(!a(t,t+1))return!1;return!0}let o=0;for(;;){let n=e.indexOf(t,o);if(n<0)return a(o,e.length);if(!a(o,n))return!1;o=n+t.length}},r,`text-split`)}function J0(e,t,n){let r=0,i=!1;for(let a of e){let e=n===`text-lower`?a.toLowerCase():a.toUpperCase();for(let a=0;a<e.length;a++){let o=e.charCodeAt(a);if(r+=o<128?1:o<2048?2:o>=56320&&o<=57343&&i?1:3,i=o>=55296&&o<=56319,r>t)return{ok:!1,error:z1(`DAG_TASK_EXECUTION_BYTE_LIMIT_EXCEEDED`,`${n} output exceeds its UTF-8 byte limit`,!1,{maxBytes:t,nodeType:n})}}}return{ok:!0,value:n===`text-lower`?e.toLowerCase():e.toUpperCase()}}const Y0={ok:!0,value:{estimatedCredits:0}},X0=P.object({});var LFe=class extends v0{nodeType=`string-to-number`;displayName=`String → Number`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`number`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];configSchemaDefinition=X0;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=Number(i.value);return isNaN(a)?{ok:!1,error:Q(`DAG_VALIDATION_STRING_TO_NUMBER_INVALID`,`Cannot convert "${i.value}" to a number`,{nodeId:t.nodeDefinition.nodeId})}:(r.setOutput(`number`,String(a)),{ok:!0,value:r.toOutput()})}},RFe=class extends v0{nodeType=`number-to-string`;displayName=`Number → String`;category=`Utility`;defaultInputPort=`number`;defaultOutputPort=`text`;inputs=[{key:`number`,label:`Number`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=X0;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`number`);return i.ok?(r.setOutput(`text`,i.value),{ok:!0,value:r.toOutput()}):i}};const zFe=P.object({separator:P.string().default(`, `)});var BFe=class extends v0{nodeType=`text-join`;displayName=`Text Join`;category=`Utility`;defaultInputPort=`items`;defaultOutputPort=`text`;inputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=zFe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`items`);if(!i.ok)return i;let a=FFe(i.value,n.separator,K1(t.byteLimits).maxTextJoinOutputBytes);return a.ok?(r.setOutput(`text`,a.value),{ok:!0,value:r.toOutput()}):a}};const VFe=P.object({separator:P.string().default(`
2757
2757
  `),trim:P.boolean().default(!0)});var HFe=class extends v0{nodeType=`text-split`;displayName=`Text Split`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`items`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`items`,label:`Items (newline-separated)`,order:0,type:`string`,required:!0}];configSchemaDefinition=VFe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=IFe(i.value,n.separator,n.trim,K1(t.byteLimits).maxTextSplitOutputBytes);return a.ok?(r.setOutput(`items`,a.value),{ok:!0,value:r.toOutput()}):a}};const UFe=P.object({search:P.string().default(``),replacement:P.string().default(``),useRegex:P.boolean().default(!1),flags:P.string().default(`g`)});var WFe=class extends v0{nodeType=`text-replace`;displayName=`Text Replace`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=UFe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a;if(n.useRegex){if(!t.regexReplaceOperation)return{ok:!1,error:z1(`DAG_TASK_ISOLATION_UNAVAILABLE`,`Regex-based text-replace requires an isolated regex executor; none was supplied for this run`,!1,{nodeId:t.nodeDefinition.nodeId})};let e=await t.regexReplaceOperation.execute({text:i.value,search:n.search,replacement:n.replacement,flags:n.flags},t.signal);if(!e.ok)return e;a=e.value}else{let e=MFe(i.value,n.search,n.replacement,K1(t.byteLimits).maxTextReplaceOutputBytes);if(!e.ok)return e;a=e.value}return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}},GFe=class extends v0{nodeType=`text-length`;displayName=`Text Length`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Length`,order:0,type:`string`,required:!0}];configSchemaDefinition=X0;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t){let n=new S0(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);return r.ok?(n.setOutput(`text`,String(r.value.length)),{ok:!0,value:n.toOutput()}):r}},KFe=class extends v0{nodeType=`text-upper`;displayName=`Text Uppercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=X0;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t){let n=new S0(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);if(!r.ok)return r;let i=J0(r.value,K1(t.byteLimits).maxTextUpperOutputBytes,`text-upper`);return i.ok?(n.setOutput(`text`,i.value),{ok:!0,value:n.toOutput()}):i}},qFe=class extends v0{nodeType=`text-lower`;displayName=`Text Lowercase`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=X0;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t){let n=new S0(e,t.nodeDefinition.nodeId),r=n.requireInputString(`text`);if(!r.ok)return r;let i=J0(r.value,K1(t.byteLimits).maxTextLowerOutputBytes,`text-lower`);return i.ok?(n.setOutput(`text`,i.value),{ok:!0,value:n.toOutput()}):i}};const JFe=P.object({mode:P.enum([`both`,`start`,`end`]).default(`both`)});var YFe=class extends v0{nodeType=`text-trim`;displayName=`Text Trim`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=JFe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=n.mode===`start`?i.value.trimStart():n.mode===`end`?i.value.trimEnd():i.value.trim();return r.setOutput(`text`,a),{ok:!0,value:r.toOutput()}}};const XFe=P.object({path:P.string().default(``),fallback:P.string().default(``)});var ZFe=class extends v0{nodeType=`json-extract`;displayName=`JSON Extract`;category=`Utility`;defaultInputPort=`json`;defaultOutputPort=`text`;inputs=[{key:`json`,label:`JSON`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Value`,order:0,type:`string`,required:!0}];configSchemaDefinition=XFe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`json`);if(!i.ok)return i;let a;try{a=JSON.parse(i.value)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_JSON_EXTRACT_INVALID_JSON`,`Input is not valid JSON`,{nodeId:t.nodeDefinition.nodeId})}}let o=n.path?n.path.split(`.`):[],s=a;for(let e of o){if(typeof s!=`object`||!s){s=void 0;break}s=s[e]}let c=s===void 0?n.fallback:String(s);return r.setOutput(`text`,c),{ok:!0,value:r.toOutput()}}};const QFe=P.object({operator:P.enum([`non-empty`,`equals`,`contains`,`starts-with`,`ends-with`]).default(`non-empty`),operand:P.string().default(``)});var $Fe=class extends v0{nodeType=`conditional-text`;displayName=`Conditional Text`;category=`Utility`;defaultInputPort=`condition`;defaultOutputPort=`text`;inputs=[{key:`condition`,label:`Condition`,order:0,type:`string`,required:!0},{key:`text_true`,label:`If True`,order:1,type:`string`,required:!0},{key:`text_false`,label:`If False`,order:2,type:`string`,required:!1}];outputs=[{key:`text`,label:`Result`,order:0,type:`string`,required:!0}];configSchemaDefinition=QFe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`condition`);if(!i.ok)return i;let a=r.requireInputString(`text_true`);if(!a.ok)return a;let o=r.getInput(`text_false`),s=i.value,c=n.operand,l;switch(n.operator){case`non-empty`:l=s.trim().length>0;break;case`equals`:l=s===c;break;case`contains`:l=s.includes(c);break;case`starts-with`:l=s.startsWith(c);break;case`ends-with`:l=s.endsWith(c)}let u=l?a.value:typeof o==`string`?o:``;return r.setOutput(`text`,u),{ok:!0,value:r.toOutput()}}};const eIe=P.object({skipEmpty:P.boolean().default(!1)}),tIe=/\S/;function nIe(e,t){if(!t){let t=1;for(let n=0;n<e.length;n++)e[n]===`
2758
2758
  `&&t++;return t}let n=0,r=!1;for(let t=0;t<e.length;t++){let i=e[t];i===`
2759
- `?(r&&n++,r=!1):!r&&tIe.test(i)&&(r=!0)}return r&&n++,n}var rIe=class extends v0{nodeType=`text-count-lines`;displayName=`Text Count Lines`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Line Count`,order:0,type:`string`,required:!0}];configSchemaDefinition=eIe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,String(nIe(i.value,n.skipEmpty))),{ok:!0,value:r.toOutput()}):i}};const iIe=P.object({times:P.number().int().min(0).max(2**53-1).default(2),separator:P.string().default(``)});var aIe=class extends v0{nodeType=`text-repeat`;displayName=`Text Repeat`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Repeated Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=iIe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=K1(t.byteLimits),o=PFe(i.value,n.separator,n.times,a.maxTextRepeatOutputBytes);return o.ok?(r.setOutput(`text`,o.value),{ok:!0,value:r.toOutput()}):o}};const oIe=P.object({start:P.number().int().default(0),end:P.number().int().optional()});var sIe=class extends v0{nodeType=`text-slice`;displayName=`Text Slice`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Sliced Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=oIe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value.slice(n.start,n.end)),{ok:!0,value:r.toOutput()}):i}},cIe=ZPe({createDefaultNodeRegistry:()=>Q0,createDefaultNodeRegistrySync:()=>Z0});function Z0(){return[new oFe,new cFe,new dFe,new mFe,new gFe,new vFe,new bFe,new SFe,new jFe,new LFe,new RFe,new BFe,new HFe,new WFe,new GFe,new KFe,new qFe,new YFe,new ZFe,new $Fe,new rIe,new aIe,new sIe]}const lIe=async()=>{try{return(await Promise.resolve().then(()=>gz)).createDefaultMediaProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default media provider definitions. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or inject mediaProviders explicitly. Cause: ${t}`)}},uIe=async()=>{try{return(await Promise.resolve().then(()=>gz)).createDefaultProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default LLM provider set for the llm-text node. A provider SDK package is likely not installed. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or pass createDagFramework({ providers: [...] }) explicitly. Cause: ${t}`)}};async function Q0(e,t=uIe,n={},r=[],i=[]){let a=e??await t(),o=[...Z0(),new iFe(a)],s=n.mediaProviders??await(n.loadMediaDefaults??lIe)(),c=de(s,`gemini-image`),l=de(s,`seedance-video`),u=await Promise.all([...[{modulePath:`@robota-sdk/dag-node-gemini-image-edit`,factories:[e=>new e.GeminiImageEditNodeDefinition({imageProviderDefinition:c}),e=>new e.GeminiImageComposeNodeDefinition({imageProviderDefinition:c})]},{modulePath:`@robota-sdk/dag-node-text-to-image`,factories:[e=>new e.TextToImageNodeDefinition({imageProviderDefinition:c})]},{modulePath:`@robota-sdk/dag-node-seedance-video`,factories:[e=>new e.SeedanceVideoNodeDefinition({videoProviderDefinition:l})]}].map(fIe),dIe(i,r)]);for(let e of u)o.push(...e);return o}async function dIe(e,t){try{return[new(await(import(`./src-DwAfU-9z-CONMoS5Y.js`))).SkillNodeDefinition({skillPort:mde(e,t)})]}catch{return[]}}async function fIe(e){let t=await pIe(e.modulePath);if(!t)return[];let n=[];for(let r of e.factories){let e=mIe(r,t);e&&n.push(e)}return n}async function pIe(e){try{switch(e){case`@robota-sdk/dag-node-gemini-image-edit`:return await import(`./src-B9UMvThT-B2KTGTWN.js`);case`@robota-sdk/dag-node-text-to-image`:return await import(`./src-BzaNFPZx-DElk_FSv.js`);case`@robota-sdk/dag-node-seedance-video`:return await import(`./src-UPsd6jNY-DI_aEmty.js`);default:return}}catch{return}}function mIe(e,t){try{return e(t)}catch{return}}var hIe=class{limit;committed=0;reserved=0;closed=!1;constructor(e){if(this.limit=e,e!==void 0&&(!Number.isFinite(e)||e<=0))throw RangeError(`Root credit limit must be positive and finite`)}close(){this.closed=!0}reserve(e){if(!Number.isFinite(e)||e<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be finite and zero or positive`,{estimatedCredits:e})};if(this.closed||this.limit!==void 0&&e>this.limit-this.committed-this.reserved)return{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds root runCreditLimit`,{estimatedCredits:e,...this.limit===void 0?{}:{runCreditLimit:this.limit}})};this.reserved+=e;let t=!1;return{ok:!0,value:{commit:()=>(t||(t=!0,this.reserved-=e,this.committed+=e),this.committed),release:()=>{t||(t=!0,this.reserved-=e)}}}}};function $0(e){if(e==null)return;if(typeof e!=`object`||Array.isArray(e))throw Error(`Invalid persisted DAG execution lineage`);let t=e,n=t.parentRunId!==void 0,r=!n||typeof t.parentRunId==`string`&&t.parentRunId.length>0;if(typeof t.rootRunId!=`string`||t.rootRunId.length===0||!r||!Number.isSafeInteger(t.depth)||t.depth<0||t.maxDepth!==void 0&&(!Number.isSafeInteger(t.maxDepth)||t.maxDepth<1)||!Array.isArray(t.ancestorCompositeNodeTypes)||!t.ancestorCompositeNodeTypes.every(e=>typeof e==`string`&&e.length>0))throw Error(`Invalid persisted DAG execution lineage`);let i=t.depth,a=t.ancestorCompositeNodeTypes.length;if(!(i===0?!n&&a===0:n&&a===i))throw Error(`Invalid persisted DAG execution lineage`);return{rootRunId:t.rootRunId,...n?{parentRunId:t.parentRunId}:{},depth:i,...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},ancestorCompositeNodeTypes:[...t.ancestorCompositeNodeTypes]}}const e2={STARTED:`execution.started`,COMPLETED:`execution.completed`,FAILED:`execution.failed`},t2={STARTED:`task.started`,COMPLETED:`task.completed`,FAILED:`task.failed`};function n2(e){let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,error:Q(`DAG_VALIDATION_INVALID_LOGICAL_DATE`,`logicalDate must be a valid ISO-8601 datetime string`,{logicalDate:e})}:{ok:!0,value:new Date(t).toISOString()}}var gIe=class{clock;constructor(e){this.clock=e}resolve(e,t){let n=this.clock.nowIso();if(e===`scheduled`){if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_MISSING_LOGICAL_DATE`,`scheduled trigger requires logicalDate`,{trigger:e})};let r=n2(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}if(!t)return{ok:!0,value:{trigger:e,logicalDate:n,requestedAt:n}};let r=n2(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}},_Ie=class{assertWithinBudget(e,t,n){if(t<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be zero or positive`,{nextEstimatedCredits:t})};let r=e+t;return typeof n==`number`&&r>n?{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds runCreditLimit`,{nextTotalCredits:r,runCreditLimit:n})}:{ok:!0,value:r}}},vIe=class{lifecycleFactory;costPolicyEvaluator;constructor(e,t){this.lifecycleFactory=e,this.costPolicyEvaluator=t}async runNode(e){let t=()=>({ok:!1,error:B1(e.context.taskRunId)});if(e.context.signal?.aborted)return t();let n=this.lifecycleFactory.create(e.context.nodeDefinition.nodeType);if(!n.ok)return n;let r=await n.value.initialize(e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return r;let i=await n.value.validateInput(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let a=await n.value.estimateCost(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!a.ok)return await n.value.dispose(e.context),a;let o=this.costPolicyEvaluator.assertWithinBudget(e.context.currentTotalCredits,a.value.estimatedCredits,e.context.runCreditLimit);if(!o.ok)return await n.value.dispose(e.context),o;if(e.context.reserveCredits){let r=await e.context.reserveCredits(a.value.estimatedCredits);if(!r.ok)return await n.value.dispose(e.context),r;if(e.context.signal?.aborted)return await n.value.dispose(e.context),t()}let s=e.context.rootCreditBudget?.reserve(a.value.estimatedCredits);if(s&&!s.ok)return await n.value.dispose(e.context),s;try{let r=await n.value.execute(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return await n.value.dispose(e.context),r;let i=await n.value.validateOutput(r.value,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let c=await n.value.dispose(e.context);return e.context.signal?.aborted?t():c.ok?(s?.value.commit(),{ok:!0,value:{output:r.value,estimatedCredits:a.value.estimatedCredits,totalCredits:o.value}}):{ok:!1,error:z1(`DAG_TASK_EXECUTION_DISPOSE_FAILED`,`Node dispose step failed after execution`,!1,{nodeType:e.context.nodeDefinition.nodeType,taskRunId:e.context.taskRunId})}}finally{s?.ok&&s.value.release()}}},yIe=class{create(e){return{ok:!1,error:Q(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},r2=class{nodeManifestRegistry;lineage;lifecycleFactory;runner;constructor(e,t,n){this.nodeManifestRegistry=e,this.lineage=n,this.lifecycleFactory=t??new yIe,this.runner=new vIe(this.lifecycleFactory,new _Ie)}async execute(e){if(!e.nodeDefinition)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_DEFINITION_MISSING`,`Task execution requires nodeDefinition in execution input`,{nodeId:e.nodeId})};let t=this.nodeManifestRegistry.getManifest(e.nodeDefinition.nodeType);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_MANIFEST_NOT_FOUND`,`Node manifest is not registered for nodeType`,{nodeType:e.nodeDefinition.nodeType})};let n=await this.runner.runNode({input:e.input,context:{executionRoot:e.executionRoot,regexReplaceOperation:e.regexReplaceOperation,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,reserveCredits:e.reserveCredits,...e.byteLimits===void 0?{}:{byteLimits:e.byteLimits},...e.signal===void 0?{}:{signal:e.signal},dagId:e.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeDefinition:e.nodeDefinition,nodeManifest:t,attempt:e.attempt,executionPath:e.executionPath,lineage:e.lineage??this.lineage??{rootRunId:e.dagRunId,depth:0,ancestorCompositeNodeTypes:[]},runCreditLimit:e.costPolicy?.runCreditLimit,currentTotalCredits:e.currentTotalCredits??0,...e.runtimeBaseUrl===void 0?{}:{runtimeBaseUrl:e.runtimeBaseUrl}}});return n.ok?{ok:!0,output:n.value.output,estimatedCredits:n.value.estimatedCredits,totalCredits:n.value.totalCredits}:n}};const i2={root:`.workflows`,workflowExt:`.json`};var bIe=class{manifestByType=new Map;constructor(e){for(let t of e)this.manifestByType.set(t.nodeType,t)}getManifest(e){return this.manifestByType.get(e)}listManifests(){return[...this.manifestByType.values()]}};function xIe(e){let t=[],n=EIe(e,``,t);return n!==void 0&&t.length===0?{ok:!0,value:n}:{ok:!1,error:t}}function a2(e,t,n){if(!Array.isArray(e)||e.length!==2)return Z1(n,t,`expected a [number, number] pair`);let r=t0(e[0],Q1(t,0),n),i=t0(e[1],Q1(t,1),n);return r===void 0||i===void 0?void 0:[r,i]}function SIe(e,t,n){if(!Array.isArray(e)||e.length!==6)return Z1(n,t,`expected a 6-tuple [linkId, srcId, srcSlot, tgtId, tgtSlot, type]`);let r=[0,1,2,3,4].map(r=>t0(e[r],Q1(t,r),n)),i=e0(e[5],Q1(t,5),n);if(r.some(e=>e===void 0)||i===void 0)return;let[a,o,s,c,l]=r;return[a,o,s,c,l,i]}function CIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e0(r.name,Q1(t,`name`),n),a=e0(r.type,Q1(t,`type`),n),o=r.link,s=o===null?null:t0(o,Q1(t,`link`),n);return i===void 0||a===void 0||s===void 0?void 0:{name:i,type:a,link:s}}function wIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e0(r.name,Q1(t,`name`),n),a=e0(r.type,Q1(t,`type`),n),o=a0(r.links,Q1(t,`links`),n,t0),s=i0(r.slot_index,Q1(t,`slot_index`),n,t0);if(i===void 0||a===void 0||o===void 0)return;let c={name:i,type:a,links:o};return s!==void 0&&(c.slot_index=s),c}function TIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e=>Q1(t,e),a=t0(r.id,i(`id`),n),o=e0(r.type,i(`type`),n),s=a2(r.pos,i(`pos`),n),c=i0(r.size,i(`size`),n,a2),l=i0(r.flags,i(`flags`),n,$1),u=i0(r.order,i(`order`),n,t0),d=i0(r.mode,i(`mode`),n,t0),f=i0(r.inputs,i(`inputs`),n,(e,t,n)=>a0(e,t,n,CIe)),p=i0(r.outputs,i(`outputs`),n,(e,t,n)=>a0(e,t,n,wIe)),m=i0(r.properties,i(`properties`),n,$1),h=i0(r.widgets_values,i(`widgets_values`),n,(e,t,n)=>Array.isArray(e)?e:Z1(n,t,`expected an array`));if(a===void 0||o===void 0||s===void 0)return;let g={id:a,type:o,pos:s};return c!==void 0&&(g.size=c),l!==void 0&&(g.flags=l),u!==void 0&&(g.order=u),d!==void 0&&(g.mode=d),f!==void 0&&(g.inputs=f),p!==void 0&&(g.outputs=p),m!==void 0&&(g.properties=m),h!==void 0&&(g.widgets_values=h),g}function EIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e=>Q1(t,e);if(`dagId`in r)return Z1(n,i(`dagId`),`a workflow file carries no dagId — that is a definition file`);let a=t0(r.last_node_id,i(`last_node_id`),n),o=t0(r.last_link_id,i(`last_link_id`),n),s=a0(r.nodes,i(`nodes`),n,TIe),c=a0(r.links,i(`links`),n,SIe),l=t0(r.version,i(`version`),n),u=i0(r.groups,i(`groups`),n,(e,t,n)=>Array.isArray(e)?e:Z1(n,t,`expected an array`)),d=i0(r.config,i(`config`),n,$1),f=i0(r.extra,i(`extra`),n,$1);if(a===void 0||o===void 0||s===void 0||c===void 0||l===void 0)return;let p={last_node_id:a,last_link_id:o,nodes:s,links:c,version:l};return u!==void 0&&(p.groups=u),d!==void 0&&(p.config=d),f!==void 0&&(p.extra=f),p}function DIe(e){return`parallel`in e}function o2(e,t){return e.id??`${e.nodeType}-${t}`}function s2(e,t){return e.find(e=>e.nodeType===t)}function c2(e,t){let n=t.map(e=>e.nodeType),r={action:`replace_node_type`,suggestion:n[0],options:n};return Q(`UNKNOWN_NODE_TYPE`,`Node type "${e}" is not registered`,{requestedType:e},r)}function OIe(e,t){let n=[],r=[],i=[],a=[],o=0;for(let s of e.pipeline)if(DIe(s)){let e=[];for(let c of s.parallel){let l=o2(c,o);o+=1;let u=s2(t,c.nodeType);if(!u)return{ok:!1,error:c2(c.nodeType,t),warnings:n};let d=a.map(e=>e.nodeId);r.push({nodeId:l,nodeType:c.nodeType,dependsOn:d,config:c.config??{}});for(let e of a){let t=c.toPort??u.defaultInputPort;if(!t){n.push({message:`Node "${l}" (${c.nodeType}) has no defaultInputPort; edge from "${e.nodeId}" requires explicit toPort`});continue}i.push({from:e.nodeId,to:l,bindings:[{outputKey:e.portKey,inputKey:t}]})}let f=s.fromPort??c.fromPort??u.defaultOutputPort;f?e.push({nodeId:l,portKey:f}):n.push({message:`Node "${l}" (${c.nodeType}) has no defaultOutputPort; downstream connections require explicit fromPort`})}a=e}else{let e=o2(s,o);o+=1;let c=s2(t,s.nodeType);if(!c)return{ok:!1,error:c2(s.nodeType,t),warnings:n};let l=a.map(e=>e.nodeId);r.push({nodeId:e,nodeType:s.nodeType,dependsOn:l,config:s.config??{}});for(let t of a){let r=s.toPort??c.defaultInputPort;if(!r){n.push({message:`Node "${e}" (${s.nodeType}) has no defaultInputPort; edge from "${t.nodeId}" requires explicit toPort`});continue}i.push({from:t.nodeId,to:e,bindings:[{outputKey:t.portKey,inputKey:r}]})}let u=s.fromPort??c.defaultOutputPort;a=u?[{nodeId:e,portKey:u}]:[]}return r.length===0?{ok:!1,error:Q(`EMPTY_PIPELINE`,`pipeline must contain at least one node`,void 0,{action:`add_node`,suggestion:`Add at least one node spec to the pipeline array`}),warnings:n}:{ok:!0,definition:{dagId:e.dagId??`dag-build-result`,version:1,status:`draft`,nodes:r,edges:i},warnings:n,nodeCount:r.length,edgeCount:i.length}}function kIe(e){return(e.startsWith(`ConversationAgent`)?e.slice(17):e).replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`).replace(/^-/,``)}function AIe(e,t){let n=new Map;for(let t of e.links)n.set(t[0],t);let r=t?.nodes??{},i=e.nodes.map(e=>{let t=r[String(e.id)],n={nodeId:t?.nodeId??`node-${e.id}`,nodeType:kIe(e.type),dependsOn:[],config:e.properties?.agent_config??{},position:e.pos[0]!==0||e.pos[1]!==0?{x:e.pos[0],y:e.pos[1]}:void 0};return t?.retryPolicy&&(n.retryPolicy=t.retryPolicy),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),t?.costPolicy&&(n.costPolicy=t.costPolicy),n}),a=new Map;e.nodes.forEach((e,t)=>{a.set(e.id,i[t])});let o=new Map,s=[],c=new Map;for(let t of e.links){let[,n,,r]=t,i=a.get(n),l=a.get(r);if(!i||!l)continue;let u=e.nodes.find(e=>e.id===n),d=e.nodes.find(e=>e.id===r),f=t[2],p=t[4],m=u?.outputs?.[f]?.name??`out${f}`,h=d?.inputs?.[p]?.name??`in${p}`,g=JSON.stringify([i.nodeId,l.nodeId]),_=o.get(g);_||(_=[],o.set(g,_),s.push({from:i.nodeId,to:l.nodeId,bindings:_})),_.push({outputKey:m,inputKey:h}),c.has(l.nodeId)||c.set(l.nodeId,new Set),c.get(l.nodeId).add(i.nodeId)}for(let e of i){let t=c.get(e.nodeId);t&&(e.dependsOn=[...t])}return{dagId:t?.dagId??`unknown`,version:t?.version??1,status:t?.status??`draft`,nodes:i,edges:s,...t?.costPolicy?{costPolicy:t.costPolicy}:{},...t?.inputSchema?{inputSchema:t.inputSchema}:{},...t?.outputSchema?{outputSchema:t.outputSchema}:{}}}const jIe={absentStatus:`draft`,absentEdgesAsEmpty:!0};function MIe(e){if(typeof e!=`object`||!e||Array.isArray(e))return`unrecognised`;let t=e;return`dagId`in t?`definition`:`links`in t||`last_node_id`in t?`workflow-file`:`unrecognised`}function NIe(e,t){let n=MIe(e);if(n===`unrecognised`)return{ok:!1,error:{format:n,issues:[{path:``,message:`expected either a workflow file (nodes + links + version) or a definition (dagId + nodes)`}]}};if(n===`workflow-file`){let r=xIe(e);return r.ok?PIe(AIe(r.value,t),n):{ok:!1,error:{format:n,issues:r.error}}}let r=l0(e,jIe);return r.ok?r:{ok:!1,error:{format:n,issues:r.error}}}function PIe(e,t){let n=l0(e);return n.ok?n:{ok:!1,error:{format:t,issues:n.error}}}function FIe(e){return e.format===`unrecognised`?`Not a DAG file: ${c0(e.issues)}.`:`Malformed ${e.format===`workflow-file`?`workflow file`:`DAG definition`}: ${c0(e.issues)}`}var IIe=class extends Error{failure;constructor(e){super(FIe(e)),this.name=`DagFileDecodeError`,this.failure=e}};function l2(e,t){let n=NIe(e,t);if(n.ok)return n.value;throw new IIe(n.error)}function LIe(e,t,n,r){for(let[i,a]of e.entries())if(a.taskRunId===t){e.set(i,{...a,leaseOwner:n,leaseUntil:r});return}}function RIe(e,t){return[...e.values()].filter(e=>e.status===`running`&&(e.leaseUntil===void 0||e.leaseUntil<=t))}function u2(e,t){return`${e}:${t}`}var zIe=class{definitions=new Map;latestPublishedVersionByDagId=new Map;dagRuns=new Map;taskRuns=new Map;async commitExecution(e,t){let n=[...this.taskRuns.values()].filter(t=>t.dagRunId===e),r=IPe(this.dagRuns.get(e),n,t);return r.dagRun&&this.dagRuns.set(e,r.dagRun),r.taskRun&&this.taskRuns.set(u2(e,r.taskRun.taskRunId),r.taskRun),r.result}async saveDefinition(e){let t=`${e.dagId}:${e.version}`;if(this.definitions.set(t,e),e.status===`published`){let t=this.latestPublishedVersionByDagId.get(e.dagId)??0;e.version>t&&this.latestPublishedVersionByDagId.set(e.dagId,e.version)}}async getDefinition(e,t){let n=`${e}:${t}`;return this.definitions.get(n)}async listDefinitions(){return[...this.definitions.values()].sort((e,t)=>e.dagId.localeCompare(t.dagId)||e.version-t.version)}async listDefinitionsByDagId(e){return[...this.definitions.values()].filter(t=>t.dagId===e).sort((e,t)=>e.version-t.version)}async getLatestPublishedDefinition(e){let t=this.latestPublishedVersionByDagId.get(e);if(t)return this.definitions.get(`${e}:${t}`)}async deleteDefinition(e,t){this.definitions.delete(`${e}:${t}`);let n=[...this.definitions.values()].filter(t=>t.dagId===e&&t.status===`published`).sort((e,t)=>e.version-t.version);if(n.length===0){this.latestPublishedVersionByDagId.delete(e);return}this.latestPublishedVersionByDagId.set(e,n[n.length-1].version)}async createDagRun(e){this.dagRuns.set(e.dagRunId,e)}async getDagRun(e){return this.dagRuns.get(e)}async listDagRuns(){return[...this.dagRuns.values()].sort((e,t)=>e.dagRunId.localeCompare(t.dagRunId))}async getDagRunByRunKey(e){for(let t of this.dagRuns.values())if(t.runKey===e)return t}async updateDagRunStatus(e,t,n){let r=this.dagRuns.get(e);if(!r)return;let i={...r,status:t,endedAt:n};this.dagRuns.set(e,i)}async deleteDagRun(e){this.dagRuns.delete(e)}async createTaskRun(e){let t=u2(e.dagRunId,e.taskRunId);this.taskRuns.set(t,e)}async getTaskRun(e){for(let t of this.taskRuns.values())if(t.taskRunId===e)return t}async listTaskRunsByDagRunId(e){let t=[];for(let n of this.taskRuns.values())n.dagRunId===e&&t.push(n);return t}async deleteTaskRunsByDagRunId(e){for(let[t,n]of this.taskRuns.entries())n.dagRunId===e&&this.taskRuns.delete(t)}async updateTaskRunStatus(e,t,n){for(let[r,i]of this.taskRuns.entries()){if(i.taskRunId!==e)continue;let a={...i,status:t,...[`failed`,`cancelled`,`queued`].includes(t)?{reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0}:{},errorCode:n?.code,errorMessage:n?.message};this.taskRuns.set(r,a);return}}async setTaskRunLease(e,t,n){LIe(this.taskRuns,e,t,n)}async listStaleRunningTaskRuns(e){return RIe(this.taskRuns,e)}async saveTaskRunSnapshots(e,t,n,r,i){for(let[a,o]of this.taskRuns.entries()){if(o.taskRunId!==e)continue;let s={...o,inputSnapshot:typeof t==`string`?t:o.inputSnapshot,outputSnapshot:typeof n==`string`?n:o.outputSnapshot,estimatedCredits:typeof r==`number`?r:o.estimatedCredits,totalCredits:typeof i==`number`?i:o.totalCredits};this.taskRuns.set(a,s);return}}async incrementTaskAttempt(e){for(let[t,n]of this.taskRuns.entries()){if(n.taskRunId!==e)continue;let r={...n,attempt:n.attempt+1,reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0};this.taskRuns.set(t,r);return}}},d2=class{pendingQueue=[];inFlight=new Map;waiters=[];async enqueue(e){this.pendingQueue.push(e),this.notifyNextWaiter()}async dequeue(e,t,n=0){let r=this.tryDequeue(e,t);return r||n<=0?r:(await this.waitForMessage(n),this.tryDequeue(e,t))}async ack(e){this.inFlight.delete(e)}async nack(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.pendingQueue.unshift(t.message),this.notifyNextWaiter())}tryDequeue(e,t){this.requeueExpiredMessages();let n=this.pendingQueue.shift();if(!n)return;let r=Date.now();return this.inFlight.set(n.messageId,{message:n,ownerId:e,visibleAtEpochMs:r+t}),n}requeueExpiredMessages(){let e=Date.now();for(let[t,n]of this.inFlight.entries())n.visibleAtEpochMs>e||(this.inFlight.delete(t),this.pendingQueue.push(n.message))}async waitForMessage(e){return new Promise(t=>{let n={resolve:()=>{clearTimeout(n.timeout),this.removeWaiter(n),t()},timeout:setTimeout(()=>{n.resolve()},e)};this.waiters.push(n)})}notifyNextWaiter(){this.waiters.shift()?.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t>=0&&this.waiters.splice(t,1)}},BIe=class{records=new Map;async acquire(e,t,n){let r=new Date().toISOString(),i=Date.now(),a=this.records.get(e);if(a&&Date.parse(a.leaseUntil)>i)return;let o={leaseKey:e,ownerId:t,acquiredAt:r,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,o),o}async release(e,t){let n=this.records.get(e);!n||n.ownerId!==t||this.records.delete(e)}async get(e){return this.records.get(e)}},VIe=class{nowIso(){return new Date().toISOString()}nowEpochMs(){return Date.now()}},HIe=class{listeners=new Set;logger;constructor(e){this.logger=e}publish(e){let t=[];for(let n of[...this.listeners])try{n(e)}catch(n){t.push(n),this.logger&&this.logger.error(`RunProgressEventBus listener threw an error`,{eventType:e.eventType,error:n instanceof Error?n.message:String(n)})}if(t.length>0&&!this.logger)throw t[0]instanceof Error?t[0]:Error(String(t[0]))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function UIe(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_INVALID`,`Payload must be a JSON object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_PARSE_FAILED`,`Failed to parse payload JSON`)}}}function WIe(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse definition snapshot JSON`)}}return u0(t,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`Definition snapshot must be a valid DAG definition object`)}async function GIe(e,t,n,r,i){let{dagRunId:a,definition:o,input:s}=e,c=o.nodes.filter(e=>e.dependsOn.length===0);if(c.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_NO_ENTRY_NODE`,`DAG must include at least one entry node (dependsOn = [])`,{dagId:o.dagId,version:o.version})};let l=Y1.transition(`created`,`QUEUE`);if(!l.ok)return l;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`created`,event:`QUEUE`})).applied)return{ok:!0,value:{taskRunIds:[]}};let u=Y1.transition(`queued`,`START`);if(!u.ok)return u;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`queued`,event:`START`})).applied)return{ok:!0,value:{taskRunIds:[]}};i?.publish({dagRunId:a,eventType:e2.STARTED,occurredAt:r.nowIso(),dagId:o.dagId,version:o.version});let d=[],f=[];for(let e of c){let n=`${a}:${e.nodeId}:attempt:1`;(await t.commitExecution(a,{kind:`admit`,dependsOn:[],taskRun:{taskRunId:n,dagRunId:a,nodeId:e.nodeId,status:`queued`,attempt:1}})).applied&&(d.push(n),f.push({messageId:`${n}:message`,dagRunId:a,taskRunId:n,nodeId:e.nodeId,attempt:1,executionPath:[`dagId:${o.dagId}`,`dagRunId:${a}`,`nodeId:${e.nodeId}`,`taskRunId:${n}`,`attempt:1`],payload:s,createdAt:r.nowIso()}))}for(let e of f)try{await n.enqueue(e)}catch(n){return KIe(a,e.taskRunId,e.nodeId,d,n,t,r,i)}return{ok:!0,value:{taskRunIds:d}}}async function KIe(e,t,n,r,i,a,o,s){let c=R1(`DAG_DISPATCH_ENQUEUE_FAILED`,`Failed to enqueue entry task`,{dagRunId:e,taskRunId:t,nodeId:n,errorMessage:i instanceof Error&&i.message.trim().length>0?i.message:`Unknown error`});Y1.transition(`running`,`COMPLETE_FAILURE`).ok&&(await a.commitExecution(e,{kind:`transition-run`,expectedStatus:`running`,event:`COMPLETE_FAILURE`,endedAt:o.nowIso()})).applied&&s?.publish({dagRunId:e,eventType:e2.FAILED,occurredAt:o.nowIso(),error:c});for(let t of r)await a.commitExecution(e,{kind:`cancel-task`,taskRunId:t,error:c});return{ok:!1,error:c}}function qIe(e,t){return e===void 0||t===void 0?e===t:e.rootRunId===t.rootRunId&&e.parentRunId===t.parentRunId&&e.depth===t.depth&&e.maxDepth===t.maxDepth&&e.ancestorCompositeNodeTypes.length===t.ancestorCompositeNodeTypes.length&&e.ancestorCompositeNodeTypes.every((e,n)=>e===t.ancestorCompositeNodeTypes[n])}var JIe=class{storage;queue;clock;runProgressEventReporter;snapshotBudget;timeSemanticsService;constructor(e,t,n,r,i){this.storage=e,this.queue=t,this.clock=n,this.runProgressEventReporter=r,this.snapshotBudget=i,this.timeSemanticsService=new gIe(n)}async createRun(e){let t=e.version?await this.storage.getDefinition(e.dagId,e.version):await this.storage.getLatestPublishedDefinition(e.dagId);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_FOUND`,`Published DAG definition was not found`,{dagId:e.dagId,hasVersion:!!e.version})};if(t.status!==`published`)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_PUBLISHED`,`Only published definitions can be executed`,{dagId:t.dagId,version:t.version,status:t.status})};let n=this.timeSemanticsService.resolve(e.trigger,e.logicalDate);if(!n.ok)return n;let r;try{r=$0(e.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Composite child run lineage is invalid`,{dagId:t.dagId})}}let i=e.rerunKey?`${t.dagId}:${n.value.logicalDate}:rerun:${e.rerunKey}`:`${t.dagId}:${n.value.logicalDate}`,a=await this.storage.getDagRunByRunKey(i);if(a){let e;try{e=$0(a.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Existing run for this run key has invalid persisted lineage`,{dagId:t.dagId,runKey:i})}}return qIe(e,r)?{ok:!0,value:{dagRunId:a.dagRunId,dagId:a.dagId,version:a.version,logicalDate:a.logicalDate,status:a.status}}:{ok:!1,error:Q(`DAG_VALIDATION_RUN_KEY_LINEAGE_MISMATCH`,`An existing run for this run key has different composite lineage`,{dagId:t.dagId,runKey:i,existingDagRunId:a.dagRunId})}}let o=this.generateDagRunId(t.dagId,n.value.logicalDate,e.rerunKey);try{let a=(a,s)=>this.storage.createDagRun({dagRunId:o,dagId:t.dagId,version:t.version,status:`created`,definitionSnapshot:a,inputSnapshot:s,runKey:i,logicalDate:n.value.logicalDate,trigger:e.trigger,...r===void 0?{}:{lineage:r},startedAt:this.clock.nowIso()});if(this.snapshotBudget){let n=await this.snapshotBudget.admitRun(t,e.input,a);if(!n.ok)return n}else await a(JSON.stringify(t),JSON.stringify(e.input))}catch(e){return this.snapshotBudget?{ok:!1,error:z1(`DAG_RUN_SNAPSHOT_PERSISTENCE_UNCERTAIN`,`Run snapshot persistence outcome is uncertain; root snapshot admission is closed`,!1)}:{ok:!1,error:R1(`DAG_DISPATCH_DAG_RUN_CREATE_FAILED`,`Failed to create DagRun`,{dagId:t.dagId,version:t.version,runKey:i,errorMessage:this.resolveErrorMessage(e instanceof Error?e:void 0)})}}return{ok:!0,value:{dagRunId:o,dagId:t.dagId,version:t.version,logicalDate:n.value.logicalDate,status:`created`}}}async startCreatedRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};if(t.status!==`created`){let n=await this.storage.listTaskRunsByDagRunId(e);return{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}if(typeof t.definitionSnapshot!=`string`||t.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:e})};let n=WIe(t.definitionSnapshot);if(!n.ok)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot is invalid`,{dagRunId:e})};let r=UIe(t.inputSnapshot??`{}`);if(!r.ok)return{ok:!1,error:Q(`DAG_VALIDATION_RUN_INPUT_SNAPSHOT_INVALID`,`DagRun input snapshot is invalid`,{dagRunId:e})};let i=await GIe({dagRunId:e,definition:n.value,input:r.value},this.storage,this.queue,this.clock,this.runProgressEventReporter);return i.ok?{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:i.value.taskRunIds}}:i}async startRun(e){let t=await this.createRun(e);if(!t.ok)return t;if(t.value.status===`created`)return this.startCreatedRun(t.value.dagRunId);let n=await this.storage.listTaskRunsByDagRunId(t.value.dagRunId);return{ok:!0,value:{dagRunId:t.value.dagRunId,dagId:t.value.dagId,version:t.value.version,logicalDate:t.value.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}generateDagRunId(e,t,n){let r=Date.parse(t);return n?`${e}:run:${r}:rerun:${n}`:`${e}:run:${r}`}resolveErrorMessage(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}},YIe=class{storage;constructor(e){this.storage=e}async getRun(e){let t=await this.storage.getDagRun(e);return t?{ok:!0,value:{dagRun:t,taskRuns:await this.storage.listTaskRunsByDagRunId(e)}}:{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}},XIe=class{storage;clock;notifier;constructor(e,t,n){this.storage=e,this.clock=t,this.notifier=n}async cancelRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};let n=Y1.transition(t.status,`CANCEL`);if(!n.ok)return n;let r=await this.storage.commitExecution(e,{kind:`transition-run`,expectedStatus:t.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(!r.applied){if(r.runStatus===`cancelled`)return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}};if(r.runStatus!==void 0){let t=Y1.transition(r.runStatus,`CANCEL`);return t.ok?this.cancelRun(e):t}return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}}}notify(e){try{this.notifier?.notifyRunCancelled(e)}catch{}}};async function f2(e,t,n,r){let i=await t.commitExecution(e,{kind:`finalize`,endedAt:n.nowIso()});if(i.error)return{ok:!1,error:i.error};if(i.runStatus===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found while finalizing run status`,{dagRunId:e})};if(!i.applied)return{ok:!0,value:void 0};let a=i.runStatus===`failed`,o=await t.listTaskRunsByDagRunId(e);return a?ZIe(e,o,n,r):r?.publish({dagRunId:e,eventType:e2.COMPLETED,occurredAt:n.nowIso()}),{ok:!0,value:void 0}}function ZIe(e,t,n,r){let i=t.find(e=>e.status===`failed`),a=typeof i?.errorCode==`string`&&typeof i.errorMessage==`string`?z1(i.errorCode,i.errorMessage,!1,{dagRunId:e,taskRunId:i.taskRunId,nodeId:i.nodeId}):z1(`DAG_TASK_EXECUTION_FAILED`,`Run completed with failure.`,!1,{dagRunId:e});r?.publish({dagRunId:e,eventType:e2.FAILED,occurredAt:n.nowIso(),error:a})}async function p2(e,t,n,r,i){await e.updateTaskRunStatus(n.taskRunId,r,i),await e.setTaskRunLease(n.taskRunId,void 0,void 0),await f2(n.dagRunId,e,t)}async function QIe(e,t){let n=X1.transition(t.status,`CANCEL`);return n.ok?(await e.updateTaskRunStatus(t.taskRunId,n.value.nextStatus,{code:`DAG_TASK_EXECUTION_ORPHANED`,category:`task_execution`,message:`Task's DAG run ${t.dagRunId} no longer exists; the task cannot be run or finalized`,retryable:!1,context:{taskRunId:t.taskRunId,dagRunId:t.dagRunId}}),await e.setTaskRunLease(t.taskRunId,void 0,void 0),{ok:!0,value:void 0}):n}async function $Ie(e,t,n,r,i){let a=await e.listStaleRunningTaskRuns(n.nowIso()),o={requeued:[],abandoned:[],skipped:[],failed:[],orphaned:[]};for(let s of a){let a=`taskRun:${s.taskRunId}`;if(!await r.acquire(a,i.workerId,i.leaseDurationMs)){o.skipped.push(s.taskRunId);continue}try{let r=await e.getTaskRun(s.taskRunId);if(r===void 0||r.status!==`running`||iLe(r,n.nowIso())){o.skipped.push(s.taskRunId);continue}await eLe(e,t,n,r,i.maxAttempts,o)}catch(e){o.failed.push({taskRunId:s.taskRunId,error:e})}finally{await r.release(a,i.workerId)}}return o}async function eLe(e,t,n,r,i,a){{let o=X1.transition(r.status,`RECLAIM`);if(!o.ok){a.skipped.push(r.taskRunId);return}let s=await e.getDagRun(r.dagRunId);if(s===void 0){if(!(await QIe(e,r)).ok){a.skipped.push(r.taskRunId);return}a.orphaned.push(r.taskRunId);return}if(tLe.has(s.status)){let t=X1.transition(r.status,`CANCEL`);if(!t.ok){a.skipped.push(r.taskRunId);return}await p2(e,n,r,t.value.nextStatus),a.abandoned.push(r.taskRunId);return}if(r.attempt>=i){let t=X1.transition(r.status,`COMPLETE_FAILURE`);if(!t.ok){a.skipped.push(r.taskRunId);return}await p2(e,n,r,t.value.nextStatus,{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${r.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:r.taskRunId,attempt:r.attempt,maxAttempts:i}}),a.abandoned.push(r.taskRunId);return}let c=r.attempt+1;await e.incrementTaskAttempt(r.taskRunId),await t.enqueue(nLe(r,c,n.nowIso())),await e.updateTaskRunStatus(r.taskRunId,o.value.nextStatus),await e.setTaskRunLease(r.taskRunId,void 0,void 0),a.requeued.push(r.taskRunId)}}const tLe=new Set([`success`,`failed`,`cancelled`]);function nLe(e,t,n){return{payload:rLe(e.inputSnapshot),messageId:`${e.taskRunId}:reclaim:${t}`,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:t,executionPath:[`dagRunId:${e.dagRunId}`,`nodeId:${e.nodeId}`,`taskRunId:${e.taskRunId}`,`attempt:${t}`,`reclaimed:true`],createdAt:n}}function rLe(e){if(e===void 0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function iLe(e,t){return e.leaseUntil!==void 0&&e.leaseUntil>t}var aLe=class{clock;lease;options;lastSweepAtMs=0;sweeping=!1;constructor(e,t,n){this.clock=e,this.lease=t,this.options=n}async sweepIfDue(e,t){let n=this.clock.nowEpochMs();if(!(this.sweeping||n-this.lastSweepAtMs<this.options.leaseDurationMs)){this.sweeping=!0;try{let n=(await $Ie(e,t,this.clock,this.lease,this.options)).failed[0];if(n===void 0)return;throw n.error}catch(e){return{code:`DAG_TASK_SWEEP_FAILED`,category:`task_execution`,message:`Stale-task sweep failed: ${e instanceof Error?e.message:String(e)}`,retryable:!0,context:{workerId:this.options.workerId}}}finally{this.lastSweepAtMs=this.clock.nowEpochMs(),this.sweeping=!1}}}};function oLe(e,t){let n=e.map(e=>e.startsWith(`attempt:`)?`attempt:${t}`:e);return n.some(e=>e.startsWith(`attempt:`))||n.push(`attempt:${t}`),n}function m2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function h2(e,t,n,r,i,a,o,s){if(r.deadLetterEnabled){let t=await cLe(e,n,r,o);if(!t.ok)return g2(a,e.messageId,t.error)}let c=await f2(e.dagRunId,i,o,s);return c.ok?_2(a,e.messageId,t,!1):g2(a,e.messageId,c.error)}async function sLe(e,t,n,r){let i=e.attempt+1,a={...e,messageId:`${e.taskRunId}:message:${i}`,attempt:i,executionPath:oLe(e.executionPath,i),createdAt:r.nowIso()};try{await n.enqueue(a)}catch(r){return g2(n,e.messageId,R1(`DAG_DISPATCH_ENQUEUE_RETRY_FAILED`,`Failed to enqueue retry message`,{taskRunId:t,attempt:i,errorMessage:m2(r)}))}return _2(n,e.messageId,t,!0)}async function cLe(e,t,n,r){if(!n.deadLetterQueue)return{ok:!1,error:Q(`DAG_VALIDATION_DEAD_LETTER_QUEUE_NOT_CONFIGURED`,`deadLetterEnabled requires deadLetterQueue to be configured`,{taskRunId:e.taskRunId})};let i={...e,messageId:`${e.taskRunId}:dlq:${r.nowEpochMs()}`,payload:{...e.payload,dlqReasonCode:t.code,dlqReasonMessage:t.message,dlqSourceMessageId:e.messageId},createdAt:r.nowIso()};try{return await n.deadLetterQueue.enqueue(i),{ok:!0,value:void 0}}catch(t){return{ok:!1,error:R1(`DAG_DISPATCH_DEAD_LETTER_ENQUEUE_FAILED`,`Failed to enqueue dead letter message`,{taskRunId:e.taskRunId,originalMessageId:e.messageId,errorMessage:m2(t)})}}}async function g2(e,t,n){return await e.ack(t),{ok:!1,error:n}}async function _2(e,t,n,r){return await e.ack(t),{ok:!0,value:{processed:!0,taskRunId:n,retried:r}}}function lLe(e){if(e.status!==`running`)return{ok:!0,value:e.status};let t=X1.transition(e.status,`RECLAIM`);return t.ok?{ok:!0,value:t.value.nextStatus}:t}function v2(e,t){return Math.max(e,t)+3e4}function uLe(e,t,n){return new Date(e.nowEpochMs()+v2(t,n)).toISOString()}async function dLe(e){let{storage:t,clock:n,message:r,taskRun:i}=e,a=i.status===`running`,o=lLe(i);if(!o.ok)return o;if(a){if(i.attempt>=e.options.maxAttempts)return{ok:!1,error:{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${i.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:i.taskRunId,attempt:i.attempt,maxAttempts:e.options.maxAttempts}}};await t.incrementTaskAttempt(i.taskRunId)}let s=a?i.attempt+1:i.attempt,c=X1.transition(o.value,`START`);return c.ok?(await t.setTaskRunLease(i.taskRunId,e.options.workerId,uLe(n,e.timeoutMs,e.options.leaseDurationMs)),await t.updateTaskRunStatus(i.taskRunId,c.value.nextStatus),e.reporter?.publish({dagRunId:r.dagRunId,eventType:t2.STARTED,occurredAt:n.nowIso(),taskRunId:i.taskRunId,nodeId:r.nodeId,input:r.payload}),{ok:!0,value:s}):c}async function fLe(e,t,n,r,i,a){let o=`taskRun:${t}`;if(!await e.acquire(o,n,r))return a();try{return await i()}finally{await e.release(o,n)}}async function pLe(e,t){let{message:n,taskRun:r,storage:i,queue:a,clock:o}=t;if(e.code!==`DAG_TASK_EXECUTION_ABANDONED`)return g2(a,n.messageId,e);let s=X1.transition(r.status,`COMPLETE_FAILURE`);return s.ok?(await i.updateTaskRunStatus(r.taskRunId,s.value.nextStatus,e),await i.setTaskRunLease(r.taskRunId,void 0,void 0),h2(n,r.taskRunId,e,t.options,i,a,o,t.reporter)):g2(a,n.messageId,s.error)}function mLe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function hLe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gLe(e,t,n){let r=e.nodes.find(e=>e.nodeId===n);if(!r)return{ok:!1,error:Q(`DAG_VALIDATION_DOWNSTREAM_NODE_NOT_FOUND`,`Downstream node was not found while building payload`,{downstreamNodeId:n})};let i=e.edges.filter(e=>e.to===n);if(i.length===0)return{ok:!0,value:{}};let a={};for(let e of i){let n=_Le(a,e,r,t);if(!n.ok)return n}return SLe(a,r.inputs??[]),{ok:!0,value:a}}function _Le(e,t,n,r){if(!t.bindings||t.bindings.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_REQUIRED`,`Incoming edge must define at least one binding`,{from:t.from,to:t.to})};let i=vLe(t.from,t.to,r);if(!i.ok)return i;let a=i.value;for(let r of t.bindings){let i=yLe(e,r,a,t,n);if(!i.ok)return i}return{ok:!0,value:void 0}}function vLe(e,t,n){let r=n.find(t=>t.nodeId===e&&t.status===`success`);if(!r||!r.outputSnapshot)return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_MISSING`,`Upstream output snapshot is missing for binding dispatch`,{from:e,to:t})};try{let n=JSON.parse(r.outputSnapshot);return hLe(n)?{ok:!0,value:n}:{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_INVALID`,`Upstream output snapshot has invalid payload shape`,{from:e,to:t})}}catch(n){return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_PARSE_FAILED`,`Failed to parse upstream output snapshot`,{from:e,to:t,errorMessage:mLe(n)})}}}function yLe(e,t,n,r,i){let a=n[t.outputKey];if(a===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_OUTPUT_KEY_MISSING`,`Binding outputKey was not found in upstream output`,{from:r.from,outputKey:t.outputKey})};if((i.inputs??[]).find(e=>e.key===t.inputKey)?.isList)return bLe(e,t.inputKey,a,r.to);let o=_0(t.inputKey);return o?xLe(e,o,a,t.inputKey,r.to,i):e[t.inputKey]===void 0?(e[t.inputKey]=a,{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_CONFLICT`,`Multiple bindings target the same input key`,{to:r.to,inputKey:t.inputKey})}}function bLe(e,t,n,r){Array.isArray(e[t])||(e[t]=[]);let i=e[t];return Array.isArray(i)?(i.push(n),{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_LIST_PAYLOAD_INVALID`,`List payload container is invalid`,{to:r,inputKey:t})}}function xLe(e,t,n,r,i,a){if(!(a.inputs??[]).find(e=>e.key===t.portKey)?.isList)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_MISSING`,`Binding inputKey does not resolve to a valid list input port`,{to:i,inputKey:r})};let o=e[t.portKey],s=Array.isArray(o)?o:[];return s[t.index]=n,e[t.portKey]=s,{ok:!0,value:void 0}}function SLe(e,t){for(let n of t){if(!n.isList)continue;let t=e[n.key];Array.isArray(t)&&(e[n.key]=t.filter(e=>e!==void 0))}}function CLe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function wLe(e,t,n,r,i,a,o){let s=t.nodes.filter(e=>e.dependsOn.includes(n));if(s.length===0)return{ok:!0,value:void 0};let c=await i.listTaskRunsByDagRunId(e.dagRunId);for(let n of s){let r=await TLe(e,t,n,c,i,a,o);if(!r.ok)return r}return{ok:!0,value:void 0}}async function TLe(e,t,n,r,i,a,o){if(r.some(e=>e.nodeId===n.nodeId)||!n.dependsOn.every(e=>r.some(t=>t.nodeId===e&&t.status===`success`)))return{ok:!0,value:void 0};let s=`${e.dagRunId}:${n.nodeId}:attempt:1`;if(!(await i.commitExecution(e.dagRunId,{kind:`admit`,dependsOn:n.dependsOn,taskRun:{taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}})).applied)return{ok:!0,value:void 0};let c=gLe(t,r,n.nodeId);if(!c.ok)return c;let l={messageId:`${s}:message:1`,dagRunId:e.dagRunId,taskRunId:s,nodeId:n.nodeId,attempt:1,executionPath:[`dagId:${e.dagId}`,`dagRunId:${e.dagRunId}`,`nodeId:${n.nodeId}`,`taskRunId:${s}`,`attempt:1`],payload:c.value,createdAt:o.nowIso()};try{await a.enqueue(l)}catch(t){let r=X1.transition(`queued`,`CANCEL`);return r.ok&&await i.updateTaskRunStatus(s,r.value.nextStatus),{ok:!1,error:R1(`DAG_DISPATCH_ENQUEUE_DOWNSTREAM_FAILED`,`Failed to enqueue downstream task`,{dagRunId:e.dagRunId,nodeId:n.nodeId,errorMessage:CLe(t)})}}return r.push({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}),{ok:!0,value:void 0}}var ELe=class{storage;queue;clock;options;runProgressEventReporter;snapshotBudget;constructor(e,t,n,r,i,a){this.storage=e,this.queue=t,this.clock=n,this.options=r,this.runProgressEventReporter=i,this.snapshotBudget=a}async handleSuccessPath(e,t,n,r,i,a,o){let s=n=>this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`success`,outputSnapshot:n,estimatedCredits:a,totalCredits:o}),c=this.snapshotBudget?await this.snapshotBudget.admitValue(`output`,i,s):{ok:!0,value:await s(JSON.stringify(i))};if(!c.ok)return this.handleFailurePath(e,t,c.error);if(!c.value.applied){let[n,r]=await Promise.all([this.storage.getDagRun(e.dagRunId),this.storage.getTaskRun(t)]);return n?.status===`running`&&r?.status===`running`&&r.attempt===e.attempt&&r.leaseOwner===this.options.workerId?this.handleFailurePath(e,t,Q(`DAG_VALIDATION_EXECUTION_SETTLEMENT_REJECTED`,`Current task attempt could not settle its successful output`,{taskRunId:t})):_2(this.queue,e.messageId,t,!1)}this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:t2.COMPLETED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,output:i});let l=await wLe(n,r,e.nodeId,i,this.storage,this.queue,this.clock);if(!l.ok)return g2(this.queue,e.messageId,l.error);let u=await f2(e.dagRunId,this.storage,this.clock,this.runProgressEventReporter);return u.ok?_2(this.queue,e.messageId,t,!1):g2(this.queue,e.messageId,u.error)}async handleFailurePath(e,t,n){let r=this.options.retryEnabled&&n.retryable&&e.attempt<this.options.maxAttempts;return(await this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`failed`,reserveRetry:r,error:n})).applied?(this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:t2.FAILED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,error:n}),r?sLe(e,t,this.queue,this.clock):h2(e,t,n,this.options,this.storage,this.queue,this.clock,this.runProgressEventReporter)):_2(this.queue,e.messageId,t,!1)}};function DLe(e,t){return z1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${t}ms`,!0,{taskRunId:e,timeoutMs:t})}function y2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function b2(e,t,n,r){return new Promise(i=>{let a=new AbortController,o=!1,s,c=e=>{o||(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),i(e))},l=n=>{if(!o){if(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),a.abort(n),!e.stopAndWait){i({ok:!1,error:n});return}Promise.resolve().then(()=>e.stopAndWait?.(t)).then(()=>i({ok:!1,error:n}),e=>i({ok:!1,error:{...n,retryable:!1,context:{...n.context,isolationStopError:y2(e)}}}))}},u=()=>l(B1(r));if(t.signal?.aborted){u();return}t.signal?.addEventListener(`abort`,u,{once:!0}),s=setTimeout(()=>l(DLe(r,n)),n);let d=e=>c({ok:!1,error:z1(`DAG_TASK_EXECUTION_EXCEPTION`,`Task executor threw an exception`,!0,{taskRunId:r,errorMessage:y2(e)})});try{e.execute({...t,signal:a.signal}).then(c,d)}catch(e){d(e)}})}function OLe(e){let t=0;for(let n of e)typeof n.totalCredits==`number`&&n.totalCredits>t&&(t=n.totalCredits);return t}function kLe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function ALe(e,t){if(typeof e.definitionSnapshot!=`string`||e.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:t})};let n;try{n=JSON.parse(e.definitionSnapshot)}catch(e){return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse DagRun definition snapshot`,{dagRunId:t,errorMessage:kLe(e)})}}return u0(n,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot has invalid shape`,{dagRunId:t})}async function x2(e,t){let n=await e.getDagRun(t.dagRunId);if(!n)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found for dequeued message`,{dagRunId:t.dagRunId})};let r=ALe(n,t.dagRunId);if(!r.ok)return r;let i=r.value,a=i.nodes.find(e=>e.nodeId===t.nodeId);return a?{ok:!0,value:{dagRun:n,definition:i,nodeDefinition:a}}:{ok:!1,error:Q(`DAG_VALIDATION_NODE_NOT_FOUND`,`Node definition not found for task execution`,{nodeId:t.nodeId,dagId:n.dagId,version:n.version})}}var jLe=class{storage;queue;lease;executor;clock;options;runProgressEventReporter;snapshotBudget;rootCreditBudget;lifecycleCreditAdmission;executionRoot;byteLimits;cancellationPollMs;activeAttempts=new Set;notifyRunCancelled(e){for(let t of this.activeAttempts)t.dagRunId===e&&t.controller.abort()}constructor(e,t,n,r,i,a,o,s,c,l,u,d=!1){if(this.storage=e,this.queue=t,this.lease=n,this.executor=r,this.clock=i,this.options=o,this.runProgressEventReporter=s,this.snapshotBudget=l,this.rootCreditBudget=u,this.lifecycleCreditAdmission=d,this.executionRoot=en(a),this.byteLimits=K1(c),this.cancellationPollMs=o.cancellationPollMs??250,!Number.isSafeInteger(this.cancellationPollMs)||this.cancellationPollMs<1||this.cancellationPollMs>6e4)throw RangeError(`cancellationPollMs must be an integer between 1 and 60000`)}sweeper;outcomesInstance;get outcomes(){return this.outcomesInstance??=new ELe(this.storage,this.queue,this.clock,this.options,this.runProgressEventReporter,this.snapshotBudget),this.outcomesInstance}async processOnce(){let e=await this.queue.dequeue(this.options.workerId,this.options.visibilityTimeoutMs,this.options.idleWaitMs);if(!e){this.sweeper??=new aLe(this.clock,this.lease,this.options);let e=await this.sweeper.sweepIfDue(this.storage,this.queue);return e?{ok:!1,error:e}:{ok:!0,value:{processed:!1}}}let t=await this.resolveTimeoutMs(e);return fLe(this.lease,e.taskRunId,this.options.workerId,v2(t,this.options.leaseDurationMs),async()=>this.processAcquiredMessage(e,t),async()=>(await this.queue.nack(e.messageId),{ok:!0,value:{processed:!1}}))}async processAcquiredMessage(e,t){let n=await this.storage.getTaskRun(e.taskRunId);if(!n){let t=Q(`DAG_VALIDATION_TASK_RUN_NOT_FOUND`,`TaskRun not found for dequeued message`,{taskRunId:e.taskRunId});return g2(this.queue,e.messageId,t)}let r=await this.cancelIfRunCancelled(e);if(r)return r;let i=this.claimDepsFor(e,n,t),a=await dLe(i);if(!a.ok)return pLe(a.error,i);let o={...e,attempt:a.value},s=await x2(this.storage,o);if(!s.ok)return g2(this.queue,e.messageId,s.error);let{dagRun:c,definition:l,nodeDefinition:u}=s.value;if(c.status===`cancelled`)return this.settleCancelledRunMessage(e);let d;try{d=$0(c.lineage)}catch{return this.outcomes.handleFailurePath(o,o.taskRunId,Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Persisted composite child run lineage is invalid`,{dagRunId:o.dagRunId}))}if(d){let t=await this.cancelIfAncestorCancelled(e,c,d);if(t)return t}let f=e=>this.storage.commitExecution(o.dagRunId,{kind:`snapshot-input`,taskRunId:o.taskRunId,attempt:o.attempt,leaseOwner:this.options.workerId,inputSnapshot:e}),p=this.snapshotBudget?await this.snapshotBudget.admitValue(`input`,o.payload,f):{ok:!0,value:await f(JSON.stringify(o.payload))};if(!p.ok)return this.outcomes.handleFailurePath(o,o.taskRunId,p.error);if(!p.value.applied)return _2(this.queue,e.messageId,o.taskRunId,!1);let m=await this.buildExecutionInput(o,c,l,u,d),h=new AbortController,g={dagRunId:o.dagRunId,taskRunId:o.taskRunId,attempt:o.attempt,controller:h};this.activeAttempts.add(g);let _,v,y=Date.now()+i.timeoutMs,b;try{let t=await this.cancelIfRunCancelled(e);if(t)return t;if(b=this.watchCommittedCancellation(g),l.costPolicy&&!this.lifecycleCreditAdmission&&!(this.executor instanceof r2)){let t=this.executor.estimateCost;if(!t)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_REQUIRED`,`Cost-limited runs require a custom executor to estimate credits before execution`,{taskRunId:o.taskRunId}));let r=await b2({execute:async e=>{let n=await t.call(this.executor,e);return n.ok?{ok:!0,output:{},estimatedCredits:n.value}:n},...this.executor.stopAndWait?{stopAndWait:this.executor.stopAndWait.bind(this.executor)}:{}},{...m,signal:h.signal},Math.max(1,y-Date.now()),e.taskRunId);if(!r.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,r.error);if(r.estimatedCredits===void 0||!Number.isFinite(r.estimatedCredits)||r.estimatedCredits<0)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_INVALID`,`Custom executor credit estimate must be a finite nonnegative number`,{taskRunId:o.taskRunId}));let i=await m.reserveCredits(r.estimatedCredits);if(!i.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,i.error);v=r.estimatedCredits}let r=y-Date.now();if(r<=0)return this.outcomes.handleFailurePath(o,n.taskRunId,z1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${i.timeoutMs}ms`,!0,{taskRunId:e.taskRunId,timeoutMs:i.timeoutMs}));_=await b2(this.executor,{...m,signal:h.signal},r,e.taskRunId)}finally{b?.(),this.activeAttempts.delete(g)}return _.ok?v!==void 0&&_.estimatedCredits!==void 0&&_.estimatedCredits!==v?this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_MISMATCH`,`Custom executor reported credits different from its preflight estimate`,{taskRunId:o.taskRunId})):this.outcomes.handleSuccessPath(o,n.taskRunId,c,l,_.output,v??_.estimatedCredits,_.totalCredits):this.outcomes.handleFailurePath(o,n.taskRunId,_.error)}watchCommittedCancellation(e){let t=!1,n,r=async()=>{if(!t){try{let n=await this.storage.getDagRun(e.dagRunId);!t&&n?.status!==`running`&&e.controller.abort()}catch{t||e.controller.abort()}!t&&!e.controller.signal.aborted&&(n=setTimeout(()=>{r()},this.cancellationPollMs))}};return n=setTimeout(()=>{r()},this.cancellationPollMs),()=>{t=!0,clearTimeout(n)}}async cancelIfRunCancelled(e){return(await this.storage.getDagRun(e.dagRunId))?.status===`cancelled`?this.settleCancelledRunMessage(e):void 0}async cancelIfAncestorCancelled(e,t,n){if(n.parentRunId===void 0)return;let r=new Set([n.rootRunId,n.parentRunId]);for(let n of r)if((await this.storage.getDagRun(n))?.status===`cancelled`)return await this.cancelOwnRunForAncestor(t),this.settleCancelledRunMessage(e)}async cancelOwnRunForAncestor(e){if(!Y1.transition(e.status,`CANCEL`).ok)return;let t=await this.storage.commitExecution(e.dagRunId,{kind:`transition-run`,expectedStatus:e.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(t.applied||t.runStatus===`cancelled`){this.notifyRunCancelled(e.dagRunId);return}if(t.runStatus!==void 0){let t=await this.storage.getDagRun(e.dagRunId);t&&await this.cancelOwnRunForAncestor(t)}}async settleCancelledRunMessage(e){let t=await this.storage.getTaskRun(e.taskRunId);if(t){let e=X1.transition(t.status,`CANCEL`);e.ok&&await this.storage.updateTaskRunStatus(t.taskRunId,e.value.nextStatus),await this.storage.setTaskRunLease(t.taskRunId,void 0,void 0)}return _2(this.queue,e.messageId,e.taskRunId,!1)}async buildExecutionInput(e,t,n,r,i){let a=OLe(await this.storage.listTaskRunsByDagRunId(e.dagRunId));return{executionRoot:this.executionRoot,...i===void 0?{}:{lineage:i},byteLimits:this.byteLimits,snapshotBudget:this.snapshotBudget,rootCreditBudget:this.rootCreditBudget,reserveCredits:n.costPolicy?async t=>{let n=await this.storage.commitExecution(e.dagRunId,{kind:`reserve-credits`,taskRunId:e.taskRunId,attempt:e.attempt,leaseOwner:this.options.workerId,estimatedCredits:t});return n.applied?{ok:!0,value:void 0}:{ok:!1,error:n.error??Q(`DAG_VALIDATION_CREDIT_RESERVATION_REJECTED`,`Task attempt lost credit reservation authority`,{taskRunId:e.taskRunId})}}:void 0,dagId:t.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:e.attempt,executionPath:e.executionPath,input:e.payload,nodeDefinition:r,costPolicy:n.costPolicy,currentTotalCredits:a}}claimDepsFor(e,t,n){return{storage:this.storage,queue:this.queue,clock:this.clock,reporter:this.runProgressEventReporter,options:this.options,timeoutMs:n,message:e,taskRun:t}}async resolveTimeoutMs(e){let t=await x2(this.storage,e);if(!t.ok)return this.options.defaultTimeoutMs;let n=t.value.nodeDefinition.timeoutMs;return typeof n==`number`&&n>0?n:this.options.defaultTimeoutMs}},MLe=class extends Error{constructor(){super(`Run advancement has stopped and cannot be restarted.`),this.name=`RunAdvancementStoppedError`}};function NLe(e){return e===`success`||e===`failed`||e===`cancelled`}function S2(e,t,n){return R1(e,t,{dagRunId:n})}var PLe=class{workerStep;runReader;logger;lifecycle=`created`;continuousDemand=!1;waiters=new Map;actorPromise=null;stopPromise=null;wakeSleep=null;constructor(e,t,n={error:()=>void 0}){this.workerStep=e,this.runReader=t,this.logger=n}async start(){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)throw new MLe;this.lifecycle=`running`,this.continuousDemand=!0,this.wake(),this.ensureActor()}waitForTerminal(e,t={}){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)return Promise.resolve({ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e)});if(t.signal?.aborted)return Promise.resolve({ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)});if(t.deadlineEpochMs!==void 0&&t.deadlineEpochMs<=Date.now())return Promise.resolve({ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)});let n=new Promise(n=>{let r={id:Symbol(e),dagRunId:e,resolve:n,signal:t.signal,settled:!1};t.signal!==void 0&&(r.abortListener=()=>{this.settle(r,{ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)})},t.signal.addEventListener(`abort`,r.abortListener,{once:!0})),t.deadlineEpochMs!==void 0&&(r.deadlineTimer=setTimeout(()=>{this.settle(r,{ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)})},Math.max(0,t.deadlineEpochMs-Date.now())),r.deadlineTimer.unref?.()),this.waiters.set(r.id,r)});return this.wake(),this.ensureActor(),n}stop(){if(this.stopPromise!==null)return this.stopPromise;this.lifecycle=`stopping`,this.continuousDemand=!1;for(let e of[...this.waiters.values()])this.settle(e,{ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e.dagRunId)});return this.wake(),this.stopPromise=(async()=>{await this.actorPromise,this.lifecycle=`stopped`})(),this.stopPromise}hasDemand(){return(this.lifecycle===`created`||this.lifecycle===`running`)&&(this.continuousDemand||this.waiters.size>0)}ensureActor(){if(!this.hasDemand()||this.actorPromise!==null)return;let e=this.runActor().catch(e=>{this.logger.error(`Run advancement actor failed unexpectedly.`,e)}).finally(()=>{this.actorPromise===e&&(this.actorPromise=null),this.hasDemand()&&this.ensureActor()});this.actorPromise=e}async runActor(){let e=25;for(;this.hasDemand();){if(await this.queryAndSettleWaiters(),!this.hasDemand())return;let t;try{t=await this.workerStep.processOnce()}catch(e){this.logger.error(`Worker step threw during run advancement.`,e),await this.sleepUntilWake(500);continue}if(!this.hasDemand())return;if(!t.ok){this.logger.error(`Worker step failed during run advancement.`,t.error),await this.sleepUntilWake(500);continue}if(t.value.processed){e=25;continue}await this.sleepUntilWake(e),e=Math.min(e*2,500)}}async queryAndSettleWaiters(){let e=new Set([...this.waiters.values()].map(e=>e.dagRunId));for(let t of e){let e;try{e=await this.runReader.getRun(t)}catch(n){e={ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_QUERY_THROW`,n instanceof Error?n.message:String(n),t)}}let n=[...this.waiters.values()].filter(e=>e.dagRunId===t);if(!e.ok||NLe(e.value.dagRun.status))for(let t of n)this.settle(t,e)}}settle(e,t){e.settled||(e.settled=!0,this.waiters.delete(e.id),e.deadlineTimer!==void 0&&clearTimeout(e.deadlineTimer),e.signal!==void 0&&e.abortListener!==void 0&&e.signal.removeEventListener(`abort`,e.abortListener),e.resolve(t),this.wake())}wake(){this.wakeSleep?.()}async sleepUntilWake(e){this.hasDemand()&&await new Promise(t=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),this.wakeSleep===r&&(this.wakeSleep=null),t())},i=setTimeout(r,e);i.unref?.(),this.wakeSleep=r,this.hasDemand()||r()})}};function FLe(e,t){let n={...t,retryEnabled:t.retryEnabled??!1,deadLetterEnabled:t.deadLetterEnabled??!1,deadLetterQueue:e.deadLetterQueue};return new jLe(e.storage,e.queue,e.lease,e.executor,e.clock,e.executionRoot,n,e.runProgressEventReporter,e.byteLimits,e.snapshotBudget,e.rootCreditBudget,e.lifecycleCreditAdmission)}function ILe(e,t){let n=new HIe,r=new JIe(e.storage,e.queue,e.clock,n,e.snapshotBudget),i=new YIe(e.storage),a=FLe({executionRoot:e.executionRoot,byteLimits:e.byteLimits,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,lifecycleCreditAdmission:e.lifecycleCreditAdmission,storage:e.storage,queue:e.queue,deadLetterQueue:e.deadLetterQueue,lease:e.lease,executor:e.executor,clock:e.clock,runProgressEventReporter:n},{...t.worker,retryEnabled:t.worker.retryEnabled??!1});return{runOrchestrator:r,runQuery:i,runCancel:new XIe(e.storage,e.clock,{notifyRunCancelled(t){e.snapshotBudget?.close(),e.rootCreditBudget?.close(),a.notifyRunCancelled(t)}}),runAdvancement:new PLe(a,i,t.logger),runProgressEventBus:n}}function C2(e,t){let{text:n,search:r,replacement:i,flags:a}=e,o;try{o=new RegExp(r,a)}catch{return{type:`invalid-regex`}}let s=Symbol(`regex output exceeds byte limit`),c=new Uint16Array(t),l=0,u=0,d=!1,f=0,p=(e,n,r)=>{for(let i=n;i<r;i++){let n=e.charCodeAt(i);if(u+=n<128?1:n<2048?2:n>=56320&&n<=57343&&d?1:3,d=n>=55296&&n<=56319,u>t)throw s;c[l++]=n}},m=(e,t,r,a)=>{for(let o=0;o<i.length;){let s=i.indexOf(`$`,o);if(s<0){p(i,o,i.length);return}p(i,o,s);let c=i[s+1];if(c===`$`)p(i,s,s+1),o=s+2;else if(c===`&`)p(e,0,e.length),o=s+2;else if(c==="`")p(n,0,r),o=s+2;else if(c===`'`)p(n,r+e.length,n.length),o=s+2;else if(c!==void 0&&c>=`0`&&c<=`9`){let e=i[s+2],n=e!==void 0&&e>=`0`&&e<=`9`?2:1,r=Number(i.slice(s+1,s+1+n));if(n===2&&r>t.length&&(n=1,r=Number(c)),r>=1&&r<=t.length){let e=t[r-1];e!==void 0&&p(e,0,e.length)}else p(i,s,s+1+n);o=s+1+n}else if(c===`<`){let e=i.indexOf(`>`,s+2);if(e>=0&&a!==void 0){let t=a[i.slice(s+2,e)];t!==void 0&&p(t,0,t.length),o=e+1}else p(i,s,s+2),o=s+2}else p(i,s,s+1),o=s+1}};try{let e=a.includes(`u`)||a.includes(`v`);for(let t=o.exec(n);t!==null;t=o.exec(n)){let r=t[0],i=t.index;if(p(n,f,i),m(r,t.slice(1),i,t.groups),f=i+r.length,!o.global)break;if(r.length===0){let t=o.lastIndex,r=n.charCodeAt(t),i=n.charCodeAt(t+1);o.lastIndex+=e&&r>=55296&&r<=56319&&i>=56320&&i<=57343?2:1}}p(n,f,n.length)}catch(e){return e===s?{type:`oversized`}:{type:`invalid-regex`}}let h=[];for(let e=0;e<l;e+=8192)h.push(String.fromCharCode(...c.subarray(e,Math.min(e+8192,l))));return{type:`result`,value:h.join(``)}}const w2=25166848,LLe=`
2759
+ `?(r&&n++,r=!1):!r&&tIe.test(i)&&(r=!0)}return r&&n++,n}var rIe=class extends v0{nodeType=`text-count-lines`;displayName=`Text Count Lines`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Line Count`,order:0,type:`string`,required:!0}];configSchemaDefinition=eIe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,String(nIe(i.value,n.skipEmpty))),{ok:!0,value:r.toOutput()}):i}};const iIe=P.object({times:P.number().int().min(0).max(2**53-1).default(2),separator:P.string().default(``)});var aIe=class extends v0{nodeType=`text-repeat`;displayName=`Text Repeat`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Repeated Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=iIe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);if(!i.ok)return i;let a=K1(t.byteLimits),o=PFe(i.value,n.separator,n.times,a.maxTextRepeatOutputBytes);return o.ok?(r.setOutput(`text`,o.value),{ok:!0,value:r.toOutput()}):o}};const oIe=P.object({start:P.number().int().default(0),end:P.number().int().optional()});var sIe=class extends v0{nodeType=`text-slice`;displayName=`Text Slice`;category=`Utility`;defaultInputPort=`text`;defaultOutputPort=`text`;inputs=[{key:`text`,label:`Text`,order:0,type:`string`,required:!0}];outputs=[{key:`text`,label:`Sliced Text`,order:0,type:`string`,required:!0}];configSchemaDefinition=oIe;async estimateCostWithConfig(){return Y0}async executeWithConfig(e,t,n){let r=new S0(e,t.nodeDefinition.nodeId),i=r.requireInputString(`text`);return i.ok?(r.setOutput(`text`,i.value.slice(n.start,n.end)),{ok:!0,value:r.toOutput()}):i}},cIe=ZPe({createDefaultNodeRegistry:()=>Q0,createDefaultNodeRegistrySync:()=>Z0});function Z0(){return[new oFe,new cFe,new dFe,new mFe,new gFe,new vFe,new bFe,new SFe,new jFe,new LFe,new RFe,new BFe,new HFe,new WFe,new GFe,new KFe,new qFe,new YFe,new ZFe,new $Fe,new rIe,new aIe,new sIe]}const lIe=async()=>{try{return(await Promise.resolve().then(()=>gz)).createDefaultMediaProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default media provider definitions. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or inject mediaProviders explicitly. Cause: ${t}`)}},uIe=async()=>{try{return(await Promise.resolve().then(()=>gz)).createDefaultProviderDefinitions()}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load the default LLM provider set for the llm-text node. A provider SDK package is likely not installed. Install @robota-sdk/agent-builtin-providers (and its provider SDKs), or pass createDagFramework({ providers: [...] }) explicitly. Cause: ${t}`)}};async function Q0(e,t=uIe,n={},r=[],i=[]){let a=e??await t(),o=[...Z0(),new iFe(a)],s=n.mediaProviders??await(n.loadMediaDefaults??lIe)(),c=de(s,`gemini-image`),l=de(s,`seedance-video`),u=await Promise.all([...[{modulePath:`@robota-sdk/dag-node-gemini-image-edit`,factories:[e=>new e.GeminiImageEditNodeDefinition({imageProviderDefinition:c}),e=>new e.GeminiImageComposeNodeDefinition({imageProviderDefinition:c})]},{modulePath:`@robota-sdk/dag-node-text-to-image`,factories:[e=>new e.TextToImageNodeDefinition({imageProviderDefinition:c})]},{modulePath:`@robota-sdk/dag-node-seedance-video`,factories:[e=>new e.SeedanceVideoNodeDefinition({videoProviderDefinition:l})]}].map(fIe),dIe(i,r)]);for(let e of u)o.push(...e);return o}async function dIe(e,t){try{return[new(await(import(`./src-DwAfU-9z-B3bEabDl.js`))).SkillNodeDefinition({skillPort:mde(e,t)})]}catch{return[]}}async function fIe(e){let t=await pIe(e.modulePath);if(!t)return[];let n=[];for(let r of e.factories){let e=mIe(r,t);e&&n.push(e)}return n}async function pIe(e){try{switch(e){case`@robota-sdk/dag-node-gemini-image-edit`:return await import(`./src-B9UMvThT-CH8RbDyz.js`);case`@robota-sdk/dag-node-text-to-image`:return await import(`./src-BzaNFPZx-DdIEi4rg.js`);case`@robota-sdk/dag-node-seedance-video`:return await import(`./src-UPsd6jNY-CpXUNTpA.js`);default:return}}catch{return}}function mIe(e,t){try{return e(t)}catch{return}}var hIe=class{limit;committed=0;reserved=0;closed=!1;constructor(e){if(this.limit=e,e!==void 0&&(!Number.isFinite(e)||e<=0))throw RangeError(`Root credit limit must be positive and finite`)}close(){this.closed=!0}reserve(e){if(!Number.isFinite(e)||e<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be finite and zero or positive`,{estimatedCredits:e})};if(this.closed||this.limit!==void 0&&e>this.limit-this.committed-this.reserved)return{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds root runCreditLimit`,{estimatedCredits:e,...this.limit===void 0?{}:{runCreditLimit:this.limit}})};this.reserved+=e;let t=!1;return{ok:!0,value:{commit:()=>(t||(t=!0,this.reserved-=e,this.committed+=e),this.committed),release:()=>{t||(t=!0,this.reserved-=e)}}}}};function $0(e){if(e==null)return;if(typeof e!=`object`||Array.isArray(e))throw Error(`Invalid persisted DAG execution lineage`);let t=e,n=t.parentRunId!==void 0,r=!n||typeof t.parentRunId==`string`&&t.parentRunId.length>0;if(typeof t.rootRunId!=`string`||t.rootRunId.length===0||!r||!Number.isSafeInteger(t.depth)||t.depth<0||t.maxDepth!==void 0&&(!Number.isSafeInteger(t.maxDepth)||t.maxDepth<1)||!Array.isArray(t.ancestorCompositeNodeTypes)||!t.ancestorCompositeNodeTypes.every(e=>typeof e==`string`&&e.length>0))throw Error(`Invalid persisted DAG execution lineage`);let i=t.depth,a=t.ancestorCompositeNodeTypes.length;if(!(i===0?!n&&a===0:n&&a===i))throw Error(`Invalid persisted DAG execution lineage`);return{rootRunId:t.rootRunId,...n?{parentRunId:t.parentRunId}:{},depth:i,...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},ancestorCompositeNodeTypes:[...t.ancestorCompositeNodeTypes]}}const e2={STARTED:`execution.started`,COMPLETED:`execution.completed`,FAILED:`execution.failed`},t2={STARTED:`task.started`,COMPLETED:`task.completed`,FAILED:`task.failed`};function n2(e){let t=Date.parse(e);return Number.isNaN(t)?{ok:!1,error:Q(`DAG_VALIDATION_INVALID_LOGICAL_DATE`,`logicalDate must be a valid ISO-8601 datetime string`,{logicalDate:e})}:{ok:!0,value:new Date(t).toISOString()}}var gIe=class{clock;constructor(e){this.clock=e}resolve(e,t){let n=this.clock.nowIso();if(e===`scheduled`){if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_MISSING_LOGICAL_DATE`,`scheduled trigger requires logicalDate`,{trigger:e})};let r=n2(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}if(!t)return{ok:!0,value:{trigger:e,logicalDate:n,requestedAt:n}};let r=n2(t);return r.ok?{ok:!0,value:{trigger:e,logicalDate:r.value,requestedAt:n}}:r}},_Ie=class{assertWithinBudget(e,t,n){if(t<0)return{ok:!1,error:Q(`DAG_VALIDATION_NEGATIVE_ESTIMATED_CREDITS`,`estimatedCredits must be zero or positive`,{nextEstimatedCredits:t})};let r=e+t;return typeof n==`number`&&r>n?{ok:!1,error:Q(`DAG_VALIDATION_CREDIT_LIMIT_EXCEEDED`,`Estimated run credits exceeds runCreditLimit`,{nextTotalCredits:r,runCreditLimit:n})}:{ok:!0,value:r}}},vIe=class{lifecycleFactory;costPolicyEvaluator;constructor(e,t){this.lifecycleFactory=e,this.costPolicyEvaluator=t}async runNode(e){let t=()=>({ok:!1,error:B1(e.context.taskRunId)});if(e.context.signal?.aborted)return t();let n=this.lifecycleFactory.create(e.context.nodeDefinition.nodeType);if(!n.ok)return n;let r=await n.value.initialize(e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return r;let i=await n.value.validateInput(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let a=await n.value.estimateCost(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!a.ok)return await n.value.dispose(e.context),a;let o=this.costPolicyEvaluator.assertWithinBudget(e.context.currentTotalCredits,a.value.estimatedCredits,e.context.runCreditLimit);if(!o.ok)return await n.value.dispose(e.context),o;if(e.context.reserveCredits){let r=await e.context.reserveCredits(a.value.estimatedCredits);if(!r.ok)return await n.value.dispose(e.context),r;if(e.context.signal?.aborted)return await n.value.dispose(e.context),t()}let s=e.context.rootCreditBudget?.reserve(a.value.estimatedCredits);if(s&&!s.ok)return await n.value.dispose(e.context),s;try{let r=await n.value.execute(e.input,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!r.ok)return await n.value.dispose(e.context),r;let i=await n.value.validateOutput(r.value,e.context);if(e.context.signal?.aborted)return await n.value.dispose(e.context),t();if(!i.ok)return await n.value.dispose(e.context),i;let c=await n.value.dispose(e.context);return e.context.signal?.aborted?t():c.ok?(s?.value.commit(),{ok:!0,value:{output:r.value,estimatedCredits:a.value.estimatedCredits,totalCredits:o.value}}):{ok:!1,error:z1(`DAG_TASK_EXECUTION_DISPOSE_FAILED`,`Node dispose step failed after execution`,!1,{nodeType:e.context.nodeDefinition.nodeType,taskRunId:e.context.taskRunId})}}finally{s?.ok&&s.value.release()}}},yIe=class{create(e){return{ok:!1,error:Q(`DAG_VALIDATION_NODE_LIFECYCLE_NOT_REGISTERED`,`Node lifecycle is not registered for nodeType`,{nodeType:e})}}},r2=class{nodeManifestRegistry;lineage;lifecycleFactory;runner;constructor(e,t,n){this.nodeManifestRegistry=e,this.lineage=n,this.lifecycleFactory=t??new yIe,this.runner=new vIe(this.lifecycleFactory,new _Ie)}async execute(e){if(!e.nodeDefinition)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_DEFINITION_MISSING`,`Task execution requires nodeDefinition in execution input`,{nodeId:e.nodeId})};let t=this.nodeManifestRegistry.getManifest(e.nodeDefinition.nodeType);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_NODE_MANIFEST_NOT_FOUND`,`Node manifest is not registered for nodeType`,{nodeType:e.nodeDefinition.nodeType})};let n=await this.runner.runNode({input:e.input,context:{executionRoot:e.executionRoot,regexReplaceOperation:e.regexReplaceOperation,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,reserveCredits:e.reserveCredits,...e.byteLimits===void 0?{}:{byteLimits:e.byteLimits},...e.signal===void 0?{}:{signal:e.signal},dagId:e.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeDefinition:e.nodeDefinition,nodeManifest:t,attempt:e.attempt,executionPath:e.executionPath,lineage:e.lineage??this.lineage??{rootRunId:e.dagRunId,depth:0,ancestorCompositeNodeTypes:[]},runCreditLimit:e.costPolicy?.runCreditLimit,currentTotalCredits:e.currentTotalCredits??0,...e.runtimeBaseUrl===void 0?{}:{runtimeBaseUrl:e.runtimeBaseUrl}}});return n.ok?{ok:!0,output:n.value.output,estimatedCredits:n.value.estimatedCredits,totalCredits:n.value.totalCredits}:n}};const i2={root:`.workflows`,workflowExt:`.json`};var bIe=class{manifestByType=new Map;constructor(e){for(let t of e)this.manifestByType.set(t.nodeType,t)}getManifest(e){return this.manifestByType.get(e)}listManifests(){return[...this.manifestByType.values()]}};function xIe(e){let t=[],n=EIe(e,``,t);return n!==void 0&&t.length===0?{ok:!0,value:n}:{ok:!1,error:t}}function a2(e,t,n){if(!Array.isArray(e)||e.length!==2)return Z1(n,t,`expected a [number, number] pair`);let r=t0(e[0],Q1(t,0),n),i=t0(e[1],Q1(t,1),n);return r===void 0||i===void 0?void 0:[r,i]}function SIe(e,t,n){if(!Array.isArray(e)||e.length!==6)return Z1(n,t,`expected a 6-tuple [linkId, srcId, srcSlot, tgtId, tgtSlot, type]`);let r=[0,1,2,3,4].map(r=>t0(e[r],Q1(t,r),n)),i=e0(e[5],Q1(t,5),n);if(r.some(e=>e===void 0)||i===void 0)return;let[a,o,s,c,l]=r;return[a,o,s,c,l,i]}function CIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e0(r.name,Q1(t,`name`),n),a=e0(r.type,Q1(t,`type`),n),o=r.link,s=o===null?null:t0(o,Q1(t,`link`),n);return i===void 0||a===void 0||s===void 0?void 0:{name:i,type:a,link:s}}function wIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e0(r.name,Q1(t,`name`),n),a=e0(r.type,Q1(t,`type`),n),o=a0(r.links,Q1(t,`links`),n,t0),s=i0(r.slot_index,Q1(t,`slot_index`),n,t0);if(i===void 0||a===void 0||o===void 0)return;let c={name:i,type:a,links:o};return s!==void 0&&(c.slot_index=s),c}function TIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e=>Q1(t,e),a=t0(r.id,i(`id`),n),o=e0(r.type,i(`type`),n),s=a2(r.pos,i(`pos`),n),c=i0(r.size,i(`size`),n,a2),l=i0(r.flags,i(`flags`),n,$1),u=i0(r.order,i(`order`),n,t0),d=i0(r.mode,i(`mode`),n,t0),f=i0(r.inputs,i(`inputs`),n,(e,t,n)=>a0(e,t,n,CIe)),p=i0(r.outputs,i(`outputs`),n,(e,t,n)=>a0(e,t,n,wIe)),m=i0(r.properties,i(`properties`),n,$1),h=i0(r.widgets_values,i(`widgets_values`),n,(e,t,n)=>Array.isArray(e)?e:Z1(n,t,`expected an array`));if(a===void 0||o===void 0||s===void 0)return;let g={id:a,type:o,pos:s};return c!==void 0&&(g.size=c),l!==void 0&&(g.flags=l),u!==void 0&&(g.order=u),d!==void 0&&(g.mode=d),f!==void 0&&(g.inputs=f),p!==void 0&&(g.outputs=p),m!==void 0&&(g.properties=m),h!==void 0&&(g.widgets_values=h),g}function EIe(e,t,n){let r=$1(e,t,n);if(r===void 0)return;let i=e=>Q1(t,e);if(`dagId`in r)return Z1(n,i(`dagId`),`a workflow file carries no dagId — that is a definition file`);let a=t0(r.last_node_id,i(`last_node_id`),n),o=t0(r.last_link_id,i(`last_link_id`),n),s=a0(r.nodes,i(`nodes`),n,TIe),c=a0(r.links,i(`links`),n,SIe),l=t0(r.version,i(`version`),n),u=i0(r.groups,i(`groups`),n,(e,t,n)=>Array.isArray(e)?e:Z1(n,t,`expected an array`)),d=i0(r.config,i(`config`),n,$1),f=i0(r.extra,i(`extra`),n,$1);if(a===void 0||o===void 0||s===void 0||c===void 0||l===void 0)return;let p={last_node_id:a,last_link_id:o,nodes:s,links:c,version:l};return u!==void 0&&(p.groups=u),d!==void 0&&(p.config=d),f!==void 0&&(p.extra=f),p}function DIe(e){return`parallel`in e}function o2(e,t){return e.id??`${e.nodeType}-${t}`}function s2(e,t){return e.find(e=>e.nodeType===t)}function c2(e,t){let n=t.map(e=>e.nodeType),r={action:`replace_node_type`,suggestion:n[0],options:n};return Q(`UNKNOWN_NODE_TYPE`,`Node type "${e}" is not registered`,{requestedType:e},r)}function OIe(e,t){let n=[],r=[],i=[],a=[],o=0;for(let s of e.pipeline)if(DIe(s)){let e=[];for(let c of s.parallel){let l=o2(c,o);o+=1;let u=s2(t,c.nodeType);if(!u)return{ok:!1,error:c2(c.nodeType,t),warnings:n};let d=a.map(e=>e.nodeId);r.push({nodeId:l,nodeType:c.nodeType,dependsOn:d,config:c.config??{}});for(let e of a){let t=c.toPort??u.defaultInputPort;if(!t){n.push({message:`Node "${l}" (${c.nodeType}) has no defaultInputPort; edge from "${e.nodeId}" requires explicit toPort`});continue}i.push({from:e.nodeId,to:l,bindings:[{outputKey:e.portKey,inputKey:t}]})}let f=s.fromPort??c.fromPort??u.defaultOutputPort;f?e.push({nodeId:l,portKey:f}):n.push({message:`Node "${l}" (${c.nodeType}) has no defaultOutputPort; downstream connections require explicit fromPort`})}a=e}else{let e=o2(s,o);o+=1;let c=s2(t,s.nodeType);if(!c)return{ok:!1,error:c2(s.nodeType,t),warnings:n};let l=a.map(e=>e.nodeId);r.push({nodeId:e,nodeType:s.nodeType,dependsOn:l,config:s.config??{}});for(let t of a){let r=s.toPort??c.defaultInputPort;if(!r){n.push({message:`Node "${e}" (${s.nodeType}) has no defaultInputPort; edge from "${t.nodeId}" requires explicit toPort`});continue}i.push({from:t.nodeId,to:e,bindings:[{outputKey:t.portKey,inputKey:r}]})}let u=s.fromPort??c.defaultOutputPort;a=u?[{nodeId:e,portKey:u}]:[]}return r.length===0?{ok:!1,error:Q(`EMPTY_PIPELINE`,`pipeline must contain at least one node`,void 0,{action:`add_node`,suggestion:`Add at least one node spec to the pipeline array`}),warnings:n}:{ok:!0,definition:{dagId:e.dagId??`dag-build-result`,version:1,status:`draft`,nodes:r,edges:i},warnings:n,nodeCount:r.length,edgeCount:i.length}}function kIe(e){return(e.startsWith(`ConversationAgent`)?e.slice(17):e).replace(/([A-Z])/g,(e,t)=>`-${t.toLowerCase()}`).replace(/^-/,``)}function AIe(e,t){let n=new Map;for(let t of e.links)n.set(t[0],t);let r=t?.nodes??{},i=e.nodes.map(e=>{let t=r[String(e.id)],n={nodeId:t?.nodeId??`node-${e.id}`,nodeType:kIe(e.type),dependsOn:[],config:e.properties?.agent_config??{},position:e.pos[0]!==0||e.pos[1]!==0?{x:e.pos[0],y:e.pos[1]}:void 0};return t?.retryPolicy&&(n.retryPolicy=t.retryPolicy),t?.timeoutMs!==void 0&&(n.timeoutMs=t.timeoutMs),t?.costPolicy&&(n.costPolicy=t.costPolicy),n}),a=new Map;e.nodes.forEach((e,t)=>{a.set(e.id,i[t])});let o=new Map,s=[],c=new Map;for(let t of e.links){let[,n,,r]=t,i=a.get(n),l=a.get(r);if(!i||!l)continue;let u=e.nodes.find(e=>e.id===n),d=e.nodes.find(e=>e.id===r),f=t[2],p=t[4],m=u?.outputs?.[f]?.name??`out${f}`,h=d?.inputs?.[p]?.name??`in${p}`,g=JSON.stringify([i.nodeId,l.nodeId]),_=o.get(g);_||(_=[],o.set(g,_),s.push({from:i.nodeId,to:l.nodeId,bindings:_})),_.push({outputKey:m,inputKey:h}),c.has(l.nodeId)||c.set(l.nodeId,new Set),c.get(l.nodeId).add(i.nodeId)}for(let e of i){let t=c.get(e.nodeId);t&&(e.dependsOn=[...t])}return{dagId:t?.dagId??`unknown`,version:t?.version??1,status:t?.status??`draft`,nodes:i,edges:s,...t?.costPolicy?{costPolicy:t.costPolicy}:{},...t?.inputSchema?{inputSchema:t.inputSchema}:{},...t?.outputSchema?{outputSchema:t.outputSchema}:{}}}const jIe={absentStatus:`draft`,absentEdgesAsEmpty:!0};function MIe(e){if(typeof e!=`object`||!e||Array.isArray(e))return`unrecognised`;let t=e;return`dagId`in t?`definition`:`links`in t||`last_node_id`in t?`workflow-file`:`unrecognised`}function NIe(e,t){let n=MIe(e);if(n===`unrecognised`)return{ok:!1,error:{format:n,issues:[{path:``,message:`expected either a workflow file (nodes + links + version) or a definition (dagId + nodes)`}]}};if(n===`workflow-file`){let r=xIe(e);return r.ok?PIe(AIe(r.value,t),n):{ok:!1,error:{format:n,issues:r.error}}}let r=l0(e,jIe);return r.ok?r:{ok:!1,error:{format:n,issues:r.error}}}function PIe(e,t){let n=l0(e);return n.ok?n:{ok:!1,error:{format:t,issues:n.error}}}function FIe(e){return e.format===`unrecognised`?`Not a DAG file: ${c0(e.issues)}.`:`Malformed ${e.format===`workflow-file`?`workflow file`:`DAG definition`}: ${c0(e.issues)}`}var IIe=class extends Error{failure;constructor(e){super(FIe(e)),this.name=`DagFileDecodeError`,this.failure=e}};function l2(e,t){let n=NIe(e,t);if(n.ok)return n.value;throw new IIe(n.error)}function LIe(e,t,n,r){for(let[i,a]of e.entries())if(a.taskRunId===t){e.set(i,{...a,leaseOwner:n,leaseUntil:r});return}}function RIe(e,t){return[...e.values()].filter(e=>e.status===`running`&&(e.leaseUntil===void 0||e.leaseUntil<=t))}function u2(e,t){return`${e}:${t}`}var zIe=class{definitions=new Map;latestPublishedVersionByDagId=new Map;dagRuns=new Map;taskRuns=new Map;async commitExecution(e,t){let n=[...this.taskRuns.values()].filter(t=>t.dagRunId===e),r=IPe(this.dagRuns.get(e),n,t);return r.dagRun&&this.dagRuns.set(e,r.dagRun),r.taskRun&&this.taskRuns.set(u2(e,r.taskRun.taskRunId),r.taskRun),r.result}async saveDefinition(e){let t=`${e.dagId}:${e.version}`;if(this.definitions.set(t,e),e.status===`published`){let t=this.latestPublishedVersionByDagId.get(e.dagId)??0;e.version>t&&this.latestPublishedVersionByDagId.set(e.dagId,e.version)}}async getDefinition(e,t){let n=`${e}:${t}`;return this.definitions.get(n)}async listDefinitions(){return[...this.definitions.values()].sort((e,t)=>e.dagId.localeCompare(t.dagId)||e.version-t.version)}async listDefinitionsByDagId(e){return[...this.definitions.values()].filter(t=>t.dagId===e).sort((e,t)=>e.version-t.version)}async getLatestPublishedDefinition(e){let t=this.latestPublishedVersionByDagId.get(e);if(t)return this.definitions.get(`${e}:${t}`)}async deleteDefinition(e,t){this.definitions.delete(`${e}:${t}`);let n=[...this.definitions.values()].filter(t=>t.dagId===e&&t.status===`published`).sort((e,t)=>e.version-t.version);if(n.length===0){this.latestPublishedVersionByDagId.delete(e);return}this.latestPublishedVersionByDagId.set(e,n[n.length-1].version)}async createDagRun(e){this.dagRuns.set(e.dagRunId,e)}async getDagRun(e){return this.dagRuns.get(e)}async listDagRuns(){return[...this.dagRuns.values()].sort((e,t)=>e.dagRunId.localeCompare(t.dagRunId))}async getDagRunByRunKey(e){for(let t of this.dagRuns.values())if(t.runKey===e)return t}async updateDagRunStatus(e,t,n){let r=this.dagRuns.get(e);if(!r)return;let i={...r,status:t,endedAt:n};this.dagRuns.set(e,i)}async deleteDagRun(e){this.dagRuns.delete(e)}async createTaskRun(e){let t=u2(e.dagRunId,e.taskRunId);this.taskRuns.set(t,e)}async getTaskRun(e){for(let t of this.taskRuns.values())if(t.taskRunId===e)return t}async listTaskRunsByDagRunId(e){let t=[];for(let n of this.taskRuns.values())n.dagRunId===e&&t.push(n);return t}async deleteTaskRunsByDagRunId(e){for(let[t,n]of this.taskRuns.entries())n.dagRunId===e&&this.taskRuns.delete(t)}async updateTaskRunStatus(e,t,n){for(let[r,i]of this.taskRuns.entries()){if(i.taskRunId!==e)continue;let a={...i,status:t,...[`failed`,`cancelled`,`queued`].includes(t)?{reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0}:{},errorCode:n?.code,errorMessage:n?.message};this.taskRuns.set(r,a);return}}async setTaskRunLease(e,t,n){LIe(this.taskRuns,e,t,n)}async listStaleRunningTaskRuns(e){return RIe(this.taskRuns,e)}async saveTaskRunSnapshots(e,t,n,r,i){for(let[a,o]of this.taskRuns.entries()){if(o.taskRunId!==e)continue;let s={...o,inputSnapshot:typeof t==`string`?t:o.inputSnapshot,outputSnapshot:typeof n==`string`?n:o.outputSnapshot,estimatedCredits:typeof r==`number`?r:o.estimatedCredits,totalCredits:typeof i==`number`?i:o.totalCredits};this.taskRuns.set(a,s);return}}async incrementTaskAttempt(e){for(let[t,n]of this.taskRuns.entries()){if(n.taskRunId!==e)continue;let r={...n,attempt:n.attempt+1,reservedCredits:void 0,reservationAttempt:void 0,reservationOwner:void 0};this.taskRuns.set(t,r);return}}},d2=class{pendingQueue=[];inFlight=new Map;waiters=[];async enqueue(e){this.pendingQueue.push(e),this.notifyNextWaiter()}async dequeue(e,t,n=0){let r=this.tryDequeue(e,t);return r||n<=0?r:(await this.waitForMessage(n),this.tryDequeue(e,t))}async ack(e){this.inFlight.delete(e)}async nack(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.pendingQueue.unshift(t.message),this.notifyNextWaiter())}tryDequeue(e,t){this.requeueExpiredMessages();let n=this.pendingQueue.shift();if(!n)return;let r=Date.now();return this.inFlight.set(n.messageId,{message:n,ownerId:e,visibleAtEpochMs:r+t}),n}requeueExpiredMessages(){let e=Date.now();for(let[t,n]of this.inFlight.entries())n.visibleAtEpochMs>e||(this.inFlight.delete(t),this.pendingQueue.push(n.message))}async waitForMessage(e){return new Promise(t=>{let n={resolve:()=>{clearTimeout(n.timeout),this.removeWaiter(n),t()},timeout:setTimeout(()=>{n.resolve()},e)};this.waiters.push(n)})}notifyNextWaiter(){this.waiters.shift()?.resolve()}removeWaiter(e){let t=this.waiters.indexOf(e);t>=0&&this.waiters.splice(t,1)}},BIe=class{records=new Map;async acquire(e,t,n){let r=new Date().toISOString(),i=Date.now(),a=this.records.get(e);if(a&&Date.parse(a.leaseUntil)>i)return;let o={leaseKey:e,ownerId:t,acquiredAt:r,leaseUntil:new Date(i+n).toISOString()};return this.records.set(e,o),o}async release(e,t){let n=this.records.get(e);!n||n.ownerId!==t||this.records.delete(e)}async get(e){return this.records.get(e)}},VIe=class{nowIso(){return new Date().toISOString()}nowEpochMs(){return Date.now()}},HIe=class{listeners=new Set;logger;constructor(e){this.logger=e}publish(e){let t=[];for(let n of[...this.listeners])try{n(e)}catch(n){t.push(n),this.logger&&this.logger.error(`RunProgressEventBus listener threw an error`,{eventType:e.eventType,error:n instanceof Error?n.message:String(n)})}if(t.length>0&&!this.logger)throw t[0]instanceof Error?t[0]:Error(String(t[0]))}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}};function UIe(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t||Array.isArray(t)?{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_INVALID`,`Payload must be a JSON object`)}:{ok:!0,value:t}}catch{return{ok:!1,error:Q(`DAG_VALIDATION_PAYLOAD_PARSE_FAILED`,`Failed to parse payload JSON`)}}}function WIe(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse definition snapshot JSON`)}}return u0(t,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`Definition snapshot must be a valid DAG definition object`)}async function GIe(e,t,n,r,i){let{dagRunId:a,definition:o,input:s}=e,c=o.nodes.filter(e=>e.dependsOn.length===0);if(c.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_NO_ENTRY_NODE`,`DAG must include at least one entry node (dependsOn = [])`,{dagId:o.dagId,version:o.version})};let l=Y1.transition(`created`,`QUEUE`);if(!l.ok)return l;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`created`,event:`QUEUE`})).applied)return{ok:!0,value:{taskRunIds:[]}};let u=Y1.transition(`queued`,`START`);if(!u.ok)return u;if(!(await t.commitExecution(a,{kind:`transition-run`,expectedStatus:`queued`,event:`START`})).applied)return{ok:!0,value:{taskRunIds:[]}};i?.publish({dagRunId:a,eventType:e2.STARTED,occurredAt:r.nowIso(),dagId:o.dagId,version:o.version});let d=[],f=[];for(let e of c){let n=`${a}:${e.nodeId}:attempt:1`;(await t.commitExecution(a,{kind:`admit`,dependsOn:[],taskRun:{taskRunId:n,dagRunId:a,nodeId:e.nodeId,status:`queued`,attempt:1}})).applied&&(d.push(n),f.push({messageId:`${n}:message`,dagRunId:a,taskRunId:n,nodeId:e.nodeId,attempt:1,executionPath:[`dagId:${o.dagId}`,`dagRunId:${a}`,`nodeId:${e.nodeId}`,`taskRunId:${n}`,`attempt:1`],payload:s,createdAt:r.nowIso()}))}for(let e of f)try{await n.enqueue(e)}catch(n){return KIe(a,e.taskRunId,e.nodeId,d,n,t,r,i)}return{ok:!0,value:{taskRunIds:d}}}async function KIe(e,t,n,r,i,a,o,s){let c=R1(`DAG_DISPATCH_ENQUEUE_FAILED`,`Failed to enqueue entry task`,{dagRunId:e,taskRunId:t,nodeId:n,errorMessage:i instanceof Error&&i.message.trim().length>0?i.message:`Unknown error`});Y1.transition(`running`,`COMPLETE_FAILURE`).ok&&(await a.commitExecution(e,{kind:`transition-run`,expectedStatus:`running`,event:`COMPLETE_FAILURE`,endedAt:o.nowIso()})).applied&&s?.publish({dagRunId:e,eventType:e2.FAILED,occurredAt:o.nowIso(),error:c});for(let t of r)await a.commitExecution(e,{kind:`cancel-task`,taskRunId:t,error:c});return{ok:!1,error:c}}function qIe(e,t){return e===void 0||t===void 0?e===t:e.rootRunId===t.rootRunId&&e.parentRunId===t.parentRunId&&e.depth===t.depth&&e.maxDepth===t.maxDepth&&e.ancestorCompositeNodeTypes.length===t.ancestorCompositeNodeTypes.length&&e.ancestorCompositeNodeTypes.every((e,n)=>e===t.ancestorCompositeNodeTypes[n])}var JIe=class{storage;queue;clock;runProgressEventReporter;snapshotBudget;timeSemanticsService;constructor(e,t,n,r,i){this.storage=e,this.queue=t,this.clock=n,this.runProgressEventReporter=r,this.snapshotBudget=i,this.timeSemanticsService=new gIe(n)}async createRun(e){let t=e.version?await this.storage.getDefinition(e.dagId,e.version):await this.storage.getLatestPublishedDefinition(e.dagId);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_FOUND`,`Published DAG definition was not found`,{dagId:e.dagId,hasVersion:!!e.version})};if(t.status!==`published`)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_NOT_PUBLISHED`,`Only published definitions can be executed`,{dagId:t.dagId,version:t.version,status:t.status})};let n=this.timeSemanticsService.resolve(e.trigger,e.logicalDate);if(!n.ok)return n;let r;try{r=$0(e.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Composite child run lineage is invalid`,{dagId:t.dagId})}}let i=e.rerunKey?`${t.dagId}:${n.value.logicalDate}:rerun:${e.rerunKey}`:`${t.dagId}:${n.value.logicalDate}`,a=await this.storage.getDagRunByRunKey(i);if(a){let e;try{e=$0(a.lineage)}catch{return{ok:!1,error:Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Existing run for this run key has invalid persisted lineage`,{dagId:t.dagId,runKey:i})}}return qIe(e,r)?{ok:!0,value:{dagRunId:a.dagRunId,dagId:a.dagId,version:a.version,logicalDate:a.logicalDate,status:a.status}}:{ok:!1,error:Q(`DAG_VALIDATION_RUN_KEY_LINEAGE_MISMATCH`,`An existing run for this run key has different composite lineage`,{dagId:t.dagId,runKey:i,existingDagRunId:a.dagRunId})}}let o=this.generateDagRunId(t.dagId,n.value.logicalDate,e.rerunKey);try{let a=(a,s)=>this.storage.createDagRun({dagRunId:o,dagId:t.dagId,version:t.version,status:`created`,definitionSnapshot:a,inputSnapshot:s,runKey:i,logicalDate:n.value.logicalDate,trigger:e.trigger,...r===void 0?{}:{lineage:r},startedAt:this.clock.nowIso()});if(this.snapshotBudget){let n=await this.snapshotBudget.admitRun(t,e.input,a);if(!n.ok)return n}else await a(JSON.stringify(t),JSON.stringify(e.input))}catch(e){return this.snapshotBudget?{ok:!1,error:z1(`DAG_RUN_SNAPSHOT_PERSISTENCE_UNCERTAIN`,`Run snapshot persistence outcome is uncertain; root snapshot admission is closed`,!1)}:{ok:!1,error:R1(`DAG_DISPATCH_DAG_RUN_CREATE_FAILED`,`Failed to create DagRun`,{dagId:t.dagId,version:t.version,runKey:i,errorMessage:this.resolveErrorMessage(e instanceof Error?e:void 0)})}}return{ok:!0,value:{dagRunId:o,dagId:t.dagId,version:t.version,logicalDate:n.value.logicalDate,status:`created`}}}async startCreatedRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};if(t.status!==`created`){let n=await this.storage.listTaskRunsByDagRunId(e);return{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}if(typeof t.definitionSnapshot!=`string`||t.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:e})};let n=WIe(t.definitionSnapshot);if(!n.ok)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot is invalid`,{dagRunId:e})};let r=UIe(t.inputSnapshot??`{}`);if(!r.ok)return{ok:!1,error:Q(`DAG_VALIDATION_RUN_INPUT_SNAPSHOT_INVALID`,`DagRun input snapshot is invalid`,{dagRunId:e})};let i=await GIe({dagRunId:e,definition:n.value,input:r.value},this.storage,this.queue,this.clock,this.runProgressEventReporter);return i.ok?{ok:!0,value:{dagRunId:e,dagId:t.dagId,version:t.version,logicalDate:t.logicalDate,taskRunIds:i.value.taskRunIds}}:i}async startRun(e){let t=await this.createRun(e);if(!t.ok)return t;if(t.value.status===`created`)return this.startCreatedRun(t.value.dagRunId);let n=await this.storage.listTaskRunsByDagRunId(t.value.dagRunId);return{ok:!0,value:{dagRunId:t.value.dagRunId,dagId:t.value.dagId,version:t.value.version,logicalDate:t.value.logicalDate,taskRunIds:n.map(e=>e.taskRunId)}}}generateDagRunId(e,t,n){let r=Date.parse(t);return n?`${e}:run:${r}:rerun:${n}`:`${e}:run:${r}`}resolveErrorMessage(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}},YIe=class{storage;constructor(e){this.storage=e}async getRun(e){let t=await this.storage.getDagRun(e);return t?{ok:!0,value:{dagRun:t,taskRuns:await this.storage.listTaskRunsByDagRunId(e)}}:{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}},XIe=class{storage;clock;notifier;constructor(e,t,n){this.storage=e,this.clock=t,this.notifier=n}async cancelRun(e){let t=await this.storage.getDagRun(e);if(!t)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})};let n=Y1.transition(t.status,`CANCEL`);if(!n.ok)return n;let r=await this.storage.commitExecution(e,{kind:`transition-run`,expectedStatus:t.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(!r.applied){if(r.runStatus===`cancelled`)return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}};if(r.runStatus!==void 0){let t=Y1.transition(r.runStatus,`CANCEL`);return t.ok?this.cancelRun(e):t}return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun was not found`,{dagRunId:e})}}return this.notify(e),{ok:!0,value:{dagRunId:e,status:`cancelled`}}}notify(e){try{this.notifier?.notifyRunCancelled(e)}catch{}}};async function f2(e,t,n,r){let i=await t.commitExecution(e,{kind:`finalize`,endedAt:n.nowIso()});if(i.error)return{ok:!1,error:i.error};if(i.runStatus===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found while finalizing run status`,{dagRunId:e})};if(!i.applied)return{ok:!0,value:void 0};let a=i.runStatus===`failed`,o=await t.listTaskRunsByDagRunId(e);return a?ZIe(e,o,n,r):r?.publish({dagRunId:e,eventType:e2.COMPLETED,occurredAt:n.nowIso()}),{ok:!0,value:void 0}}function ZIe(e,t,n,r){let i=t.find(e=>e.status===`failed`),a=typeof i?.errorCode==`string`&&typeof i.errorMessage==`string`?z1(i.errorCode,i.errorMessage,!1,{dagRunId:e,taskRunId:i.taskRunId,nodeId:i.nodeId}):z1(`DAG_TASK_EXECUTION_FAILED`,`Run completed with failure.`,!1,{dagRunId:e});r?.publish({dagRunId:e,eventType:e2.FAILED,occurredAt:n.nowIso(),error:a})}async function p2(e,t,n,r,i){await e.updateTaskRunStatus(n.taskRunId,r,i),await e.setTaskRunLease(n.taskRunId,void 0,void 0),await f2(n.dagRunId,e,t)}async function QIe(e,t){let n=X1.transition(t.status,`CANCEL`);return n.ok?(await e.updateTaskRunStatus(t.taskRunId,n.value.nextStatus,{code:`DAG_TASK_EXECUTION_ORPHANED`,category:`task_execution`,message:`Task's DAG run ${t.dagRunId} no longer exists; the task cannot be run or finalized`,retryable:!1,context:{taskRunId:t.taskRunId,dagRunId:t.dagRunId}}),await e.setTaskRunLease(t.taskRunId,void 0,void 0),{ok:!0,value:void 0}):n}async function $Ie(e,t,n,r,i){let a=await e.listStaleRunningTaskRuns(n.nowIso()),o={requeued:[],abandoned:[],skipped:[],failed:[],orphaned:[]};for(let s of a){let a=`taskRun:${s.taskRunId}`;if(!await r.acquire(a,i.workerId,i.leaseDurationMs)){o.skipped.push(s.taskRunId);continue}try{let r=await e.getTaskRun(s.taskRunId);if(r===void 0||r.status!==`running`||iLe(r,n.nowIso())){o.skipped.push(s.taskRunId);continue}await eLe(e,t,n,r,i.maxAttempts,o)}catch(e){o.failed.push({taskRunId:s.taskRunId,error:e})}finally{await r.release(a,i.workerId)}}return o}async function eLe(e,t,n,r,i,a){{let o=X1.transition(r.status,`RECLAIM`);if(!o.ok){a.skipped.push(r.taskRunId);return}let s=await e.getDagRun(r.dagRunId);if(s===void 0){if(!(await QIe(e,r)).ok){a.skipped.push(r.taskRunId);return}a.orphaned.push(r.taskRunId);return}if(tLe.has(s.status)){let t=X1.transition(r.status,`CANCEL`);if(!t.ok){a.skipped.push(r.taskRunId);return}await p2(e,n,r,t.value.nextStatus),a.abandoned.push(r.taskRunId);return}if(r.attempt>=i){let t=X1.transition(r.status,`COMPLETE_FAILURE`);if(!t.ok){a.skipped.push(r.taskRunId);return}await p2(e,n,r,t.value.nextStatus,{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${r.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:r.taskRunId,attempt:r.attempt,maxAttempts:i}}),a.abandoned.push(r.taskRunId);return}let c=r.attempt+1;await e.incrementTaskAttempt(r.taskRunId),await t.enqueue(nLe(r,c,n.nowIso())),await e.updateTaskRunStatus(r.taskRunId,o.value.nextStatus),await e.setTaskRunLease(r.taskRunId,void 0,void 0),a.requeued.push(r.taskRunId)}}const tLe=new Set([`success`,`failed`,`cancelled`]);function nLe(e,t,n){return{payload:rLe(e.inputSnapshot),messageId:`${e.taskRunId}:reclaim:${t}`,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:t,executionPath:[`dagRunId:${e.dagRunId}`,`nodeId:${e.nodeId}`,`taskRunId:${e.taskRunId}`,`attempt:${t}`,`reclaimed:true`],createdAt:n}}function rLe(e){if(e===void 0)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function iLe(e,t){return e.leaseUntil!==void 0&&e.leaseUntil>t}var aLe=class{clock;lease;options;lastSweepAtMs=0;sweeping=!1;constructor(e,t,n){this.clock=e,this.lease=t,this.options=n}async sweepIfDue(e,t){let n=this.clock.nowEpochMs();if(!(this.sweeping||n-this.lastSweepAtMs<this.options.leaseDurationMs)){this.sweeping=!0;try{let n=(await $Ie(e,t,this.clock,this.lease,this.options)).failed[0];if(n===void 0)return;throw n.error}catch(e){return{code:`DAG_TASK_SWEEP_FAILED`,category:`task_execution`,message:`Stale-task sweep failed: ${e instanceof Error?e.message:String(e)}`,retryable:!0,context:{workerId:this.options.workerId}}}finally{this.lastSweepAtMs=this.clock.nowEpochMs(),this.sweeping=!1}}}};function oLe(e,t){let n=e.map(e=>e.startsWith(`attempt:`)?`attempt:${t}`:e);return n.some(e=>e.startsWith(`attempt:`))||n.push(`attempt:${t}`),n}function m2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function h2(e,t,n,r,i,a,o,s){if(r.deadLetterEnabled){let t=await cLe(e,n,r,o);if(!t.ok)return g2(a,e.messageId,t.error)}let c=await f2(e.dagRunId,i,o,s);return c.ok?_2(a,e.messageId,t,!1):g2(a,e.messageId,c.error)}async function sLe(e,t,n,r){let i=e.attempt+1,a={...e,messageId:`${e.taskRunId}:message:${i}`,attempt:i,executionPath:oLe(e.executionPath,i),createdAt:r.nowIso()};try{await n.enqueue(a)}catch(r){return g2(n,e.messageId,R1(`DAG_DISPATCH_ENQUEUE_RETRY_FAILED`,`Failed to enqueue retry message`,{taskRunId:t,attempt:i,errorMessage:m2(r)}))}return _2(n,e.messageId,t,!0)}async function cLe(e,t,n,r){if(!n.deadLetterQueue)return{ok:!1,error:Q(`DAG_VALIDATION_DEAD_LETTER_QUEUE_NOT_CONFIGURED`,`deadLetterEnabled requires deadLetterQueue to be configured`,{taskRunId:e.taskRunId})};let i={...e,messageId:`${e.taskRunId}:dlq:${r.nowEpochMs()}`,payload:{...e.payload,dlqReasonCode:t.code,dlqReasonMessage:t.message,dlqSourceMessageId:e.messageId},createdAt:r.nowIso()};try{return await n.deadLetterQueue.enqueue(i),{ok:!0,value:void 0}}catch(t){return{ok:!1,error:R1(`DAG_DISPATCH_DEAD_LETTER_ENQUEUE_FAILED`,`Failed to enqueue dead letter message`,{taskRunId:e.taskRunId,originalMessageId:e.messageId,errorMessage:m2(t)})}}}async function g2(e,t,n){return await e.ack(t),{ok:!1,error:n}}async function _2(e,t,n,r){return await e.ack(t),{ok:!0,value:{processed:!0,taskRunId:n,retried:r}}}function lLe(e){if(e.status!==`running`)return{ok:!0,value:e.status};let t=X1.transition(e.status,`RECLAIM`);return t.ok?{ok:!0,value:t.value.nextStatus}:t}function v2(e,t){return Math.max(e,t)+3e4}function uLe(e,t,n){return new Date(e.nowEpochMs()+v2(t,n)).toISOString()}async function dLe(e){let{storage:t,clock:n,message:r,taskRun:i}=e,a=i.status===`running`,o=lLe(i);if(!o.ok)return o;if(a){if(i.attempt>=e.options.maxAttempts)return{ok:!1,error:{code:`DAG_TASK_EXECUTION_ABANDONED`,category:`task_execution`,message:`Task was abandoned by its worker ${i.attempt} time(s) and has no attempts left`,retryable:!1,context:{taskRunId:i.taskRunId,attempt:i.attempt,maxAttempts:e.options.maxAttempts}}};await t.incrementTaskAttempt(i.taskRunId)}let s=a?i.attempt+1:i.attempt,c=X1.transition(o.value,`START`);return c.ok?(await t.setTaskRunLease(i.taskRunId,e.options.workerId,uLe(n,e.timeoutMs,e.options.leaseDurationMs)),await t.updateTaskRunStatus(i.taskRunId,c.value.nextStatus),e.reporter?.publish({dagRunId:r.dagRunId,eventType:t2.STARTED,occurredAt:n.nowIso(),taskRunId:i.taskRunId,nodeId:r.nodeId,input:r.payload}),{ok:!0,value:s}):c}async function fLe(e,t,n,r,i,a){let o=`taskRun:${t}`;if(!await e.acquire(o,n,r))return a();try{return await i()}finally{await e.release(o,n)}}async function pLe(e,t){let{message:n,taskRun:r,storage:i,queue:a,clock:o}=t;if(e.code!==`DAG_TASK_EXECUTION_ABANDONED`)return g2(a,n.messageId,e);let s=X1.transition(r.status,`COMPLETE_FAILURE`);return s.ok?(await i.updateTaskRunStatus(r.taskRunId,s.value.nextStatus,e),await i.setTaskRunLease(r.taskRunId,void 0,void 0),h2(n,r.taskRunId,e,t.options,i,a,o,t.reporter)):g2(a,n.messageId,s.error)}function mLe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function hLe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function gLe(e,t,n){let r=e.nodes.find(e=>e.nodeId===n);if(!r)return{ok:!1,error:Q(`DAG_VALIDATION_DOWNSTREAM_NODE_NOT_FOUND`,`Downstream node was not found while building payload`,{downstreamNodeId:n})};let i=e.edges.filter(e=>e.to===n);if(i.length===0)return{ok:!0,value:{}};let a={};for(let e of i){let n=_Le(a,e,r,t);if(!n.ok)return n}return SLe(a,r.inputs??[]),{ok:!0,value:a}}function _Le(e,t,n,r){if(!t.bindings||t.bindings.length===0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_REQUIRED`,`Incoming edge must define at least one binding`,{from:t.from,to:t.to})};let i=vLe(t.from,t.to,r);if(!i.ok)return i;let a=i.value;for(let r of t.bindings){let i=yLe(e,r,a,t,n);if(!i.ok)return i}return{ok:!0,value:void 0}}function vLe(e,t,n){let r=n.find(t=>t.nodeId===e&&t.status===`success`);if(!r||!r.outputSnapshot)return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_MISSING`,`Upstream output snapshot is missing for binding dispatch`,{from:e,to:t})};try{let n=JSON.parse(r.outputSnapshot);return hLe(n)?{ok:!0,value:n}:{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_INVALID`,`Upstream output snapshot has invalid payload shape`,{from:e,to:t})}}catch(n){return{ok:!1,error:Q(`DAG_VALIDATION_UPSTREAM_OUTPUT_PARSE_FAILED`,`Failed to parse upstream output snapshot`,{from:e,to:t,errorMessage:mLe(n)})}}}function yLe(e,t,n,r,i){let a=n[t.outputKey];if(a===void 0)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_OUTPUT_KEY_MISSING`,`Binding outputKey was not found in upstream output`,{from:r.from,outputKey:t.outputKey})};if((i.inputs??[]).find(e=>e.key===t.inputKey)?.isList)return bLe(e,t.inputKey,a,r.to);let o=_0(t.inputKey);return o?xLe(e,o,a,t.inputKey,r.to,i):e[t.inputKey]===void 0?(e[t.inputKey]=a,{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_CONFLICT`,`Multiple bindings target the same input key`,{to:r.to,inputKey:t.inputKey})}}function bLe(e,t,n,r){Array.isArray(e[t])||(e[t]=[]);let i=e[t];return Array.isArray(i)?(i.push(n),{ok:!0,value:void 0}):{ok:!1,error:Q(`DAG_VALIDATION_BINDING_LIST_PAYLOAD_INVALID`,`List payload container is invalid`,{to:r,inputKey:t})}}function xLe(e,t,n,r,i,a){if(!(a.inputs??[]).find(e=>e.key===t.portKey)?.isList)return{ok:!1,error:Q(`DAG_VALIDATION_BINDING_INPUT_KEY_MISSING`,`Binding inputKey does not resolve to a valid list input port`,{to:i,inputKey:r})};let o=e[t.portKey],s=Array.isArray(o)?o:[];return s[t.index]=n,e[t.portKey]=s,{ok:!0,value:void 0}}function SLe(e,t){for(let n of t){if(!n.isList)continue;let t=e[n.key];Array.isArray(t)&&(e[n.key]=t.filter(e=>e!==void 0))}}function CLe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}async function wLe(e,t,n,r,i,a,o){let s=t.nodes.filter(e=>e.dependsOn.includes(n));if(s.length===0)return{ok:!0,value:void 0};let c=await i.listTaskRunsByDagRunId(e.dagRunId);for(let n of s){let r=await TLe(e,t,n,c,i,a,o);if(!r.ok)return r}return{ok:!0,value:void 0}}async function TLe(e,t,n,r,i,a,o){if(r.some(e=>e.nodeId===n.nodeId)||!n.dependsOn.every(e=>r.some(t=>t.nodeId===e&&t.status===`success`)))return{ok:!0,value:void 0};let s=`${e.dagRunId}:${n.nodeId}:attempt:1`;if(!(await i.commitExecution(e.dagRunId,{kind:`admit`,dependsOn:n.dependsOn,taskRun:{taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}})).applied)return{ok:!0,value:void 0};let c=gLe(t,r,n.nodeId);if(!c.ok)return c;let l={messageId:`${s}:message:1`,dagRunId:e.dagRunId,taskRunId:s,nodeId:n.nodeId,attempt:1,executionPath:[`dagId:${e.dagId}`,`dagRunId:${e.dagRunId}`,`nodeId:${n.nodeId}`,`taskRunId:${s}`,`attempt:1`],payload:c.value,createdAt:o.nowIso()};try{await a.enqueue(l)}catch(t){let r=X1.transition(`queued`,`CANCEL`);return r.ok&&await i.updateTaskRunStatus(s,r.value.nextStatus),{ok:!1,error:R1(`DAG_DISPATCH_ENQUEUE_DOWNSTREAM_FAILED`,`Failed to enqueue downstream task`,{dagRunId:e.dagRunId,nodeId:n.nodeId,errorMessage:CLe(t)})}}return r.push({taskRunId:s,dagRunId:e.dagRunId,nodeId:n.nodeId,status:`queued`,attempt:1}),{ok:!0,value:void 0}}var ELe=class{storage;queue;clock;options;runProgressEventReporter;snapshotBudget;constructor(e,t,n,r,i,a){this.storage=e,this.queue=t,this.clock=n,this.options=r,this.runProgressEventReporter=i,this.snapshotBudget=a}async handleSuccessPath(e,t,n,r,i,a,o){let s=n=>this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`success`,outputSnapshot:n,estimatedCredits:a,totalCredits:o}),c=this.snapshotBudget?await this.snapshotBudget.admitValue(`output`,i,s):{ok:!0,value:await s(JSON.stringify(i))};if(!c.ok)return this.handleFailurePath(e,t,c.error);if(!c.value.applied){let[n,r]=await Promise.all([this.storage.getDagRun(e.dagRunId),this.storage.getTaskRun(t)]);return n?.status===`running`&&r?.status===`running`&&r.attempt===e.attempt&&r.leaseOwner===this.options.workerId?this.handleFailurePath(e,t,Q(`DAG_VALIDATION_EXECUTION_SETTLEMENT_REJECTED`,`Current task attempt could not settle its successful output`,{taskRunId:t})):_2(this.queue,e.messageId,t,!1)}this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:t2.COMPLETED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,output:i});let l=await wLe(n,r,e.nodeId,i,this.storage,this.queue,this.clock);if(!l.ok)return g2(this.queue,e.messageId,l.error);let u=await f2(e.dagRunId,this.storage,this.clock,this.runProgressEventReporter);return u.ok?_2(this.queue,e.messageId,t,!1):g2(this.queue,e.messageId,u.error)}async handleFailurePath(e,t,n){let r=this.options.retryEnabled&&n.retryable&&e.attempt<this.options.maxAttempts;return(await this.storage.commitExecution(e.dagRunId,{kind:`settle`,taskRunId:t,attempt:e.attempt,leaseOwner:this.options.workerId,status:`failed`,reserveRetry:r,error:n})).applied?(this.runProgressEventReporter?.publish({dagRunId:e.dagRunId,eventType:t2.FAILED,occurredAt:this.clock.nowIso(),taskRunId:t,nodeId:e.nodeId,input:e.payload,error:n}),r?sLe(e,t,this.queue,this.clock):h2(e,t,n,this.options,this.storage,this.queue,this.clock,this.runProgressEventReporter)):_2(this.queue,e.messageId,t,!1)}};function DLe(e,t){return z1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${t}ms`,!0,{taskRunId:e,timeoutMs:t})}function y2(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function b2(e,t,n,r){return new Promise(i=>{let a=new AbortController,o=!1,s,c=e=>{o||(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),i(e))},l=n=>{if(!o){if(o=!0,clearTimeout(s),t.signal?.removeEventListener(`abort`,u),a.abort(n),!e.stopAndWait){i({ok:!1,error:n});return}Promise.resolve().then(()=>e.stopAndWait?.(t)).then(()=>i({ok:!1,error:n}),e=>i({ok:!1,error:{...n,retryable:!1,context:{...n.context,isolationStopError:y2(e)}}}))}},u=()=>l(B1(r));if(t.signal?.aborted){u();return}t.signal?.addEventListener(`abort`,u,{once:!0}),s=setTimeout(()=>l(DLe(r,n)),n);let d=e=>c({ok:!1,error:z1(`DAG_TASK_EXECUTION_EXCEPTION`,`Task executor threw an exception`,!0,{taskRunId:r,errorMessage:y2(e)})});try{e.execute({...t,signal:a.signal}).then(c,d)}catch(e){d(e)}})}function OLe(e){let t=0;for(let n of e)typeof n.totalCredits==`number`&&n.totalCredits>t&&(t=n.totalCredits);return t}function kLe(e){return e instanceof Error&&e.message.trim().length>0?e.message:`Unknown error`}function ALe(e,t){if(typeof e.definitionSnapshot!=`string`||e.definitionSnapshot.trim().length===0)return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_MISSING`,`DagRun definition snapshot is missing`,{dagRunId:t})};let n;try{n=JSON.parse(e.definitionSnapshot)}catch(e){return{ok:!1,error:Q(`DAG_VALIDATION_DEFINITION_SNAPSHOT_PARSE_FAILED`,`Failed to parse DagRun definition snapshot`,{dagRunId:t,errorMessage:kLe(e)})}}return u0(n,`DAG_VALIDATION_DEFINITION_SNAPSHOT_INVALID`,`DagRun definition snapshot has invalid shape`,{dagRunId:t})}async function x2(e,t){let n=await e.getDagRun(t.dagRunId);if(!n)return{ok:!1,error:Q(`DAG_VALIDATION_DAG_RUN_NOT_FOUND`,`DagRun not found for dequeued message`,{dagRunId:t.dagRunId})};let r=ALe(n,t.dagRunId);if(!r.ok)return r;let i=r.value,a=i.nodes.find(e=>e.nodeId===t.nodeId);return a?{ok:!0,value:{dagRun:n,definition:i,nodeDefinition:a}}:{ok:!1,error:Q(`DAG_VALIDATION_NODE_NOT_FOUND`,`Node definition not found for task execution`,{nodeId:t.nodeId,dagId:n.dagId,version:n.version})}}var jLe=class{storage;queue;lease;executor;clock;options;runProgressEventReporter;snapshotBudget;rootCreditBudget;lifecycleCreditAdmission;executionRoot;byteLimits;cancellationPollMs;activeAttempts=new Set;notifyRunCancelled(e){for(let t of this.activeAttempts)t.dagRunId===e&&t.controller.abort()}constructor(e,t,n,r,i,a,o,s,c,l,u,d=!1){if(this.storage=e,this.queue=t,this.lease=n,this.executor=r,this.clock=i,this.options=o,this.runProgressEventReporter=s,this.snapshotBudget=l,this.rootCreditBudget=u,this.lifecycleCreditAdmission=d,this.executionRoot=en(a),this.byteLimits=K1(c),this.cancellationPollMs=o.cancellationPollMs??250,!Number.isSafeInteger(this.cancellationPollMs)||this.cancellationPollMs<1||this.cancellationPollMs>6e4)throw RangeError(`cancellationPollMs must be an integer between 1 and 60000`)}sweeper;outcomesInstance;get outcomes(){return this.outcomesInstance??=new ELe(this.storage,this.queue,this.clock,this.options,this.runProgressEventReporter,this.snapshotBudget),this.outcomesInstance}async processOnce(){let e=await this.queue.dequeue(this.options.workerId,this.options.visibilityTimeoutMs,this.options.idleWaitMs);if(!e){this.sweeper??=new aLe(this.clock,this.lease,this.options);let e=await this.sweeper.sweepIfDue(this.storage,this.queue);return e?{ok:!1,error:e}:{ok:!0,value:{processed:!1}}}let t=await this.resolveTimeoutMs(e);return fLe(this.lease,e.taskRunId,this.options.workerId,v2(t,this.options.leaseDurationMs),async()=>this.processAcquiredMessage(e,t),async()=>(await this.queue.nack(e.messageId),{ok:!0,value:{processed:!1}}))}async processAcquiredMessage(e,t){let n=await this.storage.getTaskRun(e.taskRunId);if(!n){let t=Q(`DAG_VALIDATION_TASK_RUN_NOT_FOUND`,`TaskRun not found for dequeued message`,{taskRunId:e.taskRunId});return g2(this.queue,e.messageId,t)}let r=await this.cancelIfRunCancelled(e);if(r)return r;let i=this.claimDepsFor(e,n,t),a=await dLe(i);if(!a.ok)return pLe(a.error,i);let o={...e,attempt:a.value},s=await x2(this.storage,o);if(!s.ok)return g2(this.queue,e.messageId,s.error);let{dagRun:c,definition:l,nodeDefinition:u}=s.value;if(c.status===`cancelled`)return this.settleCancelledRunMessage(e);let d;try{d=$0(c.lineage)}catch{return this.outcomes.handleFailurePath(o,o.taskRunId,Q(`DAG_VALIDATION_RUN_LINEAGE_INVALID`,`Persisted composite child run lineage is invalid`,{dagRunId:o.dagRunId}))}if(d){let t=await this.cancelIfAncestorCancelled(e,c,d);if(t)return t}let f=e=>this.storage.commitExecution(o.dagRunId,{kind:`snapshot-input`,taskRunId:o.taskRunId,attempt:o.attempt,leaseOwner:this.options.workerId,inputSnapshot:e}),p=this.snapshotBudget?await this.snapshotBudget.admitValue(`input`,o.payload,f):{ok:!0,value:await f(JSON.stringify(o.payload))};if(!p.ok)return this.outcomes.handleFailurePath(o,o.taskRunId,p.error);if(!p.value.applied)return _2(this.queue,e.messageId,o.taskRunId,!1);let m=await this.buildExecutionInput(o,c,l,u,d),h=new AbortController,g={dagRunId:o.dagRunId,taskRunId:o.taskRunId,attempt:o.attempt,controller:h};this.activeAttempts.add(g);let _,v,y=Date.now()+i.timeoutMs,b;try{let t=await this.cancelIfRunCancelled(e);if(t)return t;if(b=this.watchCommittedCancellation(g),l.costPolicy&&!this.lifecycleCreditAdmission&&!(this.executor instanceof r2)){let t=this.executor.estimateCost;if(!t)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_REQUIRED`,`Cost-limited runs require a custom executor to estimate credits before execution`,{taskRunId:o.taskRunId}));let r=await b2({execute:async e=>{let n=await t.call(this.executor,e);return n.ok?{ok:!0,output:{},estimatedCredits:n.value}:n},...this.executor.stopAndWait?{stopAndWait:this.executor.stopAndWait.bind(this.executor)}:{}},{...m,signal:h.signal},Math.max(1,y-Date.now()),e.taskRunId);if(!r.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,r.error);if(r.estimatedCredits===void 0||!Number.isFinite(r.estimatedCredits)||r.estimatedCredits<0)return this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_INVALID`,`Custom executor credit estimate must be a finite nonnegative number`,{taskRunId:o.taskRunId}));let i=await m.reserveCredits(r.estimatedCredits);if(!i.ok)return this.outcomes.handleFailurePath(o,n.taskRunId,i.error);v=r.estimatedCredits}let r=y-Date.now();if(r<=0)return this.outcomes.handleFailurePath(o,n.taskRunId,z1(`DAG_TASK_EXECUTION_TIMEOUT`,`Task execution timed out after ${i.timeoutMs}ms`,!0,{taskRunId:e.taskRunId,timeoutMs:i.timeoutMs}));_=await b2(this.executor,{...m,signal:h.signal},r,e.taskRunId)}finally{b?.(),this.activeAttempts.delete(g)}return _.ok?v!==void 0&&_.estimatedCredits!==void 0&&_.estimatedCredits!==v?this.outcomes.handleFailurePath(o,n.taskRunId,Q(`DAG_VALIDATION_CREDIT_ESTIMATE_MISMATCH`,`Custom executor reported credits different from its preflight estimate`,{taskRunId:o.taskRunId})):this.outcomes.handleSuccessPath(o,n.taskRunId,c,l,_.output,v??_.estimatedCredits,_.totalCredits):this.outcomes.handleFailurePath(o,n.taskRunId,_.error)}watchCommittedCancellation(e){let t=!1,n,r=async()=>{if(!t){try{let n=await this.storage.getDagRun(e.dagRunId);!t&&n?.status!==`running`&&e.controller.abort()}catch{t||e.controller.abort()}!t&&!e.controller.signal.aborted&&(n=setTimeout(()=>{r()},this.cancellationPollMs))}};return n=setTimeout(()=>{r()},this.cancellationPollMs),()=>{t=!0,clearTimeout(n)}}async cancelIfRunCancelled(e){return(await this.storage.getDagRun(e.dagRunId))?.status===`cancelled`?this.settleCancelledRunMessage(e):void 0}async cancelIfAncestorCancelled(e,t,n){if(n.parentRunId===void 0)return;let r=new Set([n.rootRunId,n.parentRunId]);for(let n of r)if((await this.storage.getDagRun(n))?.status===`cancelled`)return await this.cancelOwnRunForAncestor(t),this.settleCancelledRunMessage(e)}async cancelOwnRunForAncestor(e){if(!Y1.transition(e.status,`CANCEL`).ok)return;let t=await this.storage.commitExecution(e.dagRunId,{kind:`transition-run`,expectedStatus:e.status,event:`CANCEL`,endedAt:this.clock.nowIso()});if(t.applied||t.runStatus===`cancelled`){this.notifyRunCancelled(e.dagRunId);return}if(t.runStatus!==void 0){let t=await this.storage.getDagRun(e.dagRunId);t&&await this.cancelOwnRunForAncestor(t)}}async settleCancelledRunMessage(e){let t=await this.storage.getTaskRun(e.taskRunId);if(t){let e=X1.transition(t.status,`CANCEL`);e.ok&&await this.storage.updateTaskRunStatus(t.taskRunId,e.value.nextStatus),await this.storage.setTaskRunLease(t.taskRunId,void 0,void 0)}return _2(this.queue,e.messageId,e.taskRunId,!1)}async buildExecutionInput(e,t,n,r,i){let a=OLe(await this.storage.listTaskRunsByDagRunId(e.dagRunId));return{executionRoot:this.executionRoot,...i===void 0?{}:{lineage:i},byteLimits:this.byteLimits,snapshotBudget:this.snapshotBudget,rootCreditBudget:this.rootCreditBudget,reserveCredits:n.costPolicy?async t=>{let n=await this.storage.commitExecution(e.dagRunId,{kind:`reserve-credits`,taskRunId:e.taskRunId,attempt:e.attempt,leaseOwner:this.options.workerId,estimatedCredits:t});return n.applied?{ok:!0,value:void 0}:{ok:!1,error:n.error??Q(`DAG_VALIDATION_CREDIT_RESERVATION_REJECTED`,`Task attempt lost credit reservation authority`,{taskRunId:e.taskRunId})}}:void 0,dagId:t.dagId,dagRunId:e.dagRunId,taskRunId:e.taskRunId,nodeId:e.nodeId,attempt:e.attempt,executionPath:e.executionPath,input:e.payload,nodeDefinition:r,costPolicy:n.costPolicy,currentTotalCredits:a}}claimDepsFor(e,t,n){return{storage:this.storage,queue:this.queue,clock:this.clock,reporter:this.runProgressEventReporter,options:this.options,timeoutMs:n,message:e,taskRun:t}}async resolveTimeoutMs(e){let t=await x2(this.storage,e);if(!t.ok)return this.options.defaultTimeoutMs;let n=t.value.nodeDefinition.timeoutMs;return typeof n==`number`&&n>0?n:this.options.defaultTimeoutMs}},MLe=class extends Error{constructor(){super(`Run advancement has stopped and cannot be restarted.`),this.name=`RunAdvancementStoppedError`}};function NLe(e){return e===`success`||e===`failed`||e===`cancelled`}function S2(e,t,n){return R1(e,t,{dagRunId:n})}var PLe=class{workerStep;runReader;logger;lifecycle=`created`;continuousDemand=!1;waiters=new Map;actorPromise=null;stopPromise=null;wakeSleep=null;constructor(e,t,n={error:()=>void 0}){this.workerStep=e,this.runReader=t,this.logger=n}async start(){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)throw new MLe;this.lifecycle=`running`,this.continuousDemand=!0,this.wake(),this.ensureActor()}waitForTerminal(e,t={}){if(this.lifecycle===`stopping`||this.lifecycle===`stopped`)return Promise.resolve({ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e)});if(t.signal?.aborted)return Promise.resolve({ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)});if(t.deadlineEpochMs!==void 0&&t.deadlineEpochMs<=Date.now())return Promise.resolve({ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)});let n=new Promise(n=>{let r={id:Symbol(e),dagRunId:e,resolve:n,signal:t.signal,settled:!1};t.signal!==void 0&&(r.abortListener=()=>{this.settle(r,{ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_ABORTED`,`Run terminal-state observation was aborted.`,e)})},t.signal.addEventListener(`abort`,r.abortListener,{once:!0})),t.deadlineEpochMs!==void 0&&(r.deadlineTimer=setTimeout(()=>{this.settle(r,{ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_WAIT_DEADLINE`,`Run terminal-state observation exceeded its deadline.`,e)})},Math.max(0,t.deadlineEpochMs-Date.now())),r.deadlineTimer.unref?.()),this.waiters.set(r.id,r)});return this.wake(),this.ensureActor(),n}stop(){if(this.stopPromise!==null)return this.stopPromise;this.lifecycle=`stopping`,this.continuousDemand=!1;for(let e of[...this.waiters.values()])this.settle(e,{ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_STOPPED`,`Run advancement stopped before the observed run became terminal.`,e.dagRunId)});return this.wake(),this.stopPromise=(async()=>{await this.actorPromise,this.lifecycle=`stopped`})(),this.stopPromise}hasDemand(){return(this.lifecycle===`created`||this.lifecycle===`running`)&&(this.continuousDemand||this.waiters.size>0)}ensureActor(){if(!this.hasDemand()||this.actorPromise!==null)return;let e=this.runActor().catch(e=>{this.logger.error(`Run advancement actor failed unexpectedly.`,e)}).finally(()=>{this.actorPromise===e&&(this.actorPromise=null),this.hasDemand()&&this.ensureActor()});this.actorPromise=e}async runActor(){let e=25;for(;this.hasDemand();){if(await this.queryAndSettleWaiters(),!this.hasDemand())return;let t;try{t=await this.workerStep.processOnce()}catch(e){this.logger.error(`Worker step threw during run advancement.`,e),await this.sleepUntilWake(500);continue}if(!this.hasDemand())return;if(!t.ok){this.logger.error(`Worker step failed during run advancement.`,t.error),await this.sleepUntilWake(500);continue}if(t.value.processed){e=25;continue}await this.sleepUntilWake(e),e=Math.min(e*2,500)}}async queryAndSettleWaiters(){let e=new Set([...this.waiters.values()].map(e=>e.dagRunId));for(let t of e){let e;try{e=await this.runReader.getRun(t)}catch(n){e={ok:!1,error:S2(`DAG_RUNTIME_ADVANCEMENT_QUERY_THROW`,n instanceof Error?n.message:String(n),t)}}let n=[...this.waiters.values()].filter(e=>e.dagRunId===t);if(!e.ok||NLe(e.value.dagRun.status))for(let t of n)this.settle(t,e)}}settle(e,t){e.settled||(e.settled=!0,this.waiters.delete(e.id),e.deadlineTimer!==void 0&&clearTimeout(e.deadlineTimer),e.signal!==void 0&&e.abortListener!==void 0&&e.signal.removeEventListener(`abort`,e.abortListener),e.resolve(t),this.wake())}wake(){this.wakeSleep?.()}async sleepUntilWake(e){this.hasDemand()&&await new Promise(t=>{let n=!1,r=()=>{n||(n=!0,clearTimeout(i),this.wakeSleep===r&&(this.wakeSleep=null),t())},i=setTimeout(r,e);i.unref?.(),this.wakeSleep=r,this.hasDemand()||r()})}};function FLe(e,t){let n={...t,retryEnabled:t.retryEnabled??!1,deadLetterEnabled:t.deadLetterEnabled??!1,deadLetterQueue:e.deadLetterQueue};return new jLe(e.storage,e.queue,e.lease,e.executor,e.clock,e.executionRoot,n,e.runProgressEventReporter,e.byteLimits,e.snapshotBudget,e.rootCreditBudget,e.lifecycleCreditAdmission)}function ILe(e,t){let n=new HIe,r=new JIe(e.storage,e.queue,e.clock,n,e.snapshotBudget),i=new YIe(e.storage),a=FLe({executionRoot:e.executionRoot,byteLimits:e.byteLimits,snapshotBudget:e.snapshotBudget,rootCreditBudget:e.rootCreditBudget,lifecycleCreditAdmission:e.lifecycleCreditAdmission,storage:e.storage,queue:e.queue,deadLetterQueue:e.deadLetterQueue,lease:e.lease,executor:e.executor,clock:e.clock,runProgressEventReporter:n},{...t.worker,retryEnabled:t.worker.retryEnabled??!1});return{runOrchestrator:r,runQuery:i,runCancel:new XIe(e.storage,e.clock,{notifyRunCancelled(t){e.snapshotBudget?.close(),e.rootCreditBudget?.close(),a.notifyRunCancelled(t)}}),runAdvancement:new PLe(a,i,t.logger),runProgressEventBus:n}}function C2(e,t){let{text:n,search:r,replacement:i,flags:a}=e,o;try{o=new RegExp(r,a)}catch{return{type:`invalid-regex`}}let s=Symbol(`regex output exceeds byte limit`),c=new Uint16Array(t),l=0,u=0,d=!1,f=0,p=(e,n,r)=>{for(let i=n;i<r;i++){let n=e.charCodeAt(i);if(u+=n<128?1:n<2048?2:n>=56320&&n<=57343&&d?1:3,d=n>=55296&&n<=56319,u>t)throw s;c[l++]=n}},m=(e,t,r,a)=>{for(let o=0;o<i.length;){let s=i.indexOf(`$`,o);if(s<0){p(i,o,i.length);return}p(i,o,s);let c=i[s+1];if(c===`$`)p(i,s,s+1),o=s+2;else if(c===`&`)p(e,0,e.length),o=s+2;else if(c==="`")p(n,0,r),o=s+2;else if(c===`'`)p(n,r+e.length,n.length),o=s+2;else if(c!==void 0&&c>=`0`&&c<=`9`){let e=i[s+2],n=e!==void 0&&e>=`0`&&e<=`9`?2:1,r=Number(i.slice(s+1,s+1+n));if(n===2&&r>t.length&&(n=1,r=Number(c)),r>=1&&r<=t.length){let e=t[r-1];e!==void 0&&p(e,0,e.length)}else p(i,s,s+1+n);o=s+1+n}else if(c===`<`){let e=i.indexOf(`>`,s+2);if(e>=0&&a!==void 0){let t=a[i.slice(s+2,e)];t!==void 0&&p(t,0,t.length),o=e+1}else p(i,s,s+2),o=s+2}else p(i,s,s+1),o=s+1}};try{let e=a.includes(`u`)||a.includes(`v`);for(let t=o.exec(n);t!==null;t=o.exec(n)){let r=t[0],i=t.index;if(p(n,f,i),m(r,t.slice(1),i,t.groups),f=i+r.length,!o.global)break;if(r.length===0){let t=o.lastIndex,r=n.charCodeAt(t),i=n.charCodeAt(t+1);o.lastIndex+=e&&r>=55296&&r<=56319&&i>=56320&&i<=57343?2:1}}p(n,f,n.length)}catch(e){return e===s?{type:`oversized`}:{type:`invalid-regex`}}let h=[];for(let e=0;e<l;e+=8192)h.push(String.fromCharCode(...c.subarray(e,Math.min(e+8192,l))));return{type:`result`,value:h.join(``)}}const w2=25166848,LLe=`
2760
2760
  const boundedRegexReplace = ${C2.toString()};
2761
2761
  const send = (message) => process.stdout.write(JSON.stringify(message) + '\\n');
2762
2762
  let input = '';
@@ -2814,25 +2814,25 @@ parentPort.postMessage({ type: 'ready' });
2814
2814
  `:``}}catch{return{exitCode:1,stdout:``,stderr:`Unable to enumerate local sessions.
2815
2815
  `}}}async function dBe(e,t,n){let r=uBe(e,{cliName:t.vocabulary.cliName,userSessionStore:gx(pq(t).sessions),...n?{projectSessionStore:n}:{},readPeers:()=>lBe(O4(t))});if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return process.stdout.write(r.stdout),r.exitCode;if(!r.stdout)return r.stderr&&process.stderr.write(r.stderr),r.exitCode;let i;try{i={status:`available`,sessions:await o3(Y4(t),void 0,{includeExternalEvents:!0})}}catch{i={status:`unavailable`,sessions:[]}}if((e[1]===`json`?`json`:`text`)==`json`){let e=JSON.parse(r.stdout);process.stdout.write(`${JSON.stringify({...e,supervised:i})}\n`)}else{let e=i.status===`unavailable`?` (unavailable)`:i.sessions.length===0?` (none)`:i.sessions.map(e=>` ${e.id} liveness ${e.liveness} control ${e.control} activity ${e.activity}${e.problem?` ${e.problem}`:``}`).join(`
2816
2816
  `);process.stdout.write(`${r.stdout}Supervised sessions (owned, not linked to peers or saved records):\n${e}\n`)}return r.stderr&&process.stderr.write(r.stderr),i.status===`unavailable`&&process.stderr.write(`Supervised session discovery is unavailable.
2817
- `),r.exitCode||+(i.status===`unavailable`)}const fBe=/^[a-zA-Z0-9_-]{1,64}$/u,pBe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;function mBe(e){return typeof e==`string`&&Pn(e)&&!pBe.test(e)&&Buffer.byteLength(e,`utf8`)<=4096}function hBe(e,t){if(e===void 0)return t.length===0;if(!Array.isArray(e)||e.length!==t.length)return!1;let n=[...t].sort();return[...e].sort().every((e,t)=>e===n[t])}function gBe(e,t){return typeof e==`object`&&!!e&&`kind`in e&&`id`in e&&e.id===t&&(e.kind===`ready`||e.kind===`acknowledged`||e.kind===`error`)}function h3(e){return e.exitCode!==null||e.signalCode!==null}function _Be(e){let t=``,n=e=>{t=(t+String(e)).slice(-4e3)};return e.stderr?.on(`data`,n),{read:()=>t,stop:()=>{e.stderr?.off(`data`,n)}}}const vBe=/\x1b\[[0-9;]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/gu,yBe=/[\x00-\x08\x0B-\x1F\x7F]/gu;function bBe(e){return e.replace(vBe,``).replace(yBe,``)}const xBe=/KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH/iu;function SBe(e,t){let n=e;for(let[e,r]of Object.entries(t))r===void 0||r.length<8||xBe.test(e)&&n.includes(r)&&(n=n.split(r).join(`[REDACTED]`));return n}function CBe(e,t){let n=e.split(`
2817
+ `),r.exitCode||+(i.status===`unavailable`)}function fBe(){return process.versions.bun!==void 0||!process.allowedNodeEnvironmentFlags.has(`--disable-sigusr1`)?[]:[`--disable-sigusr1`]}const pBe=/^[a-zA-Z0-9_-]{1,64}$/u,mBe=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;function hBe(e){return typeof e==`string`&&Pn(e)&&!mBe.test(e)&&Buffer.byteLength(e,`utf8`)<=4096}function gBe(e,t){if(e===void 0)return t.length===0;if(!Array.isArray(e)||e.length!==t.length)return!1;let n=[...t].sort();return[...e].sort().every((e,t)=>e===n[t])}function _Be(e,t){return typeof e==`object`&&!!e&&`kind`in e&&`id`in e&&e.id===t&&(e.kind===`ready`||e.kind===`acknowledged`||e.kind===`error`)}function h3(e){return e.exitCode!==null||e.signalCode!==null}function vBe(e){let t=``,n=e=>{t=(t+String(e)).slice(-4e3)};return e.stderr?.on(`data`,n),{read:()=>t,stop:()=>{e.stderr?.off(`data`,n)}}}const yBe=/\x1b\[[0-9;]*[A-Za-z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/gu,bBe=/[\x00-\x08\x0B-\x1F\x7F]/gu;function xBe(e){return e.replace(yBe,``).replace(bBe,``)}const SBe=/KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH/iu;function CBe(e,t){let n=e;for(let[e,r]of Object.entries(t))r===void 0||r.length<8||SBe.test(e)&&n.includes(r)&&(n=n.split(r).join(`[REDACTED]`));return n}function wBe(e,t){let n=e.split(`
2818
2818
  `);return n.length<=t?e:n.slice(-t).join(`
2819
- `)}function wBe(e,t){return CBe(xe(SBe(bBe(e),t)).trim(),20).trim()}function TBe(e){let t=e.stderr;return!t||t.readableEnded||t.destroyed?Promise.resolve():new Promise(e=>{let n=!1,r=()=>{n||(n=!0,e())};t.once(`end`,r),t.once(`close`,r),setTimeout(r,200)})}async function g3(e,t){return h3(e)?!0:new Promise(n=>{let r=setTimeout(()=>a(!1),t),i=()=>a(!0),a=t=>{clearTimeout(r),e.off(`exit`,i),n(t)};e.once(`exit`,i)})}async function _3(e){if(e.pid===void 0){if(e.connected)try{e.disconnect()}catch{}return e.unref(),!0}if(!h3(e)){try{e.kill(`SIGTERM`)}catch{}if(!await g3(e,2e3)){try{e.kill(`SIGKILL`)}catch{}await g3(e,2e3)}}if(e.connected)try{e.disconnect()}catch{}return e.unref(),h3(e)}async function v3(e,t){if(t.name!==void 0&&!G4(t.name))throw Error(`Supervised session name is invalid or too long.`);let n=t.grants??[];if(n.length>0&&t.eventEndpoint===void 0)throw Error(`External event grants need the port their endpoint listens on.`);let r=n.map(e=>e.grantId),i=n.length>0?t.root??Y4(t.productRuntime):void 0,a=T1(),o=t.entrypoint?[t.entrypoint]:a.args,s=t.execArgs??a.execArgv??[],c=N(),l=()=>{i!==void 0&&oBe(i,c)};i!==void 0&&aBe(i,c,n);let u=t.env??A1(t.productRuntime),d;try{d=on(a.execPath,[...s,...o,`--serve`,`--supervised-session-id`,c,...t.name===void 0?[]:[`--name=${t.name}`],...n.length>0?[`--supervised-external-event-grants`]:[],...t.daemon===!0?[`--daemon`]:[],...t.restricted===!0?[Fq]:[],...n.length>0&&t.eventEndpoint!==void 0?[`--external-event-port=${t.eventEndpoint.port}`,...(t.eventEndpoint.trustedProxies??[]).map(e=>`--external-event-trusted-proxy=${e}`)]:[]],{cwd:e,detached:!0,stdio:[`ignore`,`ignore`,`pipe`,`ipc`],env:u})}catch(e){throw l(),e}let f=_Be(d);try{t.onSpawn?.(d)}catch{throw await _3(d),l(),Error(`Supervised session launch observer failed.`)}return new Promise((e,t)=>{let n=!1,i=!1,a=setTimeout(()=>p(`Supervised session did not become ready in time.`),2e4),o=r=>{if(!n)if(n=!0,clearTimeout(a),r.ok){f.stop(),d.stderr?.resume(),d.stderr!==null&&d.stderr!==void 0&&`unref`in d.stderr&&typeof d.stderr.unref==`function`&&d.stderr.unref();try{d.disconnect(),d.unref(),e(c)}catch{_3(d).then(()=>t(Error(`Supervised session could not detach.`)))}}else d.stderr?.destroy(),l(),_3(d).then(e=>{t(Error(e?r.message:`${r.message} Process exit could not be confirmed.`))})},s=e=>o({ok:!1,message:e}),p=e=>{TBe(d).then(()=>{let t=wBe(f.read(),u);s(t.length>0?t:e)})};d.once(`error`,()=>p(`Supervised session process could not start.`)),d.once(`exit`,()=>p(`Supervised session process exited before it was ready.`)),d.once(`disconnect`,()=>p(`Supervised session readiness channel closed before acknowledgement.`)),d.on(`message`,e=>{if(!gBe(e,c))return s(`Supervised session sent an invalid readiness message.`);if(e.kind===`error`)return s(e.code===`grant-refused`&&typeof e.grant==`string`&&fBe.test(e.grant)&&r.includes(e.grant)?`grant ${e.grant}: refused by the session.`:e.code===`events-endpoint-failed`?`External event endpoint could not be served on its port.`:e.code===`daemon-no-endpoint`?`The daemon has no WebSocket endpoint; enable the ws transport.`:e.code===`control-path-too-long`&&mBe(e.directory)?new $4(e.directory).message:`Supervised session refused to start.`);if(e.kind===`ready`&&!i){if(!hBe(e.grants,r))return s(`Supervised session did not open exactly the external event grants it was given.`);i=!0,d.send({kind:`ack`,id:c},e=>{e&&s(`Supervised session acknowledgement failed.`)});return}e.kind===`acknowledged`&&i?o({ok:!0}):s(`Supervised session sent an out-of-order readiness message.`)})})}function y3(e){let t=Object.entries(e).filter(([,e])=>(e??0)>0);return t.length===0?`none`:t.map(([e,t])=>`${e} ${t}`).join(`, `)}function EBe(e){return`accepted ${e.accepted}; refused: ${y3(e.refused)}; settled: ${y3(e.settled)}`}function DBe(e){return e.length===0?`No external event grants.
2820
- `:`${e.map(e=>` ${e.grantId} ${e.principal} ${e.state} ${EBe(e.counters)}`).join(`
2821
- `)}\n`}const b3=`true`,OBe=[`NVDA`,`JAWS`,`VOICEOVER`,`ORCA_`];function kBe(e){let t=e?.screenReader;return typeof t==`boolean`?t:void 0}function ABe(e){let t=e.settings??!1,n=t?`settings`:void 0,r=e.env?.trim();return(r===`1`||e.inkEnv?.trim()===b3)&&(t=!0,n=`env`),r===`0`&&(t=!1,n=void 0),e.flagEnabled===!0?(t=!0,n=`flag`):e.flagEnabled===!1&&(t=!1,n=void 0),{enabled:t,channel:n}}function jBe(e){let t=e.INK_SCREEN_READER;return t!==void 0&&t.trim()!==b3||Object.keys(e).some(e=>OBe.some(t=>e.toUpperCase().startsWith(t)))}function MBe(e,t){return e===!1||t.PRODUCT_SCREEN_READER?.trim()===`0`}function x3(e,t,n){let r=ABe({settings:kBe(e),flagEnabled:t,env:n.PRODUCT_SCREEN_READER,inkEnv:n.INK_SCREEN_READER});return{screenReader:r.enabled,screenReaderChannel:r.channel,screenReaderHint:!r.enabled&&!MBe(t,n)&&jBe(n)}}const NBe={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`};function PBe(e){return[`Attach to supervised session${e.name===void 0?``:` "${LY(e.name,80)}"`} (${e.id}) to ${NBe[e.mode]}.`,`Detaching leaves the session running.`].join(`\r
2822
- `)}async function S3(e){let t=IY();if(t===void 0)return!1;try{return await t.run(async t=>(t.write(`${PBe(e)}\r\n`),RY(await t.readLine(`Attach? Type yes to attach, anything else cancels: `,{echo:!0}))))}catch{return!1}}async function FBe(e,t,n,r){let{socket:i,driverId:a,rest:o}=await $ze(e,t,n,r);return IBe(i,a,o)}function IBe(e,t,n){let r=new Set,i=[],a=t=>{if(r.size===0){if(i.length>=1024){e.destroy();return}i.push(t);return}for(let e of[...r])e(t)},o=n,s=()=>{let t=o.indexOf(`
2819
+ `)}function TBe(e,t){return wBe(xe(CBe(xBe(e),t)).trim(),20).trim()}function EBe(e){let t=e.stderr;return!t||t.readableEnded||t.destroyed?Promise.resolve():new Promise(e=>{let n=!1,r=()=>{n||(n=!0,e())};t.once(`end`,r),t.once(`close`,r),setTimeout(r,200)})}async function g3(e,t){return h3(e)?!0:new Promise(n=>{let r=setTimeout(()=>a(!1),t),i=()=>a(!0),a=t=>{clearTimeout(r),e.off(`exit`,i),n(t)};e.once(`exit`,i)})}async function _3(e){if(e.pid===void 0){if(e.connected)try{e.disconnect()}catch{}return e.unref(),!0}if(!h3(e)){try{e.kill(`SIGTERM`)}catch{}if(!await g3(e,2e3)){try{e.kill(`SIGKILL`)}catch{}await g3(e,2e3)}}if(e.connected)try{e.disconnect()}catch{}return e.unref(),h3(e)}async function v3(e,t){if(t.name!==void 0&&!G4(t.name))throw Error(`Supervised session name is invalid or too long.`);let n=t.grants??[];if(n.length>0&&t.eventEndpoint===void 0)throw Error(`External event grants need the port their endpoint listens on.`);let r=n.map(e=>e.grantId),i=n.length>0?t.root??Y4(t.productRuntime):void 0,a=T1(),o=t.entrypoint?[t.entrypoint]:a.args,s=t.execArgs??a.execArgv??[],c=N(),l=()=>{i!==void 0&&oBe(i,c)};i!==void 0&&aBe(i,c,n);let u=t.env??A1(t.productRuntime),d;try{d=on(a.execPath,[...fBe(),...s,...o,`--serve`,`--supervised-session-id`,c,...t.name===void 0?[]:[`--name=${t.name}`],...n.length>0?[`--supervised-external-event-grants`]:[],...t.daemon===!0?[`--daemon`]:[],...t.restricted===!0?[Fq]:[],...n.length>0&&t.eventEndpoint!==void 0?[`--external-event-port=${t.eventEndpoint.port}`,...(t.eventEndpoint.trustedProxies??[]).map(e=>`--external-event-trusted-proxy=${e}`)]:[]],{cwd:e,detached:!0,stdio:[`ignore`,`ignore`,`pipe`,`ipc`],env:u})}catch(e){throw l(),e}let f=vBe(d);try{t.onSpawn?.(d)}catch{throw await _3(d),l(),Error(`Supervised session launch observer failed.`)}return new Promise((e,t)=>{let n=!1,i=!1,a=setTimeout(()=>p(`Supervised session did not become ready in time.`),2e4),o=r=>{if(!n)if(n=!0,clearTimeout(a),r.ok){f.stop(),d.stderr?.resume(),d.stderr!==null&&d.stderr!==void 0&&`unref`in d.stderr&&typeof d.stderr.unref==`function`&&d.stderr.unref();try{d.disconnect(),d.unref(),e(c)}catch{_3(d).then(()=>t(Error(`Supervised session could not detach.`)))}}else d.stderr?.destroy(),l(),_3(d).then(e=>{t(Error(e?r.message:`${r.message} Process exit could not be confirmed.`))})},s=e=>o({ok:!1,message:e}),p=e=>{EBe(d).then(()=>{let t=TBe(f.read(),u);s(t.length>0?t:e)})};d.once(`error`,()=>p(`Supervised session process could not start.`)),d.once(`exit`,()=>p(`Supervised session process exited before it was ready.`)),d.once(`disconnect`,()=>p(`Supervised session readiness channel closed before acknowledgement.`)),d.on(`message`,e=>{if(!_Be(e,c))return s(`Supervised session sent an invalid readiness message.`);if(e.kind===`error`)return s(e.code===`grant-refused`&&typeof e.grant==`string`&&pBe.test(e.grant)&&r.includes(e.grant)?`grant ${e.grant}: refused by the session.`:e.code===`events-endpoint-failed`?`External event endpoint could not be served on its port.`:e.code===`daemon-no-endpoint`?`The daemon has no WebSocket endpoint; enable the ws transport.`:e.code===`control-path-too-long`&&hBe(e.directory)?new $4(e.directory).message:`Supervised session refused to start.`);if(e.kind===`ready`&&!i){if(!gBe(e.grants,r))return s(`Supervised session did not open exactly the external event grants it was given.`);i=!0,d.send({kind:`ack`,id:c},e=>{e&&s(`Supervised session acknowledgement failed.`)});return}e.kind===`acknowledged`&&i?o({ok:!0}):s(`Supervised session sent an out-of-order readiness message.`)})})}function y3(e){let t=Object.entries(e).filter(([,e])=>(e??0)>0);return t.length===0?`none`:t.map(([e,t])=>`${e} ${t}`).join(`, `)}function DBe(e){return`accepted ${e.accepted}; refused: ${y3(e.refused)}; settled: ${y3(e.settled)}`}function OBe(e){return e.length===0?`No external event grants.
2820
+ `:`${e.map(e=>` ${e.grantId} ${e.principal} ${e.state} ${DBe(e.counters)}`).join(`
2821
+ `)}\n`}const b3=`true`,kBe=[`NVDA`,`JAWS`,`VOICEOVER`,`ORCA_`];function ABe(e){let t=e?.screenReader;return typeof t==`boolean`?t:void 0}function jBe(e){let t=e.settings??!1,n=t?`settings`:void 0,r=e.env?.trim();return(r===`1`||e.inkEnv?.trim()===b3)&&(t=!0,n=`env`),r===`0`&&(t=!1,n=void 0),e.flagEnabled===!0?(t=!0,n=`flag`):e.flagEnabled===!1&&(t=!1,n=void 0),{enabled:t,channel:n}}function MBe(e){let t=e.INK_SCREEN_READER;return t!==void 0&&t.trim()!==b3||Object.keys(e).some(e=>kBe.some(t=>e.toUpperCase().startsWith(t)))}function NBe(e,t){return e===!1||t.PRODUCT_SCREEN_READER?.trim()===`0`}function x3(e,t,n){let r=jBe({settings:ABe(e),flagEnabled:t,env:n.PRODUCT_SCREEN_READER,inkEnv:n.INK_SCREEN_READER});return{screenReader:r.enabled,screenReaderChannel:r.channel,screenReaderHint:!r.enabled&&!NBe(t,n)&&MBe(n)}}const PBe={drive:`drive (send prompts, answer its questions)`,observe:`observe (read only)`};function FBe(e){return[`Attach to supervised session${e.name===void 0?``:` "${LY(e.name,80)}"`} (${e.id}) to ${PBe[e.mode]}.`,`Detaching leaves the session running.`].join(`\r
2822
+ `)}async function S3(e){let t=IY();if(t===void 0)return!1;try{return await t.run(async t=>(t.write(`${FBe(e)}\r\n`),RY(await t.readLine(`Attach? Type yes to attach, anything else cancels: `,{echo:!0}))))}catch{return!1}}async function IBe(e,t,n,r){let{socket:i,driverId:a,rest:o}=await $ze(e,t,n,r);return LBe(i,a,o)}function LBe(e,t,n){let r=new Set,i=[],a=t=>{if(r.size===0){if(i.length>=1024){e.destroy();return}i.push(t);return}for(let e of[...r])e(t)},o=n,s=()=>{let t=o.indexOf(`
2823
2823
  `);for(;t!==-1&&!e.destroyed;){let e=o.slice(0,t);if(o=o.slice(t+1),e.trim()!==``){let t=nJ(e,OTe);t.ok&&a(t.message)}t=o.indexOf(`
2824
- `)}Buffer.byteLength(o,`utf8`)>67108864&&e.destroy()};return e.on(`data`,e=>{o+=e,s()}),e.on(`error`,()=>e.destroy()),s(),e.resume(),{driverId:t,send:t=>{e.destroyed||e.write(`${JSON.stringify(t)}\n`)},subscribe:e=>{if(r.add(e),r.size===1)for(let t of i.splice(0))e(t);return()=>{r.delete(e)}},onClose:t=>e.destroyed?(queueMicrotask(t),()=>void 0):(e.once(`close`,t),()=>{e.off(`close`,t)}),detach:()=>{e.destroy()}}}const LBe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,C3=e=>`Usage: ${e} session attach <supervised-id> [--observe] [--screen-reader|--no-screen-reader]\n
2824
+ `)}Buffer.byteLength(o,`utf8`)>67108864&&e.destroy()};return e.on(`data`,e=>{o+=e,s()}),e.on(`error`,()=>e.destroy()),s(),e.resume(),{driverId:t,send:t=>{e.destroyed||e.write(`${JSON.stringify(t)}\n`)},subscribe:e=>{if(r.add(e),r.size===1)for(let t of i.splice(0))e(t);return()=>{r.delete(e)}},onClose:t=>e.destroyed?(queueMicrotask(t),()=>void 0):(e.once(`close`,t),()=>{e.off(`close`,t)}),detach:()=>{e.destroy()}}}const RBe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,C3=e=>`Usage: ${e} session attach <supervised-id> [--observe] [--screen-reader|--no-screen-reader]\n
2825
2825
  Attach this terminal to a live supervised session started with \`${e} session start --background\`.\nDrive mode (the default) sends prompts and answers the session's questions alongside its other
2826
2826
  surfaces; --observe follows the conversation read-only. Use it to check on or steer a background
2827
2827
  session; find ids with \`${e} session list\` or \`${e} session view\`.\n
2828
2828
  It asks for confirmation on this terminal first and needs an interactive terminal, so only the user
2829
2829
  can run it; a script or an agent should suggest the command instead. Detach with /exit, Ctrl-C or
2830
2830
  Ctrl-]: the session keeps running. Exits 0 after detaching, 1 when it could not attach.
2831
- `;async function w3(e){let t;try{t=await(e.open??FBe)(e.id,e.mode,e.root,e.generation)}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`Unable to attach.`}\n`),1}let n;try{n=await e.render({connection:{send:t.send,subscribe:t.subscribe,onClose:t.onClose},driverId:t.driverId})}finally{t.detach()}return process.stdout.write(`${n===`closed`?e.messages.closed:e.messages.detached}\n`),0}function T3(e,t){return{closed:`Supervised session ${e} closed the connection (it stopped, or cut this terminal off).`,detached:`Detached from ${e}. It keeps running; stop it with ${t} session stop ${e} or from ${t} session view.`}}async function RBe(e,t){let n=t.productRuntime.vocabulary.cliName;if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return process.stdout.write(C3(n)),0;let[r,...i]=e,a=i.includes(`--observe`),o=i.filter(e=>e===`--screen-reader`||e===`--no-screen-reader`);if(r===void 0||!LBe.test(r)||new Set(i).size!==i.length||o.length>1||i.some(e=>e!==`--observe`&&e!==`--screen-reader`&&e!==`--no-screen-reader`))return process.stderr.write(C3(n)),1;let s=a?`observe`:`drive`,c=`${n} session attach ${r}${a?` --observe`:``}`;if(!(t.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))return process.stderr.write(`Attaching needs an interactive terminal and the user's confirmation. Ask the user to run: ${c}\n`),1;let l=t.render;if(l===void 0)return process.stderr.write(`${n} session attach needs the interactive CLI; this runtime has no terminal UI.\n`),1;let u=o.length===0?void 0:o[0]===`--screen-reader`,d=t.root??Y4(t.productRuntime),f;try{f=(await o3(d,void 0,{includeName:!0,includeGeneration:!0})).find(e=>e.id===r)}catch{f=void 0}if(f?.liveness!==`alive`||f.control!==`available`||f.generation===void 0)return process.stderr.write(`${r} is not a live supervised session this terminal can attach to.\n`),1;let p={id:r,...f.name===void 0?{}:{name:f.name},mode:s};if(!await(t.confirm??S3)(p))return process.stderr.write(`Attach cancelled.
2832
- `),1;let m=f.name??r;return w3({id:r,mode:s,generation:f.generation,root:d,render:e=>l({...e,mode:s,sessionLabel:m,screenReaderFlag:u}),messages:T3(r,n)})}const E3=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`],D3=e=>`Usage: ${e} session view [--cwd <directory>] [--name <text>] [--pr <number>] [--state <state>] [--screen-reader|--no-screen-reader]\nStates: ${E3.join(`, `)}\n`;function zBe(e){return E3.some(t=>t===e)}async function BBe(e,t){let n=t.productRuntime.vocabulary.cliName;if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return process.stdout.write(D3(n)),0;let r,i,a,o,s;for(let t=0;t<e.length;t++){let c=e[t];if(c===`--screen-reader`||c===`--no-screen-reader`){if(r!==void 0)return process.stderr.write(D3(n)),1;r=c===`--screen-reader`}else if(c===`--cwd`&&i===void 0&&e[t+1]&&!e[t+1].startsWith(`--`))i=e[++t];else if(c===`--name`&&a===void 0&&G4(e[t+1]))a=e[++t];else if(c===`--pr`&&o===void 0&&/^[1-9][0-9]*$/u.test(e[t+1]??``)&&Number.isSafeInteger(Number(e[t+1])))o=Number(e[++t]);else if(c===`--state`&&s===void 0&&zBe(e[t+1]))s=e[++t];else return process.stderr.write(D3(n)),1}if(!(t.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))return process.stderr.write(`Session view requires an interactive TTY; use ${n} session list for finite text or JSON output.\n`),1;let c=x3(t.settings??Oq(t.productRuntime),r,t.env??t.productRuntime.environment),l;if(i!==void 0)try{if(l=Cn(i),!Dn(l).isDirectory())throw Error(`Not a directory.`)}catch{return process.stderr.write(`Unable to select a working directory for the session view.
2831
+ `;async function w3(e){let t;try{t=await(e.open??IBe)(e.id,e.mode,e.root,e.generation)}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`Unable to attach.`}\n`),1}let n;try{n=await e.render({connection:{send:t.send,subscribe:t.subscribe,onClose:t.onClose},driverId:t.driverId})}finally{t.detach()}return process.stdout.write(`${n===`closed`?e.messages.closed:e.messages.detached}\n`),0}function T3(e,t){return{closed:`Supervised session ${e} closed the connection (it stopped, or cut this terminal off).`,detached:`Detached from ${e}. It keeps running; stop it with ${t} session stop ${e} or from ${t} session view.`}}async function zBe(e,t){let n=t.productRuntime.vocabulary.cliName;if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return process.stdout.write(C3(n)),0;let[r,...i]=e,a=i.includes(`--observe`),o=i.filter(e=>e===`--screen-reader`||e===`--no-screen-reader`);if(r===void 0||!RBe.test(r)||new Set(i).size!==i.length||o.length>1||i.some(e=>e!==`--observe`&&e!==`--screen-reader`&&e!==`--no-screen-reader`))return process.stderr.write(C3(n)),1;let s=a?`observe`:`drive`,c=`${n} session attach ${r}${a?` --observe`:``}`;if(!(t.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))return process.stderr.write(`Attaching needs an interactive terminal and the user's confirmation. Ask the user to run: ${c}\n`),1;let l=t.render;if(l===void 0)return process.stderr.write(`${n} session attach needs the interactive CLI; this runtime has no terminal UI.\n`),1;let u=o.length===0?void 0:o[0]===`--screen-reader`,d=t.root??Y4(t.productRuntime),f;try{f=(await o3(d,void 0,{includeName:!0,includeGeneration:!0})).find(e=>e.id===r)}catch{f=void 0}if(f?.liveness!==`alive`||f.control!==`available`||f.generation===void 0)return process.stderr.write(`${r} is not a live supervised session this terminal can attach to.\n`),1;let p={id:r,...f.name===void 0?{}:{name:f.name},mode:s};if(!await(t.confirm??S3)(p))return process.stderr.write(`Attach cancelled.
2832
+ `),1;let m=f.name??r;return w3({id:r,mode:s,generation:f.generation,root:d,render:e=>l({...e,mode:s,sessionLabel:m,screenReaderFlag:u}),messages:T3(r,n)})}const E3=[`needs-input`,`working`,`idle`,`unknown`,`unverified`,`dead`],D3=e=>`Usage: ${e} session view [--cwd <directory>] [--name <text>] [--pr <number>] [--state <state>] [--screen-reader|--no-screen-reader]\nStates: ${E3.join(`, `)}\n`;function BBe(e){return E3.some(t=>t===e)}async function VBe(e,t){let n=t.productRuntime.vocabulary.cliName;if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return process.stdout.write(D3(n)),0;let r,i,a,o,s;for(let t=0;t<e.length;t++){let c=e[t];if(c===`--screen-reader`||c===`--no-screen-reader`){if(r!==void 0)return process.stderr.write(D3(n)),1;r=c===`--screen-reader`}else if(c===`--cwd`&&i===void 0&&e[t+1]&&!e[t+1].startsWith(`--`))i=e[++t];else if(c===`--name`&&a===void 0&&G4(e[t+1]))a=e[++t];else if(c===`--pr`&&o===void 0&&/^[1-9][0-9]*$/u.test(e[t+1]??``)&&Number.isSafeInteger(Number(e[t+1])))o=Number(e[++t]);else if(c===`--state`&&s===void 0&&BBe(e[t+1]))s=e[++t];else return process.stderr.write(D3(n)),1}if(!(t.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))return process.stderr.write(`Session view requires an interactive TTY; use ${n} session list for finite text or JSON output.\n`),1;let c=x3(t.settings??Oq(t.productRuntime),r,t.env??t.productRuntime.environment),l;if(i!==void 0)try{if(l=Cn(i),!Dn(l).isDirectory())throw Error(`Not a directory.`)}catch{return process.stderr.write(`Unable to select a working directory for the session view.
2833
2833
  `),1}if(!t.render)return process.stderr.write(`${n} session view needs the interactive CLI; this runtime has no terminal UI.\n`),1;try{let e=t.root??Y4(t.productRuntime),i=t.start,u=t.startTrustQuestion,d=l??t.launchCwd??process.cwd(),f=t.render,p,m=()=>f({...p===void 0?{}:{announce:!1,initialSelectedId:p.id,initialGroupByDirectory:p.groupByDirectory},loadRows:t=>o3(e,t,{cwd:l,name:a,pr:o,includeName:!0,includeCwd:!0,includePr:!0,includeGeneration:!0}),onStop:(n,r)=>(t.stop??s3)(n,e,r),onOpenPr:async(n,r,i)=>{if((await Zze(n,e,i))?.url!==r)throw Error(`Supervised session PR link changed or is stale.`);await(t.openUrl??Kee)(r)},...i===void 0?{}:{onStart:e=>i(d,e)},...u===void 0?{}:{startTrustQuestion:()=>u(d)},trustStatusCommand:`${n} trust status`,filteredByCwd:l!==void 0,filteredByName:a!==void 0,filteredByPr:o!==void 0,stateFilter:s,screenReader:c.screenReader,screenReaderChannel:c.screenReaderChannel,screenReaderHint:c.screenReaderHint});for(;;){let i=await m();if(i===void 0||i.kind!==`attach`)return 0;p={id:i.id,groupByDirectory:i.groupByDirectory};let a=t.renderAttached;if(a===void 0){process.stderr.write(`Attaching needs the interactive CLI; this runtime has no terminal UI.
2834
2834
  `);continue}let o=await o3(e,void 0,{includeName:!0}).catch(()=>[]),{mode:s}=i,c=o.find(e=>e.id===i.id)?.name??i.id;await w3({id:i.id,mode:s,generation:i.generation,root:e,render:e=>a({...e,mode:s,sessionLabel:c,screenReaderFlag:r,announce:!1}),messages:T3(i.id,n)})}}catch{return process.stderr.write(`Unable to render the supervised session view.
2835
- `),1}}const VBe=e=>`Usage: ${e} daemon start [--json] [--restricted-workspace]\n ${e} daemon status [--json]\n ${e} daemon stop\n ${e} daemon unlock\n`,HBe=new Set([`--json`,`--restricted-workspace`]);function UBe(e){let[t,...n]=e;if(t===`stop`||t===`unlock`)return e.length===1?{action:t}:void 0;let r=t===`start`?HBe:new Set([`--json`]);if(t!==`start`&&t!==`status`||n.some(e=>!r.has(e))||new Set(n).size!==n.length)return;let i=n.includes(`--json`);return t===`start`?{action:t,json:i,restricted:n.includes(`--restricted-workspace`)}:{action:t,json:i}}async function O3(e,t){return(await(t.list??o3)(t.root,void 0,{cwd:e,includeCwd:!0,includeGeneration:!0,includeDaemon:!0,includeName:!0})).filter(t=>t.daemon===!0&&t.liveness===`alive`&&t.control===`available`&&t.cwd===e&&t.generation!==void 0).sort((e,t)=>e.id.localeCompare(t.id))[0]}function k3(e,t){return O3(t,{...e,root:e.root??Y4(e.productRuntime)})}async function A3(e,t){let n=e.productRuntime.vocabulary.cliName;try{return await(e.connect??l3)(t.id,e.root??Y4(e.productRuntime),t.generation)}catch(e){let r=e instanceof Error?e.message:`The daemon did not hand over its connection.`;throw Error(`${r} Daemon ${t.id} is running but cannot be connected to. Run: ${n} daemon stop`)}}async function WBe(e,t,n){let r=await e.admit(t,{restricted:n}),i=n||typeof r==`object`&&!!r&&r.restricted,a={...e.env(t),PRODUCT_WS_TOKEN:Wn(32).toString(`hex`)};delete a.PRODUCT_WS_PORT;let o=await(e.launch??v3)(t,{env:a,productRuntime:e.productRuntime,root:e.root??Y4(e.productRuntime),daemon:!0,...n?{restricted:!0}:{}});try{return{id:o,url:await(e.connect??l3)(o,e.root??Y4(e.productRuntime)),restricted:i}}catch(n){try{let n=(await(e.list??o3)(e.root??Y4(e.productRuntime),void 0,{cwd:t,includeGeneration:!0})).find(e=>e.id===o);await(e.stop??s3)(o,e.root??Y4(e.productRuntime),n?.generation)}catch{}throw n}}async function GBe(e,t){let n=t.productRuntime.vocabulary.cliName,r=UBe(e);if(r===void 0)return t.stderr(VBe(n)),1;try{let e=Cn(t.cwd);if(r.action===`unlock`){let n=iBe(e,t.root??Y4(t.productRuntime));return n.outcome===`held`?(t.stderr(`A daemon start (process ${n.pid}) is still running in ${e}; its lock was kept.\n`),1):(t.stdout(n.outcome===`removed`?`Removed the daemon start lock in ${e}.\n`:`No daemon start lock in ${e}.\n`),0)}let i=await k3(t,e);if(r.action===`stop`)return i===void 0?(t.stdout(`No daemon is running in ${e}.\n`),0):(await(t.stop??s3)(i.id,t.root??Y4(t.productRuntime),i.generation),t.stdout(`Stopped daemon ${i.id}.\n`),0);if(r.action===`status`)return i===void 0?(t.stdout(r.json?`${JSON.stringify({running:!1})}\n`:`No daemon is running in ${e}.\n`),0):(t.stdout(r.json?`${JSON.stringify({running:!0,id:i.id,url:await A3(t,i)})}\n`:`Daemon ${i.id} running in ${e}.\n`),0);let a=!1,o=r.restricted,s,c,l=async i=>{if(r.restricted&&i.restricted!==!0)throw Error(`Daemon ${i.id} is running in ${e} with the project's configuration, so it cannot be started Restricted. Run: ${n} daemon stop`);if(!r.restricted&&i.restricted===!0&&await t.trusted(e))throw Error(`Daemon ${i.id} is running Restricted in ${e}, which is trusted now. To start it with the project's configuration, run: ${n} daemon stop`)};if(i!==void 0)await l(i),s=i.id,o=i.restricted===!0,c=await A3(t,i);else{let i=await(t.lock??rBe)(e,t.root??Y4(t.productRuntime),{cliName:n});try{let n=await k3(t,e);n===void 0?({id:s,url:c,restricted:o}=await WBe(t,e,r.restricted),a=!0):(await l(n),s=n.id,o=n.restricted===!0,c=await A3(t,n))}finally{i()}}return o&&t.stderr(`${jD(t.productRuntime.layout.projectSettingsPaths)}\n`),t.stdout(r.json?`${JSON.stringify({id:s,url:c})}\n`:`Daemon ${s} ${a?`started`:`running`} in ${e}.\n`),0}catch(e){return t.stderr(`${e instanceof Error?e.message:`The daemon command failed.`}\n`),1}}const j3=e=>`Usage: ${e} --attach [--screen-reader|--no-screen-reader]\n
2835
+ `),1}}const HBe=e=>`Usage: ${e} daemon start [--json] [--restricted-workspace]\n ${e} daemon status [--json]\n ${e} daemon stop\n ${e} daemon unlock\n`,UBe=new Set([`--json`,`--restricted-workspace`]);function WBe(e){let[t,...n]=e;if(t===`stop`||t===`unlock`)return e.length===1?{action:t}:void 0;let r=t===`start`?UBe:new Set([`--json`]);if(t!==`start`&&t!==`status`||n.some(e=>!r.has(e))||new Set(n).size!==n.length)return;let i=n.includes(`--json`);return t===`start`?{action:t,json:i,restricted:n.includes(`--restricted-workspace`)}:{action:t,json:i}}async function O3(e,t){return(await(t.list??o3)(t.root,void 0,{cwd:e,includeCwd:!0,includeGeneration:!0,includeDaemon:!0,includeName:!0})).filter(t=>t.daemon===!0&&t.liveness===`alive`&&t.control===`available`&&t.cwd===e&&t.generation!==void 0).sort((e,t)=>e.id.localeCompare(t.id))[0]}function k3(e,t){return O3(t,{...e,root:e.root??Y4(e.productRuntime)})}async function A3(e,t){let n=e.productRuntime.vocabulary.cliName;try{return await(e.connect??l3)(t.id,e.root??Y4(e.productRuntime),t.generation)}catch(e){let r=e instanceof Error?e.message:`The daemon did not hand over its connection.`;throw Error(`${r} Daemon ${t.id} is running but cannot be connected to. Run: ${n} daemon stop`)}}async function GBe(e,t,n){let r=await e.admit(t,{restricted:n}),i=n||typeof r==`object`&&!!r&&r.restricted,a={...e.env(t),PRODUCT_WS_TOKEN:Wn(32).toString(`hex`)};delete a.PRODUCT_WS_PORT;let o=await(e.launch??v3)(t,{env:a,productRuntime:e.productRuntime,root:e.root??Y4(e.productRuntime),daemon:!0,...n?{restricted:!0}:{}});try{return{id:o,url:await(e.connect??l3)(o,e.root??Y4(e.productRuntime)),restricted:i}}catch(n){try{let n=(await(e.list??o3)(e.root??Y4(e.productRuntime),void 0,{cwd:t,includeGeneration:!0})).find(e=>e.id===o);await(e.stop??s3)(o,e.root??Y4(e.productRuntime),n?.generation)}catch{}throw n}}async function KBe(e,t){let n=t.productRuntime.vocabulary.cliName,r=WBe(e);if(r===void 0)return t.stderr(HBe(n)),1;try{let e=Cn(t.cwd);if(r.action===`unlock`){let n=iBe(e,t.root??Y4(t.productRuntime));return n.outcome===`held`?(t.stderr(`A daemon start (process ${n.pid}) is still running in ${e}; its lock was kept.\n`),1):(t.stdout(n.outcome===`removed`?`Removed the daemon start lock in ${e}.\n`:`No daemon start lock in ${e}.\n`),0)}let i=await k3(t,e);if(r.action===`stop`)return i===void 0?(t.stdout(`No daemon is running in ${e}.\n`),0):(await(t.stop??s3)(i.id,t.root??Y4(t.productRuntime),i.generation),t.stdout(`Stopped daemon ${i.id}.\n`),0);if(r.action===`status`)return i===void 0?(t.stdout(r.json?`${JSON.stringify({running:!1})}\n`:`No daemon is running in ${e}.\n`),0):(t.stdout(r.json?`${JSON.stringify({running:!0,id:i.id,url:await A3(t,i)})}\n`:`Daemon ${i.id} running in ${e}.\n`),0);let a=!1,o=r.restricted,s,c,l=async i=>{if(r.restricted&&i.restricted!==!0)throw Error(`Daemon ${i.id} is running in ${e} with the project's configuration, so it cannot be started Restricted. Run: ${n} daemon stop`);if(!r.restricted&&i.restricted===!0&&await t.trusted(e))throw Error(`Daemon ${i.id} is running Restricted in ${e}, which is trusted now. To start it with the project's configuration, run: ${n} daemon stop`)};if(i!==void 0)await l(i),s=i.id,o=i.restricted===!0,c=await A3(t,i);else{let i=await(t.lock??rBe)(e,t.root??Y4(t.productRuntime),{cliName:n});try{let n=await k3(t,e);n===void 0?({id:s,url:c,restricted:o}=await GBe(t,e,r.restricted),a=!0):(await l(n),s=n.id,o=n.restricted===!0,c=await A3(t,n))}finally{i()}}return o&&t.stderr(`${jD(t.productRuntime.layout.projectSettingsPaths)}\n`),t.stdout(r.json?`${JSON.stringify({id:s,url:c})}\n`:`Daemon ${s} ${a?`started`:`running`} in ${e}.\n`),0}catch(e){return t.stderr(`${e instanceof Error?e.message:`The daemon command failed.`}\n`),1}}const j3=e=>`Usage: ${e} --attach [--screen-reader|--no-screen-reader]\n
2836
2836
  Open the full terminal UI on this workspace's running daemon (${e} daemon start) instead of\nstarting a session of its own: the same conversation, prompts and questions its other clients
2837
2837
  see, and its sessions to list, start and switch. The daemon's session is shaped by the daemon, so
2838
2838
  no option that shapes a session is taken; to change one, restart the daemon.
@@ -2840,42 +2840,42 @@ no option that shapes a session is taken; to change one, restart the daemon.
2840
2840
  It asks for confirmation on this terminal first and needs an interactive terminal, so only the user
2841
2841
  can run it; a script or an agent should suggest the command instead, or connect to the URL that
2842
2842
  \`${e} daemon start --json\` prints. Detach with /exit or Ctrl-C: the daemon keeps running. Exits 0\nafter detaching, 1 when it could not attach.
2843
- `;function KBe(e){return e.includes(`--attach`)&&e[0]?.startsWith(`-`)===!0}function qBe(e){if(e.includes(`--help`)||e.includes(`-h`))return{kind:`help`};let t=0,n;for(let r of e)if(r===`--attach`)t+=1;else if(r===`--screen-reader`||r===`--no-screen-reader`){if(n!==void 0)return{kind:`usage`};n=r===`--screen-reader`}else return{kind:`refused`,argument:r};return t===1?{kind:`attach`,screenReader:n}:{kind:`usage`}}async function JBe(e,t){let n=t.productRuntime.vocabulary.cliName,r=qBe(e);if(r.kind===`help`)return process.stdout.write(j3(n)),0;if(r.kind===`usage`)return process.stderr.write(j3(n)),1;if(r.kind===`refused`)return process.stderr.write(`${n} --attach does not take ${r.argument}: the daemon's session is shaped by the daemon, not by the terminal attaching to it. To run it differently, stop it with ${n} daemon stop, change its settings, and start it again with ${n} daemon start.\n`),1;let i=t.render;if(i===void 0)return process.stderr.write(`${n} --attach needs the interactive CLI; this runtime has no terminal UI.\n`),1;let a=t.root??Y4(t.productRuntime),o,s;try{o=Cn(t.cwd),s=await O3(o,{root:a,...t.list===void 0?{}:{list:t.list}})}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`Unable to find the daemon.`}\n`),1}if(s===void 0)return process.stderr.write(`No daemon is running in ${o}. Start one with: ${n} daemon start\n`),1;if(!(t.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))return process.stderr.write(`Attaching needs an interactive terminal and the user's confirmation. Ask the user to run: ${n} --attach\n`),1;let{id:c,name:l,generation:u}=s,d={id:c,...l===void 0?{}:{name:l},mode:`drive`};return await(t.confirm??S3)(d)?w3({id:c,mode:`drive`,generation:u,root:a,render:e=>i({...e,mode:`drive`,sessionLabel:l??c,screenReaderFlag:r.screenReader}),messages:{detached:`Detached from daemon ${c}. It keeps running; stop it with ${n} daemon stop.`,closed:`The daemon closed the connection (it stopped, or cut this terminal off).`},...t.open===void 0?{}:{open:t.open}}):(process.stderr.write(`Attach cancelled.
2844
- `),1)}function YBe(e){return{filePath:M(e.layout.userRoot,`keybindings.json`),...e.config.identity.docsUrl===void 0?{}:{schemaUrl:new URL(`schemas/keybindings.schema.json`,e.config.identity.docsUrl.endsWith(`/`)?e.config.identity.docsUrl:`${e.config.identity.docsUrl}/`).href}}}function XBe(e){let t=e.PRODUCT_FOCUS_EVENTS?.trim();if(t===`1`)return!0;if(t===`0`)return!1}const M3=`PRODUCT_SCREEN_READER_STARTUP_QUIET_MS`,N3=`PRODUCT_SCREEN_READER_PREPARK_MS`;function ZBe(e){return{startupQuiet:{raw:e[M3],label:M3},prepark:{raw:e[N3],label:N3}}}function QBe(e){let t={};return e.PRODUCT_IME_CURSOR===`1`&&(t.imeCursorPositioning=!0),e.PRODUCT_IME_CURSOR===`0`&&(t.imeCursorPositioning=!1),e.PRODUCT_TURN_MARKS===`1`&&(t.turnMarks=!0),e.PRODUCT_TURN_MARKS===`0`&&(t.turnMarks=!1),t}function P3(e,t){let n=t.enabled?e.createNodeKeybindingsSource({...YBe(t.productRuntime),onDiagnostic:e=>process.stderr.write(`Keybindings ${e.file} ${e.path}: ${e.message}\n`)}):void 0;return{keybindingsSource:n,theme:e.createThemeSurface({cwd:t.cwd,productRuntime:t.productRuntime,projectAccess:t.projectAccess,userHome:t.productRuntime.userHome??t.productRuntime.layout.userRoot,enabled:n!==void 0,settings:t.settings,reducedMotionFlag:t.reducedMotionFlag,env:t.env})}}function F3(e){return{...e.screenReader,screenReaderPacing:ZBe(e.env),terminalCapabilities:QBe(e.env),focusReporting:XBe(e.env),...wNe({productRuntime:e.productRuntime,settings:e.settings,env:e.env,access:e.access,cwd:e.cwd})}}function I3(e,t){return e({providerDefinitions:t.providerDefinitions,reloadPluginCommandSource:t.reloadPluginCommandSource,userSettingsPath:rC(t.productRuntime),settingsSources:iC(t.productRuntime),formatResumeCommand:t.productRuntime.vocabulary.resumeCommand})}function $Be(e,t){return async({connection:n,driverId:r,sessionLabel:i,screenReaderFlag:a,mode:o,announce:s})=>{let{cwd:c,projectAccess:l}=t,u=Oq(t.productRuntime),d=t.productRuntime.environment,{keybindingsSource:f,theme:p}=P3(e,{productRuntime:t.productRuntime,enabled:!0,cwd:c,projectAccess:l,settings:u,reducedMotionFlag:void 0,env:d});for(let{fileName:e,reason:t}of p.skipped)process.stderr.write(`Skipped theme "${e}": ${t}\n`);let{enabledCommandModules:m,disabledCommandModules:h}=Sq({productRuntime:t.productRuntime,args:{},settings:u,safeMode:t.safeMode===!0,writeError:e=>process.stderr.write(`${e}\n`)}).options,{promptHistory:g,..._}=F3({productRuntime:t.productRuntime,screenReader:x3(u,a,d),settings:u,env:d,access:l,cwd:c});return e.installTuiProcessGuards(t.productRuntime.config.identity.cliName),e.renderAttachedApp({cwd:c,productDisplayName:t.productRuntime.vocabulary.displayName,version:I1(t.productRuntime),cliAdapter:I3(e.createDefaultTuiCliAdapter,{productRuntime:t.productRuntime,providerDefinitions:t.providerDefinitions??Sz(),reloadPluginCommandSource:e=>cC(e,t.productRuntime,c,l,t.safeMode!==!0)}),..._,keybindingsSource:f,clientCommands:{commands:MCe({shellExecutable:k1(t.productRuntime.environment),editorTemporaryDirectoryPrefix:t.productRuntime.vocabulary.editorTemporaryDirectoryPrefix,keybindingsFile:f,themeCatalogue:p.cataloguePort,...m===void 0?{}:{enabledCommandModules:m},...h===void 0?{}:{disabledCommandModules:h}}),writeAppearanceSettings:e=>{n_(rC(t.productRuntime),e)}},themeRegistry:p.registry,reducedMotion:p.reducedMotion,reducedMotionOverride:p.reducedMotionOverride,connection:n,sessionLabel:i,driverId:r,mode:o,...s===void 0?{}:{announce:s}})}}const eVe=/^-?(\d+)(?:\.(\d+))?(?:[eE][+-]?\d+)?$/;function L3(e){return{exitCode:1,stdout:``,stderr:`${e}\n`}}function tVe(e){if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return{exitCode:0,stdout:`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318
2843
+ `;function qBe(e){return e.includes(`--attach`)&&e[0]?.startsWith(`-`)===!0}function JBe(e){if(e.includes(`--help`)||e.includes(`-h`))return{kind:`help`};let t=0,n;for(let r of e)if(r===`--attach`)t+=1;else if(r===`--screen-reader`||r===`--no-screen-reader`){if(n!==void 0)return{kind:`usage`};n=r===`--screen-reader`}else return{kind:`refused`,argument:r};return t===1?{kind:`attach`,screenReader:n}:{kind:`usage`}}async function YBe(e,t){let n=t.productRuntime.vocabulary.cliName,r=JBe(e);if(r.kind===`help`)return process.stdout.write(j3(n)),0;if(r.kind===`usage`)return process.stderr.write(j3(n)),1;if(r.kind===`refused`)return process.stderr.write(`${n} --attach does not take ${r.argument}: the daemon's session is shaped by the daemon, not by the terminal attaching to it. To run it differently, stop it with ${n} daemon stop, change its settings, and start it again with ${n} daemon start.\n`),1;let i=t.render;if(i===void 0)return process.stderr.write(`${n} --attach needs the interactive CLI; this runtime has no terminal UI.\n`),1;let a=t.root??Y4(t.productRuntime),o,s;try{o=Cn(t.cwd),s=await O3(o,{root:a,...t.list===void 0?{}:{list:t.list}})}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`Unable to find the daemon.`}\n`),1}if(s===void 0)return process.stderr.write(`No daemon is running in ${o}. Start one with: ${n} daemon start\n`),1;if(!(t.isTTY??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)))return process.stderr.write(`Attaching needs an interactive terminal and the user's confirmation. Ask the user to run: ${n} --attach\n`),1;let{id:c,name:l,generation:u}=s,d={id:c,...l===void 0?{}:{name:l},mode:`drive`};return await(t.confirm??S3)(d)?w3({id:c,mode:`drive`,generation:u,root:a,render:e=>i({...e,mode:`drive`,sessionLabel:l??c,screenReaderFlag:r.screenReader}),messages:{detached:`Detached from daemon ${c}. It keeps running; stop it with ${n} daemon stop.`,closed:`The daemon closed the connection (it stopped, or cut this terminal off).`},...t.open===void 0?{}:{open:t.open}}):(process.stderr.write(`Attach cancelled.
2844
+ `),1)}function XBe(e){return{filePath:M(e.layout.userRoot,`keybindings.json`),...e.config.identity.docsUrl===void 0?{}:{schemaUrl:new URL(`schemas/keybindings.schema.json`,e.config.identity.docsUrl.endsWith(`/`)?e.config.identity.docsUrl:`${e.config.identity.docsUrl}/`).href}}}function ZBe(e){let t=e.PRODUCT_FOCUS_EVENTS?.trim();if(t===`1`)return!0;if(t===`0`)return!1}const M3=`PRODUCT_SCREEN_READER_STARTUP_QUIET_MS`,N3=`PRODUCT_SCREEN_READER_PREPARK_MS`;function QBe(e){return{startupQuiet:{raw:e[M3],label:M3},prepark:{raw:e[N3],label:N3}}}function $Be(e){let t={};return e.PRODUCT_IME_CURSOR===`1`&&(t.imeCursorPositioning=!0),e.PRODUCT_IME_CURSOR===`0`&&(t.imeCursorPositioning=!1),e.PRODUCT_TURN_MARKS===`1`&&(t.turnMarks=!0),e.PRODUCT_TURN_MARKS===`0`&&(t.turnMarks=!1),t}function P3(e,t){let n=t.enabled?e.createNodeKeybindingsSource({...XBe(t.productRuntime),onDiagnostic:e=>process.stderr.write(`Keybindings ${e.file} ${e.path}: ${e.message}\n`)}):void 0;return{keybindingsSource:n,theme:e.createThemeSurface({cwd:t.cwd,productRuntime:t.productRuntime,projectAccess:t.projectAccess,userHome:t.productRuntime.userHome??t.productRuntime.layout.userRoot,enabled:n!==void 0,settings:t.settings,reducedMotionFlag:t.reducedMotionFlag,env:t.env})}}function F3(e){return{...e.screenReader,screenReaderPacing:QBe(e.env),terminalCapabilities:$Be(e.env),focusReporting:ZBe(e.env),...wNe({productRuntime:e.productRuntime,settings:e.settings,env:e.env,access:e.access,cwd:e.cwd})}}function I3(e,t){return e({providerDefinitions:t.providerDefinitions,reloadPluginCommandSource:t.reloadPluginCommandSource,userSettingsPath:rC(t.productRuntime),settingsSources:iC(t.productRuntime),formatResumeCommand:t.productRuntime.vocabulary.resumeCommand})}function eVe(e,t){return async({connection:n,driverId:r,sessionLabel:i,screenReaderFlag:a,mode:o,announce:s})=>{let{cwd:c,projectAccess:l}=t,u=Oq(t.productRuntime),d=t.productRuntime.environment,{keybindingsSource:f,theme:p}=P3(e,{productRuntime:t.productRuntime,enabled:!0,cwd:c,projectAccess:l,settings:u,reducedMotionFlag:void 0,env:d});for(let{fileName:e,reason:t}of p.skipped)process.stderr.write(`Skipped theme "${e}": ${t}\n`);let{enabledCommandModules:m,disabledCommandModules:h}=Sq({productRuntime:t.productRuntime,args:{},settings:u,safeMode:t.safeMode===!0,writeError:e=>process.stderr.write(`${e}\n`)}).options,{promptHistory:g,..._}=F3({productRuntime:t.productRuntime,screenReader:x3(u,a,d),settings:u,env:d,access:l,cwd:c});return e.installTuiProcessGuards(t.productRuntime.config.identity.cliName),e.renderAttachedApp({cwd:c,productDisplayName:t.productRuntime.vocabulary.displayName,version:I1(t.productRuntime),cliAdapter:I3(e.createDefaultTuiCliAdapter,{productRuntime:t.productRuntime,providerDefinitions:t.providerDefinitions??Sz(),reloadPluginCommandSource:e=>cC(e,t.productRuntime,c,l,t.safeMode!==!0)}),..._,keybindingsSource:f,clientCommands:{commands:MCe({shellExecutable:k1(t.productRuntime.environment),editorTemporaryDirectoryPrefix:t.productRuntime.vocabulary.editorTemporaryDirectoryPrefix,keybindingsFile:f,themeCatalogue:p.cataloguePort,...m===void 0?{}:{enabledCommandModules:m},...h===void 0?{}:{disabledCommandModules:h}}),writeAppearanceSettings:e=>{n_(rC(t.productRuntime),e)}},themeRegistry:p.registry,reducedMotion:p.reducedMotion,reducedMotionOverride:p.reducedMotionOverride,connection:n,sessionLabel:i,driverId:r,mode:o,...s===void 0?{}:{announce:s}})}}const tVe=/^-?(\d+)(?:\.(\d+))?(?:[eE][+-]?\d+)?$/;function L3(e){return{exitCode:1,stdout:``,stderr:`${e}\n`}}function nVe(e){if(e.length===1&&(e[0]===`--help`||e[0]===`-h`))return{exitCode:0,stdout:`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318
2845
2845
  Exports content-free OTLP/HTTP JSON usage, prompt traces, or completion events to a loopback collector.
2846
- `,stderr:``};let t,n=`metrics`,r=!1;for(let i=0;i<e.length;i+=2){let a=e[i],o=e[i+1];if(!o)return L3(`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318`);if(a===`--endpoint`&&t===void 0)t=o;else if(a===`--signal`&&!r&&(o===`metrics`||o===`traces`||o===`logs`))n=o,r=!0;else return L3(`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318`)}if(!t)return L3(`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318`);let i;try{i=new URL(t)}catch{return L3(`Invalid OTLP endpoint URL.`)}return i.protocol!==`http:`&&i.protocol!==`https:`||i.hostname!==`127.0.0.1`&&i.hostname!==`[::1]`||i.username||i.password||i.search||i.hash||i.pathname!==`/`?L3(`OTLP endpoint must be a loopback HTTP(S) origin without credentials or a path.`):{endpoint:i,signal:n}}async function nVe(e){if(!e.body)return``;let t=e.body.getReader(),n=[],r=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(r+=i.byteLength,r>65536)throw await t.cancel(),Error(`OTLP response exceeded the size limit.`);n.push(i)}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return new TextDecoder().decode(i)}function rVe(e,t){if(!e)return!0;let n=JSON.parse(e);if(typeof n!=`object`||!n||Array.isArray(n))return!0;let r=n.partialSuccess;if(r===void 0)return!1;if(typeof r!=`object`||!r||Array.isArray(r))return!0;let{rejectedDataPoints:i,rejectedSpans:a,rejectedLogRecords:o,errorMessage:s}=r,c=t===`traces`?a:t===`logs`?o:i;if(c!==void 0&&typeof c!=`string`&&typeof c!=`number`)return!0;let l=!1;if(typeof c==`number`){if(!Number.isSafeInteger(c)||c<0)return!0;l=c>0}else if(typeof c==`string`){let e=eVe.exec(c);if(!e)return!0;l=/[1-9]/.test(`${e[1]}${e[2]??``}`)}return l||s!==void 0&&typeof s!=`string`||typeof s==`string`&&s.length>0}async function iVe(e,t){let n=tVe(e);if(`exitCode`in n)return n;let{endpoint:r,signal:i}=n,a;try{a=v$(t)}catch{return L3(`Unable to read configured session stores.`)}if(a.corruptSessionIds.length>0||a.unsupportedSessionIds.length>0)return L3(`Stored sessions include unreadable or unsupported records; no incomplete snapshot was sent.`);if(a.records.length===0)return L3(`No readable sessions to export.`);let o=t.version??F1(),s=i===`traces`?vY(a.records,o,t.serviceName):void 0,c;if(i===`logs`)try{c=jDe(a.records,o,t.now??new Date,t.serviceName)}catch{return L3(`Unable to project recorded completion events.`)}if(s&&s.coverage.exported===0)return L3(`No valid prompt root traces to export (missing ${s.coverage.missing}, invalid ${s.coverage.invalid}, duplicate ${s.coverage.duplicate}; provider children orphaned ${s.coverage.providerChildren.orphaned}, tool children orphaned ${s.coverage.toolChildren.orphaned}).`);if(c&&c.exported===0)return L3(`No valid completion events to export (roots missing ${c.coverage.missing}, invalid ${c.coverage.invalid}, duplicate ${c.coverage.duplicate}; provider children invalid ${c.coverage.providerChildren.invalid}, orphaned ${c.coverage.providerChildren.orphaned}, duplicate ${c.coverage.providerChildren.duplicate}; tool children invalid ${c.coverage.toolChildren.invalid}, orphaned ${c.coverage.toolChildren.orphaned}, duplicate ${c.coverage.toolChildren.duplicate}).`);let l=c?.payload??s?.payload??ODe(a.records,t.now??new Date,o,t.serviceName),u=JSON.stringify(l);if((s||c)&&Buffer.byteLength(u,`utf8`)>8388608)return L3(`OTLP request exceeded the size limit; nothing was sent.`);try{let e=await(t.fetcher??fetch)(new URL(`/v1/${i}`,r),{method:`POST`,headers:{"content-type":`application/json`},body:u,redirect:`error`,signal:AbortSignal.timeout(5e3)});if(e.status!==200)return L3(`OTLP collector returned HTTP ${e.status}.`);if(e.headers.get(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`application/json`)return L3(`OTLP collector returned a non-JSON response.`);if(rVe(await nVe(e),i))return L3(`OTLP collector rejected part of the export.`)}catch{return L3(`OTLP export failed; check the loopback collector and response format.`)}return{exitCode:0,stdout:c?`Exported ${c.exported} completion event(s) to loopback collector (roots exported ${c.coverage.exported}, missing ${c.coverage.missing}, invalid ${c.coverage.invalid}, duplicate ${c.coverage.duplicate}; provider children exported ${c.coverage.providerChildren.exported}, invalid ${c.coverage.providerChildren.invalid}, orphaned ${c.coverage.providerChildren.orphaned}, duplicate ${c.coverage.providerChildren.duplicate}; tool children exported ${c.coverage.toolChildren.exported}, invalid ${c.coverage.toolChildren.invalid}, orphaned ${c.coverage.toolChildren.orphaned}, duplicate ${c.coverage.toolChildren.duplicate}).\n`:s?`Exported ${s.coverage.exported} prompt root trace(s), ${s.coverage.providerChildren.exported} provider child span(s), and ${s.coverage.toolChildren.exported} tool child span(s) to loopback collector (roots missing ${s.coverage.missing}, invalid ${s.coverage.invalid}, duplicate ${s.coverage.duplicate}; provider children invalid ${s.coverage.providerChildren.invalid}, orphaned ${s.coverage.providerChildren.orphaned}, duplicate ${s.coverage.providerChildren.duplicate}; tool children invalid ${s.coverage.toolChildren.invalid}, orphaned ${s.coverage.toolChildren.orphaned}, duplicate ${s.coverage.toolChildren.duplicate}).\n`:`Exported OTLP usage snapshot to loopback collector.
2847
- `,stderr:``}}async function aVe(e,t,n){let r=await iVe(e,{serviceName:t.config.identity.telemetryServiceName,userSessionStore:gx(pq(t).sessions),...n?{projectSessionStore:n}:{},version:I1(t)});return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.exitCode}var R3=class extends Error{reason;constructor(e){super(e===`authorize-failed`?`MCP authentication failed: no credential could be obtained for this server`:`MCP authentication failed: the server refused the credential`),this.reason=e,this.name=`MCPAuthenticationError`}};const oVe=[],sVe=new Set([`http`,`sse`,`ws`]),z3=/\$\{[^}]*\}/,B3=`{"command": "/absolute/path/to/helper", "args": ["--flag"]}`;function V3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cVe(e){return typeof e==`string`?e===`streamable-http`?`http`:e===`stdio`||e===`http`||e===`sse`||e===`ws`?e:null:null}function H3(e,t){if(!V3(e))return`\`${t}\` must be an object of string values`;let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)return`\`${t}.${r}\` must be a string`;n[r]=i}return n}function U3(e){return typeof e==`string`&&e.length<=16384&&!e.includes(`\0`)}function lVe(e){if(typeof e==`string`)return`\`headersHelper\` must be an argv object, not a shell command; write ${B3}`;if(!V3(e))return`\`headersHelper\` must be an object such as ${B3}`;if(Object.keys(e).filter(e=>e!==`command`&&e!==`args`).length>0)return"`headersHelper` accepts only `command` and `args`";let t=e.command;if(!U3(t)||t.trim()===``)return"`headersHelper.command` must be an absolute path to an executable";let n=e.args??[];return!Array.isArray(n)||n.length>128||n.some(e=>!U3(e))?"`headersHelper.args` must be an array of strings":[t,...n].some(e=>z3.test(e))?"`headersHelper` must not contain `${}` templates; the host allows its exact command and arguments":Pn(t)?{command:t,args:[...n]}:"`headersHelper.command` must be an absolute path to an executable"}const W3=2048,uVe=/^[\x21\x23-\x5b\x5d-\x7e]+$/,dVe=/^[\x20-\x7e]+$/,fVe=new Set([`clientId`,`callbackPort`,`authServerMetadataUrl`,`scopes`]);function pVe(e){if(!V3(e))return"`oauth` must be an object";if(Object.hasOwn(e,`clientSecret`))return"`oauth.clientSecret` is not accepted in a definition; the MCP login command with `--client-secret` asks for it and stores it";if(Object.keys(e).filter(e=>!fVe.has(e)).length>0)return"`oauth` accepts only `clientId`, `callbackPort`, `authServerMetadataUrl` and `scopes`";let t={},{clientId:n,callbackPort:r,authServerMetadataUrl:i,scopes:a}=e;if(n!==void 0){if(typeof n!=`string`||n.length>W3||!dVe.test(n))return"`oauth.clientId` must be a non-empty string of printable characters";t.clientId=n}if(r!==void 0){if(typeof r!=`number`||!Number.isInteger(r)||r<1||r>65535)return"`oauth.callbackPort` must be an integer port between 1 and 65535";t.callbackPort=r}if(t.clientId!==void 0&&t.callbackPort===void 0)return"`oauth.clientId` needs `oauth.callbackPort`: a pre-registered client redirects to a fixed port";if(i!==void 0){if(typeof i!=`string`||i.length>W3||!URL.canParse(i)||new URL(i).protocol!==`https:`||new URL(i).username!==``||new URL(i).password!==``)return"`oauth.authServerMetadataUrl` must be an https URL without credentials";t.authServerMetadataUrl=i}if(a!==void 0){if(!Array.isArray(a)||a.length===0||a.length>64||a.some(e=>typeof e!=`string`||e.length>W3||!uVe.test(e)))return"`oauth.scopes` must be a non-empty array of scope tokens (no spaces or quotes)";t.scopes=[...a]}return[t.clientId,t.authServerMetadataUrl,...t.scopes??[]].some(e=>e!==void 0&&z3.test(e))?"`oauth` must not contain `${}` templates":t}function mVe(e,t,n){if(!V3(e))return{entries:[],problems:[{name:``,source:t,origin:n,reason:`the configuration root is not an object`}]};let r=e.mcpServers;if(r===void 0)return{entries:[],problems:[{name:``,source:t,origin:n,reason:"no `mcpServers` key"}]};if(!V3(r))return{entries:[],problems:[{name:``,source:t,origin:n,reason:"`mcpServers` is not an object"}]};let i=[],a=[];for(let[e,o]of Object.entries(r)){if(!V3(o)){a.push({name:e,source:t,origin:n,reason:`entry "${e}" is not an object`});continue}i.push({name:e,source:t,origin:n,entry:o})}return{entries:i,problems:a}}function hVe(e){let{name:t,source:n,origin:r,entry:i}=e,a=e=>({name:t,source:n,origin:r,reason:e}),o=cVe(i.type);if(o===null)return i.type===void 0?a(i.url===void 0?"no `type`; a definition must name stdio, http, sse or ws":'no `type`, but a `url` is present — declare `"type": "http"`, `"sse"` or `"ws"` rather than letting it read as stdio'):a(`unknown transport ${JSON.stringify(i.type)}`);let s={name:t,source:n,origin:r,transport:o},c=i.protocolVersion;if(c!==void 0){if(c!==`2026-07-28`)return a('`protocolVersion` must be "2026-07-28"; omit it for legacy negotiation');if(o!==`http`&&o!==`stdio`)return a("`protocolVersion` is unavailable for this transport");s.protocolVersion=c}let l=i.skills;if(l!==void 0){if(typeof l!=`boolean`)return a("`skills` must be a boolean");if(l&&c!==`2026-07-28`)return a('`skills` requires explicit `protocolVersion: "2026-07-28"`');s.skills=l}if(o===`stdio`){let e=i.command;if(typeof e!=`string`||e.trim()===``)return a("a stdio definition needs a non-empty `command`");s.command=e;let t=i.args;if(t!==void 0){if(!Array.isArray(t)||t.some(e=>typeof e!=`string`))return a("`args` must be an array of strings");s.args=t}let n=i.cwd;if(n!==void 0){if(typeof n!=`string`||n.trim()===``||n.length>16384||n.includes(`\0`))return a("`cwd` must be a bounded non-empty string without NUL");s.cwd=n}if(i.url!==void 0)return a("a stdio definition must not carry a `url`");if(i.headersHelper!==void 0)return a("a stdio definition must not carry `headersHelper`");if(i.oauth!==void 0)return a("a stdio definition must not carry `oauth`")}else{let e=i.url;if(typeof e!=`string`||e.trim()===``)return a(`a ${o} definition needs a non-empty \`url\``);if(s.url=e,i.command!==void 0)return a(`a ${o} definition must not carry a \`command\``);if(i.args!==void 0)return a(`a ${o} definition must not carry \`args\``);if(i.cwd!==void 0)return a(`a ${o} definition must not carry \`cwd\``);let t=i.headers;if(t!==void 0){let e=H3(t,`headers`);if(typeof e==`string`)return a(e);s.headers=e}let n=i.headersHelper;if(n!==void 0){let e=lVe(n);if(typeof e==`string`)return a(e);s.headersHelper=e}let r=i.oauth;if(r!==void 0){if(n!==void 0)return a("a definition must not carry both `oauth` and `headersHelper`");let e=pVe(r);if(typeof e==`string`)return a(e);s.oauth=e}}if(i.headers!==void 0&&o===`stdio`)return a("a stdio definition must not carry `headers`");let u=i.env;if(u!==void 0){let e=H3(u,`env`);if(typeof e==`string`)return a(e);s.env=e}let d=i.timeout;if(d!==void 0){if(typeof d!=`number`||!Number.isFinite(d)||d<=0)return a("`timeout` must be a positive number of milliseconds");s.timeout=d}if(sVe.has(o)&&s.url===void 0)return a(`a ${o} definition needs a \`url\``);let f=oVe.filter(e=>i[e]!==void 0);if(f.length>0){if(o===`stdio`)return a(`a stdio definition must not carry \`${f.join("`, `")}\``);s.unsupportedAuthentication=f}return s}function G3(e,t,n){let{entries:r,problems:i}=mVe(e,t,n),a=[],o=[...i];for(let e of r){let t=hVe(e);`reason`in t?o.push(t):a.push(t)}return{definitions:a,problems:o}}const gVe=new Set([`TOKEN`,`SECRET`,`PASSWORD`,`PASSWD`,`PWD`,`KEY`,`APIKEY`,`AUTH`,`AUTHORIZATION`,`CREDENTIAL`,`CREDENTIALS`,`PAT`,`COOKIE`,`PRIVATE`,`DSN`]),_Ve=[`TOKEN`,`SECRET`,`PASSWORD`,`PASSWD`,`APIKEY`,`ACCESSKEY`,`PRIVATEKEY`,`CONNECTIONSTRING`],vVe=new Set([`DATABASE_URL`,`POSTGRES_URL`,`POSTGRESQL_URL`,`MYSQL_URL`,`REDIS_URL`,`MONGODB_URI`,`MONGODB_URL`,`MONGO_URI`,`MONGO_URL`,`AMQP_URL`,`RABBITMQ_URL`]),yVe=new Set([`PWD`,`OLDPWD`]);function K3(e){let t=e.toUpperCase();if(yVe.has(t))return!1;if(vVe.has(t))return!0;let n=t.split(/[^A-Z0-9]+/).filter(e=>e.length>0);return n.some(e=>gVe.has(e))||n.some(e=>_Ve.some(t=>e.endsWith(t)))?!0:n.join(`_`).endsWith(`CONNECTION_STRING`)}function bVe(e){return`secret:${e}`}const q3=`secret:literal`;function xVe(e){let t=e.indexOf(`.`);return t===-1?void 0:e.slice(t+1)}function J3(e,t,n){return Y3(e,t,n).map(e=>e.text).join(``)}function Y3(e,t,n){let r=xVe(t),i=r!==void 0&&K3(r),a=[...e.provenance?.[t]??[]].sort((e,t)=>e.start-t.start||e.end-t.end),o=[],s=0,c=e=>{e.length!==0&&o.push(i?{text:q3,marker:!0}:{text:e,marker:!1})};for(let e of a)c(n.slice(s,e.start)),e.secret||i?o.push({text:bVe(e.variable),marker:!0}):c(n.slice(e.start,e.end)),s=e.end;return c(n.slice(s)),i&&o.length===0&&o.push({text:q3,marker:!0}),o}const SVe=/\uE000/g,CVe=/\uE001/g,X3=/[\uE000\uE001]/g,Z3=[/sk-[A-Za-z0-9_-]{16,}/,/gh[pos]_[A-Za-z0-9]{20,}/,/github_pat_[A-Za-z0-9_]{20,}/,/glpat-[A-Za-z0-9_-]{16,}/,/xox[bpas]-[A-Za-z0-9-]{10,}/,/AKIA[0-9A-Z]{16}/,/AIza[0-9A-Za-z_-]{30,}/,/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/].map(e=>e.source).join(`|`),wVe=RegExp(`(?<![A-Za-z0-9_.-])(?:${Z3})(?![A-Za-z0-9_.-])`,`g`);RegExp(`^(?:${Z3})$`);const TVe=/(?<![A-Za-z0-9+_=-])[A-Za-z0-9+_-]{32,}={0,2}(?![A-Za-z0-9+_=-])/g,EVe=/\b(Bearer\s+)[^\s\uE000\uE001]+/gi,DVe=/(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]*:\/\/\S*/g,Q3=/(?<=^|[\s;,&=:{"'`])(-{0,2})(\\*["'`]|)([A-Za-z_][A-Za-z0-9_.-]*)\2[ \t]*([:=])(?:[ \t]*[:=])*[ \t]*/g,OVe=/^(?:proxy-)?authorization$/i,kVe=/(^|\s)(-{1,2}[A-Za-z][A-Za-z0-9_.-]*)(\s+)([^\s-]\S*)/g;function AVe(e){let t=e.replace(/=+$/,``);return t.length<32?!1:/^[0-9a-fA-F]+$/.test(t)?!(/^[0-9a-f]+$/.test(t)&&(t.length===40||t.length===64)):/[0-9]/.test(t)&&/[a-z]/.test(t)&&/[A-Z]/.test(t)}function $3(e){return!/[-_.]?(?:file|path)$/i.test(e)&&K3(e)}function e6(e){let t=/^-{1,2}([A-Za-z][A-Za-z0-9_.-]*)$/.exec(e);if(t===null)return!1;let n=t[1];return n.length>1&&!/^no-/i.test(n)&&$3(n)}function t6(e){return e.replace(/[^\uE000]+/g,``)}function jVe(e){let t=/^([A-Za-z][A-Za-z0-9._~+-]*)([ \t]+)(?=\S)/.exec(e);return t===null?t6(e):`${t[0]}${t6(e.slice(t[0].length))}`}function MVe(e){try{return decodeURIComponent(e)}catch{return e}}function n6(e){return e.split(`&`).map(e=>{let t=e.indexOf(`=`);if(t<=0||t===e.length-1)return e;let n=e.slice(0,t);return K3(MVe(n).replace(X3,``))?`${n}=${t6(e.slice(t+1))}`:e}).join(`&`)}function NVe(e){let t=e.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#\s]*)@/,(e,t,n)=>{let r=n.indexOf(`:`);return r===-1?e:`${t}${n.slice(0,r)}:${t6(n.slice(r+1))}@`}),n=t.indexOf(`#`),r=n===-1?t:t.slice(0,n),i=n===-1?``:`#${n6(t.slice(n+1))}`,a=r.indexOf(`?`);return a===-1?`${r}${i}`:`${r.slice(0,a+1)}${n6(r.slice(a+1))}${i}`}function PVe(e,t,n){let r=t;for(;r<e.length&&!n.includes(e[r]);)r+=1;return r}function r6(e,t){let n=t;for(;e[n]===`\\`;)n+=1;let r=e[n];return r!==void 0&&`"'\``.includes(r)?{escapes:n-t,quote:r}:void 0}function i6(e,t,n){if(n.escapes===0){let r=t;for(;r<e.length&&e[r]!==n.quote;)r+=e[r]===`\\`?2:1;return Math.min(r,e.length)}let r=0;for(let i=t;i<e.length;i+=1){let t=e[i];if(t===n.quote&&r===n.escapes)return i-r;r=t===`\\`?r+1:0}return e.length}function FVe(e,t){let n=0,r=t;for(;r<e.length;){let t=e[r];if(t===`\\`||`"'\``.includes(t)){let t=r6(e,r);if(t===void 0){for(;e[r]===`\\`;)r+=1;continue}r=i6(e,r+t.escapes+1,t)+t.escapes+1;continue}if(t===`{`||t===`[`)n+=1;else if((t===`}`||t===`]`)&&(--n,n===0))return r;r+=1}return e.length}function IVe(e,t,n){let r=e[t];if(r===void 0)return;if(r===`{`||r===`[`){let n=FVe(e,t);return n===t+1?void 0:{start:t+1,end:n}}let i=r6(e,t);if(i!==void 0){let n=t+i.escapes+1,r=i6(e,n,i);return r===n?void 0:{start:n,end:r}}let a;a=n.enclosingQuote===void 0?n.quotedName?`,}]
2846
+ `,stderr:``};let t,n=`metrics`,r=!1;for(let i=0;i<e.length;i+=2){let a=e[i],o=e[i+1];if(!o)return L3(`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318`);if(a===`--endpoint`&&t===void 0)t=o;else if(a===`--signal`&&!r&&(o===`metrics`||o===`traces`||o===`logs`))n=o,r=!0;else return L3(`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318`)}if(!t)return L3(`Usage: usage export [--signal metrics|traces|logs] --endpoint http://127.0.0.1:4318`);let i;try{i=new URL(t)}catch{return L3(`Invalid OTLP endpoint URL.`)}return i.protocol!==`http:`&&i.protocol!==`https:`||i.hostname!==`127.0.0.1`&&i.hostname!==`[::1]`||i.username||i.password||i.search||i.hash||i.pathname!==`/`?L3(`OTLP endpoint must be a loopback HTTP(S) origin without credentials or a path.`):{endpoint:i,signal:n}}async function rVe(e){if(!e.body)return``;let t=e.body.getReader(),n=[],r=0;for(;;){let{done:e,value:i}=await t.read();if(e)break;if(r+=i.byteLength,r>65536)throw await t.cancel(),Error(`OTLP response exceeded the size limit.`);n.push(i)}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.byteLength;return new TextDecoder().decode(i)}function iVe(e,t){if(!e)return!0;let n=JSON.parse(e);if(typeof n!=`object`||!n||Array.isArray(n))return!0;let r=n.partialSuccess;if(r===void 0)return!1;if(typeof r!=`object`||!r||Array.isArray(r))return!0;let{rejectedDataPoints:i,rejectedSpans:a,rejectedLogRecords:o,errorMessage:s}=r,c=t===`traces`?a:t===`logs`?o:i;if(c!==void 0&&typeof c!=`string`&&typeof c!=`number`)return!0;let l=!1;if(typeof c==`number`){if(!Number.isSafeInteger(c)||c<0)return!0;l=c>0}else if(typeof c==`string`){let e=tVe.exec(c);if(!e)return!0;l=/[1-9]/.test(`${e[1]}${e[2]??``}`)}return l||s!==void 0&&typeof s!=`string`||typeof s==`string`&&s.length>0}async function aVe(e,t){let n=nVe(e);if(`exitCode`in n)return n;let{endpoint:r,signal:i}=n,a;try{a=v$(t)}catch{return L3(`Unable to read configured session stores.`)}if(a.corruptSessionIds.length>0||a.unsupportedSessionIds.length>0)return L3(`Stored sessions include unreadable or unsupported records; no incomplete snapshot was sent.`);if(a.records.length===0)return L3(`No readable sessions to export.`);let o=t.version??F1(),s=i===`traces`?vY(a.records,o,t.serviceName):void 0,c;if(i===`logs`)try{c=jDe(a.records,o,t.now??new Date,t.serviceName)}catch{return L3(`Unable to project recorded completion events.`)}if(s&&s.coverage.exported===0)return L3(`No valid prompt root traces to export (missing ${s.coverage.missing}, invalid ${s.coverage.invalid}, duplicate ${s.coverage.duplicate}; provider children orphaned ${s.coverage.providerChildren.orphaned}, tool children orphaned ${s.coverage.toolChildren.orphaned}).`);if(c&&c.exported===0)return L3(`No valid completion events to export (roots missing ${c.coverage.missing}, invalid ${c.coverage.invalid}, duplicate ${c.coverage.duplicate}; provider children invalid ${c.coverage.providerChildren.invalid}, orphaned ${c.coverage.providerChildren.orphaned}, duplicate ${c.coverage.providerChildren.duplicate}; tool children invalid ${c.coverage.toolChildren.invalid}, orphaned ${c.coverage.toolChildren.orphaned}, duplicate ${c.coverage.toolChildren.duplicate}).`);let l=c?.payload??s?.payload??ODe(a.records,t.now??new Date,o,t.serviceName),u=JSON.stringify(l);if((s||c)&&Buffer.byteLength(u,`utf8`)>8388608)return L3(`OTLP request exceeded the size limit; nothing was sent.`);try{let e=await(t.fetcher??fetch)(new URL(`/v1/${i}`,r),{method:`POST`,headers:{"content-type":`application/json`},body:u,redirect:`error`,signal:AbortSignal.timeout(5e3)});if(e.status!==200)return L3(`OTLP collector returned HTTP ${e.status}.`);if(e.headers.get(`content-type`)?.split(`;`,1)[0]?.trim().toLowerCase()!==`application/json`)return L3(`OTLP collector returned a non-JSON response.`);if(iVe(await rVe(e),i))return L3(`OTLP collector rejected part of the export.`)}catch{return L3(`OTLP export failed; check the loopback collector and response format.`)}return{exitCode:0,stdout:c?`Exported ${c.exported} completion event(s) to loopback collector (roots exported ${c.coverage.exported}, missing ${c.coverage.missing}, invalid ${c.coverage.invalid}, duplicate ${c.coverage.duplicate}; provider children exported ${c.coverage.providerChildren.exported}, invalid ${c.coverage.providerChildren.invalid}, orphaned ${c.coverage.providerChildren.orphaned}, duplicate ${c.coverage.providerChildren.duplicate}; tool children exported ${c.coverage.toolChildren.exported}, invalid ${c.coverage.toolChildren.invalid}, orphaned ${c.coverage.toolChildren.orphaned}, duplicate ${c.coverage.toolChildren.duplicate}).\n`:s?`Exported ${s.coverage.exported} prompt root trace(s), ${s.coverage.providerChildren.exported} provider child span(s), and ${s.coverage.toolChildren.exported} tool child span(s) to loopback collector (roots missing ${s.coverage.missing}, invalid ${s.coverage.invalid}, duplicate ${s.coverage.duplicate}; provider children invalid ${s.coverage.providerChildren.invalid}, orphaned ${s.coverage.providerChildren.orphaned}, duplicate ${s.coverage.providerChildren.duplicate}; tool children invalid ${s.coverage.toolChildren.invalid}, orphaned ${s.coverage.toolChildren.orphaned}, duplicate ${s.coverage.toolChildren.duplicate}).\n`:`Exported OTLP usage snapshot to loopback collector.
2847
+ `,stderr:``}}async function oVe(e,t,n){let r=await aVe(e,{serviceName:t.config.identity.telemetryServiceName,userSessionStore:gx(pq(t).sessions),...n?{projectSessionStore:n}:{},version:I1(t)});return r.stdout&&process.stdout.write(r.stdout),r.stderr&&process.stderr.write(r.stderr),r.exitCode}var R3=class extends Error{reason;constructor(e){super(e===`authorize-failed`?`MCP authentication failed: no credential could be obtained for this server`:`MCP authentication failed: the server refused the credential`),this.reason=e,this.name=`MCPAuthenticationError`}};const sVe=[],cVe=new Set([`http`,`sse`,`ws`]),z3=/\$\{[^}]*\}/,B3=`{"command": "/absolute/path/to/helper", "args": ["--flag"]}`;function V3(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function lVe(e){return typeof e==`string`?e===`streamable-http`?`http`:e===`stdio`||e===`http`||e===`sse`||e===`ws`?e:null:null}function H3(e,t){if(!V3(e))return`\`${t}\` must be an object of string values`;let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)return`\`${t}.${r}\` must be a string`;n[r]=i}return n}function U3(e){return typeof e==`string`&&e.length<=16384&&!e.includes(`\0`)}function uVe(e){if(typeof e==`string`)return`\`headersHelper\` must be an argv object, not a shell command; write ${B3}`;if(!V3(e))return`\`headersHelper\` must be an object such as ${B3}`;if(Object.keys(e).filter(e=>e!==`command`&&e!==`args`).length>0)return"`headersHelper` accepts only `command` and `args`";let t=e.command;if(!U3(t)||t.trim()===``)return"`headersHelper.command` must be an absolute path to an executable";let n=e.args??[];return!Array.isArray(n)||n.length>128||n.some(e=>!U3(e))?"`headersHelper.args` must be an array of strings":[t,...n].some(e=>z3.test(e))?"`headersHelper` must not contain `${}` templates; the host allows its exact command and arguments":Pn(t)?{command:t,args:[...n]}:"`headersHelper.command` must be an absolute path to an executable"}const W3=2048,dVe=/^[\x21\x23-\x5b\x5d-\x7e]+$/,fVe=/^[\x20-\x7e]+$/,pVe=new Set([`clientId`,`callbackPort`,`authServerMetadataUrl`,`scopes`]);function mVe(e){if(!V3(e))return"`oauth` must be an object";if(Object.hasOwn(e,`clientSecret`))return"`oauth.clientSecret` is not accepted in a definition; the MCP login command with `--client-secret` asks for it and stores it";if(Object.keys(e).filter(e=>!pVe.has(e)).length>0)return"`oauth` accepts only `clientId`, `callbackPort`, `authServerMetadataUrl` and `scopes`";let t={},{clientId:n,callbackPort:r,authServerMetadataUrl:i,scopes:a}=e;if(n!==void 0){if(typeof n!=`string`||n.length>W3||!fVe.test(n))return"`oauth.clientId` must be a non-empty string of printable characters";t.clientId=n}if(r!==void 0){if(typeof r!=`number`||!Number.isInteger(r)||r<1||r>65535)return"`oauth.callbackPort` must be an integer port between 1 and 65535";t.callbackPort=r}if(t.clientId!==void 0&&t.callbackPort===void 0)return"`oauth.clientId` needs `oauth.callbackPort`: a pre-registered client redirects to a fixed port";if(i!==void 0){if(typeof i!=`string`||i.length>W3||!URL.canParse(i)||new URL(i).protocol!==`https:`||new URL(i).username!==``||new URL(i).password!==``)return"`oauth.authServerMetadataUrl` must be an https URL without credentials";t.authServerMetadataUrl=i}if(a!==void 0){if(!Array.isArray(a)||a.length===0||a.length>64||a.some(e=>typeof e!=`string`||e.length>W3||!dVe.test(e)))return"`oauth.scopes` must be a non-empty array of scope tokens (no spaces or quotes)";t.scopes=[...a]}return[t.clientId,t.authServerMetadataUrl,...t.scopes??[]].some(e=>e!==void 0&&z3.test(e))?"`oauth` must not contain `${}` templates":t}function hVe(e,t,n){if(!V3(e))return{entries:[],problems:[{name:``,source:t,origin:n,reason:`the configuration root is not an object`}]};let r=e.mcpServers;if(r===void 0)return{entries:[],problems:[{name:``,source:t,origin:n,reason:"no `mcpServers` key"}]};if(!V3(r))return{entries:[],problems:[{name:``,source:t,origin:n,reason:"`mcpServers` is not an object"}]};let i=[],a=[];for(let[e,o]of Object.entries(r)){if(!V3(o)){a.push({name:e,source:t,origin:n,reason:`entry "${e}" is not an object`});continue}i.push({name:e,source:t,origin:n,entry:o})}return{entries:i,problems:a}}function gVe(e){let{name:t,source:n,origin:r,entry:i}=e,a=e=>({name:t,source:n,origin:r,reason:e}),o=lVe(i.type);if(o===null)return i.type===void 0?a(i.url===void 0?"no `type`; a definition must name stdio, http, sse or ws":'no `type`, but a `url` is present — declare `"type": "http"`, `"sse"` or `"ws"` rather than letting it read as stdio'):a(`unknown transport ${JSON.stringify(i.type)}`);let s={name:t,source:n,origin:r,transport:o},c=i.protocolVersion;if(c!==void 0){if(c!==`2026-07-28`)return a('`protocolVersion` must be "2026-07-28"; omit it for legacy negotiation');if(o!==`http`&&o!==`stdio`)return a("`protocolVersion` is unavailable for this transport");s.protocolVersion=c}let l=i.skills;if(l!==void 0){if(typeof l!=`boolean`)return a("`skills` must be a boolean");if(l&&c!==`2026-07-28`)return a('`skills` requires explicit `protocolVersion: "2026-07-28"`');s.skills=l}if(o===`stdio`){let e=i.command;if(typeof e!=`string`||e.trim()===``)return a("a stdio definition needs a non-empty `command`");s.command=e;let t=i.args;if(t!==void 0){if(!Array.isArray(t)||t.some(e=>typeof e!=`string`))return a("`args` must be an array of strings");s.args=t}let n=i.cwd;if(n!==void 0){if(typeof n!=`string`||n.trim()===``||n.length>16384||n.includes(`\0`))return a("`cwd` must be a bounded non-empty string without NUL");s.cwd=n}if(i.url!==void 0)return a("a stdio definition must not carry a `url`");if(i.headersHelper!==void 0)return a("a stdio definition must not carry `headersHelper`");if(i.oauth!==void 0)return a("a stdio definition must not carry `oauth`")}else{let e=i.url;if(typeof e!=`string`||e.trim()===``)return a(`a ${o} definition needs a non-empty \`url\``);if(s.url=e,i.command!==void 0)return a(`a ${o} definition must not carry a \`command\``);if(i.args!==void 0)return a(`a ${o} definition must not carry \`args\``);if(i.cwd!==void 0)return a(`a ${o} definition must not carry \`cwd\``);let t=i.headers;if(t!==void 0){let e=H3(t,`headers`);if(typeof e==`string`)return a(e);s.headers=e}let n=i.headersHelper;if(n!==void 0){let e=uVe(n);if(typeof e==`string`)return a(e);s.headersHelper=e}let r=i.oauth;if(r!==void 0){if(n!==void 0)return a("a definition must not carry both `oauth` and `headersHelper`");let e=mVe(r);if(typeof e==`string`)return a(e);s.oauth=e}}if(i.headers!==void 0&&o===`stdio`)return a("a stdio definition must not carry `headers`");let u=i.env;if(u!==void 0){let e=H3(u,`env`);if(typeof e==`string`)return a(e);s.env=e}let d=i.timeout;if(d!==void 0){if(typeof d!=`number`||!Number.isFinite(d)||d<=0)return a("`timeout` must be a positive number of milliseconds");s.timeout=d}if(cVe.has(o)&&s.url===void 0)return a(`a ${o} definition needs a \`url\``);let f=sVe.filter(e=>i[e]!==void 0);if(f.length>0){if(o===`stdio`)return a(`a stdio definition must not carry \`${f.join("`, `")}\``);s.unsupportedAuthentication=f}return s}function G3(e,t,n){let{entries:r,problems:i}=hVe(e,t,n),a=[],o=[...i];for(let e of r){let t=gVe(e);`reason`in t?o.push(t):a.push(t)}return{definitions:a,problems:o}}const _Ve=new Set([`TOKEN`,`SECRET`,`PASSWORD`,`PASSWD`,`PWD`,`KEY`,`APIKEY`,`AUTH`,`AUTHORIZATION`,`CREDENTIAL`,`CREDENTIALS`,`PAT`,`COOKIE`,`PRIVATE`,`DSN`]),vVe=[`TOKEN`,`SECRET`,`PASSWORD`,`PASSWD`,`APIKEY`,`ACCESSKEY`,`PRIVATEKEY`,`CONNECTIONSTRING`],yVe=new Set([`DATABASE_URL`,`POSTGRES_URL`,`POSTGRESQL_URL`,`MYSQL_URL`,`REDIS_URL`,`MONGODB_URI`,`MONGODB_URL`,`MONGO_URI`,`MONGO_URL`,`AMQP_URL`,`RABBITMQ_URL`]),bVe=new Set([`PWD`,`OLDPWD`]);function K3(e){let t=e.toUpperCase();if(bVe.has(t))return!1;if(yVe.has(t))return!0;let n=t.split(/[^A-Z0-9]+/).filter(e=>e.length>0);return n.some(e=>_Ve.has(e))||n.some(e=>vVe.some(t=>e.endsWith(t)))?!0:n.join(`_`).endsWith(`CONNECTION_STRING`)}function xVe(e){return`secret:${e}`}const q3=`secret:literal`;function SVe(e){let t=e.indexOf(`.`);return t===-1?void 0:e.slice(t+1)}function J3(e,t,n){return Y3(e,t,n).map(e=>e.text).join(``)}function Y3(e,t,n){let r=SVe(t),i=r!==void 0&&K3(r),a=[...e.provenance?.[t]??[]].sort((e,t)=>e.start-t.start||e.end-t.end),o=[],s=0,c=e=>{e.length!==0&&o.push(i?{text:q3,marker:!0}:{text:e,marker:!1})};for(let e of a)c(n.slice(s,e.start)),e.secret||i?o.push({text:xVe(e.variable),marker:!0}):c(n.slice(e.start,e.end)),s=e.end;return c(n.slice(s)),i&&o.length===0&&o.push({text:q3,marker:!0}),o}const CVe=/\uE000/g,wVe=/\uE001/g,X3=/[\uE000\uE001]/g,Z3=[/sk-[A-Za-z0-9_-]{16,}/,/gh[pos]_[A-Za-z0-9]{20,}/,/github_pat_[A-Za-z0-9_]{20,}/,/glpat-[A-Za-z0-9_-]{16,}/,/xox[bpas]-[A-Za-z0-9-]{10,}/,/AKIA[0-9A-Z]{16}/,/AIza[0-9A-Za-z_-]{30,}/,/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/].map(e=>e.source).join(`|`),TVe=RegExp(`(?<![A-Za-z0-9_.-])(?:${Z3})(?![A-Za-z0-9_.-])`,`g`);RegExp(`^(?:${Z3})$`);const EVe=/(?<![A-Za-z0-9+_=-])[A-Za-z0-9+_-]{32,}={0,2}(?![A-Za-z0-9+_=-])/g,DVe=/\b(Bearer\s+)[^\s\uE000\uE001]+/gi,OVe=/(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]*:\/\/\S*/g,Q3=/(?<=^|[\s;,&=:{"'`])(-{0,2})(\\*["'`]|)([A-Za-z_][A-Za-z0-9_.-]*)\2[ \t]*([:=])(?:[ \t]*[:=])*[ \t]*/g,kVe=/^(?:proxy-)?authorization$/i,AVe=/(^|\s)(-{1,2}[A-Za-z][A-Za-z0-9_.-]*)(\s+)([^\s-]\S*)/g;function jVe(e){let t=e.replace(/=+$/,``);return t.length<32?!1:/^[0-9a-fA-F]+$/.test(t)?!(/^[0-9a-f]+$/.test(t)&&(t.length===40||t.length===64)):/[0-9]/.test(t)&&/[a-z]/.test(t)&&/[A-Z]/.test(t)}function $3(e){return!/[-_.]?(?:file|path)$/i.test(e)&&K3(e)}function e6(e){let t=/^-{1,2}([A-Za-z][A-Za-z0-9_.-]*)$/.exec(e);if(t===null)return!1;let n=t[1];return n.length>1&&!/^no-/i.test(n)&&$3(n)}function t6(e){return e.replace(/[^\uE000]+/g,``)}function MVe(e){let t=/^([A-Za-z][A-Za-z0-9._~+-]*)([ \t]+)(?=\S)/.exec(e);return t===null?t6(e):`${t[0]}${t6(e.slice(t[0].length))}`}function NVe(e){try{return decodeURIComponent(e)}catch{return e}}function n6(e){return e.split(`&`).map(e=>{let t=e.indexOf(`=`);if(t<=0||t===e.length-1)return e;let n=e.slice(0,t);return K3(NVe(n).replace(X3,``))?`${n}=${t6(e.slice(t+1))}`:e}).join(`&`)}function PVe(e){let t=e.replace(/^([A-Za-z][A-Za-z0-9+.-]*:\/\/)([^/?#\s]*)@/,(e,t,n)=>{let r=n.indexOf(`:`);return r===-1?e:`${t}${n.slice(0,r)}:${t6(n.slice(r+1))}@`}),n=t.indexOf(`#`),r=n===-1?t:t.slice(0,n),i=n===-1?``:`#${n6(t.slice(n+1))}`,a=r.indexOf(`?`);return a===-1?`${r}${i}`:`${r.slice(0,a+1)}${n6(r.slice(a+1))}${i}`}function FVe(e,t,n){let r=t;for(;r<e.length&&!n.includes(e[r]);)r+=1;return r}function r6(e,t){let n=t;for(;e[n]===`\\`;)n+=1;let r=e[n];return r!==void 0&&`"'\``.includes(r)?{escapes:n-t,quote:r}:void 0}function i6(e,t,n){if(n.escapes===0){let r=t;for(;r<e.length&&e[r]!==n.quote;)r+=e[r]===`\\`?2:1;return Math.min(r,e.length)}let r=0;for(let i=t;i<e.length;i+=1){let t=e[i];if(t===n.quote&&r===n.escapes)return i-r;r=t===`\\`?r+1:0}return e.length}function IVe(e,t){let n=0,r=t;for(;r<e.length;){let t=e[r];if(t===`\\`||`"'\``.includes(t)){let t=r6(e,r);if(t===void 0){for(;e[r]===`\\`;)r+=1;continue}r=i6(e,r+t.escapes+1,t)+t.escapes+1;continue}if(t===`{`||t===`[`)n+=1;else if((t===`}`||t===`]`)&&(--n,n===0))return r;r+=1}return e.length}function LVe(e,t,n){let r=e[t];if(r===void 0)return;if(r===`{`||r===`[`){let n=IVe(e,t);return n===t+1?void 0:{start:t+1,end:n}}let i=r6(e,t);if(i!==void 0){let n=t+i.escapes+1,r=i6(e,n,i);return r===n?void 0:{start:n,end:r}}let a;a=n.enclosingQuote===void 0?n.quotedName?`,}]
2848
2848
  `:n.separator===`:`||n.authorization?`
2849
2849
  `:`;&,
2850
- `:`${n.enclosingQuote}\n`;let o=PVe(e,t,a);return o===t?void 0:{start:t,end:o}}function LVe(e){Q3.lastIndex=0;let t=``,n=0;for(let r=Q3.exec(e);r!==null;r=Q3.exec(e)){let[i,a,o,s,c]=r;if(!(a.length>0?e6(`${a}${s}`):$3(s)))continue;let l=e[r.index-1],u=OVe.test(s),d=IVe(e,r.index+i.length,{separator:c,quotedName:o.length>0,enclosingQuote:o.length===0&&l!==void 0&&`"'\``.includes(l)?l:void 0,authorization:u});if(d===void 0)continue;let f=e.slice(d.start,d.end);t+=e.slice(n,d.start),t+=u?jVe(f):t6(f),n=d.end,Q3.lastIndex=Math.max(d.end,Q3.lastIndex)}return t+e.slice(n)}function a6(e){return LVe(e.replace(DVe,NVe)).replace(kVe,(e,t,n,r,i)=>e6(n)?`${t}${n}${r}${t6(i)}`:e).replace(EVe,(e,t)=>`${t}`).replace(wVe,``).replace(TVe,e=>AVe(e)?``:e)}function o6(e){let t=[];return{scanned:e.map(e=>e.marker?(t.push(e.text),``):e.text.replace(X3,`�`)).join(``),markers:t}}function s6(e,t){let n=0;return e.replace(CVe,q3).replace(SVe,()=>t[n++]??``)}function RVe(e){let{scanned:t,markers:n}=o6([{text:e,marker:!1}]);return s6(a6(t),n)}function c6(e,t,n){let{scanned:r,markers:i}=o6(Y3(e,t,n));return s6(a6(r),i)}function zVe(e,t){return t.map((n,r)=>{let i=`args[${r}]`,a=r>0?t[r-1]:void 0;if(a!==void 0&&e6(a)&&!/^-{1,2}[A-Za-z]/.test(n)){let{scanned:t,markers:r}=o6(Y3(e,i,n));return s6(t6(t),r)}return c6(e,i,n)})}function BVe(e,t,n){let r=[...e.provenance?.[t]??[]].sort((e,t)=>e.start-t.start||e.end-t.end),i=``,a=0;for(let e of r)i+=n.slice(a,e.start)+"${"+e.variable+`}`,a=e.end;return i+n.slice(a)}const l6=/[A-Za-z_][A-Za-z0-9_]*/y;function*VVe(e){let t=0;for(;;){let n=e.indexOf("${",t);if(n===-1)return;l6.lastIndex=n+2;let r=l6.exec(e);if(r===null){t=n+1;continue}let i=l6.lastIndex,a;if(e.startsWith(`:-`,i)){let t=e.indexOf(`}`,i+2);if(t===-1)return;a=e.slice(i+2,t),i=t}else if(e[i]!==`}`){t=n+1;continue}yield{index:n,literal:e.slice(n,i+1),variable:r[0],fallback:a},t=i+1}}function u6(e,t,n,r){let i=[],a=``,o=0;for(let{index:s,literal:c,variable:l,fallback:u}of VVe(e)){a+=e.slice(o,s),o=s+c.length;let d=t[l]??u;if(d===void 0){r.unset.push({variable:l,field:n,literal:c}),a+=c;continue}i.push({start:a.length,end:a.length+d.length,variable:l,secret:K3(l)}),a+=d}return a+=e.slice(o),i.length>0&&(r.provenance[n]=i),a}function d6(e,t,n,r){let i={};for(let[a,o]of Object.entries(e))i[a]=u6(o,t,`${n}.${a}`,r);return i}function HVe(e,t){let n={unset:[],provenance:{}},r={...e,unsetVariables:[]};return e.command!==void 0&&(r.command=u6(e.command,t,`command`,n)),e.args!==void 0&&(r.args=e.args.map((e,r)=>u6(e,t,`args[${r}]`,n))),e.cwd!==void 0&&(r.cwd=u6(e.cwd,t,`cwd`,n)),e.env!==void 0&&(r.env=d6(e.env,t,`env`,n)),e.url!==void 0&&(r.url=u6(e.url,t,`url`,n)),e.headers!==void 0&&(r.headers=d6(e.headers,t,`headers`,n)),r.unsetVariables=n.unset,Object.keys(n.provenance).length>0&&(r.provenance=n.provenance),r}const f6=[`managed`,`local`,`project`,`user`,`plugin`],UVe=new Map(f6.map((e,t)=>[e,t]));function p6(e){return UVe.get(e)??f6.length}function WVe(e,t){let n=new Map,r=[],i=(e,t)=>{let r=n.get(e);r?r.push(t):n.set(e,[t])};for(let t of e){for(let e of t.definitions)i(e.name,{source:t.source,origin:e.origin,definition:e});for(let e of t.problems){if(e.name===``){r.push(e);continue}i(e.name,{source:t.source,origin:e.origin,problem:e})}}let a=[];for(let[e,r]of n){let n=[...r].sort((e,t)=>p6(e.source)-p6(t.source)),i=n[0];if(i===void 0)continue;let o=n.slice(1).map(t=>({name:e,source:t.source,origin:t.origin}));if(i.definition!==void 0){a.push({name:e,source:i.source,origin:i.origin,status:`resolved`,definition:t(i.definition),shadowed:o});continue}a.push({name:e,source:i.source,origin:i.origin,status:`unresolved`,...i.problem===void 0?{}:{problem:i.problem},shadowed:o})}let o=a.sort((e,t)=>e.name.localeCompare(t.name)),s=f6[0],c=r.find(e=>e.source===s);return c===void 0?{entries:o,sourceProblems:r}:{entries:o.map(e=>e.status!==`resolved`||e.source===s?e:{name:e.name,source:e.source,origin:e.origin,status:`unresolved`,problem:{name:e.name,source:e.source,origin:e.origin,reason:`${m6} the ${s} source (${c.origin}) could not be read (${c.reason}), so a lower-trust definition cannot be trusted to be the real winner`},shadowed:e.shadowed}),sourceProblems:r}}const m6=`blocked:`;function h6(e){return e.status===`unresolved`&&(e.problem?.reason.startsWith(m6)??!1)}function GVe(e){return e.disabledReason!==void 0}function g6(e){let t=Vn(`sha256`);for(let n of e)t.update(String(n.length)),t.update(`:`),t.update(n);return t.digest(`hex`).slice(0,32)}function _6(e,t){return[e,String(t.length),...t]}function v6(e,t,n){return _6(e,Object.keys(n??{}).sort().flatMap(r=>[r,J3(t,`${e}.${r}`,n[r])]))}function y6(e){let t=(t,n)=>n===void 0?``:J3(e,t,n);return g6([`v2`,`transport`,e.transport,...e.protocolVersion===void 0?[]:[`protocolVersion`,e.protocolVersion],...e.skills===!0?[`skills`,`enabled`]:[],`command`,t(`command`,e.command),..._6(`args`,(e.args??[]).map((e,n)=>t(`args[${n}]`,e))),`cwd`,t(`cwd`,e.cwd),`url`,t(`url`,e.url),...v6(`headers`,e,e.headers),...v6(`env`,e,e.env),`timeout`,e.timeout===void 0?``:String(e.timeout),...e.headersHelper===void 0?[]:[`headersHelper`,e.headersHelper.command,..._6(`headersHelperArgs`,e.headersHelper.args)],...e.oauth===void 0?[]:[`oauth`,e.oauth.clientId??``,e.oauth.callbackPort===void 0?``:String(e.oauth.callbackPort),e.oauth.authServerMetadataUrl??``,..._6(`oauthScopes`,e.oauth.scopes??[])],...e.unsupportedAuthentication===void 0?[]:_6(`unsupportedAuthentication`,e.unsupportedAuthentication)])}const KVe=/^[A-Za-z0-9_@%+=:,./-]+$/,qVe=/[\u007f-\u009f\u2028\u2029\p{Cf}]/gu;function JVe(e){return KVe.test(e)?e:JSON.stringify(e).replace(qVe,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function b6(e){let t=(e.protocolVersion===void 0?``:` (MCP ${e.protocolVersion})`)+(e.skills===!0?` (Skills enabled)`:``);if(e.url!==void 0){let n=c6(e,`url`,e.url),r=e.headersHelper;return r===void 0?n+t:`${n} (headers from ${[r.command,...r.args].map(e=>JVe(RVe(e))).join(` `)})${t}`}return[e.command===void 0?``:c6(e,`command`,e.command),...zVe(e,e.args??[])].join(` `).trim()+t}function x6(e){return g6([`name`,e.name,`source`,e.source,`origin`,e.origin])}function S6(e){return e.definition===void 0?null:{serverId:e.name,definitionFingerprint:y6(e.definition),securityIdentity:x6(e)}}function YVe(e,t){return{kind:e.source,id:e.origin,version:t}}function XVe(e){return e.definition===void 0?``:b6(e.definition)}var C6=class{entries;options;constructor(e,t={}){this.entries=e,this.options=t}list(){let e=[];for(let t of this.entries){if(t.status!==`resolved`||GVe(t))continue;let n=S6(t);if(n===null)continue;let r={serverId:n.serverId,endpoint:XVe(t),source:t.source,provenance:YVe(t,n.definitionFingerprint),definitionFingerprint:n.definitionFingerprint,securityIdentity:n.securityIdentity,...this.options.workspace===void 0?{}:{workspace:this.options.workspace}};e.push(r)}return e}displayNames(){return new Map(this.entries.map(e=>[e.name,e.name]))}};const w6={managed:3,user:2,local:1,project:0,plugin:0};var ZVe=class{records=[];audit=[];list(){return this.records.slice()}put(e){let t=this.records.findIndex(t=>t.serverId===e.serverId&&t.approvalAuthority===e.approvalAuthority);t===-1?this.records.push(e):this.records[t]=e}listAudit(){return this.audit.slice()}appendAudit(e){this.audit.push(e)}};const QVe=new Set([`managed`,`user`]);function T6(e){return!QVe.has(e)}const E6=new Set([`managed`,`user`,`local`]);function $Ve(e,t){let n=T6(e.source)?t.repositoryKey===e.workspace?.repositoryKey&&t.workspaceGeneration===e.workspace?.generation:t.repositoryKey===void 0&&t.workspaceGeneration===void 0;return t.serverId===e.serverId&&t.source===e.source&&t.provenance.kind===e.provenance.kind&&t.provenance.id===e.provenance.id&&t.provenance.version===e.provenance.version&&t.definitionFingerprint===e.definitionFingerprint&&t.securityIdentity===e.securityIdentity&&n}function D6(e,t,n,r){return{serverId:e.serverId,source:e.source,status:t,allowed:t===`approved`,reason:n,provenance:e.provenance,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,...r===void 0?{}:{approval:r}}}var O6=class extends Error{code=`MCP_ACTIVATION_POLICY_ERROR`;constructor(e){super(e),this.name=`MCPActivationPolicyError`}},eHe=class{store;now;constructor(e=new ZVe,t=()=>new Date().toISOString()){this.store=e,this.now=t}inspect(e){if(T6(e.source)&&e.workspace?.trustState!==`trusted`)return D6(e,`untrusted`,`MCP activation requires a trusted workspace for project, plugin, and local definitions.`);let t=this.store.list().filter(t=>t.serverId===e.serverId).sort((e,t)=>w6[t.approvalAuthority]-w6[e.approvalAuthority]||t.decidedAt.localeCompare(e.decidedAt));if(t.length===0)return D6(e,`pending`,`No explicit trust approval exists for this MCP definition.`);let n=t.find(t=>$Ve(e,t));return n?D6(e,n.decision,n.decision===`approved`?`MCP definition is explicitly approved.`:`MCP definition is ${n.decision}.`,n):D6(e,`stale`,`The MCP definition, provenance, security identity, or workspace generation changed after approval.`)}admit(e){return this.inspect(e)}approve(e,t=`user`){if(!E6.has(t))throw new O6(`Project and plugin definitions may request approval but cannot approve themselves.`);if(T6(e.source)&&e.workspace?.trustState!==`trusted`)return this.inspect(e);let n=this.createRecord(e,t,`approved`);return this.save(e,n),this.inspect(e)}reject(e,t=`user`){if(!E6.has(t))throw new O6(`Project and plugin definitions may request approval but cannot reject on behalf of the operator.`);let n=this.createRecord(e,t,`rejected`);return this.save(e,n),this.inspect(e)}revoke(e,t=`user`){if(!E6.has(t))throw new O6(`Project and plugin definitions may request approval but cannot revoke operator approval.`);let n=this.createRecord(e,t,`revoked`);return this.save(e,n),this.inspect(e)}getApprovalStore(){return this.store}listAudit(){return this.store.listAudit()}createRecord(e,t,n){return{serverId:e.serverId,source:e.source,provenance:e.provenance,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,approvalAuthority:t,decision:n,...T6(e.source)?{repositoryKey:e.workspace?.repositoryKey,workspaceGeneration:e.workspace?.generation}:{},decidedAt:this.now()}}save(e,t){let n={action:t.decision===`approved`?`approve`:t.decision===`rejected`?`reject`:`revoke`,serverId:e.serverId,source:e.source,provenanceId:e.provenance.id,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,decision:t.decision,at:t.decidedAt};this.store.putWithAudit?this.store.putWithAudit(t,n):(this.store.put(t),this.store.appendAudit(n))}},tHe=class{definitions;admission;displayNames;constructor(e,t,n=new Map){this.definitions=e,this.admission=t,this.displayNames=n}list(){return this.definitions.list().map(e=>this.toSummary(this.admission.inspect(e)))}approve(e){return this.toSummary(this.decide(e,e=>this.admission.approve(e)))}reject(e){return this.toSummary(this.decide(e,e=>this.admission.reject(e)))}revoke(e){return this.toSummary(this.decide(e,e=>this.admission.revoke(e)))}decide(e,t){let n=this.definitions.list().find(t=>t.serverId===e);if(!n)throw new O6(`Unknown MCP server "${e}".`);return t(n)}toSummary(e){let t=this.displayNames.get(e.serverId);return{...e,provenanceId:e.provenance.id,...t===void 0?{}:{displayName:t}}}},k6=class extends Error{reason;constructor(e){super(`Streamable HTTP transport refused egress (${e})`),this.reason=e,this.name=`MCPTransportEgressRefusedError`}};function nHe(e,t,n){let r=new AbortController,i=new Set,a=new Set;async function o(i,o){if((i instanceof Request?i.url:String(i))!==e)throw new k6(`endpoint-mismatch`);let s=new AbortController,c=[r.signal,s.signal];o?.signal&&c.push(o.signal);let l=AbortSignal.any(c),u=setTimeout(()=>s.abort(new DOMException(`MCP HTTP opening timed out`,`TimeoutError`)),3e4),d;try{d=await _ee(new URL(e),o??{},t,n,l)}finally{clearTimeout(u)}if(!(`response`in d))throw new k6(d.reason);l.aborted&&(await d.close(),l.throwIfAborted());let f=d.response;if(!f.body)return await d.close(),f;let p=f.body.getReader(),m,h=()=>(m??=(async()=>{s.abort();try{try{await p.cancel()}catch{}await d.close()}finally{a.delete(h)}})(),m);a.add(h);try{let e=new ReadableStream({async pull(e){try{let{done:t,value:n}=await p.read();t?(await h(),e.close()):e.enqueue(n)}catch(t){await h(),e.error(t)}},cancel:()=>h()},{highWaterMark:0});return new Response(e,{status:f.status,statusText:f.statusText,headers:f.headers})}catch(e){throw await h(),e}}return{fetch:async(e,t)=>{let n=o(e,t);i.add(n);try{return await n}finally{i.delete(n)}},signal:r.signal,async close(){r.abort(),await Promise.allSettled([...i]),await Promise.all([...a].map(e=>e()))}}}const A6=8*1024*1024,j6=128*1024*1024,M6=new WeakSet;function rHe(e){M6.add(e)}function N6(e){return M6.has(e)}const P6=new br;function F6(e,t){return P6.run(e,t)}function iHe(){return P6.getStore()}var aHe=class{byRequestId=new Map;get size(){return this.byRequestId.size}record(e,t){t.requestId!==void 0&&this.byRequestId.get(t.requestId)===t&&this.byRequestId.delete(t.requestId),t.requestId=e,this.byRequestId.set(e,t)}lookup(e){return this.byRequestId.get(e)}release(e){let t=e.requestId;t!==void 0&&this.byRequestId.get(t)===e&&this.byRequestId.delete(t)}};const I6=new WeakMap;function oHe(e,t){I6.set(e,t)}function L6(e){return I6.get(e)}function R6(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function z6(e){return typeof e==`string`||typeof e==`number`}function B6(e){if(!(!R6(e)||e.jsonrpc!==`2.0`||e.method!==`tools/call`))return z6(e.id)?e.id:void 0}function V6(e){if(!R6(e)||e.jsonrpc!==`2.0`||e.method!==`notifications/cancelled`||`id`in e||!R6(e.params))return;let t=e.params.requestId;return z6(t)?t:void 0}function sHe(e){if(e?.method!==`POST`||typeof e.body!=`string`)return;let t;try{t=JSON.parse(e.body)}catch{return}let n=P6.getStore(),r=B6(t);return r!==void 0&&n?.requestId===r?n.requestAbortController?.signal:void 0}function cHe(e,t,n){if(e?.method!==`POST`||typeof e.body!=`string`)return{};let r;try{r=JSON.parse(e.body)}catch{return{}}let i=P6.getStore(),a=B6(r);if(a!==void 0)return i?.requestId===a&&i.outbound?zt(t,i.outbound):{};let o=V6(r);if(o===void 0)return{};let s=i?.requestId===o?i:n.lookup(o);return s?.outbound?zt(t,s.outbound):{}}var H6=class extends Error{constructor(){super(`MCP response exceeded the receive byte limit`),this.name=`MCPTransportResponseLimitError`}};function lHe(e,t){if(!e.body)return e;let n=0,r=e.body.pipeThrough(new TransformStream({transform(e,r){if(n+=e.byteLength,n>t)throw new H6;r.enqueue(e)}}));return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}function U6(e,t){try{return new URL(e,t).origin}catch{return`an unparseable location`}}const W6=new WeakMap;function uHe(e){return W6.get(e)}var G6=class extends Error{status;location;constructor(e,t,n){super(`Streamable HTTP transport refused a redirect (${e}) from ${U6(n)} to ${t===void 0?`an undisclosed location`:U6(t,n)}: the admitted URL is the only URL spoken to`),this.status=e,this.location=t,this.name=`MCPTransportRedirectRefusedError`}};async function dHe(e,t={}){if(e.unsupportedAuthentication!==void 0&&e.unsupportedAuthentication.length>0)return{ok:!1,reason:`unsupported-authentication`,message:`The definition declares ${e.unsupportedAuthentication.join(`, `)} authentication, which this version does not support; the server was not connected.`};if(e.authenticationRequired===!0&&e.authentication===void 0)return{ok:!1,reason:`authentication-unavailable`,message:`The definition obtains its headers dynamically and no authenticator was registered; the server was not connected.`};if(!URL.canParse(e.url))return{ok:!1,reason:`invalid-url`,message:`The configured URL is not a valid URL`};let n=new URL(e.url),r=Object.freeze({...t.policy,...t.policy?.allowedHosts?{allowedHosts:Object.freeze([...t.policy.allowedHosts])}:{}}),i=t.lookup,a=i?await Zt(n,r,i):await Zt(n,r);return a?{ok:!1,reason:`egress-policy:${a.reason}`,message:a.message}:{ok:!0,admitted:{kind:`streamable-http`,url:n,headers:{...e.headers??{}},...e.authentication===void 0?{}:{authentication:e.authentication},egress:{policy:r,...i?{lookup:i}:{}}}}}var fHe=class extends tte{callTraces;closeCarrier;constructor(e,t,n,r){super(e,t),this.callTraces=n,this.closeCarrier=r}async close(){await Promise.all([this.closeCarrier(),super.close()])}send(e,t){let n=iHe(),r=B6(e);n!==void 0&&r!==void 0&&this.callTraces.record(r,n);let i=V6(e),a=i===void 0?void 0:this.callTraces.lookup(i);return a===void 0?super.send(e,t):(a.requestAbortController?.abort(),F6(a,()=>super.send(e,t)))}};function pHe(e,t){let n=Object.entries(t);if(n.length===0)return e;let r=new Headers(e?.headers);for(let[e,t]of n)r.set(e,t);return{...e,headers:r}}async function K6(e,t,n){try{e?.signal?.throwIfAborted();let r=await n.authenticator.authorize({serverId:n.serverId,securityIdentity:n.securityIdentity,url:t.url,...e?.signal?{signal:e.signal}:{}});e?.signal?.throwIfAborted();let i=new Headers(e?.headers);for(let[e,t]of Object.entries(r))i.set(e,t);return{headers:i,credential:r}}catch{throw e?.signal?.aborted===!0?new DOMException(`The MCP request was cancelled`,`AbortError`):new R3(`authorize-failed`)}}async function mHe(e,t,n){let r=n.authentication;if(r===void 0)return e(void 0);let i=e=>e.status===401||e.status===403,a=await K6(t,n,r),o=await e(a.headers);if(!i(o))return o;let s=o.headers.get(`www-authenticate`);await o.body?.cancel().catch(()=>void 0),t?.signal?.throwIfAborted();let c;try{c=await r.authenticator.onRejected({status:o.status,...s===null?{}:{wwwAuthenticate:s},authorization:a.credential})}catch{c=`fail`}let l=t?.body===void 0||t.body===null||typeof t.body==`string`;if(c!==`retry`||!l)throw new R3(`rejected`);let u=await e((await K6(t,n,r)).headers);if(i(u))throw await u.body?.cancel().catch(()=>void 0),new R3(`rejected`);return u}function hHe(e,t={}){let n=e.url.toString(),r={...e,url:new URL(n),headers:Object.freeze({...e.headers})},i=r.egress?.lookup??t.lookup,a=nHe(n,r.egress?.policy??t.policy??{},{...t.fetch?{fetch:t.fetch}:{},...i?{lookup:i}:{}}),o=a.fetch,s=new aHe,c=async(e,t)=>{a.signal.throwIfAborted();let i=[a.signal];t?.signal&&i.push(t.signal);let c=sHe(t);c&&i.push(c);let u=AbortSignal.any(i),d=t;if(new Headers(t?.headers).get(`mcp-protocol-version`)===`2026-07-28`){let e=new Headers(t?.headers);if(e.delete(`mcp-session-id`),d={...t,headers:e},t?.method!==`POST`)throw Error(`Stateless MCP automatic stream resumption is unavailable`)}let f=pHe({...d,signal:u},cHe(d,n,s)),p=await mHe(t=>o(e,{...f,...t?{headers:t}:{},redirect:`manual`}),f,r);if(p.status>=300&&p.status<400)throw await p.body?.cancel().catch(()=>void 0),new G6(p.status,p.headers.get(`location`)??void 0,n);return p.ok||W6.set(l,{status:p.status,contentType:p.headers.get(`content-type`)??void 0}),lHe(p,typeof t?.body==`string`&&JSON.parse(t.body).method===`resources/read`&&N6(l)?j6:A6)},l=new fHe(r.url,{requestInit:{redirect:`manual`,...Object.keys(r.headers).length>0?{headers:r.headers}:{}},fetch:c},s,()=>a.close());return oHe(l,s),l}function gHe(e={}){return{kind:`streamable-http`,admit:t=>dHe(t,e),construct:t=>hHe(t,e)}}function q6(){return new DOMException(`The credential request was cancelled`,`AbortError`)}var _He=class extends Error{constructor(){super(`The credential cache was closed`),this.name=`MCPSingleFlightClosedError`}},J6=class{load;cached;flight;generation=0;closed=!1;constructor(e){this.load=e}async get(e){return(await this.getEntry(e)).value}getEntry(e){if(this.closed)return Promise.reject(new _He);if(e?.aborted===!0)return Promise.reject(q6());if(this.cached!==void 0)return Promise.resolve(this.cached);let t=this.flight??this.start();return t.waiters+=1,new Promise((n,r)=>{let i=!1,a=()=>{i=!0,--t.waiters,e?.removeEventListener(`abort`,o)},o=()=>{i||(a(),t.waiters===0&&this.flight===t&&(this.flight=void 0,t.controller.abort()),r(q6()))};e?.addEventListener(`abort`,o,{once:!0}),t.promise.then(e=>{i||(a(),n({value:e,generation:t.generation}))},e=>{i||(a(),r(e))})})}invalidate(e){this.cached?.generation===e&&(this.cached=void 0)}close(){this.closed=!0,this.cached=void 0;let e=this.flight;this.flight=void 0,e?.controller.abort()}start(){this.generation+=1;let e={generation:this.generation,controller:new AbortController,promise:Promise.resolve(),waiters:0};return e.promise=new Promise(t=>t(this.load(e.controller.signal))).then(t=>(this.flight===e&&(this.flight=void 0,this.cached={value:t,generation:e.generation}),t),t=>{throw this.flight===e&&(this.flight=void 0),t}),e.promise.catch(()=>void 0),this.flight=e,e}},Y6=class extends Error{reason;constructor(e){super(`MCP headers helper failed (${e})`),this.reason=e,this.name=`MCPHeadersHelperError`}};const vHe=new Set([`project`,`local`]);function X6(e){return vHe.has(e)}function yHe(e,t,n,r){if(!r.some(t=>t.command===e.command&&t.args.length===e.args.length&&t.args.every((t,n)=>t===e.args[n])))return`headers-helper-not-allowed`;if(X6(t)&&n?.trustState!==`trusted`)return`headers-helper-untrusted`}const bHe=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,xHe=/^[\t\x20-\x7e\x80-\xff]*$/,SHe=new Set([`host`,`content-length`,`transfer-encoding`,`connection`,`content-type`,`accept`,`mcp-session-id`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`traceparent`]),Z6=/[ \t\n\r]*/y;function CHe(e,t){if(e[t]!==`"`)return;let n=t+1;for(;n<e.length&&e[n]!==`"`;)n+=e[n]===`\\`?2:1;if(!(n>=e.length))try{return{value:JSON.parse(e.slice(t,n+1)),next:n+1}}catch{return}}function wHe(e){let t=0,n=()=>{Z6.lastIndex=t,Z6.exec(e),t=Z6.lastIndex},r=()=>{let n=CHe(e,t);if(n!==void 0)return t=n.next,n.value},i=[];if(n(),e[t]===`{`){if(t+=1,n(),e[t]===`}`)t+=1;else for(;;){let a=r();if(a===void 0||(n(),e[t]!==`:`))return;t+=1,n();let o=r();if(o===void 0)return;if(i.push([a,o]),n(),e[t]===`,`){t+=1,n();continue}if(e[t]!==`}`)return;t+=1;break}return n(),t===e.length?i:void 0}}function THe(e){let t=wHe(e);if(t===void 0)throw new Y6(`output-malformed`);if(t.length>32)throw new Y6(`too-many-headers`);let n=new Set,r={};for(let[e,i]of t){if(!bHe.test(e))throw new Y6(`header-name-invalid`);let t=e.toLowerCase();if(SHe.has(t))throw new Y6(`header-forbidden`);if(n.has(t))throw new Y6(`header-duplicate`);if(n.add(t),!xHe.test(i))throw new Y6(`header-value-invalid`);r[e]=i}return Object.freeze(r)}function EHe(e){let t=new J6(async t=>THe(await e(t))),n=new WeakMap;return{authorize:async e=>{let{value:r,generation:i}=await t.getEntry(e.signal),a=Object.freeze({...r});return n.set(a,i),a},onRejected:async e=>{let r=n.get(e.authorization);return r===void 0?`fail`:(t.invalidate(r),`retry`)},close:()=>t.close()}}const Q6=/^[A-Za-z_][A-Za-z0-9_]*$/,DHe=/\$\{[^}]*\}/,$6=/^(?:NODE_OPTIONS|NODE_PATH|NODE_EXTRA_CA_CERTS|LD_.*|DYLD_.*|PYTHONPATH|PYTHONHOME|RUBYOPT|PERL5OPT|BASH_ENV|ENV)$/i;function OHe(e){return $6.test(e)}const kHe=new Set([`sh`,`bash`,`zsh`,`fish`,`dash`,`ksh`,`cmd.exe`,`powershell.exe`,`pwsh`,`pwsh.exe`]);function e8(e,t=!1){return typeof e==`string`&&(t||e.length>0)&&e.length<=16384&&!e.includes(`\0`)&&!DHe.test(e)}function t8(e,t){let n=In(e,t);return n===``||n!==`..`&&!n.startsWith(`..${Rn}`)&&!Pn(n)}function n8(e,t){let n=e??t;return Number.isInteger(n)&&n>0&&n<=12e4?n:void 0}async function r8(e){try{let t=await nr(e);return(await rr(t)).isDirectory()?t:void 0}catch{return}}async function i8(e){try{let t=await nr(e);return(await rr(t)).isFile()?t:void 0}catch{return}}function AHe(e){return e.split(/[\\/]/).includes(`..`)}async function jHe(e,t){let n=e.definition,r=n.command,i=n.args??[];if(n.transport!==`stdio`||!e8(r)||!Pn(r)||kHe.has(jn(r).toLowerCase())||!Array.isArray(i)||i.length>128||i.some(e=>!e8(e,!0))||!e8(t.allowedRoot)||!Pn(t.allowedRoot)||!e8(t.generation))return;let a=n8(t.startupMs,1e4),o=n8(t.cleanupMs,6e3);if(a===void 0||o===void 0||o<4100||!t.executables.some(e=>e.command===r&&e.args.some(e=>e.length===i.length&&e.every((e,t)=>e===i[t]))))return;let s=await r8(t.allowedRoot),c=await i8(r);if(s===void 0||c===void 0)return;let l=n.cwd??t.allowedRoot;if(!e8(l)||AHe(l))return;let u=await r8(Ln(s,l));if(u===void 0||!t8(s,u))return;let d=n.env??{},f=t.environment??{};if(!(Object.keys(d).length>128||Object.keys(f).length>128)){for(let[e,t]of Object.entries(f))if(!Q6.test(e)||[`__proto__`,`constructor`,`prototype`].includes(e)||$6.test(e)||!e8(t,!0))return;for(let[e,n]of Object.entries(d))if(!Q6.test(e)||[`__proto__`,`constructor`,`prototype`].includes(e)||$6.test(e)||!e8(n,!0)||!t.allowedEnvironmentKeys?.includes(e)||!Object.hasOwn(f,e)||f[e]!==n)return;return Object.freeze({command:r,canonicalCommand:c,args:Object.freeze([...i]),cwd:u,canonicalRoot:s,env:Object.freeze({...f}),requestedEnvKeys:Object.freeze(Object.keys(d)),generation:t.generation,startupMs:a,cleanupMs:o,activation:e.activation})}}async function MHe(e,t){try{let n=t.admission.admit(e.activation);if(!n.allowed||n.status!==`approved`||t.authority.generation!==e.generation)return!1;let r=await r8(t.authority.allowedRoot),i=await r8(e.cwd),a=await i8(e.command),o=t.authority.executables.some(t=>t.command===e.command&&t.args.some(t=>t.length===e.args.length&&t.every((t,n)=>t===e.args[n]))),s=t.authority.environment??{},c=Object.keys(s).length===Object.keys(e.env).length&&Object.entries(s).every(([t,n])=>e.env[t]===n),l=e.requestedEnvKeys.every(e=>t.authority.allowedEnvironmentKeys?.includes(e)),u=t.admission.admit(e.activation);return u.allowed&&u.status===`approved`&&t.authority.generation===e.generation&&r===e.canonicalRoot&&i===e.cwd&&a===e.canonicalCommand&&t8(r,i)&&o&&c&&l}catch{return!1}}var $=class extends Error{reason;constructor(e){super(`MCP OAuth failed (${e})`),this.reason=e,this.name=`MCPOAuthError`}};function a8(e,t){return e instanceof $?e:e instanceof Error&&e.name===`AbortError`?new $(`cancelled`):new $(t)}const NHe=new Set([101,204,205,304]);function PHe(e){return Object.fromEntries(new Headers(e?.headers).entries())}function FHe(e){let t=e?.body;if(t==null)return``;if(typeof t==`string`||t instanceof URLSearchParams)return t;throw new $(`response-invalid`)}function o8(e){if(!e.ok)throw new $(`egress-refused`);let t=NHe.has(e.status)?null:new TextDecoder().decode(e.body);return new Response(t,{status:e.status,statusText:e.statusText,headers:e.headers})}function s8(e,t){let n={...e.fetch===void 0?{}:{fetch:e.fetch},...e.lookup===void 0?{}:{lookup:e.lookup}};return async(r,i)=>{let a=[i?.signal,t].filter(e=>e instanceof AbortSignal),o={headers:PHe(i),timeoutMs:3e4,maxResponseBytes:262144,...a.length===0?{}:{signal:AbortSignal.any(a)}},s=(i?.method??`GET`).toUpperCase();if(s===`GET`)return o8(await Xt(String(r),o,e.policy,n));if(s!==`POST`)throw new $(`response-invalid`);return o8(await gee(String(r),{...o,body:FHe(i)},e.policy,n))}}function c8(e){if(!URL.canParse(e))throw new $(`response-invalid`);let t=new URL(e);if(t.protocol!==`https:`)throw new $(`insecure-endpoint`);return t}function l8(e){let t=c8(e);return t.hash=``,t.href}function u8(e,t){return!URL.canParse(e)||!URL.canParse(t)?!1:new URL(e).href===new URL(t).href}async function d8(e){try{return await e.json()}catch{throw new $(`response-invalid`)}}async function f8(e,t){let n=await t(e,{headers:{"MCP-Protocol-Version":ei,Accept:`application/json`}});if(n.status>=400&&n.status<500)return;if(!n.ok)throw new $(`discovery-failed`);let r=mte.safeParse(await d8(n));if(!r.success)throw new $(`response-invalid`);return r.data}async function IHe(e,t){if(t.resourceMetadataUrl!==void 0){let n=c8(t.resourceMetadataUrl);if(n.origin!==e.origin)throw new $(`resource-metadata-cross-origin`);let r=await f8(n,t.fetch);if(r===void 0)throw new $(`discovery-failed`);return r}let n=e.pathname.endsWith(`/`)?e.pathname.slice(0,-1):e.pathname,r=[...n===``?[]:[new URL(`/.well-known/oauth-protected-resource${n}`,e)],new URL(`/.well-known/oauth-protected-resource`,e)];for(let e of r){let n=await f8(e,t.fetch);if(n!==void 0)return n}throw new $(`discovery-failed`)}async function LHe(e,t){if(!e.pathname.includes(`/.well-known/`))return{issuer:e.href,metadata:await p8(e,t)};let n=await t(e,{headers:{"MCP-Protocol-Version":ei,Accept:`application/json`}});if(!n.ok)throw new $(`discovery-failed`);let r=pte.safeParse(await d8(n));if(!r.success)throw new $(`response-invalid`);let i=c8(r.data.issuer);if(!rte(i).some(({url:t})=>t.href===e.href))throw new $(`issuer-mismatch`);return{issuer:i.href,metadata:r.data}}async function p8(e,t){let n;try{n=await ate(e,{fetchFn:t})}catch(e){throw a8(e,e instanceof Jee?`issuer-mismatch`:`discovery-failed`)}if(n===void 0)throw new $(`discovery-failed`);if(!u8(n.issuer,e.href))throw new $(`issuer-mismatch`);return n}async function RHe(e,t){try{return await p8(c8(e),t)}catch(e){throw a8(e,`discovery-failed`)}}async function m8(e){try{let t=l8(e.serverUrl),n,r,i;if(e.config.authServerMetadataUrl!==void 0)({issuer:n,metadata:r}=await LHe(c8(e.config.authServerMetadataUrl),e.fetch));else{let a=await IHe(new URL(t),e);if(!u8(a.resource,t))throw new $(`resource-mismatch`);let o=a.authorization_servers?.[0];if(o===void 0)throw new $(`discovery-failed`);let s=c8(o);r=await p8(s,e.fetch),n=s.href,i=a.scopes_supported}if(c8(r.authorization_endpoint),c8(r.token_endpoint),r.registration_endpoint!==void 0&&c8(r.registration_endpoint),r.code_challenge_methods_supported?.includes(`S256`)!==!0)throw new $(`pkce-unsupported`);let a=e.config.scopes?.join(` `)??e.challengeScope??(i===void 0||i.length===0?void 0:i.join(` `));return{resource:t,issuer:n,metadata:r,...a===void 0?{}:{scope:a}}}catch(e){throw a8(e,`discovery-failed`)}}const h8=`127.0.0.1`,g8=`/callback`,_8={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'`,"X-Content-Type-Options":`nosniff`,Connection:`close`};function v8(e,t){e.writeHead(t,{..._8,"Content-Type":`text/plain; charset=utf-8`}),e.end(t===404?`Not found`:`Bad request`)}function y8(e,t){if(e===null)return!1;let n=Buffer.from(e,`utf8`),r=Buffer.from(t,`utf8`);return n.length===r.length&&Kn(n,r)}function b8(e){let t=e.get(`code`),n=e.get(`iss`);return e.has(`error`)?new $(`authorization-denied`):t===null||t===``?new $(`callback-invalid`):{code:t,...n===null?{}:{iss:n}}}function x8(e){return`http://${h8}:${e}${g8}`}async function zHe(){let e=hr();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,h8,()=>t())})}catch{throw new $(`callback-unavailable`)}let t=e.address().port;return await new Promise(t=>e.close(()=>t())),t}function BHe(e){let t=!1;return{accept:n=>{let r=n.trim();if(t||!URL.canParse(r))throw new $(`callback-invalid`);let i=new URL(r);if(`${i.origin}${i.pathname}`!==e.redirectUri||i.username!==``||i.password!==``||!y8(i.searchParams.get(`state`),e.expectedState))throw new $(`callback-invalid`);t=!0;let a=b8(i.searchParams);if(a instanceof $)throw a;return a}}}async function VHe(e){let t,n=new Promise((e,n)=>{t={resolve:e,reject:n}});n.catch(()=>void 0);let r=!1,i=0,a=hr((n,a)=>{if(n.headers.host!==`${h8}:${i}`)return v8(a,400);let o=new URL(n.url??`/`,`http://${h8}:${i}`);if(o.pathname!==g8||r)return v8(a,404);if(n.method!==`GET`)return v8(a,405);if(!y8(o.searchParams.get(`state`),e.expectedState))return v8(a,400);r=!0;let c=b8(o.searchParams);a.writeHead(c instanceof $?400:200,_8),a.end(c instanceof $?`<!doctype html><title>Sign-in failed</title><p>Sign-in did not complete. Return to the application for details.</p>`:`<!doctype html><title>Signed in</title><p>Signed in. You can close this tab and return to the application.</p>`),a.once(`finish`,()=>void s()),c instanceof $?t.reject(c):t.resolve(c)}),o,s=()=>(o??=new Promise(t=>{clearTimeout(u),e.signal?.removeEventListener(`abort`,l),a.close(()=>t()),a.closeAllConnections()}),o),c=e=>{t.reject(new $(e)),s()},l=()=>c(`cancelled`),u;try{await new Promise((t,n)=>{a.once(`error`,n),a.listen(e.port??0,h8,()=>{a.off(`error`,n),t()})})}catch{throw clearTimeout(u),new $(`callback-unavailable`)}return i=a.address().port,e.signal?.aborted===!0?c(`cancelled`):e.signal?.addEventListener(`abort`,l,{once:!0}),{redirectUri:x8(i),wait:()=>(u===void 0&&o===void 0&&(u=setTimeout(()=>c(`callback-timeout`),e.timeoutMs??3e5)),n),close:s}}function S8(e,t){return{securityIdentity:e,serverUrl:l8(t)}}function C8(e){let t=Vn(`sha256`);for(let n of[e.securityIdentity,e.serverUrl])t.update(`${n.length}:${n}`);return t.digest(`hex`)}const HHe=[`clientSecret`,`refreshToken`,`scope`,`tokenEndpointAuthMethod`],UHe=[`issuer`,`authorizationEndpoint`,`tokenEndpoint`,`resource`,`clientId`,`accessToken`];function w8(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function WHe(e){if(!w8(e)||UHe.some(t=>typeof e[t]!=`string`)||HHe.some(t=>e[t]!==void 0&&typeof e[t]!=`string`))return;for(let t of[`expiresAt`,`issuedAt`]){let n=e[t];if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return}let t=e.tokenEndpointAuthMethods;if(!(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`))))return e}function T8(e){let t=t=>M(e,`${C8(t)}.json`);return{get:async e=>{let n=t(e),r;try{Qt(n),r=A(n,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw new $(`store-failed`)}let i;try{i=JSON.parse(r)}catch{throw new $(`store-failed`)}if(!w8(i)||i.version!==1||!w8(i.key)||i.key.securityIdentity!==e.securityIdentity||i.key.serverUrl!==e.serverUrl)throw new $(`store-failed`);let a=WHe(i.credential);if(a===void 0)throw new $(`store-failed`);return a},set:async(n,r)=>{try{Yt(e);let i={version:1,key:{securityIdentity:n.securityIdentity,serverUrl:n.serverUrl},credential:r};Jt(t(n),`${JSON.stringify(i,null,2)}\n`)}catch{throw new $(`store-failed`)}},delete:async e=>{try{Tn(t(e),{force:!0})}catch{throw new $(`store-failed`)}}}}const GHe={createExclusive:(e,t)=>kn(e,t,{flag:`wx`,mode:384}),read:e=>A(e,`utf8`),mtimeMs:e=>Dn(e).mtimeMs,rename:(e,t)=>wn(e,t),link:(e,t)=>gn(e,t),unlink:e=>On(e)};function KHe(e,t){return new Promise((n,r)=>{if(t?.aborted===!0)return r(new $(`cancelled`));let i=()=>{clearTimeout(a),r(new $(`cancelled`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}function E8(e,t={}){let n=t.staleMs??6e4,r=t.timeoutMs??9e4,i=t.pollMs??50,a={...GHe,...t.fs},o=(e,t)=>{let n=`${e}.${Wn(8).toString(`hex`)}.aside`;try{a.rename(e,n)}catch{return}let r=!1;try{r=t(n)}catch{}if(!r)try{a.link(n,e)}catch{}try{a.unlink(n)}catch{}},s=(e,t)=>{try{return a.createExclusive(e,t),!0}catch(e){if(e.code!==`EEXIST`)throw new $(`store-failed`)}let r;try{r={token:a.read(e),mtimeMs:a.mtimeMs(e)}}catch{return!1}return Date.now()-r.mtimeMs>n&&o(e,e=>a.read(e)===r.token&&a.mtimeMs(e)===r.mtimeMs),!1},c=(e,t)=>{try{if(a.read(e)!==t)return}catch{return}o(e,e=>a.read(e)===t)};return{withLock:async(t,n,a)=>{try{Yt(e)}catch{throw new $(`store-failed`)}let o=M(e,`${C8(t)}.lock`),l=Wn(16).toString(`hex`),u=Date.now()+r;for(;!s(o,l);){if(Date.now()>=u)throw new $(`lock-timeout`);await KHe(i,a)}try{return await n()}finally{c(o,l)}}}}function D8(e,t,n,r){if(e.token_type.toLowerCase()!==`bearer`)throw new $(`token-type-unsupported`);let i=e.refresh_token??r,a=e.expires_in;return{...t,accessToken:e.access_token,...i===void 0?{}:{refreshToken:i},...a===void 0||!Number.isFinite(a)?{}:{expiresAt:n+a*1e3,issuedAt:n},...e.scope===void 0?{}:{scope:e.scope}}}async function qHe(e,t,n,r){if(e.config.clientId!==void 0)return{client_id:e.config.clientId,...e.clientSecret===void 0?{}:{client_secret:e.clientSecret}};if(e.clientSecret!==void 0)throw new $(`client-secret-without-client-id`);if(t.metadata.registration_endpoint===void 0)throw new $(`registration-unavailable`);try{return await lte(t.issuer,{metadata:t.metadata,clientMetadata:{client_name:e.clientName,redirect_uris:[n],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`none`},...t.scope===void 0?{}:{scope:t.scope},fetchFn:r})}catch(e){throw a8(e,`registration-failed`)}}async function JHe(e,t){let n=e.readRedirect;return n===void 0?VHe({expectedState:t,...e.config.callbackPort===void 0?{}:{port:e.config.callbackPort},...e.callbackTimeoutMs===void 0?{}:{timeoutMs:e.callbackTimeoutMs},...e.signal===void 0?{}:{signal:e.signal}}):O8(e,n,t,x8(e.config.callbackPort??await zHe()))}function O8(e,t,n,r){let i=BHe({expectedState:n,redirectUri:r});return{redirectUri:r,wait:async()=>{let n=AbortSignal.timeout(e.callbackTimeoutMs??3e5),r=e.signal===void 0?n:AbortSignal.any([e.signal,n]),a=new Promise((e,t)=>{let i=()=>t(new $(n.aborted?`callback-timeout`:`cancelled`));r.aborted?i():r.addEventListener(`abort`,i,{once:!0})});a.catch(()=>void 0);let o;try{o=await Promise.race([t(r),a])}catch(e){throw a8(e,`cancelled`)}return i.accept(o)},close:async()=>void 0}}async function k8(e){let t=s8(e.network,e.signal),n=await m8({serverUrl:e.serverUrl,config:e.config,fetch:t}),r=Wn(32).toString(`base64url`),i=await JHe(e,r);try{let a=await qHe(e,n,i.redirectUri,t),o=new URL(n.resource),s;try{s=await fte(n.issuer,{metadata:n.metadata,clientInformation:a,redirectUrl:i.redirectUri,state:r,resource:o,...n.scope===void 0?{}:{scope:n.scope}})}catch(e){throw a8(e,`discovery-failed`)}if(s.authorizationUrl.protocol!==`https:`)throw new $(`insecure-endpoint`);try{await e.openBrowser(s.authorizationUrl,i.redirectUri)}catch(t){let n=e.readRedirectWhenBrowserFails,a=t instanceof $&&t.reason===`cancelled`;if(n===void 0||e.readRedirect!==void 0||a)throw a8(t,`browser-failed`);let o=i;i=O8(e,n,r,o.redirectUri),await o.close()}let c=await i.wait(),l=n.metadata.authorization_response_iss_parameter_supported===!0;if(c.iss!==void 0&&c.iss!==n.metadata.issuer||c.iss===void 0&&l)throw new $(`issuer-parameter-mismatch`);let u;try{u=await ote(n.issuer,{metadata:n.metadata,clientInformation:a,authorizationCode:c.code,...c.iss===void 0?{}:{iss:c.iss},codeVerifier:s.codeVerifier,redirectUri:i.redirectUri,resource:o,fetchFn:t})}catch(e){throw a8(e,`token-exchange-failed`)}let d=D8(u,{issuer:n.issuer,authorizationEndpoint:n.metadata.authorization_endpoint,tokenEndpoint:n.metadata.token_endpoint,...n.metadata.token_endpoint_auth_methods_supported===void 0?{}:{tokenEndpointAuthMethods:n.metadata.token_endpoint_auth_methods_supported},resource:n.resource,clientId:a.client_id,...a.client_secret===void 0?{}:{clientSecret:a.client_secret},...`token_endpoint_auth_method`in a&&a.token_endpoint_auth_method!==void 0?{tokenEndpointAuthMethod:a.token_endpoint_auth_method}:{}},(e.now??Date.now)()),f={securityIdentity:e.securityIdentity,serverUrl:n.resource};return await e.lock.withLock(f,()=>e.store.set(f,d),e.signal),{issuer:n.issuer,...d.scope===void 0?{}:{scope:d.scope}}}finally{await i.close()}}async function YHe(e){let t;try{t=await e.store.get(S8(e.securityIdentity,e.serverUrl))}catch{return`sign-in-required`}return t===void 0?`signed-out`:t.expiresAt===void 0||(e.now??Date.now)()<t.expiresAt?`signed-in`:t.refreshToken===void 0?`sign-in-required`:`expired-refreshable`}function XHe(e,t,n){let r=ute({client_id:e.clientId,...e.clientSecret===void 0?{}:{client_secret:e.clientSecret},...e.tokenEndpointAuthMethod===void 0?{}:{token_endpoint_auth_method:e.tokenEndpointAuthMethod}},[...t??e.tokenEndpointAuthMethods??[]]);if(r===`client_secret_basic`&&e.clientSecret!==void 0){let t=`${e.clientId}:${e.clientSecret}`;return{Authorization:`Basic ${Buffer.from(t,`utf8`).toString(`base64`)}`}}return n.set(`client_id`,e.clientId),r===`client_secret_post`&&e.clientSecret!==void 0&&n.set(`client_secret`,e.clientSecret),{}}async function ZHe(e){try{let t=await e.json();return typeof t==`object`&&!!t&&t.error===`unsupported_token_type`}catch{return!1}}async function A8(e,t,n,r,i){let a=new URLSearchParams({token:n,token_type_hint:r});try{let n={"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`,...XHe(t,e.authMethods,a)},o=await i(e.url,{method:`POST`,headers:n,body:a});return o.status===200?{token:r,revoked:!0}:{token:r,revoked:!1,failure:await ZHe(o)?`token-type-not-revocable`:`revocation-failed`}}catch(e){return{token:r,revoked:!1,failure:a8(e,`revocation-failed`).reason}}}function QHe(e){let t=e.revocation_endpoint;if(t===void 0)return;if(typeof t!=`string`||!URL.canParse(t)||new URL(t).protocol!==`https:`)throw new $(`insecure-endpoint`);let n=e.revocation_endpoint_auth_methods_supported;return Array.isArray(n)&&n.every(e=>typeof e==`string`)?{url:t,authMethods:n}:{url:t}}async function $He(e,t,n){let r=s8(t,n),i;try{i=QHe(await RHe(e.issuer,r))}catch(e){return{revocation:`failed`,revocationFailure:a8(e,`revocation-failed`).reason}}if(i===void 0)return{revocation:`unsupported`};let a=[];e.refreshToken!==void 0&&a.push(await A8(i,e,e.refreshToken,`refresh_token`,r)),a.push(await A8(i,e,e.accessToken,`access_token`,r));let o=a.find(e=>!e.revoked)?.failure,s=a.filter(e=>e.revoked).length;return{revocation:o===void 0?`revoked`:s===0?`failed`:`partial`,...o===void 0?{}:{revocationFailure:o},tokens:a}}async function j8(e){let t=S8(e.securityIdentity,e.serverUrl),{removed:n,credential:r}=await e.lock.withLock(t,async()=>{let n,r=!1;try{n=await e.store.get(t)}catch{r=!0}return await e.store.delete(t),{removed:r||n!==void 0,credential:n}},e.signal);return r===void 0?{removed:n,revocation:`not-attempted`}:{removed:n,...await $He(r,e.network,e.signal)}}const eUe=/^[\x21\x23-\x5b\x5d-\x7e]+(?: [\x21\x23-\x5b\x5d-\x7e]+)*$/;function tUe(e){if(e===void 0)return{};let t;try{t=ste(new Response(null,{headers:{"www-authenticate":e}}))}catch{return{}}let n=t.scope!==void 0&&t.scope.length<=512&&eUe.test(t.scope)?t.scope:void 0;return{...t.resourceMetadataUrl===void 0?{}:{resourceMetadataUrl:t.resourceMetadataUrl.href},...n===void 0?{}:{scope:n},...t.error===void 0?{}:{error:t.error}}}function nUe(e){let t=S8(e.securityIdentity,e.serverUrl),n=e.now??Date.now,r=e.expirySkewMs??6e4,i,a,o=!1,s=async n=>{throw n&&await e.store.delete(t),o||(o=!0,e.notify({kind:`login-required`,serverId:e.serverId})),new $(`login-required`)},c=e=>{if(e.expiresAt===void 0)return!1;let t=e.issuedAt===void 0?void 0:e.expiresAt-e.issuedAt,i=t===void 0?r:Math.min(r,Math.max(0,t/2));return n()>=e.expiresAt-i},l=e=>e.accessToken!==i&&!c(e),u=async(r,i,a=!1)=>{let o=r.refreshToken;if(o===void 0)return s(!0);let c={client_id:r.clientId,...r.clientSecret===void 0?{}:{client_secret:r.clientSecret},...r.tokenEndpointAuthMethod===void 0?{}:{token_endpoint_auth_method:r.tokenEndpointAuthMethod}},d;try{d=await cte(r.issuer,{metadata:{issuer:r.issuer,authorization_endpoint:r.authorizationEndpoint,token_endpoint:r.tokenEndpoint,response_types_supported:[`code`],...r.tokenEndpointAuthMethods===void 0?{}:{token_endpoint_auth_methods_supported:[...r.tokenEndpointAuthMethods]}},clientInformation:c,refreshToken:o,resource:new URL(r.resource),fetchFn:s8(e.network,i)})}catch(n){if(!(n instanceof Yee&&n.code===Xee.InvalidGrant))throw a8(n,`refresh-failed`);let r=await e.store.get(t);return r===void 0?s(!1):r.refreshToken===o?s(!0):l(r)?r:a?s(!1):u(r,i,!0)}let{accessToken:f,refreshToken:p,expiresAt:m,issuedAt:h,scope:g,..._}=r,v=D8(d,_,n(),o);return await e.store.set(t,v),v},d=async n=>{let r=a;a=void 0;let i=await e.store.get(t);if(i===void 0)return s(!1);if(r===void 0&&l(i))return i;let o=r===void 0?void 0:await m8({serverUrl:e.serverUrl,config:e.config,fetch:s8(e.network,n),...r.resourceMetadataUrl===void 0?{}:{resourceMetadataUrl:r.resourceMetadataUrl}});return e.lock.withLock(t,async()=>{let r=await e.store.get(t);return r===void 0?s(!1):o!==void 0&&(!u8(o.issuer,r.issuer)||!u8(o.metadata.token_endpoint,r.tokenEndpoint))?s(!0):l(r)?r:u(r,n)},n)},f=new J6(async e=>{let t=await d(e);return o=!1,t}),p=new WeakMap,m=0;return{authorize:async e=>{let{value:t,generation:n}=await f.getEntry(e.signal);c(t)&&(f.invalidate(n),{value:t,generation:n}=await f.getEntry(e.signal)),m=Math.max(m,n);let r=Object.freeze({Authorization:`Bearer ${t.accessToken}`});return p.set(r,{generation:n,accessToken:t.accessToken}),r},onRejected:async t=>{let n=p.get(t.authorization);if(n===void 0)return`fail`;let r=tUe(t.wwwAuthenticate);return t.status===403?(r.error===`insufficient_scope`&&e.notify({kind:`insufficient-scope`,serverId:e.serverId,...r.scope===void 0?{}:{scope:r.scope}}),`fail`):t.status===401?n.generation<m?`retry`:(i!==n.accessToken&&(i=n.accessToken,a={...r.resourceMetadataUrl===void 0?{}:{resourceMetadataUrl:r.resourceMetadataUrl}}),f.invalidate(n.generation),`retry`):`fail`},forget:()=>f.invalidate(m),close:()=>f.close()}}const M8=65536;var N8=class extends Error{reason;constructor(e){super(`Stdio transport ${e}`),this.reason=e,this.name=`MCPStdioError`}};function P8(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(new N8(`cleanup`)),t);e.then(e=>{clearTimeout(i),n(e)},()=>{clearTimeout(i),r(new N8(`cleanup`))})})}var rUe=class{snapshot;revalidate;onclose;onerror;onmessage;sensitiveDiagnostics=!0;child;closePromise;childClosed=!1;closeNotified=!1;started=!1;stderrBytes=0;stderrTruncated=!1;stdoutParts=[];stdoutBytes=0;resourceReads=new Set;resolveChildClose;childClose=new Promise(e=>{this.resolveChildClose=e});constructor(e,t){this.snapshot=e,this.revalidate=t}get stderrSummary(){return{bytes:this.stderrBytes,truncated:this.stderrTruncated}}get pid(){return this.child?.pid??null}get closedDirectChild(){return this.childClosed}get stdioStartupMs(){return this.snapshot.startupMs}notifyClose(){this.closeNotified||(this.closeNotified=!0,this.onclose?.())}receive(e){if(this.closePromise!==void 0)return;let t=0;for(;t<e.length;){let n=e.indexOf(10,t),r=n<0?e.length:n,i=e.subarray(t,r),a=N6(this)&&this.resourceReads.size>0?j6:A6;if(this.stdoutBytes+i.length>a){this.onerror?.(new N8(`receive-limit`)),this.close().catch(()=>this.onerror?.(new N8(`cleanup`)));return}if(this.stdoutParts.push(i),this.stdoutBytes+=i.length,n>=0){let e=this.stdoutBytes,t=Buffer.concat(this.stdoutParts,this.stdoutBytes).toString(`utf8`).replace(/\r$/u,``);this.stdoutParts=[],this.stdoutBytes=0;try{let n=ite(t),r=`id`in n&&n.id!==void 0&&this.resourceReads.has(n.id);if(e>8388608&&!r){this.onerror?.(new N8(`receive-limit`)),this.close().catch(()=>this.onerror?.(new N8(`cleanup`)));return}`id`in n&&n.id!==void 0&&!(`method`in n)&&this.resourceReads.delete(n.id),this.onmessage?.(n)}catch{this.onerror?.(new N8(`receive-invalid`)),this.close().catch(()=>this.onerror?.(new N8(`cleanup`)));return}}t=r+1}}async start(){if(this.started||this.closePromise!==void 0)throw new N8(`start`);if(this.started=!0,!await this.revalidate())throw new N8(`authority`);if(this.closePromise!==void 0)throw new N8(`start`);let e=Object.create(null);for(let t of hte)e[t]=this.snapshot.env[t]??``;for(let[t,n]of Object.entries(this.snapshot.env))e[t]=n;try{let t=on(this.snapshot.command,[...this.snapshot.args],{cwd:this.snapshot.cwd,env:e,stdio:[`pipe`,`pipe`,`pipe`],shell:!1,windowsHide:process.platform===`win32`});this.child=t;let n=new Promise((e,n)=>{t.once(`spawn`,()=>e()),t.once(`error`,()=>n(new N8(`start`)))});if(t.on(`error`,()=>this.onerror?.(new N8(`start`))),t.on(`close`,()=>{this.childClosed=!0,this.child=void 0,this.resolveChildClose?.(),this.notifyClose()}),t.stdin.on(`error`,()=>this.onerror?.(new N8(`send`))),t.stdout.on(`data`,e=>this.receive(e)),t.stdout.on(`error`,()=>this.onerror?.(new N8(`receive-invalid`))),t.stderr.on(`data`,e=>{this.stderrBytes=Math.min(M8,this.stderrBytes+e.length),this.stderrBytes>=M8&&(this.stderrTruncated=!0)}),await n,this.childClosed)throw new N8(`early-exit`)}catch{throw await this.close(),new N8(`start`)}}async send(e){let t=this.child;if(t===void 0||this.childClosed)throw new N8(`send`);`method`in e&&e.method===`resources/read`&&`id`in e&&N6(this)&&this.resourceReads.add(e.id);try{await new Promise((n,r)=>{t.stdin.write(dte(e),e=>{e?r(e):n()})})}catch{throw new N8(`send`)}}close(){return this.closePromise===void 0&&(this.closePromise=this.closeOwned()),this.closePromise}async closeOwned(){let e=this.child;if(this.stdoutParts=[],this.stdoutBytes=0,this.resourceReads.clear(),e===void 0){this.notifyClose();return}try{e.stdin.end();try{await P8(this.childClose,2e3)}catch{e.kill(`SIGTERM`);try{await P8(this.childClose,2e3)}catch{e.kill(`SIGKILL`),await P8(this.childClose,this.snapshot.cleanupMs-4e3)}}}catch{throw new N8(`cleanup`)}}};function F8({definition:e,activation:t}){let n=y6(e),r=x6({name:e.name,source:e.source,origin:e.origin,status:`resolved`,definition:e,shadowed:[]});return t.serverId===e.name&&t.source===e.source&&t.provenance.kind===e.source&&t.provenance.id===e.origin&&t.provenance.version===n&&t.definitionFingerprint===n&&t.securityIdentity===r&&t.endpoint===b6(e)}function I8(e){return{ok:!1,reason:e,message:`Stdio transport refused: ${e}`}}function iUe(e){return Object.freeze({...e,provenance:Object.freeze({...e.provenance}),...e.workspace===void 0?{}:{workspace:Object.freeze({...e.workspace})}})}function aUe(e){let t=new WeakMap;return{kind:`stdio`,async admit(n){try{let r={definition:n.definition,activation:iUe(n.activation)};if(!F8(r))return I8(`definition-identity`);let i=e.admission.admit(r.activation);if(!i.allowed||i.status!==`approved`||i.definitionFingerprint!==r.activation.definitionFingerprint||i.securityIdentity!==r.activation.securityIdentity)return I8(`activation`);let a=await jHe(r,e.authority);if(a===void 0||!F8(r))return I8(`authority`);let o=Object.freeze({kind:`stdio`});return t.set(o,a),{ok:!0,admitted:o}}catch{return I8(`invalid-input`)}},construct(n){let r=t.get(n);if(r===void 0)throw Error(`Stdio transport refused: invalid admission`);return new rUe(r,()=>MHe(r,e))}}}const L8=`io.modelcontextprotocol/ui`,R8=`text/html;profile=mcp-app`;function z8(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e[L8];return typeof t==`object`&&!!t&&!Array.isArray(t)}const oUe=/^[A-Za-z0-9+/]*={0,2}$/u;function sUe(e){return typeof e==`string`?e.replace(/\s+/gu,``).toLowerCase():void 0}function cUe(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return e.length/4*3-t}function lUe(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return}}function uUe(e){let t=e.text,n=e.blob;if(typeof t==`string`&&n===void 0)return t.length===0?{ok:!1,reason:`content`}:Buffer.byteLength(t,`utf8`)>2097152?{ok:!1,reason:`too-large`}:{ok:!0,html:t,mimeType:R8};if(typeof n==`string`&&t===void 0){if(n.length===0||n.length%4!=0||!oUe.test(n))return{ok:!1,reason:`content`};if(cUe(n)>2097152)return{ok:!1,reason:`too-large`};let e=lUe(Buffer.from(n,`base64`));return e===void 0||e.length===0?{ok:!1,reason:`content`}:{ok:!0,html:e,mimeType:R8}}return{ok:!1,reason:`content`}}function dUe(e,t){if(t.contents.length===0)return{ok:!1,reason:`missing`};let[n]=t.contents;return t.contents.length!==1||n===void 0?{ok:!1,reason:`content`}:n.uri===e?sUe(n.mimeType)===`text/html;profile=mcp-app`?uUe(n):{ok:!1,reason:`mime-type`}:{ok:!1,reason:`uri-mismatch`}}function fUe(e,t){let n=[];for(let r of[...e.adopted,...e.adapted])r.kind===`tool`&&r.provenance.serverId===t&&(r.ui!==void 0&&!r.ui.visibility.includes(`app`)||n.push([r.sourceName,r.canonicalName]));return Object.fromEntries(n)}var B8=class extends Error{reason;constructor(e){super(`MCP skill refused: ${e}`),this.reason=e,this.name=`MCPSkillError`}};function V8(){throw new B8(`invalid-manifest`)}function H8(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function U8(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)?JSON.stringify(e):Array.isArray(e)?`[${e.map(U8).join(`,`)}]`:H8(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${U8(e[t])}`).join(`,`)}}`:V8()}function pUe(e,t){try{let n=new URL(e),r=new URL(t),i=n.pathname.slice(0,n.pathname.lastIndexOf(`/`)+1);return n.protocol===r.protocol&&n.host===r.host&&n.username===r.username&&n.password===r.password&&r.pathname.startsWith(i)&&!r.pathname.endsWith(`/`)}catch{return!1}}function W8(e,t){if(!H8(e)||typeof e.uri!=`string`||!H8(e.frontmatter))return V8();let{name:n,description:r}=e.frontmatter;if(typeof n!=`string`||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(n)||n.length>64||typeof r!=`string`||r.length===0||r.length>1024)return V8();try{let t=new URL(e.uri),r=`${t.host}${t.pathname}`.split(`/`);if(r.at(-1)!==`SKILL.md`||decodeURIComponent(r.at(-2)??``)!==n)return V8()}catch{return V8()}let i=JSON.parse(U8(e.frontmatter)),a;if(e.resources===`dynamic`)a=`dynamic`;else{if(!Array.isArray(e.resources)||e.resources.length<1||e.resources.length>512)return V8();let t=new Set,n=0;if(a=e.resources.map(r=>!H8(r)||typeof r.uri!=`string`||typeof r.digest!=`string`||!/^sha256:[a-f0-9]{64}$/.test(r.digest)||typeof r.size!=`number`||!Number.isSafeInteger(r.size)||r.size<0||t.has(r.uri)||!pUe(e.uri,r.uri)||(t.add(r.uri),n+=r.size,n>16*1024*1024)?V8():{uri:r.uri,digest:r.digest,size:r.size}),!t.has(e.uri))return V8()}let o=Vn(`sha256`).update(U8({uri:e.uri,frontmatter:i,resources:a===`dynamic`?a:[...a].sort((e,t)=>e.uri<t.uri?-1:+(e.uri>t.uri))})).digest(`hex`);return{identity:{...t},uri:e.uri,frontmatter:i,resources:a,manifestFingerprint:o}}function mUe(e,t,n){if(e.resources===`dynamic`)throw new B8(`unsupported-dynamic`);let r=e.resources.find(e=>e.uri===t);if(!r)throw new B8(`missing-resource`);if(!H8(n)||n.uri!==t||n.mimeType!==void 0&&typeof n.mimeType!=`string`||!(typeof n.text==`string`&&!(`blob`in n)||typeof n.blob==`string`&&!(`text`in n)))throw new B8(`invalid-resource`);let i;if(typeof n.text==`string`)i=Buffer.from(n.text,`utf8`);else{if(typeof n.blob!=`string`)throw new B8(`invalid-resource`);try{i=Buffer.from(atob(n.blob),`latin1`)}catch{throw new B8(`invalid-resource`)}}if(i.byteLength!==r.size)throw new B8(`size-mismatch`);let a=`sha256:${Vn(`sha256`).update(i).digest(`hex`)}`;if(a!==r.digest)throw new B8(`digest-mismatch`);return{uri:t,digest:a,size:i.byteLength,...typeof n.text==`string`?{text:n.text}:{blob:n.blob},...n.mimeType===void 0?{}:{mimeType:n.mimeType}}}var G8=class extends Error{reason;constructor(e){super(`Unsupported stateless MCP result: ${e}; inspect the operation before any retry`),this.reason=e,this.name=`MCPStatelessProtocolError`}};function K8(e){if(typeof e.ttlMs!=`number`||!Number.isFinite(e.ttlMs)||e.ttlMs<0||e.cacheScope!==`public`&&e.cacheScope!==`private`)throw Error(`Invalid stateless MCP cache metadata`);return{ttlMs:e.ttlMs,cacheScope:e.cacheScope,receivedAtMs:Date.now()}}const hUe={"~standard":{version:1,vendor:`robota-agent-mcp`,validate:e=>typeof e==`object`&&e&&!Array.isArray(e)?{value:e}:{issues:[{message:`expected a result object`}]}}};function gUe(e,t){let n=new Map,r=new Map,i=0,a=(e,t)=>{(r.get(e)??0)>t||(r.set(e,t),n.delete(e))},o=e=>{if(e.resultType!==`complete`)throw new B8(`invalid-manifest`);K8(e)};return{async list(s){if(!Number.isSafeInteger(s.maxPages)||s.maxPages<1)throw new B8(`page-bound`);let c=++i,l=[],u=new Set,d=new Set,f;for(let i=0;i<s.maxPages;i++){let i=await t(`skills/list`,f===void 0?{}:{cursor:f},s);if(o(i),!Array.isArray(i.skills))throw new B8(`invalid-manifest`);for(let t of i.skills){typeof t==`object`&&t&&`uri`in t&&typeof t.uri==`string`&&a(t.uri,c);let n=W8(t,e);if(u.has(n.uri))throw new B8(`invalid-manifest`);u.add(n.uri),l.push(n)}if(i.nextCursor===void 0){for(let e of l)r.get(e.uri)===c&&n.set(e.uri,structuredClone(e));return l}if(typeof i.nextCursor!=`string`||i.nextCursor.length===0||d.has(i.nextCursor))throw new B8(`invalid-manifest`);f=i.nextCursor,d.add(f)}throw new B8(`page-bound`)},async get(s,c){let l=++i;a(s,l);let u=await t(`skills/get`,{uri:s},c);if(r.get(s)!==l)throw new B8(`changed-manifest`);o(u);let d=W8(u.skill,e);if(d.uri!==s)throw new B8(`invalid-manifest`);return n.set(s,structuredClone(d)),d},async read(r,i,a){let o=n.get(r.uri);if(!o||r.identity.serverId!==e.serverId||r.identity.catalogGeneration!==e.catalogGeneration||o.manifestFingerprint!==r.manifestFingerprint||W8(r,e).manifestFingerprint!==o.manifestFingerprint)throw new B8(`changed-manifest`);if(o.resources===`dynamic`)throw new B8(`unsupported-dynamic`);if(!o.resources.some(e=>e.uri===i))throw new B8(`missing-resource`);try{let e=await t(`resources/read`,{uri:i},a);if(e.resultType!==`complete`||!Array.isArray(e.contents)||e.contents.length!==1)throw new B8(`invalid-resource`);let s=K8(e);if(n.get(r.uri)?.manifestFingerprint!==o.manifestFingerprint)throw new B8(`changed-manifest`);return{...mUe(o,i,e.contents[0]),cacheHint:s}}catch(e){throw n.get(r.uri)?.manifestFingerprint===o.manifestFingerprint&&n.delete(r.uri),e}}}}function _Ue(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e[`io.modelcontextprotocol/skills`];return typeof t!=`object`||!t||Array.isArray(t)?!1:!(`directoryRead`in t)||typeof t.directoryRead==`boolean`}const q8=[`anthropic`,`maxResultSizeChars`].join(`/`);function vUe(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`invalid`,reason:`invalid-type`};let t=e;if(!Object.hasOwn(t,q8))return{kind:`absent`};let n=t[q8];return typeof n!=`number`||!Number.isSafeInteger(n)?{kind:`invalid`,reason:`invalid-type`}:n<=25e3||n>5e5?{kind:`invalid`,reason:`out-of-range`}:{kind:`accepted`,maxResultChars:n}}const yUe=/\s/u,bUe=[`model`,`app`];function xUe(e){return e===`model`||e===`app`}function SUe(e){if(e===void 0)return bUe;if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(!xUe(n)||t.includes(n))return;t.push(n)}return t}function CUe(e){return e.startsWith(`ui://`)&&e.length>5&&!yUe.test(e)}function wUe(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`absent`};let t=e;if(!Object.hasOwn(t,`ui`))return{kind:`absent`};let n=t.ui;if(typeof n!=`object`||!n||Array.isArray(n))return{kind:`invalid`,reason:`invalid-type`};let r=n,i=SUe(r.visibility);if(i===void 0)return{kind:`invalid`,reason:`invalid-visibility`};let a=r.resourceUri;if(a!==void 0){if(typeof a!=`string`)return{kind:`invalid`,reason:`invalid-type`,visibility:i};if(!CUe(a))return{kind:`invalid`,reason:`invalid-uri`,visibility:i}}return a===void 0?i.includes(`model`)&&i.includes(`app`)?{kind:`absent`}:{kind:`accepted`,visibility:i}:{kind:`accepted`,resourceUri:a,visibility:i}}var J8=class extends Error{failure;constructor(e){super(`MCP discovery failed (${e.domain}, ${e.kind}): ${e.message}`),this.failure=e,this.name=`MCPDiscoveryError`}};function Y8(e){return{serverId:e.serverId,protocolVersion:e.protocolVersion,serverVersion:e.serverVersion,...e.catalogGeneration===void 0?{}:{catalogGeneration:e.catalogGeneration}}}function X8(e,t){return e.serverId===t.serverId&&e.protocolVersion===t.protocolVersion&&e.serverVersion===t.serverVersion&&e.catalogGeneration===t.catalogGeneration}function Z8(e){if(e===null)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Date)return e;if(Array.isArray(e))return e.map(e=>Z8(e));if(typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Z8(r);return t}return String(e)}function Q8(e){let t=Z8(e);return jt.isObject(t)?t:{}}var $8=class extends Error{kind;details;constructor(e,t,n){super(t),this.kind=e,this.details=n,this.name=`MCPSessionError`}};const e5={name:`mcp-client`,version:`0.0.0`},t5=`2026-07-28`;function n5(e,t,n,r){let i=new qee({name:e.name,version:e.version},{capabilities:{...n===void 0?{}:{elicitation:{form:{}}},...r===!0?{extensions:{[L8]:{mimeTypes:[R8]}}}:{}},inputRequired:{autoFulfill:n!==void 0},...t===void 0?{}:{versionNegotiation:{mode:{pin:t}}}});return n!==void 0&&i.setRequestHandler(`elicitation/create`,(e,t)=>n(e.params,t.mcpReq.signal)),i}function r5(e){return e instanceof ti&&e.code===ni.RequestTimeout}function i5(e){let t=Q8(e),n=t.content;return{content:Array.isArray(n)?n.filter(jt.isObject):[],structuredContent:t.structuredContent,isError:typeof t.isError==`boolean`&&t.isError}}function a5(e){let t=Q8(e).contents;return{contents:Array.isArray(t)?t.map(e=>jt.isObject(e)?e:{}):[]}}function o5(e){let t=[`tools`,`prompts`,`resources`],n={tools:void 0,prompts:void 0,resources:void 0};for(let r of t){let t=e?.[r];t!==void 0&&(n[r]={listChanged:t.listChanged??!1})}return n}function TUe(e){return e}function EUe(e,t){let n=e._meta,r=vUe(n),i=t?wUe(n):{kind:`absent`};return{name:e.name,description:e.description,inputSchema:TUe(e.inputSchema),outputSchema:e.outputSchema===void 0?void 0:Q8(e.outputSchema),...r.kind===`absent`?{}:{resultSizeMetadata:r},...i.kind===`accepted`?{ui:{...i.resourceUri===void 0?{}:{resourceUri:i.resourceUri},visibility:i.visibility}}:i.kind===`invalid`&&i.visibility!==void 0?{ui:{visibility:i.visibility}}:{},...i.kind===`invalid`?{uiProblem:i.reason}:{}}}function DUe(e){return{name:e.name,description:e.description,arguments:e.arguments}}function OUe(e){return{uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType}}function kUe(e,t,n){return t instanceof Zee?new J8({kind:t.code===Qee.InvalidParams?`invalid-cursor`:`protocol`,domain:e,message:t.message,code:t.code,pagesSeen:n}):r5(t)?new J8({kind:`timeout`,domain:e,message:t instanceof Error?t.message:String(t),pagesSeen:n}):new J8({kind:`protocol`,domain:e,message:t instanceof Error?t.message:String(t),pagesSeen:n})}function AUe(e,t,n){if(t>=n)throw new J8({kind:`page-bound-exceeded`,domain:e,message:`Exceeded the configured page bound of ${n} for "${e}"`,pagesSeen:t})}async function jUe(e,t,n,r,i){try{return await i(n,{timeout:r.perRequestTimeoutMs,signal:r.signal})}catch(n){throw kUe(e,n,t)}}function MUe(e,t,n){if(n!==void 0){if(n===``)throw new J8({kind:`invalid-cursor`,domain:e,message:`Server returned an empty nextCursor for "${e}"`,pagesSeen:t});return n}}async function s5(e,t,n,r,i){if(t===void 0)return{state:{kind:`unsupported`},items:[],pages:0};let a=[],o=[],s,c=0;for(;;){AUe(e,c,n.maxPages);let t=await jUe(e,c,s,n,r);c+=1,a.push(...t.items.map(i)),t.cacheHint&&o.push(t.cacheHint);let l=MUe(e,c,t.nextCursor);if(l===void 0)break;s=l}return{state:{kind:`supported`,count:a.length,listChanged:t.listChanged},items:a,pages:c,...o.length===0?{}:{cacheHints:o}}}async function c5(e,t,n,r,i,a=!1){return{identity:n,instructions:r,tools:await s5(`tools`,t.tools,i,async(t,r)=>{let i=await e.request({method:`tools/list`,params:t===void 0?{}:{cursor:t}},r);return{items:i.tools,nextCursor:i.nextCursor,...n.protocolVersion===`2026-07-28`?{cacheHint:K8(i)}:{}}},e=>EUe(e,a)),prompts:await s5(`prompts`,t.prompts,i,async(t,r)=>{let i=await e.request({method:`prompts/list`,params:t===void 0?{}:{cursor:t}},r);return{items:i.prompts,nextCursor:i.nextCursor,...n.protocolVersion===`2026-07-28`?{cacheHint:K8(i)}:{}}},DUe),resources:await s5(`resources`,t.resources,i,async(t,r)=>{let i=await e.request({method:`resources/list`,params:t===void 0?{}:{cursor:t}},r);return{items:i.resources,nextCursor:i.nextCursor,...n.protocolVersion===`2026-07-28`?{cacheHint:K8(i)}:{}}},OUe)}}var l5=class{calls=new Set;open;enter(e){let t={...e};return this.calls.add(t),()=>{this.calls.delete(t),this.firstWithPort()===void 0&&(this.open?.abort(),this.open=void 0)}}answerable(){let e=this.firstWithPort();if(e!==void 0)return this.open??=new AbortController,{ask:e,withdrawn:this.open.signal}}firstWithPort(){for(let e of this.calls)if(e.ask!==void 0)return e.ask}};function u5(e){return async(t,n)=>{if(t.mode===`url`)return{action:`decline`};let r=e.calls.answerable();if(r===void 0)return{action:`decline`};let i=[n,r.withdrawn].filter(e=>e!==void 0);return RUe({serverId:e.serverId(),params:t,ask:r.ask,signal:AbortSignal.any(i)})}}const d5=`respond`,f5={action:`cancel`},NUe={action:`decline`},PUe=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/u,FUe=/^\d{4}-\d{2}-\d{2}$/u,IUe=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/u;function LUe(e){let t=e.codePointAt(0)??0;return t<32||t>=127&&t<=159||t===8232||t===8233||/\s/u.test(e)}function p5(e,t){let n=[],r=!1;for(let t of e){if(LUe(t)){r=!0;continue}r&&n.length>0&&n.push(` `),r=!1,n.push(t)}return n.length<=t?n.join(``):`${n.slice(0,t).join(``)}…`}async function RUe(e){let{serverId:t,params:n,signal:r}=e,i=r===void 0?void 0:{signal:r},a=async t=>{try{return await e.ask(t,i)}catch{return}},o=`mcp-elicitation-${N()}`,s=await a({id:`${o}-0`,title:`MCP server ${JSON.stringify(t)} asks for input`,description:p5(n.message,400),options:[{value:d5,label:`Respond`},{value:`decline`,label:`Decline`,description:`Tell the server you will not answer`}],maxSelect:1,maxVisible:8});if(s===void 0||s.type!==`answer`)return f5;if(s.values[0]!==d5)return NUe;let c=new Set(n.requestedSchema.required??[]),l={},u=0;for(let[e,r]of Object.entries(n.requestedSchema.properties)){u+=1;let n=BUe(t,e,r,c.has(e)),i=await zUe(`${o}-${u}`,n,a);if(i.kind===`cancel`)return f5;i.kind===`value`&&(l[e]=i.value)}return{action:`accept`,content:l}}async function zUe(e,t,n){let r;for(let i=0;i<2;i+=1){let a=r===void 0?t.request.description:[r,t.request.description].filter(Boolean).join(` `),o=await n({...t.request,id:i===0?e:`${e}-again`,...a===void 0?{}:{description:a}});if(o===void 0||o.type!==`answer`)return{kind:`cancel`};let s=t.parse(o);if(s.kind!==`invalid`)return s;r=`Invalid answer: ${s.reason}.`}return{kind:`cancel`}}function BUe(e,t,n,r){let i=`MCP server ${JSON.stringify(e)} asks: ${p5(n.title??t,80)}`,a=K3(t)||n.title!==void 0&&K3(n.title)?`Caution: this field is named like a credential; what you enter is shown as typed and sent to the server.`:void 0,o=e=>{let t=[n.description===void 0?void 0:p5(n.description,400),e,a].filter(Boolean).join(` `);return t.length===0?void 0:t};if(n.type===`boolean`){let e=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}],t=r?void 0:m5(e);return{request:{title:i,description:o(void 0),options:e,maxSelect:1,maxVisible:8,...n.default===void 0?{}:{default:{values:[n.default?`yes`:`no`]}}},parse:e=>{let n=e.values[0];return n===`yes`?{kind:`value`,value:!0}:n===`no`?{kind:`value`,value:!1}:t!==void 0&&n===t?{kind:`skip`}:{kind:`invalid`,reason:`not one of the offered choices`}}}}if(n.type===`array`)return VUe(i,o(void 0),n,r);if(n.type===`string`){if(`enum`in n||`oneOf`in n){let e=HUe(n),t=new Set(e.map(e=>e.value)),a=r?void 0:m5(e);return{request:{title:i,description:o(void 0),options:e,maxSelect:1,maxVisible:8,...n.default!==void 0&&t.has(n.default)?{default:{values:[n.default]}}:{}},parse:e=>{let n=e.values[0];return n!==void 0&&t.has(n)?{kind:`value`,value:n}:a!==void 0&&n===a?{kind:`skip`}:{kind:`invalid`,reason:`not one of the offered choices`}}}}let e=[GUe(n.minLength,n.maxLength),KUe(n.format),n.default===void 0?void 0:`Default: ${p5(n.default,60)}.`,r?void 0:`Leave empty to skip.`].filter(Boolean);return{request:{title:i,description:o(e.length===0?void 0:e.join(` `)),allowFreeText:!0,allowEmpty:!r,...n.default===void 0?{}:{placeholder:p5(n.default,60),default:{text:n.default}}},parse:e=>{let t=e.text??``;if(t.length===0)return r?{kind:`invalid`,reason:`an answer is required`}:{kind:`skip`};let i=[...t].length;if(n.minLength!==void 0&&i<n.minLength)return{kind:`invalid`,reason:`at least ${n.minLength} characters`};if(n.maxLength!==void 0&&i>n.maxLength)return{kind:`invalid`,reason:`at most ${n.maxLength} characters`};let a=qUe(n.format,t);return a===void 0?{kind:`value`,value:t}:{kind:`invalid`,reason:a}}}}let s=n.type===`integer`,c=WUe(n.minimum,n.maximum);return{request:{title:i,description:o([`${s?`A whole number`:`A number`}${c}.`,n.default===void 0?void 0:`Default: ${n.default}.`,r?void 0:`Leave empty to skip.`].filter(Boolean).join(` `)),allowFreeText:!0,allowEmpty:!r,...n.default===void 0?{}:{placeholder:String(n.default),default:{text:String(n.default)}}},parse:e=>{let t=(e.text??``).trim();if(t.length===0)return r?{kind:`invalid`,reason:`an answer is required`}:{kind:`skip`};if(!PUe.test(t))return{kind:`invalid`,reason:`not a number`};let i=Number(t);return Number.isFinite(i)?s&&!Number.isInteger(i)?{kind:`invalid`,reason:`not a whole number`}:n.minimum!==void 0&&i<n.minimum?{kind:`invalid`,reason:`at least ${n.minimum}`}:n.maximum!==void 0&&i>n.maximum?{kind:`invalid`,reason:`at most ${n.maximum}`}:{kind:`value`,value:i}:{kind:`invalid`,reason:`not a number`}}}}function VUe(e,t,n,r){let i=UUe(n),a=new Map(i.map((e,t)=>[e.value,t])),o=Math.max(1,Math.min(n.maxItems??i.length,i.length)),s=Math.min(n.minItems??+!!r,o),c=(n.default??[]).filter(e=>a.has(e)).slice(0,o),l=e=>[...e].sort((e,t)=>(a.get(e)??0)-(a.get(t)??0));if(o===1){let n=!r||s===0?m5(i):void 0;return{request:{title:e,description:t,options:i,maxSelect:1,maxVisible:8,...c.length===0?{}:{default:{values:c}}},parse:e=>{let t=e.values[0];return t!==void 0&&a.has(t)?{kind:`value`,value:[t]}:n!==void 0&&t===n?r?{kind:`value`,value:[]}:{kind:`skip`}:{kind:`invalid`,reason:`not one of the offered choices`}}}}return{request:{title:e,description:t,options:i,minSelect:r?s:0,maxSelect:o,...c.length===0?{}:{default:{values:c}}},parse:e=>{let t=e.values.filter(e=>a.has(e));return t.length===e.values.length?t.length===0&&!r?{kind:`skip`}:t.length===0&&s===0?{kind:`value`,value:[]}:t.length<s?{kind:`invalid`,reason:r?`choose at least ${s}`:`choose none or at least ${s}`}:t.length>o?{kind:`invalid`,reason:`choose at most ${o}`}:{kind:`value`,value:l(t)}:{kind:`invalid`,reason:`not one of the offered choices`}}}}function HUe(e){if(`oneOf`in e)return e.oneOf.map(e=>({value:e.const,label:p5(e.title,60)}));if(`enum`in e){let t=`enumNames`in e?e.enumNames:void 0;return e.enum.map((e,n)=>({value:e,label:p5(t?.[n]??e,60)}))}return[]}function UUe(e){let t=e.items;return`anyOf`in t?t.anyOf.map(e=>({value:e.const,label:p5(e.title,60)})):t.enum.map(e=>({value:e,label:p5(e,60)}))}function m5(e){let t=``;for(;e.some(e=>e.value===t);)t+=`\0`;return e.push({value:t,label:`Leave unanswered`}),t}function WUe(e,t){return e!==void 0&&t!==void 0?` from ${e} to ${t}`:e===void 0?t===void 0?``:` of at most ${t}`:` of at least ${e}`}function GUe(e,t){if(e!==void 0&&t!==void 0)return`Between ${e} and ${t} characters.`;if(e!==void 0)return`At least ${e} characters.`;if(t!==void 0)return`At most ${t} characters.`}function KUe(e){switch(e){case`email`:return`An email address.`;case`uri`:return`A URI.`;case`date`:return`A date (YYYY-MM-DD).`;case`date-time`:return`A date and time (RFC 3339, such as 2026-01-31T09:00:00Z).`;default:return}}function qUe(e,t){switch(e){case`email`:return/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)?void 0:`not an email address`;case`uri`:return URL.canParse(t)?void 0:`not a URI`;case`date`:{if(!FUe.test(t))return`not a date (YYYY-MM-DD)`;let e=new Date(`${t}T00:00:00Z`);return!Number.isNaN(e.getTime())&&e.toISOString().startsWith(t)?void 0:`not a calendar date`}case`date-time`:return IUe.test(t)&&!Number.isNaN(Date.parse(t))?void 0:`not a date and time (RFC 3339)`;default:return}}async function JUe(e,t){let n=e.transport!==void 0;await e.close(),n||await t.close()}function YUe(e){if(!(e instanceof ti)||e.code!==ni.EraNegotiationFailed)return e;let t=e.data?.cause;return t instanceof Error?t:e}function XUe(e){return e instanceof ri||e instanceof ti&&!(e instanceof ete)&&e.code===ni.EraNegotiationFailed&&e.data===void 0}const ZUe=/^application\/json\b/i;function QUe(e,t){let n=uHe(t);return!(e instanceof ri)&&n!==void 0&&!(n.contentType!==void 0&&ZUe.test(n.contentType))?new $8(`initialize-failed`,`Stateless MCP discovery was answered with HTTP ${n.status}`,{status:n.status}):new $8(`unsupported-protocol-version`,`Server does not support the explicitly selected stateless MCP version`)}function $Ue(e){if(!(e instanceof ti))return;let t=e.data;switch(e.code){case ni.UnsupportedResultType:return new G8(t?.resultType===`input_required`?`input_required`:`unknown-result`);case ni.CapabilityNotSupported:return typeof t?.method==`string`?new G8(`input_required`):void 0;case ni.InputRequiredRoundsExceeded:return new G8(`input_required`);default:return}}function eWe(e){return e instanceof ti&&e.code===ni.InvalidResult}async function tWe(e){let t=e.transport;e.skills===!0&&rHe(t);let n=`sensitiveDiagnostics`in t&&t.sensitiveDiagnostics===!0,r=new l5,i=n5(e.clientInfo??e5,t5,e.elicitation===!0?u5({serverId:()=>e.serverId,calls:r}):void 0,e.apps===!0),a,o=()=>a??=JUe(i,t),s,c;try{e.signal?.throwIfAborted();let n=`stdioStartupMs`in t&&typeof t.stdioStartupMs==`number`?Math.min(e.timeouts.startupMs,t.stdioStartupMs):e.timeouts.startupMs,r=new Promise((t,r)=>{s=setTimeout(()=>r(new $8(`startup-timeout`,`Stateless MCP startup timed out`)),n),c=()=>r(new $8(`initialize-failed`,`Stateless MCP startup cancelled`)),e.signal?.addEventListener(`abort`,c,{once:!0})});if(await Promise.race([i.connect(t,{timeout:n,signal:e.signal}),r]),i.getNegotiatedProtocolVersion()!==`2026-07-28`)throw new $8(`unsupported-protocol-version`,`Server does not support the explicitly selected stateless MCP version`)}catch(r){await o();let i=YUe(r),a=XUe(i)?QUe(i,t):i,s=r5(a)&&e.signal?.aborted!==!0||a instanceof $8&&a.kind===`startup-timeout`;throw n?a instanceof N8&&a.reason===`authority`||a instanceof $8&&a.kind===`unsupported-protocol-version`?a:new $8(s?`startup-timeout`:`initialize-failed`,`Stdio stateless MCP startup failed`):s&&!(a instanceof $8)?new $8(`startup-timeout`,`Stateless MCP startup timed out`):a}finally{s!==void 0&&clearTimeout(s),c&&e.signal?.removeEventListener(`abort`,c)}try{let s=i.getDiscoverResult();if(s===void 0)throw Error(`Stateless MCP discovery was not retained`);let c=i.getServerVersion();if(s._meta?.[$ee]!==void 0&&c===void 0)throw Error(`Stateless MCP discovery has no valid server metadata`);let l=i.getServerCapabilities()??{},u=o5(l),d={serverId:e.serverId,serverName:c===void 0?e.serverId:c.name,serverVersion:c===void 0?``:c.version,protocolVersion:t5,catalogGeneration:N(),...c===void 0?{serverInfoProvided:!1}:{}},f=i.getInstructions(),p=L6(t),m=async(e,t,r)=>{try{if(a)throw Error(`Stateless MCP carrier is closed`);return await e()}catch(e){let i=$Ue(e);if(i!==void 0)throw await o(),i;if(r!==void 0&&eWe(e)){let e=r();throw e instanceof G8&&await o(),e}throw(t?.aborted||r5(e))&&(await o(),n)?new N8(`cancelled`):n?new N8(`send`):e}},h=e.skills&&u.resources&&_Ue(l.extensions)?gUe(d,(t,n,r)=>{let a={signal:r?.signal,timeout:r?.timeoutMs??e.timeouts.perCallMs};return m(async()=>({...t===`resources/read`?await i.readResource({uri:String(n.uri)},{...a,cacheMode:`bypass`}):await i.request({method:t,params:n},hUe,a),resultType:`complete`}),r?.signal,()=>new B8(t===`resources/read`?`invalid-resource`:`invalid-manifest`))}):void 0,g=e.apps===!0&&z8(l.extensions)&&u.resources!==void 0,_=[...h===void 0?[]:[`Skills metadata and verified file reads`],...e.apps===!0?[`the UI extension for tool views`]:[]];return{...h===void 0?{}:{skills:h},...g?{apps:g}:{},identity:d,instructions:f,declaredCapabilities:u,discoveryCacheHint:K8(s),compatibilityDiagnostics:[...e.skills&&h===void 0?[{capability:`skills`,reason:`Skills requires a valid advertised extension and Resources capability.`}]:[],...e.elicitation===!0?[]:[{capability:`input_required`,reason:`No MRTR client input capability is offered; unsupported results close the carrier without replay.`}],{capability:`subscriptions`,reason:`This surface does not open subscription streams; listChanged watches require explicit host refresh.`},{capability:`extensions`,reason:_.length===0?`No optional extension is offered or activated by this surface.`:`Only host-selected ${_.join(` and `)} are available; activation stays host-owned.`}],discover:async e=>{try{return await c5({request:(e,t)=>m(()=>i.request(e,t),t.signal)},u,d,f,e,g)}catch(e){throw n?new N8(`send`):e}},async callTool(t,a,s){if(!u.tools)throw Error(`Stateless MCP server did not declare tools`);let c=async()=>i5(await m(()=>i.request({method:`tools/call`,params:{name:t,arguments:a}},{signal:s?.signal,timeout:s?.timeoutMs??e.timeouts.perCallMs}),s?.signal,()=>new G8(`invalid-tool-result`))),l=p?{requestAbortController:new AbortController,...s?.outboundTraceContext?{outbound:s.outboundTraceContext}:{}}:void 0,d=r.enter({ask:s?.ask,signal:s?.signal});try{return l?await F6(l,c):await c()}catch(e){throw e instanceof G8?(await o(),e):n&&!(e instanceof N8)?new N8(`send`):e}finally{d(),l&&p?.release(l)}},async readResource(t,n){if(!u.resources)throw Error(`Stateless MCP server did not declare resources`);return a5(await m(()=>i.readResource({uri:t},{signal:n?.signal,timeout:n?.timeoutMs??e.timeouts.perCallMs,cacheMode:`bypass`}),n?.signal))},onListChanged:()=>()=>void 0,close:o}}catch(e){throw await o(),n?new $8(`initialize-failed`,`Invalid stdio stateless MCP discovery metadata`):e}}const nWe=new Set([`2024-11-05`,`2025-03-26`,`2025-06-18`,`2025-11-25`]);function h5(e){return e instanceof Error?e.message:String(e)}function g5(e){return`sensitiveDiagnostics`in e&&e.sensitiveDiagnostics===!0}function rWe(e){let t=e.transport;return`stdioStartupMs`in t&&typeof t.stdioStartupMs==`number`?Math.min(e.timeouts.startupMs,t.stdioStartupMs):e.timeouts.startupMs}function _5(e,t){return r5(e)&&t?.aborted!==!0||e instanceof $8&&e.kind===`startup-timeout`}async function iWe(e,t){let n,r;try{if(g5(t.transport)&&t.signal?.aborted)throw new $8(`initialize-failed`,`Stdio session startup cancelled`);let i=rWe(t),a=e.connect(t.transport,{timeout:i,signal:t.signal});if(g5(t.transport)){let e=new Promise((e,a)=>{n=setTimeout(()=>a(new $8(`startup-timeout`,`Stdio session startup timed out`)),i),r=()=>a(new $8(`initialize-failed`,`Stdio session startup cancelled`)),t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0})});await Promise.race([a,e])}else await a}catch(n){if(g5(t.transport)){try{await t.transport.close()}catch{throw new N8(`cleanup`)}if(n instanceof N8&&n.reason===`authority`)throw n;let e=_5(n,t.signal);throw new $8(e?`startup-timeout`:`initialize-failed`,e?`Stdio session startup timed out`:`Stdio session startup failed`)}throw await e.close(),n instanceof R3||n instanceof k6?n:_5(n,t.signal)?new $8(`startup-timeout`,`MCP session startup exceeded ${t.timeouts.startupMs}ms`,{cause:h5(n)}):new $8(`initialize-failed`,h5(n),{cause:h5(n)})}finally{n!==void 0&&clearTimeout(n),r!==void 0&&t.signal?.removeEventListener(`abort`,r)}}async function aWe(e,t){let n=e.getNegotiatedProtocolVersion();if(n===void 0||!nWe.has(n))throw await e.close(),new $8(`unsupported-protocol-version`,g5(t)?`Stdio server negotiated an unsupported MCP protocol version`:`Server negotiated unsupported MCP protocol version "${n??`unknown`}"`,g5(t)?void 0:{protocolVersion:n});return n}async function oWe(e){let t=e.getServerVersion();if(t===void 0)throw await e.close(),new $8(`initialize-failed`,`Server did not report serverInfo after initialize`);return t}function sWe(e,t){e.setNotificationHandler(`notifications/tools/list_changed`,()=>{t.forEach(e=>e(`tools`))}),e.setNotificationHandler(`notifications/prompts/list_changed`,()=>{t.forEach(e=>e(`prompts`))}),e.setNotificationHandler(`notifications/resources/list_changed`,()=>{t.forEach(e=>e(`resources`))})}async function cWe(e){if(e.skills&&e.protocolVersion!==`2026-07-28`)throw new $8(`unsupported-protocol-version`,`Skills require explicit stateless protocol selection`);if(e.protocolVersion===`2026-07-28`)return tWe(e);if(e.protocolVersion!==void 0)throw new $8(`unsupported-protocol-version`,`Unsupported explicitly selected MCP protocol version`);let t=new l5,n=n5(e.clientInfo??e5,void 0,e.elicitation===!0?u5({serverId:()=>e.serverId,calls:t}):void 0,e.apps===!0);await iWe(n,e);let r=await aWe(n,e.transport),i=await oWe(n),a={serverId:e.serverId,serverName:i.name,serverVersion:i.version,protocolVersion:r},o=n.getInstructions(),s=n.getServerCapabilities(),c=o5(s),l=e.apps===!0&&z8(s?.extensions)&&c.resources!==void 0,u=L6(e.transport),d=new Set;sWe(n,d);let f=new Map,p,m=()=>(p??=n.close(),p),h=async()=>{if(!(!(`closedDirectChild`in e.transport)||e.transport.closedDirectChild!==!0)){try{await m()}catch{throw new N8(`cleanup`)}throw new N8(`early-exit`)}},g=async(e,t)=>{throw t?.aborted||r5(e)?(await m(),new N8(`cancelled`)):(await h(),new N8(`send`))};return{...l?{apps:l}:{},identity:a,instructions:o,declaredCapabilities:c,async discover(t){try{let e=await c5(n,c,a,o,t,l);return f=new Map(e.tools.items.flatMap(e=>e.outputSchema===void 0?[]:[[e.name,e.outputSchema]])),e}catch(n){throw g5(e.transport)?t.signal?.aborted||n instanceof J8&&n.failure.kind===`timeout`?(await m(),new N8(`cancelled`)):(await h(),new N8(`send`)):n}},async callTool(r,i,a){let o=f.get(r),s=()=>n.callTool({name:r,arguments:i},{timeout:a?.timeoutMs,signal:a?.signal,...o===void 0?{}:{toolDefinition:{name:r,inputSchema:{type:`object`},outputSchema:o}}}),c=a?.outboundTraceContext,l=u===void 0?void 0:{requestAbortController:new AbortController,...c?{outbound:c}:{}},d=t.enter({ask:a?.ask,signal:a?.signal});try{return i5(l?await F6(l,s):await s())}catch(t){if(g5(e.transport))return g(t,a?.signal);throw t}finally{d(),l&&u?.release(l)}},async readResource(t,r){if(c.resources===void 0)throw Error(`MCP server did not declare resources`);try{return a5(await n.readResource({uri:t},{timeout:r?.timeoutMs,signal:r?.signal}))}catch(t){if(g5(e.transport))return g(t,r?.signal);throw t}},onListChanged(e){return d.add(e),()=>{d.delete(e)}},async close(){await m()}}}const lWe=/[^A-Za-z0-9_-]/g;function v5(e){return e.replace(lWe,`_`)}function uWe(e){return Vn(`sha1`).update(e).digest(`hex`).slice(0,8)}function dWe(e,t,n=``){let r=uWe(e),i=r.length+2;if(t<=i)return r.slice(0,Math.max(t,0));let a=t-i,o=Math.min(a,Math.max(Math.ceil(a/2),n.length)),s=a-o;return`${e.slice(0,o)}~${r}~${s>0?e.slice(e.length-s):``}`}function y5(e,t,n=64){let r=`${e}__${t}`,i=`${v5(e)}__${v5(t)}`,a=i!==r;return i.length<=n?a?{name:i,changed:!0,reason:`renamed`}:{name:i,changed:!1}:{name:dWe(i,n,`${v5(e)}__`),changed:!0,reason:a?`renamed, truncated`:`truncated`}}function fWe(e){let t=[...e].sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),n=new Map,r=new Map,i=[];for(let e of t){let t=r.get(e.name);if(t===void 0){r.set(e.name,e.key),n.set(e.key,e.name);continue}i.push({key:e.key,name:e.name,reason:`collides with ${t} after sanitisation/truncation`})}return{winners:n,losers:i}}const pWe=Qe(`ThirdPartySchema`),mWe=new Set([`object`,`array`,`string`,`number`,`integer`,`boolean`,`null`]);function b5(){return{anyOf:[{type:`string`},{type:`number`},{type:`boolean`},{type:`object`},{type:`array`},{type:`null`}]}}function x5(e){return Array.isArray(e.anyOf)?!0:typeof e.type==`string`&&mWe.has(e.type)}function S5(e,t,n){let r=e;if(Object.prototype.hasOwnProperty.call(r,`$schema`)){let{$schema:e,...i}=r;n.push(`${t}.$schema`),r=i}if(Array.isArray(r.anyOf)&&(r={...r,anyOf:r.anyOf.map((e,r)=>S5(e,`${t}.anyOf[${r}]`,n))}),typeof r.additionalProperties==`object`&&r.additionalProperties!==null){let e=`${t}.additionalProperties`;x5(r.additionalProperties)?r={...r,additionalProperties:S5(r.additionalProperties,e,n)}:(n.push(e),r={...r,additionalProperties:b5()})}if(r.type===`object`){let e=r.properties;if(!e)return r;let i={};for(let[r,a]of Object.entries(e)){let e=`${t}.${r}`;if(!x5(a)){n.push(e),i[r]=b5();continue}i[r]=S5(a,e,n)}return{...r,properties:i}}if(r.type===`array`&&r.items){let e=`${t}[]`;if(!x5(r.items)){n.push(e);let{items:t,...i}=r;return i}return{...r,items:S5(r.items,e,n)}}return r}function C5(e){let t=[];return x5(e)?{schema:S5(e,``,t),unenforceable:t}:{schema:{type:`object`},unenforceable:[``]}}var hWe=class{toolName;parameters;report;narrowed;reported=!1;constructor(e,t,n){this.toolName=e,this.parameters=t,this.report=n}validate(e){this.narrowed??=C5(this.parameters),!this.reported&&this.narrowed.unenforceable.length>0&&(this.reported=!0,(this.report??((e,t)=>{pWe.warn(`MCP tool schema is only partly enforceable`,{tool:e,paths:t})}))(this.toolName,this.narrowed.unenforceable));let t=pe(this.narrowed.schema,e,``);return{isValid:t.length===0,errors:t}}};function gWe(e){return e===`streamable-http`||e===`stdio`}function w5(e,t){let n=[];return e&&n.push(e),t&&n.push(`narrowed`),n.length>0?n.join(`, `):void 0}function _We(){let e={kind:`unsupported`};return{tools:e,prompts:e,resources:e}}function vWe(e){return e?{tools:e.tools.state,prompts:e.prompts.state,resources:e.resources.state}:_We()}function yWe(e){return{kind:`server`,serverId:e.serverId,name:e.serverId,reason:`transport ${e.transport} is not supported: MCP standard transports are stdio and Streamable HTTP`}}function bWe(e,t,n){return{serverId:e.serverId,origin:e.origin,transport:t,identity:n?.identity,instructions:n?.instructions,capabilities:vWe(n)}}function xWe(e,t){return{serverId:e.serverId,serverName:t.identity.serverName,serverVersion:t.identity.serverVersion,protocolVersion:t.identity.protocolVersion,origin:e.origin}}function SWe(e,t,n,r){let i=[];if(t.tools.state.kind===`supported`)for(let a of t.tools.items){if(a.ui!==void 0&&!a.ui.visibility.includes(`model`)){r.push({kind:`tool`,serverId:e,name:y5(e,a.name).name,reason:`app-only tool; this host offers tools to the model only`});continue}i.push({kind:`tool`,key:`${e}::tool::${a.name}`,serverId:e,sourceName:a.name,description:a.description,namingResult:y5(e,a.name),provenance:n,inputSchema:a.inputSchema,resultSizeMetadata:a.resultSizeMetadata,ui:a.ui,uiProblem:a.uiProblem})}return i}function CWe(e,t,n){let r=[];if(t.prompts.state.kind===`supported`)for(let i of t.prompts.items)r.push({kind:`prompt`,key:`${e}::prompt::${i.name}`,serverId:e,sourceName:i.name,description:i.description,namingResult:y5(e,i.name),provenance:n,promptArguments:i.arguments??[]});return r}function wWe(e,t,n){let r=[];if(t.resources.state.kind===`supported`)for(let i of t.resources.items)r.push({kind:`resource`,key:`${e}::resource::${i.name}`,serverId:e,sourceName:i.name,description:i.description,namingResult:y5(e,i.name),provenance:n,uri:i.uri,mimeType:i.mimeType});return r}function TWe(e,t,n){for(let r of t){let t=e.get(r.key);t&&n.push({kind:t.kind,serverId:t.serverId,name:r.name,reason:r.reason})}}function EWe(e,t,n){let r=C5(e.inputSchema);r.unenforceable.length>0&&n?.report?.(t,r.unenforceable);let i=w5(e.namingResult.reason,r.unenforceable.length>0);return e.resultSizeMetadata?.kind===`invalid`&&n?.reportResultSizeProblem?.(e.resultSizeMetadata.reason),e.uiProblem!==void 0&&n?.reportUiMetadataProblem?.(t,e.uiProblem),{kind:`tool`,canonicalName:t,sourceName:e.sourceName,description:e.description,schema:r.schema,...e.resultSizeMetadata?.kind===`accepted`?{maxResultChars:e.resultSizeMetadata.maxResultChars}:{},...e.ui===void 0?{}:{ui:e.ui},unenforceablePaths:r.unenforceable,provenance:e.provenance,disposition:i?`adapted`:`adopted`,reason:i}}function DWe(e,t){let n=w5(e.namingResult.reason,!1);return{kind:`prompt`,canonicalName:t,sourceName:e.sourceName,description:e.description,arguments:e.promptArguments,provenance:e.provenance,disposition:n?`adapted`:`adopted`,reason:n}}function OWe(e,t){let n=w5(e.namingResult.reason,!1);return{kind:`resource`,canonicalName:t,uri:e.uri,sourceName:e.sourceName,description:e.description,mimeType:e.mimeType,provenance:e.provenance,disposition:n?`adapted`:`adopted`,reason:n}}function kWe(e,t,n){return e.kind===`tool`?EWe(e,t,n):e.kind===`prompt`?DWe(e,t):OWe(e,t)}function AWe(e,t){let n=[],r=[],i=[];for(let t of e){if(!gWe(t.transport)){r.push(yWe(t));continue}let{discovery:e}=t;if(n.push(bWe(t,t.transport,e)),!e)continue;let a=xWe(t,e);i.push(...SWe(t.serverId,e,a,r)),i.push(...CWe(t.serverId,e,a)),i.push(...wWe(t.serverId,e,a))}let{winners:a,losers:o}=fWe(i.map(e=>({key:e.key,name:e.namingResult.name})));TWe(new Map(i.map(e=>[e.key,e])),o,r);let s=[],c=[];for(let e of i){let n=a.get(e.key);if(n===void 0)continue;let r=kWe(e,n,t);(r.disposition===`adapted`?c:s).push(r)}return{servers:n,adopted:s,adapted:c,rejected:r}}const jWe={initialMs:500,maxMs:3e4,factor:2,maxAttempts:5},MWe={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function T5(){return{tools:!1,prompts:!1,resources:!1}}function E5(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function D5(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function NWe(e){if(e instanceof $8){let t=e.details?.status;return typeof t==`number`?t:void 0}let t=E5(e,`status`);if(typeof t==`number`)return t;let n=E5(e,`statusCode`);if(typeof n==`number`)return n;let r=E5(e,`code`);if(typeof r==`number`&&r>=100&&r<600)return r}function PWe(e){let t=E5(e,`code`);return typeof t==`string`?t:void 0}function FWe(e){let t=E5(e,`code`);if(typeof t==`number`&&t<0)return t;let n=E5(E5(e,`data`),`code`);return typeof n==`number`?n:void 0}function IWe(e,t){return e===401||e===403||t.includes(`401`)||t.includes(`403`)||t.includes(`unauthorized`)}function LWe(e,t,n){return e===404||t===-32601||n.includes(`not found`)}function RWe(e,t,n){return t===-32602||n.includes(`invalid url`)||n.includes(`unsupported protocol`)||n.includes(`invalid params`)}function zWe(e,t,n){return typeof e==`number`&&e>=500&&e<600||t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ETIMEDOUT`||n.includes(`econnrefused`)||n.includes(`econnreset`)||n.includes(`etimedout`)||n.includes(`timed out`)||n.includes(`timeout`)||n.includes(`fetch failed`)||n.includes(`failed to fetch`)||n.includes(`network`)}function O5(e){if(e instanceof k5)return e.classification;if(e instanceof G8)return`config`;if(e instanceof k6)return e.reason===`unresolvable`?`transient`:`config`;if(e instanceof G6||e instanceof H6||e instanceof N8&&(e.reason===`authority`||e.reason===`cleanup`||e.reason===`receive-limit`||e.reason===`receive-invalid`))return`config`;if(e instanceof nte||e instanceof R3)return`auth`;if(e instanceof $8&&e.kind===`unsupported-protocol-version`)return`config`;let t=D5(e).toLowerCase(),n=NWe(e),r=PWe(e),i=FWe(e);return IWe(n,t)?`auth`:LWe(n,i,t)?`not-found`:RWe(e,i,t)?`config`:(zWe(n,r,t),`transient`)}var k5=class extends Error{classification;constructor(e,t,n){super(t,n),this.classification=e,this.name=`MCPSupervisorError`}},BWe=class{options;state={kind:`idle`};backoff;clock;liveSession;lastKnownGood;lastBackgroundRefreshFailure;lastBackgroundCloseFailure;pendingAttempt;resolvePendingRetry;activeAbortController;retryTimerHandle;idleTimerHandle;unsubscribeListChanged;shutdownPromise;constructor(e){this.options=e,this.backoff={...jWe,...e.backoff},this.clock=e.clock??MWe}getState(){return this.state}async ensureConnected(e){let t=this.state;if(t.kind===`connected`)return this.noteActivity(),this.liveSession;if(t.kind===`closed`)throw Error(`MCPConnectionSupervisor is shut down; it cannot reconnect (create a new instance)`);if(t.kind===`connecting`)return this.expectPendingAttempt();if(t.kind===`failed`){if(t.retry===`pending`)return this.expectPendingAttempt();throw new k5(t.classification,`connection failed (${t.classification}): ${t.message}; call retry() explicitly`)}return this.beginConnect(1,e)}async discover(e){return this.withDefaultBudget(e,async e=>{let t=await this.ensureConnected(e);this.noteActivity();let n;try{n=await t.discover({maxPages:this.options.discovery?.maxPages??50,perRequestTimeoutMs:this.options.timeouts.perCallMs,signal:e})}catch(e){throw this.retireSelfClosedStdioSession(t,e),e}return this.lastKnownGood={identity:Y8(t.identity),discovery:n,retainedAt:this.clock.now(),stale:T5()},n})}async refresh(e,t){return this.withDefaultBudget(t,async t=>{let n=await this.ensureConnected(t);this.noteActivity();try{let r=await n.discover({maxPages:this.options.discovery?.maxPages??50,perRequestTimeoutMs:this.options.timeouts.perCallMs,signal:t});return this.recordRefreshSuccess(e,n.identity,r)}catch(t){this.retireSelfClosedStdioSession(n,t);let r=O5(t),i=D5(t);throw this.recordRefreshFailure(e,r,i),new k5(r,i,{cause:t})}})}async callTool(e,t,n){return this.withDefaultBudget(n?.signal,async r=>{let i=await this.ensureConnected(r);this.noteActivity();try{return await i.callTool(e,t,{signal:r,timeoutMs:this.options.timeouts.toolCallMs,...n?.outboundTraceContext?{outboundTraceContext:n.outboundTraceContext}:{},...n?.ask?{ask:n.ask}:{}})}catch(e){throw this.retireSelfClosedStdioSession(i,e),new k5(O5(e),D5(e),{cause:e})}})}async readResource(e,t){return this.withDefaultBudget(t?.signal,async t=>{let n=await this.ensureConnected(t);this.noteActivity();try{return await n.readResource(e,{signal:t,timeoutMs:this.options.timeouts.perCallMs})}catch(e){throw this.retireSelfClosedStdioSession(n,e),new k5(O5(e),D5(e),{cause:e})}})}getLastKnownGood(){return this.lastKnownGood}async getSkillsSession(e){let t=await this.ensureConnected(e),n=t.skills;if(!n)return;let r=(e,n)=>this.withDefaultBudget(e?.signal,async r=>{if(await this.ensureConnected(r)!==t)throw new B8(`changed-manifest`);this.noteActivity();try{return await n({...e,signal:r,timeoutMs:e?.timeoutMs??this.options.timeouts.perCallMs})}catch(e){throw this.retireSelfClosedStdioSession(t,e),e}});return{list:e=>r(e,t=>n.list({...t,maxPages:e.maxPages})),get:(e,t)=>r(t,t=>n.get(e,t)),read:(e,t,i)=>r(i,r=>n.read(e,t,r))}}get lastRefreshFailure(){return this.lastBackgroundRefreshFailure}get lastCloseFailure(){return this.lastBackgroundCloseFailure}async retry(e){let t=this.state;if(t.kind===`connected`)return this.noteActivity(),this.liveSession;if(t.kind===`closed`)throw Error(`MCPConnectionSupervisor is shut down; it cannot reconnect (create a new instance)`);return t.kind===`connecting`||t.kind===`failed`&&t.retry===`pending`?this.expectPendingAttempt():this.beginConnect(1,e)}shutdown(){return this.shutdownPromise===void 0&&(this.shutdownPromise=this.shutdownOwned()),this.shutdownPromise}async shutdownOwned(){if(this.state.kind===`closed`)return;this.clearRetryTimer(),this.clearIdleTimer(),this.activeAbortController?.abort(),this.activeAbortController=void 0;let e=this.pendingAttempt;this.pendingAttempt=void 0,this.unsubscribeListChanged&&=(this.unsubscribeListChanged(),void 0);let t=this.liveSession;if(this.liveSession=void 0,this.setState({kind:`closed`}),t&&await t.close(),this.options.awaitOpenCleanupOnTimeout&&e){let t=await e;if(!t.ok&&t.error.cause instanceof N8&&t.error.cause.reason===`cleanup`)throw t.error}}setState(e){this.state=e,this.options.onStateChange?.(e)}expectPendingAttempt(){let e=this.pendingAttempt;if(!e)throw Error(`MCPConnectionSupervisor invariant violated: no attempt is pending for this state`);return this.settle(e)}noteActivity(){this.state.kind===`connected`&&this.armIdleTimer()}withDefaultBudget(e,t){if(e)return t(e);let n=new AbortController;return this.withTimeout(t(n.signal),this.options.timeouts.globalDefaultMs,()=>n.abort(),this.options.awaitOpenCleanupOnTimeout)}withTimeout(e,t,n,r=!1,i){return new Promise((a,o)=>{let s=!1,c=!1,l=this.clock.setTimeout(()=>{s||(r?c=!0:s=!0,n?.(),r||o(Error(`operation timed out after ${t}ms`)))},t);e.then(e=>{if(!s)if(s=!0,this.clock.clearTimeout(l),c)if(i)try{i(e).then(()=>o(Error(`operation timed out after ${t}ms`)),o)}catch(e){o(e)}else o(Error(`operation timed out after ${t}ms`));else a(e)},e=>{s||(s=!0,this.clock.clearTimeout(l),o(e))})})}async settle(e){let t=await e;if(!t.ok)throw t.error;return t.session}beginConnect(e,t){return this.settle(this.startAttempt(e,t))}startAttempt(e,t){this.setState({kind:`connecting`,attempt:e});let n=new AbortController;this.activeAbortController=n,t&&(t.aborted?n.abort():t.addEventListener(`abort`,()=>n.abort(),{once:!0}));let r=this.runOpenAttempt(e,n);return this.pendingAttempt=r,r}async runOpenAttempt(e,t){try{let e=await this.withTimeout(this.options.openSession(t.signal),this.options.timeouts.startupMs,()=>t.abort(),this.options.awaitOpenCleanupOnTimeout,e=>e.close());if(this.clearActiveController(t),this.state.kind===`closed`||t.signal.aborted){try{await e.close()}catch(e){if(this.options.awaitOpenCleanupOnTimeout){let t=e instanceof N8&&e.reason===`cleanup`?e:new N8(`cleanup`);return{ok:!1,error:new k5(`config`,t.message,{cause:t})}}this.recordBackgroundCloseFailure(e)}return{ok:!1,error:new k5(`config`,`supervisor was shut down while the open attempt was settling`)}}return this.onConnected(e),{ok:!0,session:e}}catch(n){this.clearActiveController(t);let r=O5(n),i=D5(n);return this.recordOpenFailure(e,r,i),{ok:!1,error:new k5(r,i,{cause:n})}}}clearActiveController(e){this.activeAbortController===e&&(this.activeAbortController=void 0)}retireSelfClosedStdioSession(e,t){!(t instanceof N8)||t.reason!==`cancelled`&&t.reason!==`cleanup`&&t.reason!==`early-exit`&&t.reason!==`receive-limit`&&t.reason!==`receive-invalid`||this.liveSession!==e||this.state.kind===`closed`||(this.clearIdleTimer(),this.unsubscribeListChanged?.(),this.unsubscribeListChanged=void 0,this.liveSession=void 0,t.reason===`cleanup`?this.setState({kind:`failed`,classification:`config`,message:t.message,attempt:1,retry:`manual-retry`}):this.setState({kind:`idle`}))}recordOpenFailure(e,t,n){if(this.state.kind!==`closed`)if(t===`transient`&&e<this.backoff.maxAttempts){let r=Math.min(this.backoff.maxMs,this.backoff.initialMs*this.backoff.factor**(e-1));this.setState({kind:`failed`,classification:t,message:n,attempt:e,retry:`pending`}),this.armRetryTimer(e,r)}else this.setState({kind:`failed`,classification:t,message:n,attempt:e,retry:`manual-retry`})}onConnected(e){let t=Y8(e.identity);this.lastKnownGood&&!X8(this.lastKnownGood.identity,t)&&(this.lastKnownGood=void 0),this.liveSession=e,this.pendingAttempt=void 0,this.clearRetryTimer(),this.unsubscribeListChanged=e.onListChanged(e=>this.handleListChanged(e)),this.setState({kind:`connected`,identity:e.identity}),this.armIdleTimer()}handleListChanged(e){this.lastKnownGood&&={...this.lastKnownGood,stale:{...this.lastKnownGood.stale,[e]:!0}},this.refreshInBackground(e)}refreshInBackground(e){return this.refresh(e).then(()=>void 0,t=>this.recordBackgroundRefreshFailure(e,t))}recordBackgroundRefreshFailure(e,t){this.lastBackgroundRefreshFailure={domain:e,message:D5(t),at:this.clock.now()}}recordBackgroundCloseFailure(e){this.lastBackgroundCloseFailure={message:D5(e),at:this.clock.now()}}recordRefreshSuccess(e,t,n){let r=Y8(t),i=this.lastKnownGood&&X8(this.lastKnownGood.identity,r)?this.lastKnownGood:void 0,a=VWe(i?.discovery,e,n),o={...i?.stale??T5(),[e]:!1};return this.lastKnownGood={identity:r,discovery:a,retainedAt:this.clock.now(),stale:o},a}recordRefreshFailure(e,t,n){this.lastKnownGood&&={...this.lastKnownGood,stale:{...this.lastKnownGood.stale,[e]:!0},lastError:{classification:t,message:n}}}armRetryTimer(e,t){this.clearRetryTimer(),this.pendingAttempt=new Promise(e=>{this.resolvePendingRetry=e}),this.retryTimerHandle=this.clock.setTimeout(()=>{this.retryTimerHandle=void 0;let t=this.resolvePendingRetry;this.resolvePendingRetry=void 0,this.startAttempt(e+1).then(e=>t?.(e))},t)}clearRetryTimer(){this.retryTimerHandle!==void 0&&(this.clock.clearTimeout(this.retryTimerHandle),this.retryTimerHandle=void 0),this.resolvePendingRetry&&=(this.resolvePendingRetry({ok:!1,error:new k5(`config`,`MCP connection recovery was cancelled`)}),void 0)}armIdleTimer(){this.clearIdleTimer(),this.idleTimerHandle=this.clock.setTimeout(()=>{this.idleTimerHandle=void 0,this.handleIdleTimeout()},this.options.timeouts.idleMs)}clearIdleTimer(){this.idleTimerHandle!==void 0&&(this.clock.clearTimeout(this.idleTimerHandle),this.idleTimerHandle=void 0)}async handleIdleTimeout(){let e=this.liveSession;this.liveSession=void 0,this.unsubscribeListChanged&&=(this.unsubscribeListChanged(),void 0),this.setState({kind:`idle`}),e&&await e.close().then(()=>void 0,e=>this.recordBackgroundCloseFailure(e))}};function VWe(e,t,n){if(!e)return n;switch(t){case`tools`:return{...e,identity:n.identity,instructions:n.instructions,tools:n.tools};case`prompts`:return{...e,identity:n.identity,instructions:n.instructions,prompts:n.prompts};case`resources`:return{...e,identity:n.identity,instructions:n.instructions,resources:n.resources}}}function A5(e,t=!1){if(typeof e!=`string`)return!1;try{let n=atob(e);return t||n.length>0}catch{return!1}}function j5(e){return typeof e==`string`&&/^[A-Za-z][A-Za-z0-9+.-]*:[^\s]*$/u.test(e)}function HWe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function UWe(e){if(e.type===`audio`)return typeof e.mimeType!=`string`||!/^audio\/[A-Za-z0-9.+-]+$/u.test(e.mimeType)||!A5(e.data)?{diagnostic:`MCP audio omitted: invalid MIME type or base64 data`}:{part:{type:`audio_inline`,mimeType:e.mimeType,data:e.data}};if(e.type===`resource_link`){if(!j5(e.uri)||typeof e.name!=`string`||!e.name.length)return{diagnostic:`MCP resource link omitted: invalid URI or name`};for(let t of[`mimeType`,`title`,`description`])if(e[t]!==void 0&&typeof e[t]!=`string`)return{diagnostic:`MCP resource link omitted: invalid metadata`};return e.size!==void 0&&(typeof e.size!=`number`||!Number.isSafeInteger(e.size)||e.size<0)?{diagnostic:`MCP resource link omitted: invalid size`}:{part:{type:`resource_link`,uri:e.uri,name:e.name,...typeof e.mimeType==`string`?{mimeType:e.mimeType}:{},...typeof e.title==`string`?{title:e.title}:{},...typeof e.description==`string`?{description:e.description}:{},...typeof e.size==`number`?{size:e.size}:{}}}}if(e.type===`resource`){let t=e.resource;if(!HWe(t)||!j5(t.uri)||t.mimeType!==void 0&&typeof t.mimeType!=`string`)return{diagnostic:`MCP embedded resource omitted: invalid URI or metadata`};let n={type:`resource_embedded`,uri:t.uri,...typeof t.mimeType==`string`?{mimeType:t.mimeType}:{}};return typeof t.text==`string`&&t.blob===void 0?{part:{...n,text:t.text}}:t.text===void 0&&A5(t.blob,!0)?{part:{...n,blob:t.blob}}:{diagnostic:`MCP embedded resource omitted: expected text or base64 blob`}}}function WWe(e,t){if(typeof e!=`string`||![`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e))return`MCP image omitted: unsupported MIME type`;if(typeof t!=`string`||!t.length||t.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/u.test(t))return`MCP image omitted: invalid base64 data`;let n=atob(t.slice(0,48)),r=atob(t.slice(-48)),i=t.length/4*3-(t.endsWith(`==`)?2:+!!t.endsWith(`=`));return(e===`image/png`?n.startsWith(`‰PNG\r
2850
+ `:`${n.enclosingQuote}\n`;let o=FVe(e,t,a);return o===t?void 0:{start:t,end:o}}function RVe(e){Q3.lastIndex=0;let t=``,n=0;for(let r=Q3.exec(e);r!==null;r=Q3.exec(e)){let[i,a,o,s,c]=r;if(!(a.length>0?e6(`${a}${s}`):$3(s)))continue;let l=e[r.index-1],u=kVe.test(s),d=LVe(e,r.index+i.length,{separator:c,quotedName:o.length>0,enclosingQuote:o.length===0&&l!==void 0&&`"'\``.includes(l)?l:void 0,authorization:u});if(d===void 0)continue;let f=e.slice(d.start,d.end);t+=e.slice(n,d.start),t+=u?MVe(f):t6(f),n=d.end,Q3.lastIndex=Math.max(d.end,Q3.lastIndex)}return t+e.slice(n)}function a6(e){return RVe(e.replace(OVe,PVe)).replace(AVe,(e,t,n,r,i)=>e6(n)?`${t}${n}${r}${t6(i)}`:e).replace(DVe,(e,t)=>`${t}`).replace(TVe,``).replace(EVe,e=>jVe(e)?``:e)}function o6(e){let t=[];return{scanned:e.map(e=>e.marker?(t.push(e.text),``):e.text.replace(X3,`�`)).join(``),markers:t}}function s6(e,t){let n=0;return e.replace(wVe,q3).replace(CVe,()=>t[n++]??``)}function zVe(e){let{scanned:t,markers:n}=o6([{text:e,marker:!1}]);return s6(a6(t),n)}function c6(e,t,n){let{scanned:r,markers:i}=o6(Y3(e,t,n));return s6(a6(r),i)}function BVe(e,t){return t.map((n,r)=>{let i=`args[${r}]`,a=r>0?t[r-1]:void 0;if(a!==void 0&&e6(a)&&!/^-{1,2}[A-Za-z]/.test(n)){let{scanned:t,markers:r}=o6(Y3(e,i,n));return s6(t6(t),r)}return c6(e,i,n)})}function VVe(e,t,n){let r=[...e.provenance?.[t]??[]].sort((e,t)=>e.start-t.start||e.end-t.end),i=``,a=0;for(let e of r)i+=n.slice(a,e.start)+"${"+e.variable+`}`,a=e.end;return i+n.slice(a)}const l6=/[A-Za-z_][A-Za-z0-9_]*/y;function*HVe(e){let t=0;for(;;){let n=e.indexOf("${",t);if(n===-1)return;l6.lastIndex=n+2;let r=l6.exec(e);if(r===null){t=n+1;continue}let i=l6.lastIndex,a;if(e.startsWith(`:-`,i)){let t=e.indexOf(`}`,i+2);if(t===-1)return;a=e.slice(i+2,t),i=t}else if(e[i]!==`}`){t=n+1;continue}yield{index:n,literal:e.slice(n,i+1),variable:r[0],fallback:a},t=i+1}}function u6(e,t,n,r){let i=[],a=``,o=0;for(let{index:s,literal:c,variable:l,fallback:u}of HVe(e)){a+=e.slice(o,s),o=s+c.length;let d=t[l]??u;if(d===void 0){r.unset.push({variable:l,field:n,literal:c}),a+=c;continue}i.push({start:a.length,end:a.length+d.length,variable:l,secret:K3(l)}),a+=d}return a+=e.slice(o),i.length>0&&(r.provenance[n]=i),a}function d6(e,t,n,r){let i={};for(let[a,o]of Object.entries(e))i[a]=u6(o,t,`${n}.${a}`,r);return i}function UVe(e,t){let n={unset:[],provenance:{}},r={...e,unsetVariables:[]};return e.command!==void 0&&(r.command=u6(e.command,t,`command`,n)),e.args!==void 0&&(r.args=e.args.map((e,r)=>u6(e,t,`args[${r}]`,n))),e.cwd!==void 0&&(r.cwd=u6(e.cwd,t,`cwd`,n)),e.env!==void 0&&(r.env=d6(e.env,t,`env`,n)),e.url!==void 0&&(r.url=u6(e.url,t,`url`,n)),e.headers!==void 0&&(r.headers=d6(e.headers,t,`headers`,n)),r.unsetVariables=n.unset,Object.keys(n.provenance).length>0&&(r.provenance=n.provenance),r}const f6=[`managed`,`local`,`project`,`user`,`plugin`],WVe=new Map(f6.map((e,t)=>[e,t]));function p6(e){return WVe.get(e)??f6.length}function GVe(e,t){let n=new Map,r=[],i=(e,t)=>{let r=n.get(e);r?r.push(t):n.set(e,[t])};for(let t of e){for(let e of t.definitions)i(e.name,{source:t.source,origin:e.origin,definition:e});for(let e of t.problems){if(e.name===``){r.push(e);continue}i(e.name,{source:t.source,origin:e.origin,problem:e})}}let a=[];for(let[e,r]of n){let n=[...r].sort((e,t)=>p6(e.source)-p6(t.source)),i=n[0];if(i===void 0)continue;let o=n.slice(1).map(t=>({name:e,source:t.source,origin:t.origin}));if(i.definition!==void 0){a.push({name:e,source:i.source,origin:i.origin,status:`resolved`,definition:t(i.definition),shadowed:o});continue}a.push({name:e,source:i.source,origin:i.origin,status:`unresolved`,...i.problem===void 0?{}:{problem:i.problem},shadowed:o})}let o=a.sort((e,t)=>e.name.localeCompare(t.name)),s=f6[0],c=r.find(e=>e.source===s);return c===void 0?{entries:o,sourceProblems:r}:{entries:o.map(e=>e.status!==`resolved`||e.source===s?e:{name:e.name,source:e.source,origin:e.origin,status:`unresolved`,problem:{name:e.name,source:e.source,origin:e.origin,reason:`${m6} the ${s} source (${c.origin}) could not be read (${c.reason}), so a lower-trust definition cannot be trusted to be the real winner`},shadowed:e.shadowed}),sourceProblems:r}}const m6=`blocked:`;function h6(e){return e.status===`unresolved`&&(e.problem?.reason.startsWith(m6)??!1)}function KVe(e){return e.disabledReason!==void 0}function g6(e){let t=Vn(`sha256`);for(let n of e)t.update(String(n.length)),t.update(`:`),t.update(n);return t.digest(`hex`).slice(0,32)}function _6(e,t){return[e,String(t.length),...t]}function v6(e,t,n){return _6(e,Object.keys(n??{}).sort().flatMap(r=>[r,J3(t,`${e}.${r}`,n[r])]))}function y6(e){let t=(t,n)=>n===void 0?``:J3(e,t,n);return g6([`v2`,`transport`,e.transport,...e.protocolVersion===void 0?[]:[`protocolVersion`,e.protocolVersion],...e.skills===!0?[`skills`,`enabled`]:[],`command`,t(`command`,e.command),..._6(`args`,(e.args??[]).map((e,n)=>t(`args[${n}]`,e))),`cwd`,t(`cwd`,e.cwd),`url`,t(`url`,e.url),...v6(`headers`,e,e.headers),...v6(`env`,e,e.env),`timeout`,e.timeout===void 0?``:String(e.timeout),...e.headersHelper===void 0?[]:[`headersHelper`,e.headersHelper.command,..._6(`headersHelperArgs`,e.headersHelper.args)],...e.oauth===void 0?[]:[`oauth`,e.oauth.clientId??``,e.oauth.callbackPort===void 0?``:String(e.oauth.callbackPort),e.oauth.authServerMetadataUrl??``,..._6(`oauthScopes`,e.oauth.scopes??[])],...e.unsupportedAuthentication===void 0?[]:_6(`unsupportedAuthentication`,e.unsupportedAuthentication)])}const qVe=/^[A-Za-z0-9_@%+=:,./-]+$/,JVe=/[\u007f-\u009f\u2028\u2029\p{Cf}]/gu;function YVe(e){return qVe.test(e)?e:JSON.stringify(e).replace(JVe,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function b6(e){let t=(e.protocolVersion===void 0?``:` (MCP ${e.protocolVersion})`)+(e.skills===!0?` (Skills enabled)`:``);if(e.url!==void 0){let n=c6(e,`url`,e.url),r=e.headersHelper;return r===void 0?n+t:`${n} (headers from ${[r.command,...r.args].map(e=>YVe(zVe(e))).join(` `)})${t}`}return[e.command===void 0?``:c6(e,`command`,e.command),...BVe(e,e.args??[])].join(` `).trim()+t}function x6(e){return g6([`name`,e.name,`source`,e.source,`origin`,e.origin])}function S6(e){return e.definition===void 0?null:{serverId:e.name,definitionFingerprint:y6(e.definition),securityIdentity:x6(e)}}function XVe(e,t){return{kind:e.source,id:e.origin,version:t}}function ZVe(e){return e.definition===void 0?``:b6(e.definition)}var C6=class{entries;options;constructor(e,t={}){this.entries=e,this.options=t}list(){let e=[];for(let t of this.entries){if(t.status!==`resolved`||KVe(t))continue;let n=S6(t);if(n===null)continue;let r={serverId:n.serverId,endpoint:ZVe(t),source:t.source,provenance:XVe(t,n.definitionFingerprint),definitionFingerprint:n.definitionFingerprint,securityIdentity:n.securityIdentity,...this.options.workspace===void 0?{}:{workspace:this.options.workspace}};e.push(r)}return e}displayNames(){return new Map(this.entries.map(e=>[e.name,e.name]))}};const w6={managed:3,user:2,local:1,project:0,plugin:0};var QVe=class{records=[];audit=[];list(){return this.records.slice()}put(e){let t=this.records.findIndex(t=>t.serverId===e.serverId&&t.approvalAuthority===e.approvalAuthority);t===-1?this.records.push(e):this.records[t]=e}listAudit(){return this.audit.slice()}appendAudit(e){this.audit.push(e)}};const $Ve=new Set([`managed`,`user`]);function T6(e){return!$Ve.has(e)}const E6=new Set([`managed`,`user`,`local`]);function eHe(e,t){let n=T6(e.source)?t.repositoryKey===e.workspace?.repositoryKey&&t.workspaceGeneration===e.workspace?.generation:t.repositoryKey===void 0&&t.workspaceGeneration===void 0;return t.serverId===e.serverId&&t.source===e.source&&t.provenance.kind===e.provenance.kind&&t.provenance.id===e.provenance.id&&t.provenance.version===e.provenance.version&&t.definitionFingerprint===e.definitionFingerprint&&t.securityIdentity===e.securityIdentity&&n}function D6(e,t,n,r){return{serverId:e.serverId,source:e.source,status:t,allowed:t===`approved`,reason:n,provenance:e.provenance,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,...r===void 0?{}:{approval:r}}}var O6=class extends Error{code=`MCP_ACTIVATION_POLICY_ERROR`;constructor(e){super(e),this.name=`MCPActivationPolicyError`}},tHe=class{store;now;constructor(e=new QVe,t=()=>new Date().toISOString()){this.store=e,this.now=t}inspect(e){if(T6(e.source)&&e.workspace?.trustState!==`trusted`)return D6(e,`untrusted`,`MCP activation requires a trusted workspace for project, plugin, and local definitions.`);let t=this.store.list().filter(t=>t.serverId===e.serverId).sort((e,t)=>w6[t.approvalAuthority]-w6[e.approvalAuthority]||t.decidedAt.localeCompare(e.decidedAt));if(t.length===0)return D6(e,`pending`,`No explicit trust approval exists for this MCP definition.`);let n=t.find(t=>eHe(e,t));return n?D6(e,n.decision,n.decision===`approved`?`MCP definition is explicitly approved.`:`MCP definition is ${n.decision}.`,n):D6(e,`stale`,`The MCP definition, provenance, security identity, or workspace generation changed after approval.`)}admit(e){return this.inspect(e)}approve(e,t=`user`){if(!E6.has(t))throw new O6(`Project and plugin definitions may request approval but cannot approve themselves.`);if(T6(e.source)&&e.workspace?.trustState!==`trusted`)return this.inspect(e);let n=this.createRecord(e,t,`approved`);return this.save(e,n),this.inspect(e)}reject(e,t=`user`){if(!E6.has(t))throw new O6(`Project and plugin definitions may request approval but cannot reject on behalf of the operator.`);let n=this.createRecord(e,t,`rejected`);return this.save(e,n),this.inspect(e)}revoke(e,t=`user`){if(!E6.has(t))throw new O6(`Project and plugin definitions may request approval but cannot revoke operator approval.`);let n=this.createRecord(e,t,`revoked`);return this.save(e,n),this.inspect(e)}getApprovalStore(){return this.store}listAudit(){return this.store.listAudit()}createRecord(e,t,n){return{serverId:e.serverId,source:e.source,provenance:e.provenance,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,approvalAuthority:t,decision:n,...T6(e.source)?{repositoryKey:e.workspace?.repositoryKey,workspaceGeneration:e.workspace?.generation}:{},decidedAt:this.now()}}save(e,t){let n={action:t.decision===`approved`?`approve`:t.decision===`rejected`?`reject`:`revoke`,serverId:e.serverId,source:e.source,provenanceId:e.provenance.id,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,decision:t.decision,at:t.decidedAt};this.store.putWithAudit?this.store.putWithAudit(t,n):(this.store.put(t),this.store.appendAudit(n))}},nHe=class{definitions;admission;displayNames;constructor(e,t,n=new Map){this.definitions=e,this.admission=t,this.displayNames=n}list(){return this.definitions.list().map(e=>this.toSummary(this.admission.inspect(e)))}approve(e){return this.toSummary(this.decide(e,e=>this.admission.approve(e)))}reject(e){return this.toSummary(this.decide(e,e=>this.admission.reject(e)))}revoke(e){return this.toSummary(this.decide(e,e=>this.admission.revoke(e)))}decide(e,t){let n=this.definitions.list().find(t=>t.serverId===e);if(!n)throw new O6(`Unknown MCP server "${e}".`);return t(n)}toSummary(e){let t=this.displayNames.get(e.serverId);return{...e,provenanceId:e.provenance.id,...t===void 0?{}:{displayName:t}}}},k6=class extends Error{reason;constructor(e){super(`Streamable HTTP transport refused egress (${e})`),this.reason=e,this.name=`MCPTransportEgressRefusedError`}};function rHe(e,t,n){let r=new AbortController,i=new Set,a=new Set;async function o(i,o){if((i instanceof Request?i.url:String(i))!==e)throw new k6(`endpoint-mismatch`);let s=new AbortController,c=[r.signal,s.signal];o?.signal&&c.push(o.signal);let l=AbortSignal.any(c),u=setTimeout(()=>s.abort(new DOMException(`MCP HTTP opening timed out`,`TimeoutError`)),3e4),d;try{d=await _ee(new URL(e),o??{},t,n,l)}finally{clearTimeout(u)}if(!(`response`in d))throw new k6(d.reason);l.aborted&&(await d.close(),l.throwIfAborted());let f=d.response;if(!f.body)return await d.close(),f;let p=f.body.getReader(),m,h=()=>(m??=(async()=>{s.abort();try{try{await p.cancel()}catch{}await d.close()}finally{a.delete(h)}})(),m);a.add(h);try{let e=new ReadableStream({async pull(e){try{let{done:t,value:n}=await p.read();t?(await h(),e.close()):e.enqueue(n)}catch(t){await h(),e.error(t)}},cancel:()=>h()},{highWaterMark:0});return new Response(e,{status:f.status,statusText:f.statusText,headers:f.headers})}catch(e){throw await h(),e}}return{fetch:async(e,t)=>{let n=o(e,t);i.add(n);try{return await n}finally{i.delete(n)}},signal:r.signal,async close(){r.abort(),await Promise.allSettled([...i]),await Promise.all([...a].map(e=>e()))}}}const A6=8*1024*1024,j6=128*1024*1024,M6=new WeakSet;function iHe(e){M6.add(e)}function N6(e){return M6.has(e)}const P6=new br;function F6(e,t){return P6.run(e,t)}function aHe(){return P6.getStore()}var oHe=class{byRequestId=new Map;get size(){return this.byRequestId.size}record(e,t){t.requestId!==void 0&&this.byRequestId.get(t.requestId)===t&&this.byRequestId.delete(t.requestId),t.requestId=e,this.byRequestId.set(e,t)}lookup(e){return this.byRequestId.get(e)}release(e){let t=e.requestId;t!==void 0&&this.byRequestId.get(t)===e&&this.byRequestId.delete(t)}};const I6=new WeakMap;function sHe(e,t){I6.set(e,t)}function L6(e){return I6.get(e)}function R6(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function z6(e){return typeof e==`string`||typeof e==`number`}function B6(e){if(!(!R6(e)||e.jsonrpc!==`2.0`||e.method!==`tools/call`))return z6(e.id)?e.id:void 0}function V6(e){if(!R6(e)||e.jsonrpc!==`2.0`||e.method!==`notifications/cancelled`||`id`in e||!R6(e.params))return;let t=e.params.requestId;return z6(t)?t:void 0}function cHe(e){if(e?.method!==`POST`||typeof e.body!=`string`)return;let t;try{t=JSON.parse(e.body)}catch{return}let n=P6.getStore(),r=B6(t);return r!==void 0&&n?.requestId===r?n.requestAbortController?.signal:void 0}function lHe(e,t,n){if(e?.method!==`POST`||typeof e.body!=`string`)return{};let r;try{r=JSON.parse(e.body)}catch{return{}}let i=P6.getStore(),a=B6(r);if(a!==void 0)return i?.requestId===a&&i.outbound?zt(t,i.outbound):{};let o=V6(r);if(o===void 0)return{};let s=i?.requestId===o?i:n.lookup(o);return s?.outbound?zt(t,s.outbound):{}}var H6=class extends Error{constructor(){super(`MCP response exceeded the receive byte limit`),this.name=`MCPTransportResponseLimitError`}};function uHe(e,t){if(!e.body)return e;let n=0,r=e.body.pipeThrough(new TransformStream({transform(e,r){if(n+=e.byteLength,n>t)throw new H6;r.enqueue(e)}}));return new Response(r,{status:e.status,statusText:e.statusText,headers:e.headers})}function U6(e,t){try{return new URL(e,t).origin}catch{return`an unparseable location`}}const W6=new WeakMap;function dHe(e){return W6.get(e)}var G6=class extends Error{status;location;constructor(e,t,n){super(`Streamable HTTP transport refused a redirect (${e}) from ${U6(n)} to ${t===void 0?`an undisclosed location`:U6(t,n)}: the admitted URL is the only URL spoken to`),this.status=e,this.location=t,this.name=`MCPTransportRedirectRefusedError`}};async function fHe(e,t={}){if(e.unsupportedAuthentication!==void 0&&e.unsupportedAuthentication.length>0)return{ok:!1,reason:`unsupported-authentication`,message:`The definition declares ${e.unsupportedAuthentication.join(`, `)} authentication, which this version does not support; the server was not connected.`};if(e.authenticationRequired===!0&&e.authentication===void 0)return{ok:!1,reason:`authentication-unavailable`,message:`The definition obtains its headers dynamically and no authenticator was registered; the server was not connected.`};if(!URL.canParse(e.url))return{ok:!1,reason:`invalid-url`,message:`The configured URL is not a valid URL`};let n=new URL(e.url),r=Object.freeze({...t.policy,...t.policy?.allowedHosts?{allowedHosts:Object.freeze([...t.policy.allowedHosts])}:{}}),i=t.lookup,a=i?await Zt(n,r,i):await Zt(n,r);return a?{ok:!1,reason:`egress-policy:${a.reason}`,message:a.message}:{ok:!0,admitted:{kind:`streamable-http`,url:n,headers:{...e.headers??{}},...e.authentication===void 0?{}:{authentication:e.authentication},egress:{policy:r,...i?{lookup:i}:{}}}}}var pHe=class extends tte{callTraces;closeCarrier;constructor(e,t,n,r){super(e,t),this.callTraces=n,this.closeCarrier=r}async close(){await Promise.all([this.closeCarrier(),super.close()])}send(e,t){let n=aHe(),r=B6(e);n!==void 0&&r!==void 0&&this.callTraces.record(r,n);let i=V6(e),a=i===void 0?void 0:this.callTraces.lookup(i);return a===void 0?super.send(e,t):(a.requestAbortController?.abort(),F6(a,()=>super.send(e,t)))}};function mHe(e,t){let n=Object.entries(t);if(n.length===0)return e;let r=new Headers(e?.headers);for(let[e,t]of n)r.set(e,t);return{...e,headers:r}}async function K6(e,t,n){try{e?.signal?.throwIfAborted();let r=await n.authenticator.authorize({serverId:n.serverId,securityIdentity:n.securityIdentity,url:t.url,...e?.signal?{signal:e.signal}:{}});e?.signal?.throwIfAborted();let i=new Headers(e?.headers);for(let[e,t]of Object.entries(r))i.set(e,t);return{headers:i,credential:r}}catch{throw e?.signal?.aborted===!0?new DOMException(`The MCP request was cancelled`,`AbortError`):new R3(`authorize-failed`)}}async function hHe(e,t,n){let r=n.authentication;if(r===void 0)return e(void 0);let i=e=>e.status===401||e.status===403,a=await K6(t,n,r),o=await e(a.headers);if(!i(o))return o;let s=o.headers.get(`www-authenticate`);await o.body?.cancel().catch(()=>void 0),t?.signal?.throwIfAborted();let c;try{c=await r.authenticator.onRejected({status:o.status,...s===null?{}:{wwwAuthenticate:s},authorization:a.credential})}catch{c=`fail`}let l=t?.body===void 0||t.body===null||typeof t.body==`string`;if(c!==`retry`||!l)throw new R3(`rejected`);let u=await e((await K6(t,n,r)).headers);if(i(u))throw await u.body?.cancel().catch(()=>void 0),new R3(`rejected`);return u}function gHe(e,t={}){let n=e.url.toString(),r={...e,url:new URL(n),headers:Object.freeze({...e.headers})},i=r.egress?.lookup??t.lookup,a=rHe(n,r.egress?.policy??t.policy??{},{...t.fetch?{fetch:t.fetch}:{},...i?{lookup:i}:{}}),o=a.fetch,s=new oHe,c=async(e,t)=>{a.signal.throwIfAborted();let i=[a.signal];t?.signal&&i.push(t.signal);let c=cHe(t);c&&i.push(c);let u=AbortSignal.any(i),d=t;if(new Headers(t?.headers).get(`mcp-protocol-version`)===`2026-07-28`){let e=new Headers(t?.headers);if(e.delete(`mcp-session-id`),d={...t,headers:e},t?.method!==`POST`)throw Error(`Stateless MCP automatic stream resumption is unavailable`)}let f=mHe({...d,signal:u},lHe(d,n,s)),p=await hHe(t=>o(e,{...f,...t?{headers:t}:{},redirect:`manual`}),f,r);if(p.status>=300&&p.status<400)throw await p.body?.cancel().catch(()=>void 0),new G6(p.status,p.headers.get(`location`)??void 0,n);return p.ok||W6.set(l,{status:p.status,contentType:p.headers.get(`content-type`)??void 0}),uHe(p,typeof t?.body==`string`&&JSON.parse(t.body).method===`resources/read`&&N6(l)?j6:A6)},l=new pHe(r.url,{requestInit:{redirect:`manual`,...Object.keys(r.headers).length>0?{headers:r.headers}:{}},fetch:c},s,()=>a.close());return sHe(l,s),l}function _He(e={}){return{kind:`streamable-http`,admit:t=>fHe(t,e),construct:t=>gHe(t,e)}}function q6(){return new DOMException(`The credential request was cancelled`,`AbortError`)}var vHe=class extends Error{constructor(){super(`The credential cache was closed`),this.name=`MCPSingleFlightClosedError`}},J6=class{load;cached;flight;generation=0;closed=!1;constructor(e){this.load=e}async get(e){return(await this.getEntry(e)).value}getEntry(e){if(this.closed)return Promise.reject(new vHe);if(e?.aborted===!0)return Promise.reject(q6());if(this.cached!==void 0)return Promise.resolve(this.cached);let t=this.flight??this.start();return t.waiters+=1,new Promise((n,r)=>{let i=!1,a=()=>{i=!0,--t.waiters,e?.removeEventListener(`abort`,o)},o=()=>{i||(a(),t.waiters===0&&this.flight===t&&(this.flight=void 0,t.controller.abort()),r(q6()))};e?.addEventListener(`abort`,o,{once:!0}),t.promise.then(e=>{i||(a(),n({value:e,generation:t.generation}))},e=>{i||(a(),r(e))})})}invalidate(e){this.cached?.generation===e&&(this.cached=void 0)}close(){this.closed=!0,this.cached=void 0;let e=this.flight;this.flight=void 0,e?.controller.abort()}start(){this.generation+=1;let e={generation:this.generation,controller:new AbortController,promise:Promise.resolve(),waiters:0};return e.promise=new Promise(t=>t(this.load(e.controller.signal))).then(t=>(this.flight===e&&(this.flight=void 0,this.cached={value:t,generation:e.generation}),t),t=>{throw this.flight===e&&(this.flight=void 0),t}),e.promise.catch(()=>void 0),this.flight=e,e}},Y6=class extends Error{reason;constructor(e){super(`MCP headers helper failed (${e})`),this.reason=e,this.name=`MCPHeadersHelperError`}};const yHe=new Set([`project`,`local`]);function X6(e){return yHe.has(e)}function bHe(e,t,n,r){if(!r.some(t=>t.command===e.command&&t.args.length===e.args.length&&t.args.every((t,n)=>t===e.args[n])))return`headers-helper-not-allowed`;if(X6(t)&&n?.trustState!==`trusted`)return`headers-helper-untrusted`}const xHe=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,SHe=/^[\t\x20-\x7e\x80-\xff]*$/,CHe=new Set([`host`,`content-length`,`transfer-encoding`,`connection`,`content-type`,`accept`,`mcp-session-id`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`traceparent`]),Z6=/[ \t\n\r]*/y;function wHe(e,t){if(e[t]!==`"`)return;let n=t+1;for(;n<e.length&&e[n]!==`"`;)n+=e[n]===`\\`?2:1;if(!(n>=e.length))try{return{value:JSON.parse(e.slice(t,n+1)),next:n+1}}catch{return}}function THe(e){let t=0,n=()=>{Z6.lastIndex=t,Z6.exec(e),t=Z6.lastIndex},r=()=>{let n=wHe(e,t);if(n!==void 0)return t=n.next,n.value},i=[];if(n(),e[t]===`{`){if(t+=1,n(),e[t]===`}`)t+=1;else for(;;){let a=r();if(a===void 0||(n(),e[t]!==`:`))return;t+=1,n();let o=r();if(o===void 0)return;if(i.push([a,o]),n(),e[t]===`,`){t+=1,n();continue}if(e[t]!==`}`)return;t+=1;break}return n(),t===e.length?i:void 0}}function EHe(e){let t=THe(e);if(t===void 0)throw new Y6(`output-malformed`);if(t.length>32)throw new Y6(`too-many-headers`);let n=new Set,r={};for(let[e,i]of t){if(!xHe.test(e))throw new Y6(`header-name-invalid`);let t=e.toLowerCase();if(CHe.has(t))throw new Y6(`header-forbidden`);if(n.has(t))throw new Y6(`header-duplicate`);if(n.add(t),!SHe.test(i))throw new Y6(`header-value-invalid`);r[e]=i}return Object.freeze(r)}function DHe(e){let t=new J6(async t=>EHe(await e(t))),n=new WeakMap;return{authorize:async e=>{let{value:r,generation:i}=await t.getEntry(e.signal),a=Object.freeze({...r});return n.set(a,i),a},onRejected:async e=>{let r=n.get(e.authorization);return r===void 0?`fail`:(t.invalidate(r),`retry`)},close:()=>t.close()}}const Q6=/^[A-Za-z_][A-Za-z0-9_]*$/,OHe=/\$\{[^}]*\}/,$6=/^(?:NODE_OPTIONS|NODE_PATH|NODE_EXTRA_CA_CERTS|LD_.*|DYLD_.*|PYTHONPATH|PYTHONHOME|RUBYOPT|PERL5OPT|BASH_ENV|ENV)$/i;function kHe(e){return $6.test(e)}const AHe=new Set([`sh`,`bash`,`zsh`,`fish`,`dash`,`ksh`,`cmd.exe`,`powershell.exe`,`pwsh`,`pwsh.exe`]);function e8(e,t=!1){return typeof e==`string`&&(t||e.length>0)&&e.length<=16384&&!e.includes(`\0`)&&!OHe.test(e)}function t8(e,t){let n=In(e,t);return n===``||n!==`..`&&!n.startsWith(`..${Rn}`)&&!Pn(n)}function n8(e,t){let n=e??t;return Number.isInteger(n)&&n>0&&n<=12e4?n:void 0}async function r8(e){try{let t=await nr(e);return(await rr(t)).isDirectory()?t:void 0}catch{return}}async function i8(e){try{let t=await nr(e);return(await rr(t)).isFile()?t:void 0}catch{return}}function jHe(e){return e.split(/[\\/]/).includes(`..`)}async function MHe(e,t){let n=e.definition,r=n.command,i=n.args??[];if(n.transport!==`stdio`||!e8(r)||!Pn(r)||AHe.has(jn(r).toLowerCase())||!Array.isArray(i)||i.length>128||i.some(e=>!e8(e,!0))||!e8(t.allowedRoot)||!Pn(t.allowedRoot)||!e8(t.generation))return;let a=n8(t.startupMs,1e4),o=n8(t.cleanupMs,6e3);if(a===void 0||o===void 0||o<4100||!t.executables.some(e=>e.command===r&&e.args.some(e=>e.length===i.length&&e.every((e,t)=>e===i[t]))))return;let s=await r8(t.allowedRoot),c=await i8(r);if(s===void 0||c===void 0)return;let l=n.cwd??t.allowedRoot;if(!e8(l)||jHe(l))return;let u=await r8(Ln(s,l));if(u===void 0||!t8(s,u))return;let d=n.env??{},f=t.environment??{};if(!(Object.keys(d).length>128||Object.keys(f).length>128)){for(let[e,t]of Object.entries(f))if(!Q6.test(e)||[`__proto__`,`constructor`,`prototype`].includes(e)||$6.test(e)||!e8(t,!0))return;for(let[e,n]of Object.entries(d))if(!Q6.test(e)||[`__proto__`,`constructor`,`prototype`].includes(e)||$6.test(e)||!e8(n,!0)||!t.allowedEnvironmentKeys?.includes(e)||!Object.hasOwn(f,e)||f[e]!==n)return;return Object.freeze({command:r,canonicalCommand:c,args:Object.freeze([...i]),cwd:u,canonicalRoot:s,env:Object.freeze({...f}),requestedEnvKeys:Object.freeze(Object.keys(d)),generation:t.generation,startupMs:a,cleanupMs:o,activation:e.activation})}}async function NHe(e,t){try{let n=t.admission.admit(e.activation);if(!n.allowed||n.status!==`approved`||t.authority.generation!==e.generation)return!1;let r=await r8(t.authority.allowedRoot),i=await r8(e.cwd),a=await i8(e.command),o=t.authority.executables.some(t=>t.command===e.command&&t.args.some(t=>t.length===e.args.length&&t.every((t,n)=>t===e.args[n]))),s=t.authority.environment??{},c=Object.keys(s).length===Object.keys(e.env).length&&Object.entries(s).every(([t,n])=>e.env[t]===n),l=e.requestedEnvKeys.every(e=>t.authority.allowedEnvironmentKeys?.includes(e)),u=t.admission.admit(e.activation);return u.allowed&&u.status===`approved`&&t.authority.generation===e.generation&&r===e.canonicalRoot&&i===e.cwd&&a===e.canonicalCommand&&t8(r,i)&&o&&c&&l}catch{return!1}}var $=class extends Error{reason;constructor(e){super(`MCP OAuth failed (${e})`),this.reason=e,this.name=`MCPOAuthError`}};function a8(e,t){return e instanceof $?e:e instanceof Error&&e.name===`AbortError`?new $(`cancelled`):new $(t)}const PHe=new Set([101,204,205,304]);function FHe(e){return Object.fromEntries(new Headers(e?.headers).entries())}function IHe(e){let t=e?.body;if(t==null)return``;if(typeof t==`string`||t instanceof URLSearchParams)return t;throw new $(`response-invalid`)}function o8(e){if(!e.ok)throw new $(`egress-refused`);let t=PHe.has(e.status)?null:new TextDecoder().decode(e.body);return new Response(t,{status:e.status,statusText:e.statusText,headers:e.headers})}function s8(e,t){let n={...e.fetch===void 0?{}:{fetch:e.fetch},...e.lookup===void 0?{}:{lookup:e.lookup}};return async(r,i)=>{let a=[i?.signal,t].filter(e=>e instanceof AbortSignal),o={headers:FHe(i),timeoutMs:3e4,maxResponseBytes:262144,...a.length===0?{}:{signal:AbortSignal.any(a)}},s=(i?.method??`GET`).toUpperCase();if(s===`GET`)return o8(await Xt(String(r),o,e.policy,n));if(s!==`POST`)throw new $(`response-invalid`);return o8(await gee(String(r),{...o,body:IHe(i)},e.policy,n))}}function c8(e){if(!URL.canParse(e))throw new $(`response-invalid`);let t=new URL(e);if(t.protocol!==`https:`)throw new $(`insecure-endpoint`);return t}function l8(e){let t=c8(e);return t.hash=``,t.href}function u8(e,t){return!URL.canParse(e)||!URL.canParse(t)?!1:new URL(e).href===new URL(t).href}async function d8(e){try{return await e.json()}catch{throw new $(`response-invalid`)}}async function f8(e,t){let n=await t(e,{headers:{"MCP-Protocol-Version":ei,Accept:`application/json`}});if(n.status>=400&&n.status<500)return;if(!n.ok)throw new $(`discovery-failed`);let r=mte.safeParse(await d8(n));if(!r.success)throw new $(`response-invalid`);return r.data}async function LHe(e,t){if(t.resourceMetadataUrl!==void 0){let n=c8(t.resourceMetadataUrl);if(n.origin!==e.origin)throw new $(`resource-metadata-cross-origin`);let r=await f8(n,t.fetch);if(r===void 0)throw new $(`discovery-failed`);return r}let n=e.pathname.endsWith(`/`)?e.pathname.slice(0,-1):e.pathname,r=[...n===``?[]:[new URL(`/.well-known/oauth-protected-resource${n}`,e)],new URL(`/.well-known/oauth-protected-resource`,e)];for(let e of r){let n=await f8(e,t.fetch);if(n!==void 0)return n}throw new $(`discovery-failed`)}async function RHe(e,t){if(!e.pathname.includes(`/.well-known/`))return{issuer:e.href,metadata:await p8(e,t)};let n=await t(e,{headers:{"MCP-Protocol-Version":ei,Accept:`application/json`}});if(!n.ok)throw new $(`discovery-failed`);let r=pte.safeParse(await d8(n));if(!r.success)throw new $(`response-invalid`);let i=c8(r.data.issuer);if(!rte(i).some(({url:t})=>t.href===e.href))throw new $(`issuer-mismatch`);return{issuer:i.href,metadata:r.data}}async function p8(e,t){let n;try{n=await ate(e,{fetchFn:t})}catch(e){throw a8(e,e instanceof Jee?`issuer-mismatch`:`discovery-failed`)}if(n===void 0)throw new $(`discovery-failed`);if(!u8(n.issuer,e.href))throw new $(`issuer-mismatch`);return n}async function zHe(e,t){try{return await p8(c8(e),t)}catch(e){throw a8(e,`discovery-failed`)}}async function m8(e){try{let t=l8(e.serverUrl),n,r,i;if(e.config.authServerMetadataUrl!==void 0)({issuer:n,metadata:r}=await RHe(c8(e.config.authServerMetadataUrl),e.fetch));else{let a=await LHe(new URL(t),e);if(!u8(a.resource,t))throw new $(`resource-mismatch`);let o=a.authorization_servers?.[0];if(o===void 0)throw new $(`discovery-failed`);let s=c8(o);r=await p8(s,e.fetch),n=s.href,i=a.scopes_supported}if(c8(r.authorization_endpoint),c8(r.token_endpoint),r.registration_endpoint!==void 0&&c8(r.registration_endpoint),r.code_challenge_methods_supported?.includes(`S256`)!==!0)throw new $(`pkce-unsupported`);let a=e.config.scopes?.join(` `)??e.challengeScope??(i===void 0||i.length===0?void 0:i.join(` `));return{resource:t,issuer:n,metadata:r,...a===void 0?{}:{scope:a}}}catch(e){throw a8(e,`discovery-failed`)}}const h8=`127.0.0.1`,g8=`/callback`,_8={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'`,"X-Content-Type-Options":`nosniff`,Connection:`close`};function v8(e,t){e.writeHead(t,{..._8,"Content-Type":`text/plain; charset=utf-8`}),e.end(t===404?`Not found`:`Bad request`)}function y8(e,t){if(e===null)return!1;let n=Buffer.from(e,`utf8`),r=Buffer.from(t,`utf8`);return n.length===r.length&&Kn(n,r)}function b8(e){let t=e.get(`code`),n=e.get(`iss`);return e.has(`error`)?new $(`authorization-denied`):t===null||t===``?new $(`callback-invalid`):{code:t,...n===null?{}:{iss:n}}}function x8(e){return`http://${h8}:${e}${g8}`}async function BHe(){let e=hr();try{await new Promise((t,n)=>{e.once(`error`,n),e.listen(0,h8,()=>t())})}catch{throw new $(`callback-unavailable`)}let t=e.address().port;return await new Promise(t=>e.close(()=>t())),t}function VHe(e){let t=!1;return{accept:n=>{let r=n.trim();if(t||!URL.canParse(r))throw new $(`callback-invalid`);let i=new URL(r);if(`${i.origin}${i.pathname}`!==e.redirectUri||i.username!==``||i.password!==``||!y8(i.searchParams.get(`state`),e.expectedState))throw new $(`callback-invalid`);t=!0;let a=b8(i.searchParams);if(a instanceof $)throw a;return a}}}async function HHe(e){let t,n=new Promise((e,n)=>{t={resolve:e,reject:n}});n.catch(()=>void 0);let r=!1,i=0,a=hr((n,a)=>{if(n.headers.host!==`${h8}:${i}`)return v8(a,400);let o=new URL(n.url??`/`,`http://${h8}:${i}`);if(o.pathname!==g8||r)return v8(a,404);if(n.method!==`GET`)return v8(a,405);if(!y8(o.searchParams.get(`state`),e.expectedState))return v8(a,400);r=!0;let c=b8(o.searchParams);a.writeHead(c instanceof $?400:200,_8),a.end(c instanceof $?`<!doctype html><title>Sign-in failed</title><p>Sign-in did not complete. Return to the application for details.</p>`:`<!doctype html><title>Signed in</title><p>Signed in. You can close this tab and return to the application.</p>`),a.once(`finish`,()=>void s()),c instanceof $?t.reject(c):t.resolve(c)}),o,s=()=>(o??=new Promise(t=>{clearTimeout(u),e.signal?.removeEventListener(`abort`,l),a.close(()=>t()),a.closeAllConnections()}),o),c=e=>{t.reject(new $(e)),s()},l=()=>c(`cancelled`),u;try{await new Promise((t,n)=>{a.once(`error`,n),a.listen(e.port??0,h8,()=>{a.off(`error`,n),t()})})}catch{throw clearTimeout(u),new $(`callback-unavailable`)}return i=a.address().port,e.signal?.aborted===!0?c(`cancelled`):e.signal?.addEventListener(`abort`,l,{once:!0}),{redirectUri:x8(i),wait:()=>(u===void 0&&o===void 0&&(u=setTimeout(()=>c(`callback-timeout`),e.timeoutMs??3e5)),n),close:s}}function S8(e,t){return{securityIdentity:e,serverUrl:l8(t)}}function C8(e){let t=Vn(`sha256`);for(let n of[e.securityIdentity,e.serverUrl])t.update(`${n.length}:${n}`);return t.digest(`hex`)}const UHe=[`clientSecret`,`refreshToken`,`scope`,`tokenEndpointAuthMethod`],WHe=[`issuer`,`authorizationEndpoint`,`tokenEndpoint`,`resource`,`clientId`,`accessToken`];function w8(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function GHe(e){if(!w8(e)||WHe.some(t=>typeof e[t]!=`string`)||UHe.some(t=>e[t]!==void 0&&typeof e[t]!=`string`))return;for(let t of[`expiresAt`,`issuedAt`]){let n=e[t];if(n!==void 0&&(typeof n!=`number`||!Number.isFinite(n)))return}let t=e.tokenEndpointAuthMethods;if(!(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`))))return e}function T8(e){let t=t=>M(e,`${C8(t)}.json`);return{get:async e=>{let n=t(e),r;try{Qt(n),r=A(n,`utf8`)}catch(e){if(e.code===`ENOENT`)return;throw new $(`store-failed`)}let i;try{i=JSON.parse(r)}catch{throw new $(`store-failed`)}if(!w8(i)||i.version!==1||!w8(i.key)||i.key.securityIdentity!==e.securityIdentity||i.key.serverUrl!==e.serverUrl)throw new $(`store-failed`);let a=GHe(i.credential);if(a===void 0)throw new $(`store-failed`);return a},set:async(n,r)=>{try{Yt(e);let i={version:1,key:{securityIdentity:n.securityIdentity,serverUrl:n.serverUrl},credential:r};Jt(t(n),`${JSON.stringify(i,null,2)}\n`)}catch{throw new $(`store-failed`)}},delete:async e=>{try{Tn(t(e),{force:!0})}catch{throw new $(`store-failed`)}}}}const KHe={createExclusive:(e,t)=>kn(e,t,{flag:`wx`,mode:384}),read:e=>A(e,`utf8`),mtimeMs:e=>Dn(e).mtimeMs,rename:(e,t)=>wn(e,t),link:(e,t)=>gn(e,t),unlink:e=>On(e)};function qHe(e,t){return new Promise((n,r)=>{if(t?.aborted===!0)return r(new $(`cancelled`));let i=()=>{clearTimeout(a),r(new $(`cancelled`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}function E8(e,t={}){let n=t.staleMs??6e4,r=t.timeoutMs??9e4,i=t.pollMs??50,a={...KHe,...t.fs},o=(e,t)=>{let n=`${e}.${Wn(8).toString(`hex`)}.aside`;try{a.rename(e,n)}catch{return}let r=!1;try{r=t(n)}catch{}if(!r)try{a.link(n,e)}catch{}try{a.unlink(n)}catch{}},s=(e,t)=>{try{return a.createExclusive(e,t),!0}catch(e){if(e.code!==`EEXIST`)throw new $(`store-failed`)}let r;try{r={token:a.read(e),mtimeMs:a.mtimeMs(e)}}catch{return!1}return Date.now()-r.mtimeMs>n&&o(e,e=>a.read(e)===r.token&&a.mtimeMs(e)===r.mtimeMs),!1},c=(e,t)=>{try{if(a.read(e)!==t)return}catch{return}o(e,e=>a.read(e)===t)};return{withLock:async(t,n,a)=>{try{Yt(e)}catch{throw new $(`store-failed`)}let o=M(e,`${C8(t)}.lock`),l=Wn(16).toString(`hex`),u=Date.now()+r;for(;!s(o,l);){if(Date.now()>=u)throw new $(`lock-timeout`);await qHe(i,a)}try{return await n()}finally{c(o,l)}}}}function D8(e,t,n,r){if(e.token_type.toLowerCase()!==`bearer`)throw new $(`token-type-unsupported`);let i=e.refresh_token??r,a=e.expires_in;return{...t,accessToken:e.access_token,...i===void 0?{}:{refreshToken:i},...a===void 0||!Number.isFinite(a)?{}:{expiresAt:n+a*1e3,issuedAt:n},...e.scope===void 0?{}:{scope:e.scope}}}async function JHe(e,t,n,r){if(e.config.clientId!==void 0)return{client_id:e.config.clientId,...e.clientSecret===void 0?{}:{client_secret:e.clientSecret}};if(e.clientSecret!==void 0)throw new $(`client-secret-without-client-id`);if(t.metadata.registration_endpoint===void 0)throw new $(`registration-unavailable`);try{return await lte(t.issuer,{metadata:t.metadata,clientMetadata:{client_name:e.clientName,redirect_uris:[n],grant_types:[`authorization_code`,`refresh_token`],response_types:[`code`],token_endpoint_auth_method:`none`},...t.scope===void 0?{}:{scope:t.scope},fetchFn:r})}catch(e){throw a8(e,`registration-failed`)}}async function YHe(e,t){let n=e.readRedirect;return n===void 0?HHe({expectedState:t,...e.config.callbackPort===void 0?{}:{port:e.config.callbackPort},...e.callbackTimeoutMs===void 0?{}:{timeoutMs:e.callbackTimeoutMs},...e.signal===void 0?{}:{signal:e.signal}}):O8(e,n,t,x8(e.config.callbackPort??await BHe()))}function O8(e,t,n,r){let i=VHe({expectedState:n,redirectUri:r});return{redirectUri:r,wait:async()=>{let n=AbortSignal.timeout(e.callbackTimeoutMs??3e5),r=e.signal===void 0?n:AbortSignal.any([e.signal,n]),a=new Promise((e,t)=>{let i=()=>t(new $(n.aborted?`callback-timeout`:`cancelled`));r.aborted?i():r.addEventListener(`abort`,i,{once:!0})});a.catch(()=>void 0);let o;try{o=await Promise.race([t(r),a])}catch(e){throw a8(e,`cancelled`)}return i.accept(o)},close:async()=>void 0}}async function k8(e){let t=s8(e.network,e.signal),n=await m8({serverUrl:e.serverUrl,config:e.config,fetch:t}),r=Wn(32).toString(`base64url`),i=await YHe(e,r);try{let a=await JHe(e,n,i.redirectUri,t),o=new URL(n.resource),s;try{s=await fte(n.issuer,{metadata:n.metadata,clientInformation:a,redirectUrl:i.redirectUri,state:r,resource:o,...n.scope===void 0?{}:{scope:n.scope}})}catch(e){throw a8(e,`discovery-failed`)}if(s.authorizationUrl.protocol!==`https:`)throw new $(`insecure-endpoint`);try{await e.openBrowser(s.authorizationUrl,i.redirectUri)}catch(t){let n=e.readRedirectWhenBrowserFails,a=t instanceof $&&t.reason===`cancelled`;if(n===void 0||e.readRedirect!==void 0||a)throw a8(t,`browser-failed`);let o=i;i=O8(e,n,r,o.redirectUri),await o.close()}let c=await i.wait(),l=n.metadata.authorization_response_iss_parameter_supported===!0;if(c.iss!==void 0&&c.iss!==n.metadata.issuer||c.iss===void 0&&l)throw new $(`issuer-parameter-mismatch`);let u;try{u=await ote(n.issuer,{metadata:n.metadata,clientInformation:a,authorizationCode:c.code,...c.iss===void 0?{}:{iss:c.iss},codeVerifier:s.codeVerifier,redirectUri:i.redirectUri,resource:o,fetchFn:t})}catch(e){throw a8(e,`token-exchange-failed`)}let d=D8(u,{issuer:n.issuer,authorizationEndpoint:n.metadata.authorization_endpoint,tokenEndpoint:n.metadata.token_endpoint,...n.metadata.token_endpoint_auth_methods_supported===void 0?{}:{tokenEndpointAuthMethods:n.metadata.token_endpoint_auth_methods_supported},resource:n.resource,clientId:a.client_id,...a.client_secret===void 0?{}:{clientSecret:a.client_secret},...`token_endpoint_auth_method`in a&&a.token_endpoint_auth_method!==void 0?{tokenEndpointAuthMethod:a.token_endpoint_auth_method}:{}},(e.now??Date.now)()),f={securityIdentity:e.securityIdentity,serverUrl:n.resource};return await e.lock.withLock(f,()=>e.store.set(f,d),e.signal),{issuer:n.issuer,...d.scope===void 0?{}:{scope:d.scope}}}finally{await i.close()}}async function XHe(e){let t;try{t=await e.store.get(S8(e.securityIdentity,e.serverUrl))}catch{return`sign-in-required`}return t===void 0?`signed-out`:t.expiresAt===void 0||(e.now??Date.now)()<t.expiresAt?`signed-in`:t.refreshToken===void 0?`sign-in-required`:`expired-refreshable`}function ZHe(e,t,n){let r=ute({client_id:e.clientId,...e.clientSecret===void 0?{}:{client_secret:e.clientSecret},...e.tokenEndpointAuthMethod===void 0?{}:{token_endpoint_auth_method:e.tokenEndpointAuthMethod}},[...t??e.tokenEndpointAuthMethods??[]]);if(r===`client_secret_basic`&&e.clientSecret!==void 0){let t=`${e.clientId}:${e.clientSecret}`;return{Authorization:`Basic ${Buffer.from(t,`utf8`).toString(`base64`)}`}}return n.set(`client_id`,e.clientId),r===`client_secret_post`&&e.clientSecret!==void 0&&n.set(`client_secret`,e.clientSecret),{}}async function QHe(e){try{let t=await e.json();return typeof t==`object`&&!!t&&t.error===`unsupported_token_type`}catch{return!1}}async function A8(e,t,n,r,i){let a=new URLSearchParams({token:n,token_type_hint:r});try{let n={"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`,...ZHe(t,e.authMethods,a)},o=await i(e.url,{method:`POST`,headers:n,body:a});return o.status===200?{token:r,revoked:!0}:{token:r,revoked:!1,failure:await QHe(o)?`token-type-not-revocable`:`revocation-failed`}}catch(e){return{token:r,revoked:!1,failure:a8(e,`revocation-failed`).reason}}}function $He(e){let t=e.revocation_endpoint;if(t===void 0)return;if(typeof t!=`string`||!URL.canParse(t)||new URL(t).protocol!==`https:`)throw new $(`insecure-endpoint`);let n=e.revocation_endpoint_auth_methods_supported;return Array.isArray(n)&&n.every(e=>typeof e==`string`)?{url:t,authMethods:n}:{url:t}}async function eUe(e,t,n){let r=s8(t,n),i;try{i=$He(await zHe(e.issuer,r))}catch(e){return{revocation:`failed`,revocationFailure:a8(e,`revocation-failed`).reason}}if(i===void 0)return{revocation:`unsupported`};let a=[];e.refreshToken!==void 0&&a.push(await A8(i,e,e.refreshToken,`refresh_token`,r)),a.push(await A8(i,e,e.accessToken,`access_token`,r));let o=a.find(e=>!e.revoked)?.failure,s=a.filter(e=>e.revoked).length;return{revocation:o===void 0?`revoked`:s===0?`failed`:`partial`,...o===void 0?{}:{revocationFailure:o},tokens:a}}async function j8(e){let t=S8(e.securityIdentity,e.serverUrl),{removed:n,credential:r}=await e.lock.withLock(t,async()=>{let n,r=!1;try{n=await e.store.get(t)}catch{r=!0}return await e.store.delete(t),{removed:r||n!==void 0,credential:n}},e.signal);return r===void 0?{removed:n,revocation:`not-attempted`}:{removed:n,...await eUe(r,e.network,e.signal)}}const tUe=/^[\x21\x23-\x5b\x5d-\x7e]+(?: [\x21\x23-\x5b\x5d-\x7e]+)*$/;function nUe(e){if(e===void 0)return{};let t;try{t=ste(new Response(null,{headers:{"www-authenticate":e}}))}catch{return{}}let n=t.scope!==void 0&&t.scope.length<=512&&tUe.test(t.scope)?t.scope:void 0;return{...t.resourceMetadataUrl===void 0?{}:{resourceMetadataUrl:t.resourceMetadataUrl.href},...n===void 0?{}:{scope:n},...t.error===void 0?{}:{error:t.error}}}function rUe(e){let t=S8(e.securityIdentity,e.serverUrl),n=e.now??Date.now,r=e.expirySkewMs??6e4,i,a,o=!1,s=async n=>{throw n&&await e.store.delete(t),o||(o=!0,e.notify({kind:`login-required`,serverId:e.serverId})),new $(`login-required`)},c=e=>{if(e.expiresAt===void 0)return!1;let t=e.issuedAt===void 0?void 0:e.expiresAt-e.issuedAt,i=t===void 0?r:Math.min(r,Math.max(0,t/2));return n()>=e.expiresAt-i},l=e=>e.accessToken!==i&&!c(e),u=async(r,i,a=!1)=>{let o=r.refreshToken;if(o===void 0)return s(!0);let c={client_id:r.clientId,...r.clientSecret===void 0?{}:{client_secret:r.clientSecret},...r.tokenEndpointAuthMethod===void 0?{}:{token_endpoint_auth_method:r.tokenEndpointAuthMethod}},d;try{d=await cte(r.issuer,{metadata:{issuer:r.issuer,authorization_endpoint:r.authorizationEndpoint,token_endpoint:r.tokenEndpoint,response_types_supported:[`code`],...r.tokenEndpointAuthMethods===void 0?{}:{token_endpoint_auth_methods_supported:[...r.tokenEndpointAuthMethods]}},clientInformation:c,refreshToken:o,resource:new URL(r.resource),fetchFn:s8(e.network,i)})}catch(n){if(!(n instanceof Yee&&n.code===Xee.InvalidGrant))throw a8(n,`refresh-failed`);let r=await e.store.get(t);return r===void 0?s(!1):r.refreshToken===o?s(!0):l(r)?r:a?s(!1):u(r,i,!0)}let{accessToken:f,refreshToken:p,expiresAt:m,issuedAt:h,scope:g,..._}=r,v=D8(d,_,n(),o);return await e.store.set(t,v),v},d=async n=>{let r=a;a=void 0;let i=await e.store.get(t);if(i===void 0)return s(!1);if(r===void 0&&l(i))return i;let o=r===void 0?void 0:await m8({serverUrl:e.serverUrl,config:e.config,fetch:s8(e.network,n),...r.resourceMetadataUrl===void 0?{}:{resourceMetadataUrl:r.resourceMetadataUrl}});return e.lock.withLock(t,async()=>{let r=await e.store.get(t);return r===void 0?s(!1):o!==void 0&&(!u8(o.issuer,r.issuer)||!u8(o.metadata.token_endpoint,r.tokenEndpoint))?s(!0):l(r)?r:u(r,n)},n)},f=new J6(async e=>{let t=await d(e);return o=!1,t}),p=new WeakMap,m=0;return{authorize:async e=>{let{value:t,generation:n}=await f.getEntry(e.signal);c(t)&&(f.invalidate(n),{value:t,generation:n}=await f.getEntry(e.signal)),m=Math.max(m,n);let r=Object.freeze({Authorization:`Bearer ${t.accessToken}`});return p.set(r,{generation:n,accessToken:t.accessToken}),r},onRejected:async t=>{let n=p.get(t.authorization);if(n===void 0)return`fail`;let r=nUe(t.wwwAuthenticate);return t.status===403?(r.error===`insufficient_scope`&&e.notify({kind:`insufficient-scope`,serverId:e.serverId,...r.scope===void 0?{}:{scope:r.scope}}),`fail`):t.status===401?n.generation<m?`retry`:(i!==n.accessToken&&(i=n.accessToken,a={...r.resourceMetadataUrl===void 0?{}:{resourceMetadataUrl:r.resourceMetadataUrl}}),f.invalidate(n.generation),`retry`):`fail`},forget:()=>f.invalidate(m),close:()=>f.close()}}const M8=65536;var N8=class extends Error{reason;constructor(e){super(`Stdio transport ${e}`),this.reason=e,this.name=`MCPStdioError`}};function P8(e,t){return new Promise((n,r)=>{let i=setTimeout(()=>r(new N8(`cleanup`)),t);e.then(e=>{clearTimeout(i),n(e)},()=>{clearTimeout(i),r(new N8(`cleanup`))})})}var iUe=class{snapshot;revalidate;onclose;onerror;onmessage;sensitiveDiagnostics=!0;child;closePromise;childClosed=!1;closeNotified=!1;started=!1;stderrBytes=0;stderrTruncated=!1;stdoutParts=[];stdoutBytes=0;resourceReads=new Set;resolveChildClose;childClose=new Promise(e=>{this.resolveChildClose=e});constructor(e,t){this.snapshot=e,this.revalidate=t}get stderrSummary(){return{bytes:this.stderrBytes,truncated:this.stderrTruncated}}get pid(){return this.child?.pid??null}get closedDirectChild(){return this.childClosed}get stdioStartupMs(){return this.snapshot.startupMs}notifyClose(){this.closeNotified||(this.closeNotified=!0,this.onclose?.())}receive(e){if(this.closePromise!==void 0)return;let t=0;for(;t<e.length;){let n=e.indexOf(10,t),r=n<0?e.length:n,i=e.subarray(t,r),a=N6(this)&&this.resourceReads.size>0?j6:A6;if(this.stdoutBytes+i.length>a){this.onerror?.(new N8(`receive-limit`)),this.close().catch(()=>this.onerror?.(new N8(`cleanup`)));return}if(this.stdoutParts.push(i),this.stdoutBytes+=i.length,n>=0){let e=this.stdoutBytes,t=Buffer.concat(this.stdoutParts,this.stdoutBytes).toString(`utf8`).replace(/\r$/u,``);this.stdoutParts=[],this.stdoutBytes=0;try{let n=ite(t),r=`id`in n&&n.id!==void 0&&this.resourceReads.has(n.id);if(e>8388608&&!r){this.onerror?.(new N8(`receive-limit`)),this.close().catch(()=>this.onerror?.(new N8(`cleanup`)));return}`id`in n&&n.id!==void 0&&!(`method`in n)&&this.resourceReads.delete(n.id),this.onmessage?.(n)}catch{this.onerror?.(new N8(`receive-invalid`)),this.close().catch(()=>this.onerror?.(new N8(`cleanup`)));return}}t=r+1}}async start(){if(this.started||this.closePromise!==void 0)throw new N8(`start`);if(this.started=!0,!await this.revalidate())throw new N8(`authority`);if(this.closePromise!==void 0)throw new N8(`start`);let e=Object.create(null);for(let t of hte)e[t]=this.snapshot.env[t]??``;for(let[t,n]of Object.entries(this.snapshot.env))e[t]=n;try{let t=on(this.snapshot.command,[...this.snapshot.args],{cwd:this.snapshot.cwd,env:e,stdio:[`pipe`,`pipe`,`pipe`],shell:!1,windowsHide:process.platform===`win32`});this.child=t;let n=new Promise((e,n)=>{t.once(`spawn`,()=>e()),t.once(`error`,()=>n(new N8(`start`)))});if(t.on(`error`,()=>this.onerror?.(new N8(`start`))),t.on(`close`,()=>{this.childClosed=!0,this.child=void 0,this.resolveChildClose?.(),this.notifyClose()}),t.stdin.on(`error`,()=>this.onerror?.(new N8(`send`))),t.stdout.on(`data`,e=>this.receive(e)),t.stdout.on(`error`,()=>this.onerror?.(new N8(`receive-invalid`))),t.stderr.on(`data`,e=>{this.stderrBytes=Math.min(M8,this.stderrBytes+e.length),this.stderrBytes>=M8&&(this.stderrTruncated=!0)}),await n,this.childClosed)throw new N8(`early-exit`)}catch{throw await this.close(),new N8(`start`)}}async send(e){let t=this.child;if(t===void 0||this.childClosed)throw new N8(`send`);`method`in e&&e.method===`resources/read`&&`id`in e&&N6(this)&&this.resourceReads.add(e.id);try{await new Promise((n,r)=>{t.stdin.write(dte(e),e=>{e?r(e):n()})})}catch{throw new N8(`send`)}}close(){return this.closePromise===void 0&&(this.closePromise=this.closeOwned()),this.closePromise}async closeOwned(){let e=this.child;if(this.stdoutParts=[],this.stdoutBytes=0,this.resourceReads.clear(),e===void 0){this.notifyClose();return}try{e.stdin.end();try{await P8(this.childClose,2e3)}catch{e.kill(`SIGTERM`);try{await P8(this.childClose,2e3)}catch{e.kill(`SIGKILL`),await P8(this.childClose,this.snapshot.cleanupMs-4e3)}}}catch{throw new N8(`cleanup`)}}};function F8({definition:e,activation:t}){let n=y6(e),r=x6({name:e.name,source:e.source,origin:e.origin,status:`resolved`,definition:e,shadowed:[]});return t.serverId===e.name&&t.source===e.source&&t.provenance.kind===e.source&&t.provenance.id===e.origin&&t.provenance.version===n&&t.definitionFingerprint===n&&t.securityIdentity===r&&t.endpoint===b6(e)}function I8(e){return{ok:!1,reason:e,message:`Stdio transport refused: ${e}`}}function aUe(e){return Object.freeze({...e,provenance:Object.freeze({...e.provenance}),...e.workspace===void 0?{}:{workspace:Object.freeze({...e.workspace})}})}function oUe(e){let t=new WeakMap;return{kind:`stdio`,async admit(n){try{let r={definition:n.definition,activation:aUe(n.activation)};if(!F8(r))return I8(`definition-identity`);let i=e.admission.admit(r.activation);if(!i.allowed||i.status!==`approved`||i.definitionFingerprint!==r.activation.definitionFingerprint||i.securityIdentity!==r.activation.securityIdentity)return I8(`activation`);let a=await MHe(r,e.authority);if(a===void 0||!F8(r))return I8(`authority`);let o=Object.freeze({kind:`stdio`});return t.set(o,a),{ok:!0,admitted:o}}catch{return I8(`invalid-input`)}},construct(n){let r=t.get(n);if(r===void 0)throw Error(`Stdio transport refused: invalid admission`);return new iUe(r,()=>NHe(r,e))}}}const L8=`io.modelcontextprotocol/ui`,R8=`text/html;profile=mcp-app`;function z8(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e[L8];return typeof t==`object`&&!!t&&!Array.isArray(t)}const sUe=/^[A-Za-z0-9+/]*={0,2}$/u;function cUe(e){return typeof e==`string`?e.replace(/\s+/gu,``).toLowerCase():void 0}function lUe(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`);return e.length/4*3-t}function uUe(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return}}function dUe(e){let t=e.text,n=e.blob;if(typeof t==`string`&&n===void 0)return t.length===0?{ok:!1,reason:`content`}:Buffer.byteLength(t,`utf8`)>2097152?{ok:!1,reason:`too-large`}:{ok:!0,html:t,mimeType:R8};if(typeof n==`string`&&t===void 0){if(n.length===0||n.length%4!=0||!sUe.test(n))return{ok:!1,reason:`content`};if(lUe(n)>2097152)return{ok:!1,reason:`too-large`};let e=uUe(Buffer.from(n,`base64`));return e===void 0||e.length===0?{ok:!1,reason:`content`}:{ok:!0,html:e,mimeType:R8}}return{ok:!1,reason:`content`}}function fUe(e,t){if(t.contents.length===0)return{ok:!1,reason:`missing`};let[n]=t.contents;return t.contents.length!==1||n===void 0?{ok:!1,reason:`content`}:n.uri===e?cUe(n.mimeType)===`text/html;profile=mcp-app`?dUe(n):{ok:!1,reason:`mime-type`}:{ok:!1,reason:`uri-mismatch`}}function pUe(e,t){let n=[];for(let r of[...e.adopted,...e.adapted])r.kind===`tool`&&r.provenance.serverId===t&&(r.ui!==void 0&&!r.ui.visibility.includes(`app`)||n.push([r.sourceName,r.canonicalName]));return Object.fromEntries(n)}var B8=class extends Error{reason;constructor(e){super(`MCP skill refused: ${e}`),this.reason=e,this.name=`MCPSkillError`}};function V8(){throw new B8(`invalid-manifest`)}function H8(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null)}function U8(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)?JSON.stringify(e):Array.isArray(e)?`[${e.map(U8).join(`,`)}]`:H8(e)?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${U8(e[t])}`).join(`,`)}}`:V8()}function mUe(e,t){try{let n=new URL(e),r=new URL(t),i=n.pathname.slice(0,n.pathname.lastIndexOf(`/`)+1);return n.protocol===r.protocol&&n.host===r.host&&n.username===r.username&&n.password===r.password&&r.pathname.startsWith(i)&&!r.pathname.endsWith(`/`)}catch{return!1}}function W8(e,t){if(!H8(e)||typeof e.uri!=`string`||!H8(e.frontmatter))return V8();let{name:n,description:r}=e.frontmatter;if(typeof n!=`string`||!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(n)||n.length>64||typeof r!=`string`||r.length===0||r.length>1024)return V8();try{let t=new URL(e.uri),r=`${t.host}${t.pathname}`.split(`/`);if(r.at(-1)!==`SKILL.md`||decodeURIComponent(r.at(-2)??``)!==n)return V8()}catch{return V8()}let i=JSON.parse(U8(e.frontmatter)),a;if(e.resources===`dynamic`)a=`dynamic`;else{if(!Array.isArray(e.resources)||e.resources.length<1||e.resources.length>512)return V8();let t=new Set,n=0;if(a=e.resources.map(r=>!H8(r)||typeof r.uri!=`string`||typeof r.digest!=`string`||!/^sha256:[a-f0-9]{64}$/.test(r.digest)||typeof r.size!=`number`||!Number.isSafeInteger(r.size)||r.size<0||t.has(r.uri)||!mUe(e.uri,r.uri)||(t.add(r.uri),n+=r.size,n>16*1024*1024)?V8():{uri:r.uri,digest:r.digest,size:r.size}),!t.has(e.uri))return V8()}let o=Vn(`sha256`).update(U8({uri:e.uri,frontmatter:i,resources:a===`dynamic`?a:[...a].sort((e,t)=>e.uri<t.uri?-1:+(e.uri>t.uri))})).digest(`hex`);return{identity:{...t},uri:e.uri,frontmatter:i,resources:a,manifestFingerprint:o}}function hUe(e,t,n){if(e.resources===`dynamic`)throw new B8(`unsupported-dynamic`);let r=e.resources.find(e=>e.uri===t);if(!r)throw new B8(`missing-resource`);if(!H8(n)||n.uri!==t||n.mimeType!==void 0&&typeof n.mimeType!=`string`||!(typeof n.text==`string`&&!(`blob`in n)||typeof n.blob==`string`&&!(`text`in n)))throw new B8(`invalid-resource`);let i;if(typeof n.text==`string`)i=Buffer.from(n.text,`utf8`);else{if(typeof n.blob!=`string`)throw new B8(`invalid-resource`);try{i=Buffer.from(atob(n.blob),`latin1`)}catch{throw new B8(`invalid-resource`)}}if(i.byteLength!==r.size)throw new B8(`size-mismatch`);let a=`sha256:${Vn(`sha256`).update(i).digest(`hex`)}`;if(a!==r.digest)throw new B8(`digest-mismatch`);return{uri:t,digest:a,size:i.byteLength,...typeof n.text==`string`?{text:n.text}:{blob:n.blob},...n.mimeType===void 0?{}:{mimeType:n.mimeType}}}var G8=class extends Error{reason;constructor(e){super(`Unsupported stateless MCP result: ${e}; inspect the operation before any retry`),this.reason=e,this.name=`MCPStatelessProtocolError`}};function K8(e){if(typeof e.ttlMs!=`number`||!Number.isFinite(e.ttlMs)||e.ttlMs<0||e.cacheScope!==`public`&&e.cacheScope!==`private`)throw Error(`Invalid stateless MCP cache metadata`);return{ttlMs:e.ttlMs,cacheScope:e.cacheScope,receivedAtMs:Date.now()}}const gUe={"~standard":{version:1,vendor:`robota-agent-mcp`,validate:e=>typeof e==`object`&&e&&!Array.isArray(e)?{value:e}:{issues:[{message:`expected a result object`}]}}};function _Ue(e,t){let n=new Map,r=new Map,i=0,a=(e,t)=>{(r.get(e)??0)>t||(r.set(e,t),n.delete(e))},o=e=>{if(e.resultType!==`complete`)throw new B8(`invalid-manifest`);K8(e)};return{async list(s){if(!Number.isSafeInteger(s.maxPages)||s.maxPages<1)throw new B8(`page-bound`);let c=++i,l=[],u=new Set,d=new Set,f;for(let i=0;i<s.maxPages;i++){let i=await t(`skills/list`,f===void 0?{}:{cursor:f},s);if(o(i),!Array.isArray(i.skills))throw new B8(`invalid-manifest`);for(let t of i.skills){typeof t==`object`&&t&&`uri`in t&&typeof t.uri==`string`&&a(t.uri,c);let n=W8(t,e);if(u.has(n.uri))throw new B8(`invalid-manifest`);u.add(n.uri),l.push(n)}if(i.nextCursor===void 0){for(let e of l)r.get(e.uri)===c&&n.set(e.uri,structuredClone(e));return l}if(typeof i.nextCursor!=`string`||i.nextCursor.length===0||d.has(i.nextCursor))throw new B8(`invalid-manifest`);f=i.nextCursor,d.add(f)}throw new B8(`page-bound`)},async get(s,c){let l=++i;a(s,l);let u=await t(`skills/get`,{uri:s},c);if(r.get(s)!==l)throw new B8(`changed-manifest`);o(u);let d=W8(u.skill,e);if(d.uri!==s)throw new B8(`invalid-manifest`);return n.set(s,structuredClone(d)),d},async read(r,i,a){let o=n.get(r.uri);if(!o||r.identity.serverId!==e.serverId||r.identity.catalogGeneration!==e.catalogGeneration||o.manifestFingerprint!==r.manifestFingerprint||W8(r,e).manifestFingerprint!==o.manifestFingerprint)throw new B8(`changed-manifest`);if(o.resources===`dynamic`)throw new B8(`unsupported-dynamic`);if(!o.resources.some(e=>e.uri===i))throw new B8(`missing-resource`);try{let e=await t(`resources/read`,{uri:i},a);if(e.resultType!==`complete`||!Array.isArray(e.contents)||e.contents.length!==1)throw new B8(`invalid-resource`);let s=K8(e);if(n.get(r.uri)?.manifestFingerprint!==o.manifestFingerprint)throw new B8(`changed-manifest`);return{...hUe(o,i,e.contents[0]),cacheHint:s}}catch(e){throw n.get(r.uri)?.manifestFingerprint===o.manifestFingerprint&&n.delete(r.uri),e}}}}function vUe(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e[`io.modelcontextprotocol/skills`];return typeof t!=`object`||!t||Array.isArray(t)?!1:!(`directoryRead`in t)||typeof t.directoryRead==`boolean`}const q8=[`anthropic`,`maxResultSizeChars`].join(`/`);function yUe(e){if(e===void 0)return{kind:`absent`};if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`invalid`,reason:`invalid-type`};let t=e;if(!Object.hasOwn(t,q8))return{kind:`absent`};let n=t[q8];return typeof n!=`number`||!Number.isSafeInteger(n)?{kind:`invalid`,reason:`invalid-type`}:n<=25e3||n>5e5?{kind:`invalid`,reason:`out-of-range`}:{kind:`accepted`,maxResultChars:n}}const bUe=/\s/u,xUe=[`model`,`app`];function SUe(e){return e===`model`||e===`app`}function CUe(e){if(e===void 0)return xUe;if(!Array.isArray(e)||e.length===0)return;let t=[];for(let n of e){if(!SUe(n)||t.includes(n))return;t.push(n)}return t}function wUe(e){return e.startsWith(`ui://`)&&e.length>5&&!bUe.test(e)}function TUe(e){if(typeof e!=`object`||!e||Array.isArray(e))return{kind:`absent`};let t=e;if(!Object.hasOwn(t,`ui`))return{kind:`absent`};let n=t.ui;if(typeof n!=`object`||!n||Array.isArray(n))return{kind:`invalid`,reason:`invalid-type`};let r=n,i=CUe(r.visibility);if(i===void 0)return{kind:`invalid`,reason:`invalid-visibility`};let a=r.resourceUri;if(a!==void 0){if(typeof a!=`string`)return{kind:`invalid`,reason:`invalid-type`,visibility:i};if(!wUe(a))return{kind:`invalid`,reason:`invalid-uri`,visibility:i}}return a===void 0?i.includes(`model`)&&i.includes(`app`)?{kind:`absent`}:{kind:`accepted`,visibility:i}:{kind:`accepted`,resourceUri:a,visibility:i}}var J8=class extends Error{failure;constructor(e){super(`MCP discovery failed (${e.domain}, ${e.kind}): ${e.message}`),this.failure=e,this.name=`MCPDiscoveryError`}};function Y8(e){return{serverId:e.serverId,protocolVersion:e.protocolVersion,serverVersion:e.serverVersion,...e.catalogGeneration===void 0?{}:{catalogGeneration:e.catalogGeneration}}}function X8(e,t){return e.serverId===t.serverId&&e.protocolVersion===t.protocolVersion&&e.serverVersion===t.serverVersion&&e.catalogGeneration===t.catalogGeneration}function Z8(e){if(e===null)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`||e instanceof Date)return e;if(Array.isArray(e))return e.map(e=>Z8(e));if(typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=Z8(r);return t}return String(e)}function Q8(e){let t=Z8(e);return jt.isObject(t)?t:{}}var $8=class extends Error{kind;details;constructor(e,t,n){super(t),this.kind=e,this.details=n,this.name=`MCPSessionError`}};const e5={name:`mcp-client`,version:`0.0.0`},t5=`2026-07-28`;function n5(e,t,n,r){let i=new qee({name:e.name,version:e.version},{capabilities:{...n===void 0?{}:{elicitation:{form:{}}},...r===!0?{extensions:{[L8]:{mimeTypes:[R8]}}}:{}},inputRequired:{autoFulfill:n!==void 0},...t===void 0?{}:{versionNegotiation:{mode:{pin:t}}}});return n!==void 0&&i.setRequestHandler(`elicitation/create`,(e,t)=>n(e.params,t.mcpReq.signal)),i}function r5(e){return e instanceof ti&&e.code===ni.RequestTimeout}function i5(e){let t=Q8(e),n=t.content;return{content:Array.isArray(n)?n.filter(jt.isObject):[],structuredContent:t.structuredContent,isError:typeof t.isError==`boolean`&&t.isError}}function a5(e){let t=Q8(e).contents;return{contents:Array.isArray(t)?t.map(e=>jt.isObject(e)?e:{}):[]}}function o5(e){let t=[`tools`,`prompts`,`resources`],n={tools:void 0,prompts:void 0,resources:void 0};for(let r of t){let t=e?.[r];t!==void 0&&(n[r]={listChanged:t.listChanged??!1})}return n}function EUe(e){return e}function DUe(e,t){let n=e._meta,r=yUe(n),i=t?TUe(n):{kind:`absent`};return{name:e.name,description:e.description,inputSchema:EUe(e.inputSchema),outputSchema:e.outputSchema===void 0?void 0:Q8(e.outputSchema),...r.kind===`absent`?{}:{resultSizeMetadata:r},...i.kind===`accepted`?{ui:{...i.resourceUri===void 0?{}:{resourceUri:i.resourceUri},visibility:i.visibility}}:i.kind===`invalid`&&i.visibility!==void 0?{ui:{visibility:i.visibility}}:{},...i.kind===`invalid`?{uiProblem:i.reason}:{}}}function OUe(e){return{name:e.name,description:e.description,arguments:e.arguments}}function kUe(e){return{uri:e.uri,name:e.name,description:e.description,mimeType:e.mimeType}}function AUe(e,t,n){return t instanceof Zee?new J8({kind:t.code===Qee.InvalidParams?`invalid-cursor`:`protocol`,domain:e,message:t.message,code:t.code,pagesSeen:n}):r5(t)?new J8({kind:`timeout`,domain:e,message:t instanceof Error?t.message:String(t),pagesSeen:n}):new J8({kind:`protocol`,domain:e,message:t instanceof Error?t.message:String(t),pagesSeen:n})}function jUe(e,t,n){if(t>=n)throw new J8({kind:`page-bound-exceeded`,domain:e,message:`Exceeded the configured page bound of ${n} for "${e}"`,pagesSeen:t})}async function MUe(e,t,n,r,i){try{return await i(n,{timeout:r.perRequestTimeoutMs,signal:r.signal})}catch(n){throw AUe(e,n,t)}}function NUe(e,t,n){if(n!==void 0){if(n===``)throw new J8({kind:`invalid-cursor`,domain:e,message:`Server returned an empty nextCursor for "${e}"`,pagesSeen:t});return n}}async function s5(e,t,n,r,i){if(t===void 0)return{state:{kind:`unsupported`},items:[],pages:0};let a=[],o=[],s,c=0;for(;;){jUe(e,c,n.maxPages);let t=await MUe(e,c,s,n,r);c+=1,a.push(...t.items.map(i)),t.cacheHint&&o.push(t.cacheHint);let l=NUe(e,c,t.nextCursor);if(l===void 0)break;s=l}return{state:{kind:`supported`,count:a.length,listChanged:t.listChanged},items:a,pages:c,...o.length===0?{}:{cacheHints:o}}}async function c5(e,t,n,r,i,a=!1){return{identity:n,instructions:r,tools:await s5(`tools`,t.tools,i,async(t,r)=>{let i=await e.request({method:`tools/list`,params:t===void 0?{}:{cursor:t}},r);return{items:i.tools,nextCursor:i.nextCursor,...n.protocolVersion===`2026-07-28`?{cacheHint:K8(i)}:{}}},e=>DUe(e,a)),prompts:await s5(`prompts`,t.prompts,i,async(t,r)=>{let i=await e.request({method:`prompts/list`,params:t===void 0?{}:{cursor:t}},r);return{items:i.prompts,nextCursor:i.nextCursor,...n.protocolVersion===`2026-07-28`?{cacheHint:K8(i)}:{}}},OUe),resources:await s5(`resources`,t.resources,i,async(t,r)=>{let i=await e.request({method:`resources/list`,params:t===void 0?{}:{cursor:t}},r);return{items:i.resources,nextCursor:i.nextCursor,...n.protocolVersion===`2026-07-28`?{cacheHint:K8(i)}:{}}},kUe)}}var l5=class{calls=new Set;open;enter(e){let t={...e};return this.calls.add(t),()=>{this.calls.delete(t),this.firstWithPort()===void 0&&(this.open?.abort(),this.open=void 0)}}answerable(){let e=this.firstWithPort();if(e!==void 0)return this.open??=new AbortController,{ask:e,withdrawn:this.open.signal}}firstWithPort(){for(let e of this.calls)if(e.ask!==void 0)return e.ask}};function u5(e){return async(t,n)=>{if(t.mode===`url`)return{action:`decline`};let r=e.calls.answerable();if(r===void 0)return{action:`decline`};let i=[n,r.withdrawn].filter(e=>e!==void 0);return zUe({serverId:e.serverId(),params:t,ask:r.ask,signal:AbortSignal.any(i)})}}const d5=`respond`,f5={action:`cancel`},PUe={action:`decline`},FUe=/^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/u,IUe=/^\d{4}-\d{2}-\d{2}$/u,LUe=/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$/u;function RUe(e){let t=e.codePointAt(0)??0;return t<32||t>=127&&t<=159||t===8232||t===8233||/\s/u.test(e)}function p5(e,t){let n=[],r=!1;for(let t of e){if(RUe(t)){r=!0;continue}r&&n.length>0&&n.push(` `),r=!1,n.push(t)}return n.length<=t?n.join(``):`${n.slice(0,t).join(``)}…`}async function zUe(e){let{serverId:t,params:n,signal:r}=e,i=r===void 0?void 0:{signal:r},a=async t=>{try{return await e.ask(t,i)}catch{return}},o=`mcp-elicitation-${N()}`,s=await a({id:`${o}-0`,title:`MCP server ${JSON.stringify(t)} asks for input`,description:p5(n.message,400),options:[{value:d5,label:`Respond`},{value:`decline`,label:`Decline`,description:`Tell the server you will not answer`}],maxSelect:1,maxVisible:8});if(s===void 0||s.type!==`answer`)return f5;if(s.values[0]!==d5)return PUe;let c=new Set(n.requestedSchema.required??[]),l={},u=0;for(let[e,r]of Object.entries(n.requestedSchema.properties)){u+=1;let n=VUe(t,e,r,c.has(e)),i=await BUe(`${o}-${u}`,n,a);if(i.kind===`cancel`)return f5;i.kind===`value`&&(l[e]=i.value)}return{action:`accept`,content:l}}async function BUe(e,t,n){let r;for(let i=0;i<2;i+=1){let a=r===void 0?t.request.description:[r,t.request.description].filter(Boolean).join(` `),o=await n({...t.request,id:i===0?e:`${e}-again`,...a===void 0?{}:{description:a}});if(o===void 0||o.type!==`answer`)return{kind:`cancel`};let s=t.parse(o);if(s.kind!==`invalid`)return s;r=`Invalid answer: ${s.reason}.`}return{kind:`cancel`}}function VUe(e,t,n,r){let i=`MCP server ${JSON.stringify(e)} asks: ${p5(n.title??t,80)}`,a=K3(t)||n.title!==void 0&&K3(n.title)?`Caution: this field is named like a credential; what you enter is shown as typed and sent to the server.`:void 0,o=e=>{let t=[n.description===void 0?void 0:p5(n.description,400),e,a].filter(Boolean).join(` `);return t.length===0?void 0:t};if(n.type===`boolean`){let e=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}],t=r?void 0:m5(e);return{request:{title:i,description:o(void 0),options:e,maxSelect:1,maxVisible:8,...n.default===void 0?{}:{default:{values:[n.default?`yes`:`no`]}}},parse:e=>{let n=e.values[0];return n===`yes`?{kind:`value`,value:!0}:n===`no`?{kind:`value`,value:!1}:t!==void 0&&n===t?{kind:`skip`}:{kind:`invalid`,reason:`not one of the offered choices`}}}}if(n.type===`array`)return HUe(i,o(void 0),n,r);if(n.type===`string`){if(`enum`in n||`oneOf`in n){let e=UUe(n),t=new Set(e.map(e=>e.value)),a=r?void 0:m5(e);return{request:{title:i,description:o(void 0),options:e,maxSelect:1,maxVisible:8,...n.default!==void 0&&t.has(n.default)?{default:{values:[n.default]}}:{}},parse:e=>{let n=e.values[0];return n!==void 0&&t.has(n)?{kind:`value`,value:n}:a!==void 0&&n===a?{kind:`skip`}:{kind:`invalid`,reason:`not one of the offered choices`}}}}let e=[KUe(n.minLength,n.maxLength),qUe(n.format),n.default===void 0?void 0:`Default: ${p5(n.default,60)}.`,r?void 0:`Leave empty to skip.`].filter(Boolean);return{request:{title:i,description:o(e.length===0?void 0:e.join(` `)),allowFreeText:!0,allowEmpty:!r,...n.default===void 0?{}:{placeholder:p5(n.default,60),default:{text:n.default}}},parse:e=>{let t=e.text??``;if(t.length===0)return r?{kind:`invalid`,reason:`an answer is required`}:{kind:`skip`};let i=[...t].length;if(n.minLength!==void 0&&i<n.minLength)return{kind:`invalid`,reason:`at least ${n.minLength} characters`};if(n.maxLength!==void 0&&i>n.maxLength)return{kind:`invalid`,reason:`at most ${n.maxLength} characters`};let a=JUe(n.format,t);return a===void 0?{kind:`value`,value:t}:{kind:`invalid`,reason:a}}}}let s=n.type===`integer`,c=GUe(n.minimum,n.maximum);return{request:{title:i,description:o([`${s?`A whole number`:`A number`}${c}.`,n.default===void 0?void 0:`Default: ${n.default}.`,r?void 0:`Leave empty to skip.`].filter(Boolean).join(` `)),allowFreeText:!0,allowEmpty:!r,...n.default===void 0?{}:{placeholder:String(n.default),default:{text:String(n.default)}}},parse:e=>{let t=(e.text??``).trim();if(t.length===0)return r?{kind:`invalid`,reason:`an answer is required`}:{kind:`skip`};if(!FUe.test(t))return{kind:`invalid`,reason:`not a number`};let i=Number(t);return Number.isFinite(i)?s&&!Number.isInteger(i)?{kind:`invalid`,reason:`not a whole number`}:n.minimum!==void 0&&i<n.minimum?{kind:`invalid`,reason:`at least ${n.minimum}`}:n.maximum!==void 0&&i>n.maximum?{kind:`invalid`,reason:`at most ${n.maximum}`}:{kind:`value`,value:i}:{kind:`invalid`,reason:`not a number`}}}}function HUe(e,t,n,r){let i=WUe(n),a=new Map(i.map((e,t)=>[e.value,t])),o=Math.max(1,Math.min(n.maxItems??i.length,i.length)),s=Math.min(n.minItems??+!!r,o),c=(n.default??[]).filter(e=>a.has(e)).slice(0,o),l=e=>[...e].sort((e,t)=>(a.get(e)??0)-(a.get(t)??0));if(o===1){let n=!r||s===0?m5(i):void 0;return{request:{title:e,description:t,options:i,maxSelect:1,maxVisible:8,...c.length===0?{}:{default:{values:c}}},parse:e=>{let t=e.values[0];return t!==void 0&&a.has(t)?{kind:`value`,value:[t]}:n!==void 0&&t===n?r?{kind:`value`,value:[]}:{kind:`skip`}:{kind:`invalid`,reason:`not one of the offered choices`}}}}return{request:{title:e,description:t,options:i,minSelect:r?s:0,maxSelect:o,...c.length===0?{}:{default:{values:c}}},parse:e=>{let t=e.values.filter(e=>a.has(e));return t.length===e.values.length?t.length===0&&!r?{kind:`skip`}:t.length===0&&s===0?{kind:`value`,value:[]}:t.length<s?{kind:`invalid`,reason:r?`choose at least ${s}`:`choose none or at least ${s}`}:t.length>o?{kind:`invalid`,reason:`choose at most ${o}`}:{kind:`value`,value:l(t)}:{kind:`invalid`,reason:`not one of the offered choices`}}}}function UUe(e){if(`oneOf`in e)return e.oneOf.map(e=>({value:e.const,label:p5(e.title,60)}));if(`enum`in e){let t=`enumNames`in e?e.enumNames:void 0;return e.enum.map((e,n)=>({value:e,label:p5(t?.[n]??e,60)}))}return[]}function WUe(e){let t=e.items;return`anyOf`in t?t.anyOf.map(e=>({value:e.const,label:p5(e.title,60)})):t.enum.map(e=>({value:e,label:p5(e,60)}))}function m5(e){let t=``;for(;e.some(e=>e.value===t);)t+=`\0`;return e.push({value:t,label:`Leave unanswered`}),t}function GUe(e,t){return e!==void 0&&t!==void 0?` from ${e} to ${t}`:e===void 0?t===void 0?``:` of at most ${t}`:` of at least ${e}`}function KUe(e,t){if(e!==void 0&&t!==void 0)return`Between ${e} and ${t} characters.`;if(e!==void 0)return`At least ${e} characters.`;if(t!==void 0)return`At most ${t} characters.`}function qUe(e){switch(e){case`email`:return`An email address.`;case`uri`:return`A URI.`;case`date`:return`A date (YYYY-MM-DD).`;case`date-time`:return`A date and time (RFC 3339, such as 2026-01-31T09:00:00Z).`;default:return}}function JUe(e,t){switch(e){case`email`:return/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(t)?void 0:`not an email address`;case`uri`:return URL.canParse(t)?void 0:`not a URI`;case`date`:{if(!IUe.test(t))return`not a date (YYYY-MM-DD)`;let e=new Date(`${t}T00:00:00Z`);return!Number.isNaN(e.getTime())&&e.toISOString().startsWith(t)?void 0:`not a calendar date`}case`date-time`:return LUe.test(t)&&!Number.isNaN(Date.parse(t))?void 0:`not a date and time (RFC 3339)`;default:return}}async function YUe(e,t){let n=e.transport!==void 0;await e.close(),n||await t.close()}function XUe(e){if(!(e instanceof ti)||e.code!==ni.EraNegotiationFailed)return e;let t=e.data?.cause;return t instanceof Error?t:e}function ZUe(e){return e instanceof ri||e instanceof ti&&!(e instanceof ete)&&e.code===ni.EraNegotiationFailed&&e.data===void 0}const QUe=/^application\/json\b/i;function $Ue(e,t){let n=dHe(t);return!(e instanceof ri)&&n!==void 0&&!(n.contentType!==void 0&&QUe.test(n.contentType))?new $8(`initialize-failed`,`Stateless MCP discovery was answered with HTTP ${n.status}`,{status:n.status}):new $8(`unsupported-protocol-version`,`Server does not support the explicitly selected stateless MCP version`)}function eWe(e){if(!(e instanceof ti))return;let t=e.data;switch(e.code){case ni.UnsupportedResultType:return new G8(t?.resultType===`input_required`?`input_required`:`unknown-result`);case ni.CapabilityNotSupported:return typeof t?.method==`string`?new G8(`input_required`):void 0;case ni.InputRequiredRoundsExceeded:return new G8(`input_required`);default:return}}function tWe(e){return e instanceof ti&&e.code===ni.InvalidResult}async function nWe(e){let t=e.transport;e.skills===!0&&iHe(t);let n=`sensitiveDiagnostics`in t&&t.sensitiveDiagnostics===!0,r=new l5,i=n5(e.clientInfo??e5,t5,e.elicitation===!0?u5({serverId:()=>e.serverId,calls:r}):void 0,e.apps===!0),a,o=()=>a??=YUe(i,t),s,c;try{e.signal?.throwIfAborted();let n=`stdioStartupMs`in t&&typeof t.stdioStartupMs==`number`?Math.min(e.timeouts.startupMs,t.stdioStartupMs):e.timeouts.startupMs,r=new Promise((t,r)=>{s=setTimeout(()=>r(new $8(`startup-timeout`,`Stateless MCP startup timed out`)),n),c=()=>r(new $8(`initialize-failed`,`Stateless MCP startup cancelled`)),e.signal?.addEventListener(`abort`,c,{once:!0})});if(await Promise.race([i.connect(t,{timeout:n,signal:e.signal}),r]),i.getNegotiatedProtocolVersion()!==`2026-07-28`)throw new $8(`unsupported-protocol-version`,`Server does not support the explicitly selected stateless MCP version`)}catch(r){await o();let i=XUe(r),a=ZUe(i)?$Ue(i,t):i,s=r5(a)&&e.signal?.aborted!==!0||a instanceof $8&&a.kind===`startup-timeout`;throw n?a instanceof N8&&a.reason===`authority`||a instanceof $8&&a.kind===`unsupported-protocol-version`?a:new $8(s?`startup-timeout`:`initialize-failed`,`Stdio stateless MCP startup failed`):s&&!(a instanceof $8)?new $8(`startup-timeout`,`Stateless MCP startup timed out`):a}finally{s!==void 0&&clearTimeout(s),c&&e.signal?.removeEventListener(`abort`,c)}try{let s=i.getDiscoverResult();if(s===void 0)throw Error(`Stateless MCP discovery was not retained`);let c=i.getServerVersion();if(s._meta?.[$ee]!==void 0&&c===void 0)throw Error(`Stateless MCP discovery has no valid server metadata`);let l=i.getServerCapabilities()??{},u=o5(l),d={serverId:e.serverId,serverName:c===void 0?e.serverId:c.name,serverVersion:c===void 0?``:c.version,protocolVersion:t5,catalogGeneration:N(),...c===void 0?{serverInfoProvided:!1}:{}},f=i.getInstructions(),p=L6(t),m=async(e,t,r)=>{try{if(a)throw Error(`Stateless MCP carrier is closed`);return await e()}catch(e){let i=eWe(e);if(i!==void 0)throw await o(),i;if(r!==void 0&&tWe(e)){let e=r();throw e instanceof G8&&await o(),e}throw(t?.aborted||r5(e))&&(await o(),n)?new N8(`cancelled`):n?new N8(`send`):e}},h=e.skills&&u.resources&&vUe(l.extensions)?_Ue(d,(t,n,r)=>{let a={signal:r?.signal,timeout:r?.timeoutMs??e.timeouts.perCallMs};return m(async()=>({...t===`resources/read`?await i.readResource({uri:String(n.uri)},{...a,cacheMode:`bypass`}):await i.request({method:t,params:n},gUe,a),resultType:`complete`}),r?.signal,()=>new B8(t===`resources/read`?`invalid-resource`:`invalid-manifest`))}):void 0,g=e.apps===!0&&z8(l.extensions)&&u.resources!==void 0,_=[...h===void 0?[]:[`Skills metadata and verified file reads`],...e.apps===!0?[`the UI extension for tool views`]:[]];return{...h===void 0?{}:{skills:h},...g?{apps:g}:{},identity:d,instructions:f,declaredCapabilities:u,discoveryCacheHint:K8(s),compatibilityDiagnostics:[...e.skills&&h===void 0?[{capability:`skills`,reason:`Skills requires a valid advertised extension and Resources capability.`}]:[],...e.elicitation===!0?[]:[{capability:`input_required`,reason:`No MRTR client input capability is offered; unsupported results close the carrier without replay.`}],{capability:`subscriptions`,reason:`This surface does not open subscription streams; listChanged watches require explicit host refresh.`},{capability:`extensions`,reason:_.length===0?`No optional extension is offered or activated by this surface.`:`Only host-selected ${_.join(` and `)} are available; activation stays host-owned.`}],discover:async e=>{try{return await c5({request:(e,t)=>m(()=>i.request(e,t),t.signal)},u,d,f,e,g)}catch(e){throw n?new N8(`send`):e}},async callTool(t,a,s){if(!u.tools)throw Error(`Stateless MCP server did not declare tools`);let c=async()=>i5(await m(()=>i.request({method:`tools/call`,params:{name:t,arguments:a}},{signal:s?.signal,timeout:s?.timeoutMs??e.timeouts.perCallMs}),s?.signal,()=>new G8(`invalid-tool-result`))),l=p?{requestAbortController:new AbortController,...s?.outboundTraceContext?{outbound:s.outboundTraceContext}:{}}:void 0,d=r.enter({ask:s?.ask,signal:s?.signal});try{return l?await F6(l,c):await c()}catch(e){throw e instanceof G8?(await o(),e):n&&!(e instanceof N8)?new N8(`send`):e}finally{d(),l&&p?.release(l)}},async readResource(t,n){if(!u.resources)throw Error(`Stateless MCP server did not declare resources`);return a5(await m(()=>i.readResource({uri:t},{signal:n?.signal,timeout:n?.timeoutMs??e.timeouts.perCallMs,cacheMode:`bypass`}),n?.signal))},onListChanged:()=>()=>void 0,close:o}}catch(e){throw await o(),n?new $8(`initialize-failed`,`Invalid stdio stateless MCP discovery metadata`):e}}const rWe=new Set([`2024-11-05`,`2025-03-26`,`2025-06-18`,`2025-11-25`]);function h5(e){return e instanceof Error?e.message:String(e)}function g5(e){return`sensitiveDiagnostics`in e&&e.sensitiveDiagnostics===!0}function iWe(e){let t=e.transport;return`stdioStartupMs`in t&&typeof t.stdioStartupMs==`number`?Math.min(e.timeouts.startupMs,t.stdioStartupMs):e.timeouts.startupMs}function _5(e,t){return r5(e)&&t?.aborted!==!0||e instanceof $8&&e.kind===`startup-timeout`}async function aWe(e,t){let n,r;try{if(g5(t.transport)&&t.signal?.aborted)throw new $8(`initialize-failed`,`Stdio session startup cancelled`);let i=iWe(t),a=e.connect(t.transport,{timeout:i,signal:t.signal});if(g5(t.transport)){let e=new Promise((e,a)=>{n=setTimeout(()=>a(new $8(`startup-timeout`,`Stdio session startup timed out`)),i),r=()=>a(new $8(`initialize-failed`,`Stdio session startup cancelled`)),t.signal?.aborted?r():t.signal?.addEventListener(`abort`,r,{once:!0})});await Promise.race([a,e])}else await a}catch(n){if(g5(t.transport)){try{await t.transport.close()}catch{throw new N8(`cleanup`)}if(n instanceof N8&&n.reason===`authority`)throw n;let e=_5(n,t.signal);throw new $8(e?`startup-timeout`:`initialize-failed`,e?`Stdio session startup timed out`:`Stdio session startup failed`)}throw await e.close(),n instanceof R3||n instanceof k6?n:_5(n,t.signal)?new $8(`startup-timeout`,`MCP session startup exceeded ${t.timeouts.startupMs}ms`,{cause:h5(n)}):new $8(`initialize-failed`,h5(n),{cause:h5(n)})}finally{n!==void 0&&clearTimeout(n),r!==void 0&&t.signal?.removeEventListener(`abort`,r)}}async function oWe(e,t){let n=e.getNegotiatedProtocolVersion();if(n===void 0||!rWe.has(n))throw await e.close(),new $8(`unsupported-protocol-version`,g5(t)?`Stdio server negotiated an unsupported MCP protocol version`:`Server negotiated unsupported MCP protocol version "${n??`unknown`}"`,g5(t)?void 0:{protocolVersion:n});return n}async function sWe(e){let t=e.getServerVersion();if(t===void 0)throw await e.close(),new $8(`initialize-failed`,`Server did not report serverInfo after initialize`);return t}function cWe(e,t){e.setNotificationHandler(`notifications/tools/list_changed`,()=>{t.forEach(e=>e(`tools`))}),e.setNotificationHandler(`notifications/prompts/list_changed`,()=>{t.forEach(e=>e(`prompts`))}),e.setNotificationHandler(`notifications/resources/list_changed`,()=>{t.forEach(e=>e(`resources`))})}async function lWe(e){if(e.skills&&e.protocolVersion!==`2026-07-28`)throw new $8(`unsupported-protocol-version`,`Skills require explicit stateless protocol selection`);if(e.protocolVersion===`2026-07-28`)return nWe(e);if(e.protocolVersion!==void 0)throw new $8(`unsupported-protocol-version`,`Unsupported explicitly selected MCP protocol version`);let t=new l5,n=n5(e.clientInfo??e5,void 0,e.elicitation===!0?u5({serverId:()=>e.serverId,calls:t}):void 0,e.apps===!0);await aWe(n,e);let r=await oWe(n,e.transport),i=await sWe(n),a={serverId:e.serverId,serverName:i.name,serverVersion:i.version,protocolVersion:r},o=n.getInstructions(),s=n.getServerCapabilities(),c=o5(s),l=e.apps===!0&&z8(s?.extensions)&&c.resources!==void 0,u=L6(e.transport),d=new Set;cWe(n,d);let f=new Map,p,m=()=>(p??=n.close(),p),h=async()=>{if(!(!(`closedDirectChild`in e.transport)||e.transport.closedDirectChild!==!0)){try{await m()}catch{throw new N8(`cleanup`)}throw new N8(`early-exit`)}},g=async(e,t)=>{throw t?.aborted||r5(e)?(await m(),new N8(`cancelled`)):(await h(),new N8(`send`))};return{...l?{apps:l}:{},identity:a,instructions:o,declaredCapabilities:c,async discover(t){try{let e=await c5(n,c,a,o,t,l);return f=new Map(e.tools.items.flatMap(e=>e.outputSchema===void 0?[]:[[e.name,e.outputSchema]])),e}catch(n){throw g5(e.transport)?t.signal?.aborted||n instanceof J8&&n.failure.kind===`timeout`?(await m(),new N8(`cancelled`)):(await h(),new N8(`send`)):n}},async callTool(r,i,a){let o=f.get(r),s=()=>n.callTool({name:r,arguments:i},{timeout:a?.timeoutMs,signal:a?.signal,...o===void 0?{}:{toolDefinition:{name:r,inputSchema:{type:`object`},outputSchema:o}}}),c=a?.outboundTraceContext,l=u===void 0?void 0:{requestAbortController:new AbortController,...c?{outbound:c}:{}},d=t.enter({ask:a?.ask,signal:a?.signal});try{return i5(l?await F6(l,s):await s())}catch(t){if(g5(e.transport))return g(t,a?.signal);throw t}finally{d(),l&&u?.release(l)}},async readResource(t,r){if(c.resources===void 0)throw Error(`MCP server did not declare resources`);try{return a5(await n.readResource({uri:t},{timeout:r?.timeoutMs,signal:r?.signal}))}catch(t){if(g5(e.transport))return g(t,r?.signal);throw t}},onListChanged(e){return d.add(e),()=>{d.delete(e)}},async close(){await m()}}}const uWe=/[^A-Za-z0-9_-]/g;function v5(e){return e.replace(uWe,`_`)}function dWe(e){return Vn(`sha1`).update(e).digest(`hex`).slice(0,8)}function fWe(e,t,n=``){let r=dWe(e),i=r.length+2;if(t<=i)return r.slice(0,Math.max(t,0));let a=t-i,o=Math.min(a,Math.max(Math.ceil(a/2),n.length)),s=a-o;return`${e.slice(0,o)}~${r}~${s>0?e.slice(e.length-s):``}`}function y5(e,t,n=64){let r=`${e}__${t}`,i=`${v5(e)}__${v5(t)}`,a=i!==r;return i.length<=n?a?{name:i,changed:!0,reason:`renamed`}:{name:i,changed:!1}:{name:fWe(i,n,`${v5(e)}__`),changed:!0,reason:a?`renamed, truncated`:`truncated`}}function pWe(e){let t=[...e].sort((e,t)=>e.key<t.key?-1:+(e.key>t.key)),n=new Map,r=new Map,i=[];for(let e of t){let t=r.get(e.name);if(t===void 0){r.set(e.name,e.key),n.set(e.key,e.name);continue}i.push({key:e.key,name:e.name,reason:`collides with ${t} after sanitisation/truncation`})}return{winners:n,losers:i}}const mWe=Qe(`ThirdPartySchema`),hWe=new Set([`object`,`array`,`string`,`number`,`integer`,`boolean`,`null`]);function b5(){return{anyOf:[{type:`string`},{type:`number`},{type:`boolean`},{type:`object`},{type:`array`},{type:`null`}]}}function x5(e){return Array.isArray(e.anyOf)?!0:typeof e.type==`string`&&hWe.has(e.type)}function S5(e,t,n){let r=e;if(Object.prototype.hasOwnProperty.call(r,`$schema`)){let{$schema:e,...i}=r;n.push(`${t}.$schema`),r=i}if(Array.isArray(r.anyOf)&&(r={...r,anyOf:r.anyOf.map((e,r)=>S5(e,`${t}.anyOf[${r}]`,n))}),typeof r.additionalProperties==`object`&&r.additionalProperties!==null){let e=`${t}.additionalProperties`;x5(r.additionalProperties)?r={...r,additionalProperties:S5(r.additionalProperties,e,n)}:(n.push(e),r={...r,additionalProperties:b5()})}if(r.type===`object`){let e=r.properties;if(!e)return r;let i={};for(let[r,a]of Object.entries(e)){let e=`${t}.${r}`;if(!x5(a)){n.push(e),i[r]=b5();continue}i[r]=S5(a,e,n)}return{...r,properties:i}}if(r.type===`array`&&r.items){let e=`${t}[]`;if(!x5(r.items)){n.push(e);let{items:t,...i}=r;return i}return{...r,items:S5(r.items,e,n)}}return r}function C5(e){let t=[];return x5(e)?{schema:S5(e,``,t),unenforceable:t}:{schema:{type:`object`},unenforceable:[``]}}var gWe=class{toolName;parameters;report;narrowed;reported=!1;constructor(e,t,n){this.toolName=e,this.parameters=t,this.report=n}validate(e){this.narrowed??=C5(this.parameters),!this.reported&&this.narrowed.unenforceable.length>0&&(this.reported=!0,(this.report??((e,t)=>{mWe.warn(`MCP tool schema is only partly enforceable`,{tool:e,paths:t})}))(this.toolName,this.narrowed.unenforceable));let t=pe(this.narrowed.schema,e,``);return{isValid:t.length===0,errors:t}}};function _We(e){return e===`streamable-http`||e===`stdio`}function w5(e,t){let n=[];return e&&n.push(e),t&&n.push(`narrowed`),n.length>0?n.join(`, `):void 0}function vWe(){let e={kind:`unsupported`};return{tools:e,prompts:e,resources:e}}function yWe(e){return e?{tools:e.tools.state,prompts:e.prompts.state,resources:e.resources.state}:vWe()}function bWe(e){return{kind:`server`,serverId:e.serverId,name:e.serverId,reason:`transport ${e.transport} is not supported: MCP standard transports are stdio and Streamable HTTP`}}function xWe(e,t,n){return{serverId:e.serverId,origin:e.origin,transport:t,identity:n?.identity,instructions:n?.instructions,capabilities:yWe(n)}}function SWe(e,t){return{serverId:e.serverId,serverName:t.identity.serverName,serverVersion:t.identity.serverVersion,protocolVersion:t.identity.protocolVersion,origin:e.origin}}function CWe(e,t,n,r){let i=[];if(t.tools.state.kind===`supported`)for(let a of t.tools.items){if(a.ui!==void 0&&!a.ui.visibility.includes(`model`)){r.push({kind:`tool`,serverId:e,name:y5(e,a.name).name,reason:`app-only tool; this host offers tools to the model only`});continue}i.push({kind:`tool`,key:`${e}::tool::${a.name}`,serverId:e,sourceName:a.name,description:a.description,namingResult:y5(e,a.name),provenance:n,inputSchema:a.inputSchema,resultSizeMetadata:a.resultSizeMetadata,ui:a.ui,uiProblem:a.uiProblem})}return i}function wWe(e,t,n){let r=[];if(t.prompts.state.kind===`supported`)for(let i of t.prompts.items)r.push({kind:`prompt`,key:`${e}::prompt::${i.name}`,serverId:e,sourceName:i.name,description:i.description,namingResult:y5(e,i.name),provenance:n,promptArguments:i.arguments??[]});return r}function TWe(e,t,n){let r=[];if(t.resources.state.kind===`supported`)for(let i of t.resources.items)r.push({kind:`resource`,key:`${e}::resource::${i.name}`,serverId:e,sourceName:i.name,description:i.description,namingResult:y5(e,i.name),provenance:n,uri:i.uri,mimeType:i.mimeType});return r}function EWe(e,t,n){for(let r of t){let t=e.get(r.key);t&&n.push({kind:t.kind,serverId:t.serverId,name:r.name,reason:r.reason})}}function DWe(e,t,n){let r=C5(e.inputSchema);r.unenforceable.length>0&&n?.report?.(t,r.unenforceable);let i=w5(e.namingResult.reason,r.unenforceable.length>0);return e.resultSizeMetadata?.kind===`invalid`&&n?.reportResultSizeProblem?.(e.resultSizeMetadata.reason),e.uiProblem!==void 0&&n?.reportUiMetadataProblem?.(t,e.uiProblem),{kind:`tool`,canonicalName:t,sourceName:e.sourceName,description:e.description,schema:r.schema,...e.resultSizeMetadata?.kind===`accepted`?{maxResultChars:e.resultSizeMetadata.maxResultChars}:{},...e.ui===void 0?{}:{ui:e.ui},unenforceablePaths:r.unenforceable,provenance:e.provenance,disposition:i?`adapted`:`adopted`,reason:i}}function OWe(e,t){let n=w5(e.namingResult.reason,!1);return{kind:`prompt`,canonicalName:t,sourceName:e.sourceName,description:e.description,arguments:e.promptArguments,provenance:e.provenance,disposition:n?`adapted`:`adopted`,reason:n}}function kWe(e,t){let n=w5(e.namingResult.reason,!1);return{kind:`resource`,canonicalName:t,uri:e.uri,sourceName:e.sourceName,description:e.description,mimeType:e.mimeType,provenance:e.provenance,disposition:n?`adapted`:`adopted`,reason:n}}function AWe(e,t,n){return e.kind===`tool`?DWe(e,t,n):e.kind===`prompt`?OWe(e,t):kWe(e,t)}function jWe(e,t){let n=[],r=[],i=[];for(let t of e){if(!_We(t.transport)){r.push(bWe(t));continue}let{discovery:e}=t;if(n.push(xWe(t,t.transport,e)),!e)continue;let a=SWe(t,e);i.push(...CWe(t.serverId,e,a,r)),i.push(...wWe(t.serverId,e,a)),i.push(...TWe(t.serverId,e,a))}let{winners:a,losers:o}=pWe(i.map(e=>({key:e.key,name:e.namingResult.name})));EWe(new Map(i.map(e=>[e.key,e])),o,r);let s=[],c=[];for(let e of i){let n=a.get(e.key);if(n===void 0)continue;let r=AWe(e,n,t);(r.disposition===`adapted`?c:s).push(r)}return{servers:n,adopted:s,adapted:c,rejected:r}}const MWe={initialMs:500,maxMs:3e4,factor:2,maxAttempts:5},NWe={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function T5(){return{tools:!1,prompts:!1,resources:!1}}function E5(e,t){if(typeof e==`object`&&e&&t in e)return e[t]}function D5(e){return e instanceof Error?e.message:typeof e==`string`?e:String(e)}function PWe(e){if(e instanceof $8){let t=e.details?.status;return typeof t==`number`?t:void 0}let t=E5(e,`status`);if(typeof t==`number`)return t;let n=E5(e,`statusCode`);if(typeof n==`number`)return n;let r=E5(e,`code`);if(typeof r==`number`&&r>=100&&r<600)return r}function FWe(e){let t=E5(e,`code`);return typeof t==`string`?t:void 0}function IWe(e){let t=E5(e,`code`);if(typeof t==`number`&&t<0)return t;let n=E5(E5(e,`data`),`code`);return typeof n==`number`?n:void 0}function LWe(e,t){return e===401||e===403||t.includes(`401`)||t.includes(`403`)||t.includes(`unauthorized`)}function RWe(e,t,n){return e===404||t===-32601||n.includes(`not found`)}function zWe(e,t,n){return t===-32602||n.includes(`invalid url`)||n.includes(`unsupported protocol`)||n.includes(`invalid params`)}function BWe(e,t,n){return typeof e==`number`&&e>=500&&e<600||t===`ECONNREFUSED`||t===`ECONNRESET`||t===`ETIMEDOUT`||n.includes(`econnrefused`)||n.includes(`econnreset`)||n.includes(`etimedout`)||n.includes(`timed out`)||n.includes(`timeout`)||n.includes(`fetch failed`)||n.includes(`failed to fetch`)||n.includes(`network`)}function O5(e){if(e instanceof k5)return e.classification;if(e instanceof G8)return`config`;if(e instanceof k6)return e.reason===`unresolvable`?`transient`:`config`;if(e instanceof G6||e instanceof H6||e instanceof N8&&(e.reason===`authority`||e.reason===`cleanup`||e.reason===`receive-limit`||e.reason===`receive-invalid`))return`config`;if(e instanceof nte||e instanceof R3)return`auth`;if(e instanceof $8&&e.kind===`unsupported-protocol-version`)return`config`;let t=D5(e).toLowerCase(),n=PWe(e),r=FWe(e),i=IWe(e);return LWe(n,t)?`auth`:RWe(n,i,t)?`not-found`:zWe(e,i,t)?`config`:(BWe(n,r,t),`transient`)}var k5=class extends Error{classification;constructor(e,t,n){super(t,n),this.classification=e,this.name=`MCPSupervisorError`}},VWe=class{options;state={kind:`idle`};backoff;clock;liveSession;lastKnownGood;lastBackgroundRefreshFailure;lastBackgroundCloseFailure;pendingAttempt;resolvePendingRetry;activeAbortController;retryTimerHandle;idleTimerHandle;unsubscribeListChanged;shutdownPromise;constructor(e){this.options=e,this.backoff={...MWe,...e.backoff},this.clock=e.clock??NWe}getState(){return this.state}async ensureConnected(e){let t=this.state;if(t.kind===`connected`)return this.noteActivity(),this.liveSession;if(t.kind===`closed`)throw Error(`MCPConnectionSupervisor is shut down; it cannot reconnect (create a new instance)`);if(t.kind===`connecting`)return this.expectPendingAttempt();if(t.kind===`failed`){if(t.retry===`pending`)return this.expectPendingAttempt();throw new k5(t.classification,`connection failed (${t.classification}): ${t.message}; call retry() explicitly`)}return this.beginConnect(1,e)}async discover(e){return this.withDefaultBudget(e,async e=>{let t=await this.ensureConnected(e);this.noteActivity();let n;try{n=await t.discover({maxPages:this.options.discovery?.maxPages??50,perRequestTimeoutMs:this.options.timeouts.perCallMs,signal:e})}catch(e){throw this.retireSelfClosedStdioSession(t,e),e}return this.lastKnownGood={identity:Y8(t.identity),discovery:n,retainedAt:this.clock.now(),stale:T5()},n})}async refresh(e,t){return this.withDefaultBudget(t,async t=>{let n=await this.ensureConnected(t);this.noteActivity();try{let r=await n.discover({maxPages:this.options.discovery?.maxPages??50,perRequestTimeoutMs:this.options.timeouts.perCallMs,signal:t});return this.recordRefreshSuccess(e,n.identity,r)}catch(t){this.retireSelfClosedStdioSession(n,t);let r=O5(t),i=D5(t);throw this.recordRefreshFailure(e,r,i),new k5(r,i,{cause:t})}})}async callTool(e,t,n){return this.withDefaultBudget(n?.signal,async r=>{let i=await this.ensureConnected(r);this.noteActivity();try{return await i.callTool(e,t,{signal:r,timeoutMs:this.options.timeouts.toolCallMs,...n?.outboundTraceContext?{outboundTraceContext:n.outboundTraceContext}:{},...n?.ask?{ask:n.ask}:{}})}catch(e){throw this.retireSelfClosedStdioSession(i,e),new k5(O5(e),D5(e),{cause:e})}})}async readResource(e,t){return this.withDefaultBudget(t?.signal,async t=>{let n=await this.ensureConnected(t);this.noteActivity();try{return await n.readResource(e,{signal:t,timeoutMs:this.options.timeouts.perCallMs})}catch(e){throw this.retireSelfClosedStdioSession(n,e),new k5(O5(e),D5(e),{cause:e})}})}getLastKnownGood(){return this.lastKnownGood}async getSkillsSession(e){let t=await this.ensureConnected(e),n=t.skills;if(!n)return;let r=(e,n)=>this.withDefaultBudget(e?.signal,async r=>{if(await this.ensureConnected(r)!==t)throw new B8(`changed-manifest`);this.noteActivity();try{return await n({...e,signal:r,timeoutMs:e?.timeoutMs??this.options.timeouts.perCallMs})}catch(e){throw this.retireSelfClosedStdioSession(t,e),e}});return{list:e=>r(e,t=>n.list({...t,maxPages:e.maxPages})),get:(e,t)=>r(t,t=>n.get(e,t)),read:(e,t,i)=>r(i,r=>n.read(e,t,r))}}get lastRefreshFailure(){return this.lastBackgroundRefreshFailure}get lastCloseFailure(){return this.lastBackgroundCloseFailure}async retry(e){let t=this.state;if(t.kind===`connected`)return this.noteActivity(),this.liveSession;if(t.kind===`closed`)throw Error(`MCPConnectionSupervisor is shut down; it cannot reconnect (create a new instance)`);return t.kind===`connecting`||t.kind===`failed`&&t.retry===`pending`?this.expectPendingAttempt():this.beginConnect(1,e)}shutdown(){return this.shutdownPromise===void 0&&(this.shutdownPromise=this.shutdownOwned()),this.shutdownPromise}async shutdownOwned(){if(this.state.kind===`closed`)return;this.clearRetryTimer(),this.clearIdleTimer(),this.activeAbortController?.abort(),this.activeAbortController=void 0;let e=this.pendingAttempt;this.pendingAttempt=void 0,this.unsubscribeListChanged&&=(this.unsubscribeListChanged(),void 0);let t=this.liveSession;if(this.liveSession=void 0,this.setState({kind:`closed`}),t&&await t.close(),this.options.awaitOpenCleanupOnTimeout&&e){let t=await e;if(!t.ok&&t.error.cause instanceof N8&&t.error.cause.reason===`cleanup`)throw t.error}}setState(e){this.state=e,this.options.onStateChange?.(e)}expectPendingAttempt(){let e=this.pendingAttempt;if(!e)throw Error(`MCPConnectionSupervisor invariant violated: no attempt is pending for this state`);return this.settle(e)}noteActivity(){this.state.kind===`connected`&&this.armIdleTimer()}withDefaultBudget(e,t){if(e)return t(e);let n=new AbortController;return this.withTimeout(t(n.signal),this.options.timeouts.globalDefaultMs,()=>n.abort(),this.options.awaitOpenCleanupOnTimeout)}withTimeout(e,t,n,r=!1,i){return new Promise((a,o)=>{let s=!1,c=!1,l=this.clock.setTimeout(()=>{s||(r?c=!0:s=!0,n?.(),r||o(Error(`operation timed out after ${t}ms`)))},t);e.then(e=>{if(!s)if(s=!0,this.clock.clearTimeout(l),c)if(i)try{i(e).then(()=>o(Error(`operation timed out after ${t}ms`)),o)}catch(e){o(e)}else o(Error(`operation timed out after ${t}ms`));else a(e)},e=>{s||(s=!0,this.clock.clearTimeout(l),o(e))})})}async settle(e){let t=await e;if(!t.ok)throw t.error;return t.session}beginConnect(e,t){return this.settle(this.startAttempt(e,t))}startAttempt(e,t){this.setState({kind:`connecting`,attempt:e});let n=new AbortController;this.activeAbortController=n,t&&(t.aborted?n.abort():t.addEventListener(`abort`,()=>n.abort(),{once:!0}));let r=this.runOpenAttempt(e,n);return this.pendingAttempt=r,r}async runOpenAttempt(e,t){try{let e=await this.withTimeout(this.options.openSession(t.signal),this.options.timeouts.startupMs,()=>t.abort(),this.options.awaitOpenCleanupOnTimeout,e=>e.close());if(this.clearActiveController(t),this.state.kind===`closed`||t.signal.aborted){try{await e.close()}catch(e){if(this.options.awaitOpenCleanupOnTimeout){let t=e instanceof N8&&e.reason===`cleanup`?e:new N8(`cleanup`);return{ok:!1,error:new k5(`config`,t.message,{cause:t})}}this.recordBackgroundCloseFailure(e)}return{ok:!1,error:new k5(`config`,`supervisor was shut down while the open attempt was settling`)}}return this.onConnected(e),{ok:!0,session:e}}catch(n){this.clearActiveController(t);let r=O5(n),i=D5(n);return this.recordOpenFailure(e,r,i),{ok:!1,error:new k5(r,i,{cause:n})}}}clearActiveController(e){this.activeAbortController===e&&(this.activeAbortController=void 0)}retireSelfClosedStdioSession(e,t){!(t instanceof N8)||t.reason!==`cancelled`&&t.reason!==`cleanup`&&t.reason!==`early-exit`&&t.reason!==`receive-limit`&&t.reason!==`receive-invalid`||this.liveSession!==e||this.state.kind===`closed`||(this.clearIdleTimer(),this.unsubscribeListChanged?.(),this.unsubscribeListChanged=void 0,this.liveSession=void 0,t.reason===`cleanup`?this.setState({kind:`failed`,classification:`config`,message:t.message,attempt:1,retry:`manual-retry`}):this.setState({kind:`idle`}))}recordOpenFailure(e,t,n){if(this.state.kind!==`closed`)if(t===`transient`&&e<this.backoff.maxAttempts){let r=Math.min(this.backoff.maxMs,this.backoff.initialMs*this.backoff.factor**(e-1));this.setState({kind:`failed`,classification:t,message:n,attempt:e,retry:`pending`}),this.armRetryTimer(e,r)}else this.setState({kind:`failed`,classification:t,message:n,attempt:e,retry:`manual-retry`})}onConnected(e){let t=Y8(e.identity);this.lastKnownGood&&!X8(this.lastKnownGood.identity,t)&&(this.lastKnownGood=void 0),this.liveSession=e,this.pendingAttempt=void 0,this.clearRetryTimer(),this.unsubscribeListChanged=e.onListChanged(e=>this.handleListChanged(e)),this.setState({kind:`connected`,identity:e.identity}),this.armIdleTimer()}handleListChanged(e){this.lastKnownGood&&={...this.lastKnownGood,stale:{...this.lastKnownGood.stale,[e]:!0}},this.refreshInBackground(e)}refreshInBackground(e){return this.refresh(e).then(()=>void 0,t=>this.recordBackgroundRefreshFailure(e,t))}recordBackgroundRefreshFailure(e,t){this.lastBackgroundRefreshFailure={domain:e,message:D5(t),at:this.clock.now()}}recordBackgroundCloseFailure(e){this.lastBackgroundCloseFailure={message:D5(e),at:this.clock.now()}}recordRefreshSuccess(e,t,n){let r=Y8(t),i=this.lastKnownGood&&X8(this.lastKnownGood.identity,r)?this.lastKnownGood:void 0,a=HWe(i?.discovery,e,n),o={...i?.stale??T5(),[e]:!1};return this.lastKnownGood={identity:r,discovery:a,retainedAt:this.clock.now(),stale:o},a}recordRefreshFailure(e,t,n){this.lastKnownGood&&={...this.lastKnownGood,stale:{...this.lastKnownGood.stale,[e]:!0},lastError:{classification:t,message:n}}}armRetryTimer(e,t){this.clearRetryTimer(),this.pendingAttempt=new Promise(e=>{this.resolvePendingRetry=e}),this.retryTimerHandle=this.clock.setTimeout(()=>{this.retryTimerHandle=void 0;let t=this.resolvePendingRetry;this.resolvePendingRetry=void 0,this.startAttempt(e+1).then(e=>t?.(e))},t)}clearRetryTimer(){this.retryTimerHandle!==void 0&&(this.clock.clearTimeout(this.retryTimerHandle),this.retryTimerHandle=void 0),this.resolvePendingRetry&&=(this.resolvePendingRetry({ok:!1,error:new k5(`config`,`MCP connection recovery was cancelled`)}),void 0)}armIdleTimer(){this.clearIdleTimer(),this.idleTimerHandle=this.clock.setTimeout(()=>{this.idleTimerHandle=void 0,this.handleIdleTimeout()},this.options.timeouts.idleMs)}clearIdleTimer(){this.idleTimerHandle!==void 0&&(this.clock.clearTimeout(this.idleTimerHandle),this.idleTimerHandle=void 0)}async handleIdleTimeout(){let e=this.liveSession;this.liveSession=void 0,this.unsubscribeListChanged&&=(this.unsubscribeListChanged(),void 0),this.setState({kind:`idle`}),e&&await e.close().then(()=>void 0,e=>this.recordBackgroundCloseFailure(e))}};function HWe(e,t,n){if(!e)return n;switch(t){case`tools`:return{...e,identity:n.identity,instructions:n.instructions,tools:n.tools};case`prompts`:return{...e,identity:n.identity,instructions:n.instructions,prompts:n.prompts};case`resources`:return{...e,identity:n.identity,instructions:n.instructions,resources:n.resources}}}function A5(e,t=!1){if(typeof e!=`string`)return!1;try{let n=atob(e);return t||n.length>0}catch{return!1}}function j5(e){return typeof e==`string`&&/^[A-Za-z][A-Za-z0-9+.-]*:[^\s]*$/u.test(e)}function UWe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Date)}function WWe(e){if(e.type===`audio`)return typeof e.mimeType!=`string`||!/^audio\/[A-Za-z0-9.+-]+$/u.test(e.mimeType)||!A5(e.data)?{diagnostic:`MCP audio omitted: invalid MIME type or base64 data`}:{part:{type:`audio_inline`,mimeType:e.mimeType,data:e.data}};if(e.type===`resource_link`){if(!j5(e.uri)||typeof e.name!=`string`||!e.name.length)return{diagnostic:`MCP resource link omitted: invalid URI or name`};for(let t of[`mimeType`,`title`,`description`])if(e[t]!==void 0&&typeof e[t]!=`string`)return{diagnostic:`MCP resource link omitted: invalid metadata`};return e.size!==void 0&&(typeof e.size!=`number`||!Number.isSafeInteger(e.size)||e.size<0)?{diagnostic:`MCP resource link omitted: invalid size`}:{part:{type:`resource_link`,uri:e.uri,name:e.name,...typeof e.mimeType==`string`?{mimeType:e.mimeType}:{},...typeof e.title==`string`?{title:e.title}:{},...typeof e.description==`string`?{description:e.description}:{},...typeof e.size==`number`?{size:e.size}:{}}}}if(e.type===`resource`){let t=e.resource;if(!UWe(t)||!j5(t.uri)||t.mimeType!==void 0&&typeof t.mimeType!=`string`)return{diagnostic:`MCP embedded resource omitted: invalid URI or metadata`};let n={type:`resource_embedded`,uri:t.uri,...typeof t.mimeType==`string`?{mimeType:t.mimeType}:{}};return typeof t.text==`string`&&t.blob===void 0?{part:{...n,text:t.text}}:t.text===void 0&&A5(t.blob,!0)?{part:{...n,blob:t.blob}}:{diagnostic:`MCP embedded resource omitted: expected text or base64 blob`}}}function GWe(e,t){if(typeof e!=`string`||![`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e))return`MCP image omitted: unsupported MIME type`;if(typeof t!=`string`||!t.length||t.length%4!=0||!/^[A-Za-z0-9+/]+={0,2}$/u.test(t))return`MCP image omitted: invalid base64 data`;let n=atob(t.slice(0,48)),r=atob(t.slice(-48)),i=t.length/4*3-(t.endsWith(`==`)?2:+!!t.endsWith(`=`));return(e===`image/png`?n.startsWith(`‰PNG\r
2851
2851
  
2852
- `)&&n.slice(12,16)===`IHDR`&&i>=45&&r.endsWith("\0\0\0\0IEND®B`‚"):e===`image/jpeg`?n.startsWith(`ÿØÿ`)&&i>=20&&r.endsWith(`ÿÙ`):e===`image/gif`?(n.startsWith(`GIF87a`)||n.startsWith(`GIF89a`))&&i>=14&&r.endsWith(`;`):n.startsWith(`RIFF`)&&n.slice(8,12)===`WEBP`&&i>=20&&n.charCodeAt(4)+n.charCodeAt(5)*256+n.charCodeAt(6)*65536+n.charCodeAt(7)*16777216===i-8)?void 0:`MCP image omitted: invalid image data`}function GWe(e){return e.type===`object`?{...e,type:`object`,properties:e.properties??{}}:{type:`object`,properties:{}}}function M5(e){let t=[];for(let n of e)n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
2853
- `)}var KWe=class{entry;invoker;options;schema;provenance;eventService;validator;constructor(e,t,n){this.entry=e,this.invoker=t,this.options=n,this.provenance=Object.freeze({sourceId:e.provenance.serverId,component:e.sourceName,origin:e.provenance.origin,...e.provenance.serverVersion?{version:e.provenance.serverVersion}:{},protocolVersion:e.provenance.protocolVersion}),this.schema={name:e.canonicalName,description:e.description??``,parameters:GWe(e.schema)},this.validator=new hWe(this.schema.name,this.schema.parameters,n?.report)}getName(){return this.schema.name}getDescription(){return this.schema.description}validate(e){return this.validateParameters(e).isValid}validateParameters(e){return this.validator.validate(e)}async execute(e,t){let n;try{if(this.options?.isDispatchAdmitted&&!await this.options.isDispatchAdmitted())return{success:!1,error:`MCP call refused: admission or installed source changed. Review /mcp status and restart after approving the current source.`};if(t?.signal?.aborted)throw new DOMException(`Execution interrupted by user`,`AbortError`);n=await this.invoker.callTool(this.entry.sourceName,e,{signal:t?.signal,...t?.outboundTraceContext?{outboundTraceContext:t.outboundTraceContext}:{},...t?.ask?{ask:t.ask}:{}})}catch(e){if(t?.signal?.aborted)throw new DOMException(`Execution interrupted by user`,`AbortError`);let n=this.options?.authFailureNotice;if(n!==void 0&&O5(e)===`auth`)return{success:!1,error:n};throw Error(`MCP tool call failed`)}let r=[],i;for(let e of n.content)if(e.type===`text`&&typeof e.text==`string`)r.push({type:`text`,text:e.text});else if(e.type===`image`){let t=WWe(e.mimeType,e.data);t?(i??=t,r.push({type:`text`,text:t})):typeof e.mimeType==`string`&&typeof e.data==`string`&&r.push({type:`image_inline`,mimeType:e.mimeType,data:e.data})}else{let t=UWe(e);t&&`part`in t?r.push(t.part):t&&(i??=t.diagnostic,r.push({type:`text`,text:t.diagnostic}))}if(n.isError||i){let e=M5(n.content);return dt(this.schema.name,{success:!1,...n.structuredContent===void 0?{}:{data:Z8(n.structuredContent)},...r.length?{parts:r}:{},error:[e,i].filter(Boolean).join(`
2854
- `)||`${this.schema.name} reported an error`},this.options?.admission,this.entry.maxResultChars)}let a=n.structuredContent===void 0?M5(n.content):Z8(n.structuredContent),o=await this.readAppView(e,n,t?.signal);return dt(this.schema.name,{success:!0,data:a,...r.length?{parts:r}:{},...o?{view:o}:{}},this.options?.admission,this.entry.maxResultChars)}async readAppView(e,t,n){let r=this.entry.ui?.resourceUri;if(r===void 0||this.invoker.readResource===void 0)return;let i=e=>{this.options?.reportAppViewProblem?.(e)},a;try{if(this.options?.isDispatchAdmitted&&!await this.options.isDispatchAdmitted())return i(`not-admitted`);a=await this.invoker.readResource(r,{signal:n})}catch{return i(`read-failed`)}let o=dUe(r,a);return o.ok?{sourceId:this.entry.provenance.serverId,resourceUri:r,mimeType:o.mimeType,html:o.html,...t.structuredContent===void 0?{}:{structuredContent:Z8(t.structuredContent)},toolInput:e,callableTools:this.options?.appCallableTools??{}}:i(o.reason)}setEventService(e){this.eventService=e}};function qWe(e,t,n){return new KWe(e,t,n)}var N5=class extends Error{constructor(){super(`The value is too long.`),this.name=`HiddenPromptTooLongError`}};const JWe=new Set([``,`\b`]);function P5(e,t={input:process.stdin,output:process.stderr},n={}){let{input:r,output:i}=t,a=n.maxLength??4096,o=r.isTTY===!0&&typeof r.setRawMode==`function`;return i.write(e),new Promise((e,t)=>{let s=``,c=()=>l(Error(`Cancelled.`)),l=a=>{n.signal?.removeEventListener(`abort`,c),r.removeListener(`data`,d),r.removeListener(`end`,u),o&&r.setRawMode?.(!1),r.pause(),o&&i.write(`
2852
+ `)&&n.slice(12,16)===`IHDR`&&i>=45&&r.endsWith("\0\0\0\0IEND®B`‚"):e===`image/jpeg`?n.startsWith(`ÿØÿ`)&&i>=20&&r.endsWith(`ÿÙ`):e===`image/gif`?(n.startsWith(`GIF87a`)||n.startsWith(`GIF89a`))&&i>=14&&r.endsWith(`;`):n.startsWith(`RIFF`)&&n.slice(8,12)===`WEBP`&&i>=20&&n.charCodeAt(4)+n.charCodeAt(5)*256+n.charCodeAt(6)*65536+n.charCodeAt(7)*16777216===i-8)?void 0:`MCP image omitted: invalid image data`}function KWe(e){return e.type===`object`?{...e,type:`object`,properties:e.properties??{}}:{type:`object`,properties:{}}}function M5(e){let t=[];for(let n of e)n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
2853
+ `)}var qWe=class{entry;invoker;options;schema;provenance;eventService;validator;constructor(e,t,n){this.entry=e,this.invoker=t,this.options=n,this.provenance=Object.freeze({sourceId:e.provenance.serverId,component:e.sourceName,origin:e.provenance.origin,...e.provenance.serverVersion?{version:e.provenance.serverVersion}:{},protocolVersion:e.provenance.protocolVersion}),this.schema={name:e.canonicalName,description:e.description??``,parameters:KWe(e.schema)},this.validator=new gWe(this.schema.name,this.schema.parameters,n?.report)}getName(){return this.schema.name}getDescription(){return this.schema.description}validate(e){return this.validateParameters(e).isValid}validateParameters(e){return this.validator.validate(e)}async execute(e,t){let n;try{if(this.options?.isDispatchAdmitted&&!await this.options.isDispatchAdmitted())return{success:!1,error:`MCP call refused: admission or installed source changed. Review /mcp status and restart after approving the current source.`};if(t?.signal?.aborted)throw new DOMException(`Execution interrupted by user`,`AbortError`);n=await this.invoker.callTool(this.entry.sourceName,e,{signal:t?.signal,...t?.outboundTraceContext?{outboundTraceContext:t.outboundTraceContext}:{},...t?.ask?{ask:t.ask}:{}})}catch(e){if(t?.signal?.aborted)throw new DOMException(`Execution interrupted by user`,`AbortError`);let n=this.options?.authFailureNotice;if(n!==void 0&&O5(e)===`auth`)return{success:!1,error:n};throw Error(`MCP tool call failed`)}let r=[],i;for(let e of n.content)if(e.type===`text`&&typeof e.text==`string`)r.push({type:`text`,text:e.text});else if(e.type===`image`){let t=GWe(e.mimeType,e.data);t?(i??=t,r.push({type:`text`,text:t})):typeof e.mimeType==`string`&&typeof e.data==`string`&&r.push({type:`image_inline`,mimeType:e.mimeType,data:e.data})}else{let t=WWe(e);t&&`part`in t?r.push(t.part):t&&(i??=t.diagnostic,r.push({type:`text`,text:t.diagnostic}))}if(n.isError||i){let e=M5(n.content);return dt(this.schema.name,{success:!1,...n.structuredContent===void 0?{}:{data:Z8(n.structuredContent)},...r.length?{parts:r}:{},error:[e,i].filter(Boolean).join(`
2854
+ `)||`${this.schema.name} reported an error`},this.options?.admission,this.entry.maxResultChars)}let a=n.structuredContent===void 0?M5(n.content):Z8(n.structuredContent),o=await this.readAppView(e,n,t?.signal);return dt(this.schema.name,{success:!0,data:a,...r.length?{parts:r}:{},...o?{view:o}:{}},this.options?.admission,this.entry.maxResultChars)}async readAppView(e,t,n){let r=this.entry.ui?.resourceUri;if(r===void 0||this.invoker.readResource===void 0)return;let i=e=>{this.options?.reportAppViewProblem?.(e)},a;try{if(this.options?.isDispatchAdmitted&&!await this.options.isDispatchAdmitted())return i(`not-admitted`);a=await this.invoker.readResource(r,{signal:n})}catch{return i(`read-failed`)}let o=fUe(r,a);return o.ok?{sourceId:this.entry.provenance.serverId,resourceUri:r,mimeType:o.mimeType,html:o.html,...t.structuredContent===void 0?{}:{structuredContent:Z8(t.structuredContent)},toolInput:e,callableTools:this.options?.appCallableTools??{}}:i(o.reason)}setEventService(e){this.eventService=e}};function JWe(e,t,n){return new qWe(e,t,n)}var N5=class extends Error{constructor(){super(`The value is too long.`),this.name=`HiddenPromptTooLongError`}};const YWe=new Set([``,`\b`]);function P5(e,t={input:process.stdin,output:process.stderr},n={}){let{input:r,output:i}=t,a=n.maxLength??4096,o=r.isTTY===!0&&typeof r.setRawMode==`function`;return i.write(e),new Promise((e,t)=>{let s=``,c=()=>l(Error(`Cancelled.`)),l=a=>{n.signal?.removeEventListener(`abort`,c),r.removeListener(`data`,d),r.removeListener(`end`,u),o&&r.setRawMode?.(!1),r.pause(),o&&i.write(`
2855
2855
  `),a===void 0?e(s):t(a)},u=()=>l(),d=e=>{for(let t of String(e)){if(t===`\r`||t===`
2856
- `||o&&t===``)return l();if(o&&t===``)return l(Error(`Cancelled.`));if(o&&JWe.has(t)){s=s.slice(0,-1);continue}if(s+=t,s.length>a)return l(new N5)}};if(n.signal?.aborted===!0)return l(Error(`Cancelled.`));n.signal?.addEventListener(`abort`,c,{once:!0}),o&&r.setRawMode?.(!0),r.on(`data`,d),r.on(`end`,u),r.resume()})}function YWe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F5(e){let t=e instanceof Error?e.message:String(e),n=/\bat position (\d+)(?: \(line (\d+) column (\d+)\))?$/i.exec(t);if(n===null)return`invalid JSON`;let[,r,i,a]=n;return i!==void 0&&a!==void 0?`invalid JSON (line ${i}, column ${a})`:`invalid JSON (position ${r})`}function I5(e){if(e.kind===`host`)return e.scope;switch(e.scope){case`project`:return`project`;case`project-local`:return`local`}}function XWe(e){let t=Yp(e,`resolve MCP server definitions`);if(t===void 0||t.trim()===``)return;let n=I5(e),r=e.displayName,i;try{i=JSON.parse(t)}catch(e){return{source:n,origin:r,definitions:[],problems:[{name:``,source:n,origin:r,reason:F5(e)}]}}if(YWe(i)&&i.mcpServers===void 0)return;let a=G3(i,n,r);return{source:n,origin:r,definitions:a.definitions,problems:a.problems}}function L5(e,t,n=[]){let r=[...n];for(let t of e){let e=XWe(t);e!==void 0&&r.push(e)}let i=r.flatMap(e=>e.problems),{entries:a,sourceProblems:o}=WVe(r,e=>HVe(e,t));return{entries:a,problems:i,sourceProblems:o}}function R5(e){return M(mq(e),`mcp-credentials`)}const ZWe=/[\u007f-\u009f\u2028\u2029\p{Cf}]/gu;function QWe(e){return JSON.stringify(e).replace(ZWe,e=>{let t=(e.codePointAt(0)??0).toString(16);return t.length>4?`\\u{${t}}`:`\\u${t.padStart(4,`0`)}`})}function $We(e){if(e.kind===`login-required`){let t=tt(e.serverId),n=t??`<server>`,r=`run /mcp login ${n} in this session, or mcp login ${n} in a terminal`;return t===void 0?`An MCP server whose name cannot be shown safely needs you to sign in: ${r}`:`MCP server ${t} needs you to sign in: ${r}`}let t=QWe(e.serverId);return e.scope===void 0?`MCP server ${t} refused the request: the signed-in account lacks a required scope.`:`MCP server ${t} refused the request: it requires the scope "${e.scope}".`}function eGe(e){let t=e.directory??R5(e.productRuntime),n=T8(t),r=E8(t),i=e.openBrowser??(e=>cq(e)),a=new Set;return{signIn:async(t,o,{noBrowser:s,readRedirect:c,confirmBrowser:l,signal:u})=>{let d,f=c===void 0?void 0:async e=>{if(d===void 0)throw new $(`cancelled`);let t=await c(d,e);if(t.length>16384)throw new $(`redirect-too-long`);return t};await k8({clientName:e.productRuntime.config.identity.mcpClientName,securityIdentity:t.securityIdentity,serverUrl:o.url??``,config:o.oauth??{},store:n,lock:r,network:e.network,...e.callbackTimeoutMs===void 0?{}:{callbackTimeoutMs:e.callbackTimeoutMs},...f===void 0?{}:s?{readRedirect:f}:{readRedirectWhenBrowserFails:f},...u===void 0?{}:{signal:u},openBrowser:async(e,t)=>{if(d={authorizationUrl:e.href,redirectUri:t},s)return;let n=l===void 0?`open`:await l(d,u??new AbortController().signal);if(n===`cancel`)throw new $(`cancelled`);if(n===`paste`)throw new $(`browser-failed`);await i(e)}}),a.delete(t.serverId)},authenticatorFor:(t,i)=>nUe({serverId:t.serverId,securityIdentity:t.securityIdentity,serverUrl:i.url??``,config:i.oauth??{},store:n,lock:r,network:e.network,notify:n=>{n.kind===`login-required`&&a.add(t.serverId),e.reportDiagnostic($We(n))}}),state:async(e,t)=>{let r=await YHe({securityIdentity:e.securityIdentity,serverUrl:t.url??``,store:n});return r===`signed-out`&&a.has(e.serverId)?`sign-in-required`:r},signOut:async(t,i)=>{let o=await j8({securityIdentity:t.securityIdentity,serverUrl:i.url??``,store:n,lock:r,network:e.network});return a.delete(t.serverId),o}}}const z5={refresh_token:`refresh token`,access_token:`access token`};function tGe(e){let t=e.revocationFailure??`revocation-failed`;switch(e.revocation){case`revoked`:return`The tokens were revoked.`;case`not-attempted`:return`There were no tokens to revoke.`;case`unsupported`:return`The authorization server offers no token revocation; the tokens stay valid until they expire.`;case`failed`:return`Token revocation failed (${t}); the tokens stay valid until they expire.`;case`partial`:return(e.tokens??[]).map(e=>e.revoked?`The ${z5[e.token]} was revoked.`:`The ${z5[e.token]} was not (${e.failure??`revocation-failed`}) and stays valid until it expires.`).join(` `)}}function B5(e,t){let{entries:n}=L5(t.settingsSources,t.env),r=n.find(t=>t.name===e);if(r===void 0){t.stderr(`No MCP server named "${e}" is configured.\n`);return}if(h6(r)){t.stderr(`MCP server "${e}" is blocked: the managed MCP source could not be read.\n`);return}let i=r.definition;if(r.status!==`resolved`||i===void 0){t.stderr(`MCP server "${e}" cannot be used: ${r.problem?.reason??`unresolved`}.\n`);return}if(i.transport!==`http`||i.oauth===void 0){t.stderr(`MCP server "${e}" does not declare \`oauth\`; there is nothing to sign in to.\n`);return}if(i.unsetVariables.some(e=>e.field===`url`)){t.stderr(`MCP server "${e}" has an unset variable in its url.\n`);return}return{entry:r,definition:i}}function V5(e,t,n,r){let i=e.filter(e=>!t.includes(e)),a=i[0];if(i.length!==1||a===void 0||a.startsWith(`-`)){r.stderr(n);return}return a}async function nGe(e,t){let n=e.includes(`--client-secret`),r=e.includes(`--no-browser`),i=V5(e,[`--client-secret`,`--no-browser`],`Usage: {{cli}} mcp login <name> [--client-secret] [--no-browser]
2856
+ `||o&&t===``)return l();if(o&&t===``)return l(Error(`Cancelled.`));if(o&&YWe.has(t)){s=s.slice(0,-1);continue}if(s+=t,s.length>a)return l(new N5)}};if(n.signal?.aborted===!0)return l(Error(`Cancelled.`));n.signal?.addEventListener(`abort`,c,{once:!0}),o&&r.setRawMode?.(!0),r.on(`data`,d),r.on(`end`,u),r.resume()})}function XWe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function F5(e){let t=e instanceof Error?e.message:String(e),n=/\bat position (\d+)(?: \(line (\d+) column (\d+)\))?$/i.exec(t);if(n===null)return`invalid JSON`;let[,r,i,a]=n;return i!==void 0&&a!==void 0?`invalid JSON (line ${i}, column ${a})`:`invalid JSON (position ${r})`}function I5(e){if(e.kind===`host`)return e.scope;switch(e.scope){case`project`:return`project`;case`project-local`:return`local`}}function ZWe(e){let t=Yp(e,`resolve MCP server definitions`);if(t===void 0||t.trim()===``)return;let n=I5(e),r=e.displayName,i;try{i=JSON.parse(t)}catch(e){return{source:n,origin:r,definitions:[],problems:[{name:``,source:n,origin:r,reason:F5(e)}]}}if(XWe(i)&&i.mcpServers===void 0)return;let a=G3(i,n,r);return{source:n,origin:r,definitions:a.definitions,problems:a.problems}}function L5(e,t,n=[]){let r=[...n];for(let t of e){let e=ZWe(t);e!==void 0&&r.push(e)}let i=r.flatMap(e=>e.problems),{entries:a,sourceProblems:o}=GVe(r,e=>UVe(e,t));return{entries:a,problems:i,sourceProblems:o}}function R5(e){return M(mq(e),`mcp-credentials`)}const QWe=/[\u007f-\u009f\u2028\u2029\p{Cf}]/gu;function $We(e){return JSON.stringify(e).replace(QWe,e=>{let t=(e.codePointAt(0)??0).toString(16);return t.length>4?`\\u{${t}}`:`\\u${t.padStart(4,`0`)}`})}function eGe(e){if(e.kind===`login-required`){let t=tt(e.serverId),n=t??`<server>`,r=`run /mcp login ${n} in this session, or mcp login ${n} in a terminal`;return t===void 0?`An MCP server whose name cannot be shown safely needs you to sign in: ${r}`:`MCP server ${t} needs you to sign in: ${r}`}let t=$We(e.serverId);return e.scope===void 0?`MCP server ${t} refused the request: the signed-in account lacks a required scope.`:`MCP server ${t} refused the request: it requires the scope "${e.scope}".`}function tGe(e){let t=e.directory??R5(e.productRuntime),n=T8(t),r=E8(t),i=e.openBrowser??(e=>cq(e)),a=new Set;return{signIn:async(t,o,{noBrowser:s,readRedirect:c,confirmBrowser:l,signal:u})=>{let d,f=c===void 0?void 0:async e=>{if(d===void 0)throw new $(`cancelled`);let t=await c(d,e);if(t.length>16384)throw new $(`redirect-too-long`);return t};await k8({clientName:e.productRuntime.config.identity.mcpClientName,securityIdentity:t.securityIdentity,serverUrl:o.url??``,config:o.oauth??{},store:n,lock:r,network:e.network,...e.callbackTimeoutMs===void 0?{}:{callbackTimeoutMs:e.callbackTimeoutMs},...f===void 0?{}:s?{readRedirect:f}:{readRedirectWhenBrowserFails:f},...u===void 0?{}:{signal:u},openBrowser:async(e,t)=>{if(d={authorizationUrl:e.href,redirectUri:t},s)return;let n=l===void 0?`open`:await l(d,u??new AbortController().signal);if(n===`cancel`)throw new $(`cancelled`);if(n===`paste`)throw new $(`browser-failed`);await i(e)}}),a.delete(t.serverId)},authenticatorFor:(t,i)=>rUe({serverId:t.serverId,securityIdentity:t.securityIdentity,serverUrl:i.url??``,config:i.oauth??{},store:n,lock:r,network:e.network,notify:n=>{n.kind===`login-required`&&a.add(t.serverId),e.reportDiagnostic(eGe(n))}}),state:async(e,t)=>{let r=await XHe({securityIdentity:e.securityIdentity,serverUrl:t.url??``,store:n});return r===`signed-out`&&a.has(e.serverId)?`sign-in-required`:r},signOut:async(t,i)=>{let o=await j8({securityIdentity:t.securityIdentity,serverUrl:i.url??``,store:n,lock:r,network:e.network});return a.delete(t.serverId),o}}}const z5={refresh_token:`refresh token`,access_token:`access token`};function nGe(e){let t=e.revocationFailure??`revocation-failed`;switch(e.revocation){case`revoked`:return`The tokens were revoked.`;case`not-attempted`:return`There were no tokens to revoke.`;case`unsupported`:return`The authorization server offers no token revocation; the tokens stay valid until they expire.`;case`failed`:return`Token revocation failed (${t}); the tokens stay valid until they expire.`;case`partial`:return(e.tokens??[]).map(e=>e.revoked?`The ${z5[e.token]} was revoked.`:`The ${z5[e.token]} was not (${e.failure??`revocation-failed`}) and stays valid until it expires.`).join(` `)}}function B5(e,t){let{entries:n}=L5(t.settingsSources,t.env),r=n.find(t=>t.name===e);if(r===void 0){t.stderr(`No MCP server named "${e}" is configured.\n`);return}if(h6(r)){t.stderr(`MCP server "${e}" is blocked: the managed MCP source could not be read.\n`);return}let i=r.definition;if(r.status!==`resolved`||i===void 0){t.stderr(`MCP server "${e}" cannot be used: ${r.problem?.reason??`unresolved`}.\n`);return}if(i.transport!==`http`||i.oauth===void 0){t.stderr(`MCP server "${e}" does not declare \`oauth\`; there is nothing to sign in to.\n`);return}if(i.unsetVariables.some(e=>e.field===`url`)){t.stderr(`MCP server "${e}" has an unset variable in its url.\n`);return}return{entry:r,definition:i}}function V5(e,t,n,r){let i=e.filter(e=>!t.includes(e)),a=i[0];if(i.length!==1||a===void 0||a.startsWith(`-`)){r.stderr(n);return}return a}async function rGe(e,t){let n=e.includes(`--client-secret`),r=e.includes(`--no-browser`),i=V5(e,[`--client-secret`,`--no-browser`],`Usage: {{cli}} mcp login <name> [--client-secret] [--no-browser]
2857
2857
  `.replaceAll(`{{cli}}`,t.productRuntime.config.identity.cliName),t);if(i===void 0)return 1;let a=B5(i,t);if(a===void 0)return 1;let{entry:o,definition:s}=a,c=s.oauth??{},l;if(n){if(c.clientId===void 0)return t.stderr(`MCP server "${i}" registers its client dynamically; a client secret needs \`oauth.clientId\`.\n`),1;try{l=await(t.promptSecret??(()=>P5(`Client secret: `)))()}catch{return t.stderr(`No client secret was read.
2858
2858
  `),1}if(l===``)return t.stderr(`No client secret was read.
2859
2859
  `),1}let u=t.openBrowser??(e=>cq(e)),d=t.promptRedirect??(e=>P5(`Redirect URL (not echoed): `,void 0,{signal:e,maxLength:16384})),f=e=>d(e).catch(e=>{throw e instanceof N5?new $(`redirect-too-long`):e}),p=t.credentialDirectory??R5(t.productRuntime);try{await k8({clientName:t.productRuntime.config.identity.mcpClientName,securityIdentity:x6(o),serverUrl:s.url??``,config:c,...l===void 0?{}:{clientSecret:l},store:T8(p),lock:E8(p),network:t.network??{},...t.callbackTimeoutMs===void 0?{}:{callbackTimeoutMs:t.callbackTimeoutMs},...r?{readRedirect:f}:{},openBrowser:async(e,n)=>{if(r){t.stdout(`To sign in to MCP server "${i}", open this URL in a browser:\n${e.href}\n\nAfter you approve, the browser is sent to ${n}, which may not load.\nCopy the full address from its address bar and paste it here.
2860
2860
  `);return}t.stdout(`Opening your browser to sign in to MCP server "${i}".\nIf it does not open, visit:\n${e.href}\n`),await u(e).catch(()=>t.stderr(`The browser could not be opened.
2861
- `))}})}catch(e){let n=e instanceof $?e.reason:`unexpected-error`;return t.stderr(`Sign-in to MCP server "${i}" failed (${n}).\n`),1}return t.stdout(`Signed in to MCP server "${i}".\n`),0}async function rGe(e,t){let n=V5(e,[],`Usage: {{cli}} mcp logout <name>
2862
- `.replaceAll(`{{cli}}`,t.productRuntime.config.identity.cliName),t);if(n===void 0)return 1;let r=B5(n,t);if(r===void 0)return 1;let i=t.credentialDirectory??R5(t.productRuntime),a;try{a=await j8({securityIdentity:x6(r.entry),serverUrl:r.definition.url??``,store:T8(i),lock:E8(i),network:t.network??{}})}catch(e){let r=e instanceof $?e.reason:`unexpected-error`;return t.stderr(`Sign-out of MCP server "${n}" failed (${r}).\n`),1}return t.stdout(`${a.removed?`Signed out of`:`Not signed in to`} MCP server "${n}". ${tGe(a)}\n`),0}function H5(e){return e.status===`trusted`?`trusted`:e.trustState}function U5(e){return e.status===`trusted`?e.identity.displayPath:e.displayPath}function iGe(e,t){process.stdout.write(`Workspace trust: ${H5(e)}\n`);let n=U5(e);n!==void 0&&process.stdout.write(`Workspace: ${n}\n`),e.status!==`trusted`&&(process.stdout.write(`Project settings, hooks, plugins, skills, and provider overrides are disabled.
2863
- `),e.trustState!==`identity-unavailable`&&process.stdout.write(`Grant access with: ${t.config.identity.cliName} trust --yes\n`))}function aGe(e,t,n,r){let i=g4(e,t,n);return{state:H5(e),workspace:U5(e)??t,askable:i!==void 0,loads:i?.loads??[],...e.status===`trusted`?{providerEnvRefs:b4(Rq(t,{productRuntime:n,projectAccess:e}).settingsSources,r)}:{}}}async function oGe(e,t,n,r=cf(pq(n).workspaceTrust,n.layout.projectStateDirectories),i){let a=e.find(e=>!e.startsWith(`-`))??(e.includes(`--yes`)?`grant`:`status`);if(![`status`,`grant`,`revoke`].includes(a))return process.stderr.write(`Usage: ${n.config.identity.cliName} trust [status [--json]|grant|revoke] [--yes]\n`),1;if(a!==`status`&&process.stdin.isTTY!==!0&&!e.includes(`--yes`))return process.stderr.write(`${n.config.identity.cliName} trust ${a} requires --yes in headless mode.\n`),1;try{let o=a===`grant`?await r.grant(t):a===`revoke`?await r.revoke(t):await r.inspect(t);return a===`status`&&e.includes(`--json`)?(process.stdout.write(`${JSON.stringify(aGe(o,t,n,i??Sz()))}\n`),0):(iGe(o,n),a===`status`&&o.status!==`trusted`&&process.stdout.write(m4(o.identity,t,n)),a===`grant`?o.status===`trusted`?0:1:a===`revoke`?+(o.status===`trusted`):0)}catch(e){return process.stderr.write(`Workspace trust ${a} failed: ${e instanceof Error?e.message:String(e)}\n`),1}}function sGe(e){let t,n,r=[],i=[],a=e.includes(Fq),o=e.filter(e=>e!==Fq);if(o[0]===`--background`){for(let e=1;e<o.length;e+=2){let a=o[e+1];if(a===void 0)return;if(o[e]===`--name`&&t===void 0)t=a;else if(o[e]===`--external-event-grant`)r.push(a);else if(o[e]===`--external-event-port`&&n===void 0)n=a;else if(o[e]===`--external-event-trusted-proxy`)i.push(a);else return}return{...t===void 0?{}:{name:t},restricted:a,grantFiles:r,...n===void 0?{}:{port:n},trustedProxies:i}}}function cGe(e){if(e.grantFiles.length===0){if(e.port!==void 0||e.trustedProxies.length>0)throw Error(`--external-event-port and --external-event-trusted-proxy go only with external event grants`);return}if(e.port===void 0)throw Error(`--external-event-grant needs --external-event-port: the loopback port the owner's proxy forwards to`);let t=Number(e.port);if(!/^[0-9]+$/u.test(e.port)||t<1||t>65535)throw Error(`--external-event-port must be an integer in 1..65535`);if(!e.trustedProxies.every(e=>pr(e)!==0))throw Error(`--external-event-trusted-proxy must be a literal IP address`);return{port:t,trustedProxies:e.trustedProxies}}async function lGe(e,t,n){let[r,i,a,o]=e,s=r===`list`&&i!==void 0&&(a===void 0||a===`--json`&&o===void 0),c=r===`revoke`&&i!==void 0&&a!==void 0&&o===void 0;if(!s&&!c)return process.stderr.write(`Usage: {{cli}} session events list <supervised-id> [--json]
2861
+ `))}})}catch(e){let n=e instanceof $?e.reason:`unexpected-error`;return t.stderr(`Sign-in to MCP server "${i}" failed (${n}).\n`),1}return t.stdout(`Signed in to MCP server "${i}".\n`),0}async function iGe(e,t){let n=V5(e,[],`Usage: {{cli}} mcp logout <name>
2862
+ `.replaceAll(`{{cli}}`,t.productRuntime.config.identity.cliName),t);if(n===void 0)return 1;let r=B5(n,t);if(r===void 0)return 1;let i=t.credentialDirectory??R5(t.productRuntime),a;try{a=await j8({securityIdentity:x6(r.entry),serverUrl:r.definition.url??``,store:T8(i),lock:E8(i),network:t.network??{}})}catch(e){let r=e instanceof $?e.reason:`unexpected-error`;return t.stderr(`Sign-out of MCP server "${n}" failed (${r}).\n`),1}return t.stdout(`${a.removed?`Signed out of`:`Not signed in to`} MCP server "${n}". ${nGe(a)}\n`),0}function H5(e){return e.status===`trusted`?`trusted`:e.trustState}function U5(e){return e.status===`trusted`?e.identity.displayPath:e.displayPath}function aGe(e,t){process.stdout.write(`Workspace trust: ${H5(e)}\n`);let n=U5(e);n!==void 0&&process.stdout.write(`Workspace: ${n}\n`),e.status!==`trusted`&&(process.stdout.write(`Project settings, hooks, plugins, skills, and provider overrides are disabled.
2863
+ `),e.trustState!==`identity-unavailable`&&process.stdout.write(`Grant access with: ${t.config.identity.cliName} trust --yes\n`))}function oGe(e,t,n,r){let i=g4(e,t,n);return{state:H5(e),workspace:U5(e)??t,askable:i!==void 0,loads:i?.loads??[],...e.status===`trusted`?{providerEnvRefs:b4(Rq(t,{productRuntime:n,projectAccess:e}).settingsSources,r)}:{}}}async function sGe(e,t,n,r=cf(pq(n).workspaceTrust,n.layout.projectStateDirectories),i){let a=e.find(e=>!e.startsWith(`-`))??(e.includes(`--yes`)?`grant`:`status`);if(![`status`,`grant`,`revoke`].includes(a))return process.stderr.write(`Usage: ${n.config.identity.cliName} trust [status [--json]|grant|revoke] [--yes]\n`),1;if(a!==`status`&&process.stdin.isTTY!==!0&&!e.includes(`--yes`))return process.stderr.write(`${n.config.identity.cliName} trust ${a} requires --yes in headless mode.\n`),1;try{let o=a===`grant`?await r.grant(t):a===`revoke`?await r.revoke(t):await r.inspect(t);return a===`status`&&e.includes(`--json`)?(process.stdout.write(`${JSON.stringify(oGe(o,t,n,i??Sz()))}\n`),0):(aGe(o,n),a===`status`&&o.status!==`trusted`&&process.stdout.write(m4(o.identity,t,n)),a===`grant`?o.status===`trusted`?0:1:a===`revoke`?+(o.status===`trusted`):0)}catch(e){return process.stderr.write(`Workspace trust ${a} failed: ${e instanceof Error?e.message:String(e)}\n`),1}}function cGe(e){let t,n,r=[],i=[],a=e.includes(Fq),o=e.filter(e=>e!==Fq);if(o[0]===`--background`){for(let e=1;e<o.length;e+=2){let a=o[e+1];if(a===void 0)return;if(o[e]===`--name`&&t===void 0)t=a;else if(o[e]===`--external-event-grant`)r.push(a);else if(o[e]===`--external-event-port`&&n===void 0)n=a;else if(o[e]===`--external-event-trusted-proxy`)i.push(a);else return}return{...t===void 0?{}:{name:t},restricted:a,grantFiles:r,...n===void 0?{}:{port:n},trustedProxies:i}}}function lGe(e){if(e.grantFiles.length===0){if(e.port!==void 0||e.trustedProxies.length>0)throw Error(`--external-event-port and --external-event-trusted-proxy go only with external event grants`);return}if(e.port===void 0)throw Error(`--external-event-grant needs --external-event-port: the loopback port the owner's proxy forwards to`);let t=Number(e.port);if(!/^[0-9]+$/u.test(e.port)||t<1||t>65535)throw Error(`--external-event-port must be an integer in 1..65535`);if(!e.trustedProxies.every(e=>pr(e)!==0))throw Error(`--external-event-trusted-proxy must be a literal IP address`);return{port:t,trustedProxies:e.trustedProxies}}async function uGe(e,t,n){let[r,i,a,o]=e,s=r===`list`&&i!==void 0&&(a===void 0||a===`--json`&&o===void 0),c=r===`revoke`&&i!==void 0&&a!==void 0&&o===void 0;if(!s&&!c)return process.stderr.write(`Usage: {{cli}} session events list <supervised-id> [--json]
2864
2864
  {{cli}} session events revoke <supervised-id> <grant-id>
2865
- `.replaceAll(`{{cli}}`,n.config.identity.cliName)),1;try{if(c)return await tBe(i,a,t),process.stdout.write(`Revoked external event grant ${a} on supervised session ${i}.\n`),0;let e=await eBe(i,t);return process.stdout.write(a===`--json`?`${JSON.stringify({id:i,grants:e})}\n`:DBe(e)),0}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`Supervised session external events are unavailable.`}\n`),1}}async function uGe(e,t=process.argv,n=process.cwd(),r={},i,a){let o=aD(e),s={...e,productRuntime:o},c=Y4(o),l=new Map,u=(e=n)=>{let t=l.get(e)??(e===n?m.settingsSources:void 0);if(t===void 0)throw Error(`Supervised workspace settings have not been admitted.`);return{...x4(o,t,s.providerDefinitions??Sz()),...r}},d=Nve(t.slice(2),o);if(d!==void 0)return process.stdout.write(d),process.exitCode=0,!0;if(Sze(t[2]))return process.exitCode=await Tze({version:I1(o),terminal:new ZD,cwd:n,options:s,isTTY:process.stdin.isTTY===!0},t.slice(3),t[2]),!0;let f=async()=>a===void 0?void 0:$Be(a,{productRuntime:o,cwd:n,projectAccess:await Lq(n,s),...s.providerDefinitions===void 0?{}:{providerDefinitions:s.providerDefinitions},...s.safeMode===!0?{safeMode:!0}:{}});if(KBe(xq(t).slice(2))){let e=await f();return process.exitCode=await JBe(t.slice(2),{cwd:n,productRuntime:o,...e===void 0?{}:{render:e}}),!0}if(t[2]===`session`&&t[3]===`stop`){if(t.length!==5)return process.stderr.write(`Usage: ${o.config.identity.cliName} session stop <supervised-id>\n`),process.exitCode=1,!0;try{await s3(t[4],c),process.stdout.write(`Stopped supervised session ${t[4]}.\n`)}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to stop supervised session.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`events`)return process.exitCode=await lGe(t.slice(4),c,o),!0;if(t[2]===`session`&&t[3]===`rename`){if(t.length!==6||!G4(t[5]))return process.stderr.write(`Usage: ${o.config.identity.cliName} session rename <supervised-id> <name>\n`),process.exitCode=1,!0;try{let e=t[4];await Jze(e,t[5],c),process.stdout.write(`Renamed supervised session ${e}.\n`),process.exitCode=0}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to rename supervised session.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`link-pr`){if(t.length!==6||!K4(t[5]))return process.stderr.write(`Usage: ${o.config.identity.cliName} session link-pr <supervised-id> <https-pr-url>\n`),process.exitCode=1,!0;try{let e=t[4];await Yze(e,t[5],c),process.stdout.write(`Linked PR to supervised session ${e}.\n`),process.exitCode=0}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to link supervised session PR.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`unlink-pr`){if(t.length!==5)return process.stderr.write(`Usage: ${o.config.identity.cliName} session unlink-pr <supervised-id>\n`),process.exitCode=1,!0;try{let e=t[4];await Xze(e,c),process.stdout.write(`Unlinked PR from supervised session ${e}.\n`),process.exitCode=0}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to unlink supervised session PR.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`attach`){let e=await f();return process.exitCode=await RBe(t.slice(4),{productRuntime:o,...e===void 0?{}:{render:e}}),!0}if(t[2]===`session`&&t[3]===`view`){let e=await f();return process.exitCode=await BBe(t.slice(4),{productRuntime:o,launchCwd:n,render:i,...e===void 0?{}:{renderAttached:e},startTrustQuestion:async e=>g4(await Lq(e,{productRuntime:o}),e,o),start:async(e,t)=>{let n=await Lq(e,{productRuntime:o}),i=t===`restricted`;if(t===`trust`&&h4(n)&&(n=await _4(e,o)),kD(n)&&!(i&&h4(n)))throw Error(AD(n,e,o.config.identity.cliName));return S1(r,{telemetryServiceName:o.config.identity.telemetryServiceName,serviceVersion:I1(o),surface:`serve`}),l.set(e,Rq(e,{productRuntime:o,projectAccess:i?$d(`untrusted`,e):n}).settingsSources),v3(e,{productRuntime:o,env:u(e),...i?{restricted:!0}:{}})}}),!0}if(t[2]===`daemon`)return process.exitCode=await GBe(t.slice(3),{productRuntime:o,cwd:n,env:u,admit:async(e,{restricted:t})=>{let i=await Lq(e,e===Cn(n)?s:{productRuntime:o});if(kD(i)&&!(t&&h4(i)))throw Error(AD(i,e,o.config.identity.cliName));return S1(r,{telemetryServiceName:o.config.identity.telemetryServiceName,serviceVersion:I1(o),surface:`serve`}),l.set(e,Rq(e,{productRuntime:o,projectAccess:t?$d(`untrusted`,e):i}).settingsSources),{restricted:t||i.status===`restricted`}},trusted:async e=>(await Lq(e,e===Cn(n)?s:{productRuntime:o})).status===`trusted`,stdout:e=>process.stdout.write(e),stderr:e=>process.stderr.write(e)}),!0;let p=await Lq(n,s),m=Rq(n,{...s,projectAccess:p});if(Nq(m.settingsSources,s.providerDefinitions??Sz()),t[2]===`mcp`&&(t[3]===`login`||t[3]===`logout`)){let e=t[3]===`login`?nGe:rGe;return process.exitCode=await e(t.slice(4),{settingsSources:m.settingsSources,env:o.environment,productRuntime:o,stdout:e=>process.stdout.write(e),stderr:e=>process.stderr.write(e)}),!0}if(t[2]===`trust`)return process.exitCode=await oGe(t.slice(3),n,o,void 0,s.providerDefinitions),!0;if(t[2]===`usage`){let e=t.slice(3),n=m.sessionStoreScope===`project`?m.sessionStore:void 0;return process.exitCode=e[0]===`export`?await aVe(e.slice(1),o,n):tMe(e,o,n),!0}if(t[2]===`session`&&t[3]===`analyze`)return await N1(t.slice(4),n,m.sessionStoreScope===`project`?m.sessionStore:void 0,gx(o.layout.userPaths.sessions)),!0;if(t[2]===`session`&&t[3]===`list`)return process.exitCode=await dBe(t.slice(4),o,m.sessionStoreScope===`project`?m.sessionStore:void 0),!0;if(t[2]===`session`&&t[3]===`start`){let e=sGe(t.slice(4));if(e===void 0)return process.stderr.write(`Usage: {{cli}} session start --background [--name <name>] [--restricted-workspace]
2865
+ `.replaceAll(`{{cli}}`,n.config.identity.cliName)),1;try{if(c)return await tBe(i,a,t),process.stdout.write(`Revoked external event grant ${a} on supervised session ${i}.\n`),0;let e=await eBe(i,t);return process.stdout.write(a===`--json`?`${JSON.stringify({id:i,grants:e})}\n`:OBe(e)),0}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`Supervised session external events are unavailable.`}\n`),1}}async function dGe(e,t=process.argv,n=process.cwd(),r={},i,a){let o=aD(e),s={...e,productRuntime:o},c=Y4(o),l=new Map,u=(e=n)=>{let t=l.get(e)??(e===n?m.settingsSources:void 0);if(t===void 0)throw Error(`Supervised workspace settings have not been admitted.`);return{...x4(o,t,s.providerDefinitions??Sz()),...r}},d=Nve(t.slice(2),o);if(d!==void 0)return process.stdout.write(d),process.exitCode=0,!0;if(Sze(t[2]))return process.exitCode=await Tze({version:I1(o),terminal:new ZD,cwd:n,options:s,isTTY:process.stdin.isTTY===!0},t.slice(3),t[2]),!0;let f=async()=>a===void 0?void 0:eVe(a,{productRuntime:o,cwd:n,projectAccess:await Lq(n,s),...s.providerDefinitions===void 0?{}:{providerDefinitions:s.providerDefinitions},...s.safeMode===!0?{safeMode:!0}:{}});if(qBe(xq(t).slice(2))){let e=await f();return process.exitCode=await YBe(t.slice(2),{cwd:n,productRuntime:o,...e===void 0?{}:{render:e}}),!0}if(t[2]===`session`&&t[3]===`stop`){if(t.length!==5)return process.stderr.write(`Usage: ${o.config.identity.cliName} session stop <supervised-id>\n`),process.exitCode=1,!0;try{await s3(t[4],c),process.stdout.write(`Stopped supervised session ${t[4]}.\n`)}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to stop supervised session.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`events`)return process.exitCode=await uGe(t.slice(4),c,o),!0;if(t[2]===`session`&&t[3]===`rename`){if(t.length!==6||!G4(t[5]))return process.stderr.write(`Usage: ${o.config.identity.cliName} session rename <supervised-id> <name>\n`),process.exitCode=1,!0;try{let e=t[4];await Jze(e,t[5],c),process.stdout.write(`Renamed supervised session ${e}.\n`),process.exitCode=0}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to rename supervised session.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`link-pr`){if(t.length!==6||!K4(t[5]))return process.stderr.write(`Usage: ${o.config.identity.cliName} session link-pr <supervised-id> <https-pr-url>\n`),process.exitCode=1,!0;try{let e=t[4];await Yze(e,t[5],c),process.stdout.write(`Linked PR to supervised session ${e}.\n`),process.exitCode=0}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to link supervised session PR.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`unlink-pr`){if(t.length!==5)return process.stderr.write(`Usage: ${o.config.identity.cliName} session unlink-pr <supervised-id>\n`),process.exitCode=1,!0;try{let e=t[4];await Xze(e,c),process.stdout.write(`Unlinked PR from supervised session ${e}.\n`),process.exitCode=0}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Unable to unlink supervised session PR.`}\n`),process.exitCode=1}return!0}if(t[2]===`session`&&t[3]===`attach`){let e=await f();return process.exitCode=await zBe(t.slice(4),{productRuntime:o,...e===void 0?{}:{render:e}}),!0}if(t[2]===`session`&&t[3]===`view`){let e=await f();return process.exitCode=await VBe(t.slice(4),{productRuntime:o,launchCwd:n,render:i,...e===void 0?{}:{renderAttached:e},startTrustQuestion:async e=>g4(await Lq(e,{productRuntime:o}),e,o),start:async(e,t)=>{let n=await Lq(e,{productRuntime:o}),i=t===`restricted`;if(t===`trust`&&h4(n)&&(n=await _4(e,o)),kD(n)&&!(i&&h4(n)))throw Error(AD(n,e,o.config.identity.cliName));return S1(r,{telemetryServiceName:o.config.identity.telemetryServiceName,serviceVersion:I1(o),surface:`serve`}),l.set(e,Rq(e,{productRuntime:o,projectAccess:i?$d(`untrusted`,e):n}).settingsSources),v3(e,{productRuntime:o,env:u(e),...i?{restricted:!0}:{}})}}),!0}if(t[2]===`daemon`)return process.exitCode=await KBe(t.slice(3),{productRuntime:o,cwd:n,env:u,admit:async(e,{restricted:t})=>{let i=await Lq(e,e===Cn(n)?s:{productRuntime:o});if(kD(i)&&!(t&&h4(i)))throw Error(AD(i,e,o.config.identity.cliName));return S1(r,{telemetryServiceName:o.config.identity.telemetryServiceName,serviceVersion:I1(o),surface:`serve`}),l.set(e,Rq(e,{productRuntime:o,projectAccess:t?$d(`untrusted`,e):i}).settingsSources),{restricted:t||i.status===`restricted`}},trusted:async e=>(await Lq(e,e===Cn(n)?s:{productRuntime:o})).status===`trusted`,stdout:e=>process.stdout.write(e),stderr:e=>process.stderr.write(e)}),!0;let p=await Lq(n,s),m=Rq(n,{...s,projectAccess:p});if(Nq(m.settingsSources,s.providerDefinitions??Sz()),t[2]===`mcp`&&(t[3]===`login`||t[3]===`logout`)){let e=t[3]===`login`?rGe:iGe;return process.exitCode=await e(t.slice(4),{settingsSources:m.settingsSources,env:o.environment,productRuntime:o,stdout:e=>process.stdout.write(e),stderr:e=>process.stderr.write(e)}),!0}if(t[2]===`trust`)return process.exitCode=await sGe(t.slice(3),n,o,void 0,s.providerDefinitions),!0;if(t[2]===`usage`){let e=t.slice(3),n=m.sessionStoreScope===`project`?m.sessionStore:void 0;return process.exitCode=e[0]===`export`?await oVe(e.slice(1),o,n):tMe(e,o,n),!0}if(t[2]===`session`&&t[3]===`analyze`)return await N1(t.slice(4),n,m.sessionStoreScope===`project`?m.sessionStore:void 0,gx(o.layout.userPaths.sessions)),!0;if(t[2]===`session`&&t[3]===`list`)return process.exitCode=await dBe(t.slice(4),o,m.sessionStoreScope===`project`?m.sessionStore:void 0),!0;if(t[2]===`session`&&t[3]===`start`){let e=cGe(t.slice(4));if(e===void 0)return process.stderr.write(`Usage: {{cli}} session start --background [--name <name>] [--restricted-workspace]
2866
2866
  [--external-event-grant <file>]... [--external-event-port <port>]
2867
2867
  [--external-event-trusted-proxy <ip>]...
2868
- `.replaceAll(`{{cli}}`,o.config.identity.cliName)),process.exitCode=1,!0;let i,a;try{a=cGe(e),i=rO(e.grantFiles),a!==void 0&&$A({grants:i,trustedProxies:a.trustedProxies})}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`grant refused`}\n`),process.exitCode=1,!0}if(kD(m.projectAccess)&&!(e.restricted&&h4(m.projectAccess)))return process.stderr.write(`${AD(m.projectAccess,n,o.config.identity.cliName)}\n`),process.exitCode=1,!0;try{S1(r,{telemetryServiceName:o.config.identity.telemetryServiceName,serviceVersion:I1(o),surface:`serve`}),(e.restricted||m.projectAccess.status===`restricted`)&&process.stderr.write(`${jD(o.layout.projectSettingsPaths)}\n`),e.restricted&&l.set(n,Rq(n,{productRuntime:o,projectAccess:$d(`untrusted`,n)}).settingsSources);let t=await v3(n,{productRuntime:o,env:u(),...e.name===void 0?{}:{name:e.name},...e.restricted?{restricted:!0}:{},...i.length>0&&a!==void 0?{grants:i,eventEndpoint:a}:{}});process.stdout.write(`Supervised session: ${t}\n`)}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Supervised session could not start.`}\n`),process.exitCode=1}return!0}return t[2]===`eval`?(process.exitCode=await P1(t.slice(3),n,{settingsSources:m.settingsSources,projectAccess:m.projectAccess,environment:o.environment,resolveProviderCredential:(s.providerConnectionHost??gq(o)).resolveCredential}),!0):!1}const W5=[`v`,`prompt`,`cwd`,`repo`];function dGe(e,t){return`Usage: ${e} open '${t}://open?v=1&prompt=<text>[&cwd=<absolute path>|&repo=<owner/name>]'`}function G5(e){return[...e].length}const fGe=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/u,K5=/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/u,pGe=/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/;function q5(e){let t=[...e].map(e=>K5.test(e)?`\\u{${(e.codePointAt(0)??0).toString(16)}}`:e).join(``),n=[...t];return n.length>80?`${n.slice(0,80).join(``)}\u2026`:t}function J5(e){return{ok:!1,reason:e}}function mGe(e){let t=e.host.toLowerCase(),n=e.pathname;return t.length>0?n===``||n===`/`?t:void 0:n.toLowerCase()}function Y5(e){return typeof e==`object`&&!!e&&!(e instanceof Map)}function hGe(e){let t=new Map;for(let[n,r]of e.searchParams){if(!W5.includes(n))return J5(`\`${q5(n)}\` is not an accepted key; only ${W5.join(`, `)} are.`);if(t.has(n))return J5(`\`${q5(n)}\` appears more than once.`);t.set(n,r)}return t}function gGe(e){if(e===void 0)return;let t=e.replace(/\r\n/g,`
2869
- `);return t.includes(`\r`)?J5(`the prompt contains a carriage return.`):fGe.test(t)?J5(`the prompt contains a control or invisible formatting character.`):G5(t)>5e3?J5(`the prompt is longer than 5000 characters.`):t.trimStart().startsWith(`/`)?J5("a link may carry a prompt but not a command: the prompt begins with `/`."):t}function _Ge(e){if(e===void 0)return;if(K5.test(e))return J5(`the cwd contains a control or invisible formatting character.`);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return J5(`the cwd is a UNC or network path.`);let t=e.startsWith(`/`),n=/^[A-Za-z]:[\\/]/.test(e);return!t&&!n?J5(`the cwd is not an absolute path.`):e.split(/[\\/]/).includes(`..`)?J5("the cwd contains a `..` segment."):e}function vGe(e){let t=e.get(`v`);if(t===void 0)return J5("the link carries no `v`.");if(t!==`1`)return J5(`\`v=${q5(t)}\` is not version 1.`);let n=gGe(e.get(`prompt`));if(Y5(n))return n;let r=_Ge(e.get(`cwd`));if(Y5(r))return r;let i=e.get(`repo`);return i!==void 0&&!pGe.test(i)?J5(`\`${q5(i)}\` is not an \`owner/name\` slug.`):r===void 0&&i===void 0?J5("the link names no target: pass `cwd` or `repo`."):{ok:!0,intent:{version:t,prompt:n,cwd:r,repo:r===void 0?i:void 0,repoSuperseded:r!==void 0&&i!==void 0}}}function yGe(e,t){if(G5(e)>8192)return J5(`the link is longer than 8192 characters.`);let n;try{n=new URL(e)}catch{return J5(`the link is not a URL.`)}if(n.protocol!==`${t}:`)return J5(`\`${q5(n.protocol)}\` is not the selected protocol scheme.`);if(n.hash.length>0)return J5(`the link carries a fragment.`);if(mGe(n)!==`open`)return J5(`the only accepted launch verb is ${t}://open.`);let r=hGe(n);return Y5(r)?r:vGe(r)}function bGe(e){let t=e.trim().replace(/\.git$/,``),n=/^[^@\s]+@[^:\s]+:(?<owner>[^/\s]+)\/(?<name>[^/\s]+)$/u.exec(t);if(n?.groups)return`${n.groups.owner}/${n.groups.name}`;let r=/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(?<owner>[^/\s]+)\/(?<name>[^/\s]+)$/iu.exec(t);if(r?.groups)return`${r.groups.owner}/${r.groups.name}`}function X5(e){return{ok:!1,reason:e}}async function Z5(e,t){let n;try{n=await t.inspectTrust(e)}catch(t){return X5(`the workspace trust state of ${q5(e)} could not be read (${q5(String(t))}); the link is refused rather than opened unchecked.`)}return n===`trusted`?{ok:!0,cwd:e}:X5(`${q5(e)} is not a trusted workspace (${n}). A link opens only what you have already trusted — run \`${t.cliName} trust --yes\` there first.`)}async function xGe(e,t){let n;try{n=await t.listGrants()}catch(e){return X5(`the workspace trust store could not be read (${q5(String(e))}).`)}if(n===void 0)return X5("this host cannot list workspace trust grants, so `repo=` cannot be resolved; open the link with `cwd=` instead.");let r=new Map;for(let i of n){if(i.state!==`trusted`)continue;let n=await t.readRemoteUrl(i.worktreeRoot);if(n===void 0||bGe(n)!==e)continue;let a=r.get(i.repositoryKey)??[];a.push(i.worktreeRoot),r.set(i.repositoryKey,a)}if(r.size===0)return X5(`no trusted local clone of \`${q5(e)}\` is recorded. Open the link with \`cwd=<absolute path>\`, or run this CLI in that clone and trust it first.`);if(r.size>1){let t=[...r.values()].flat().join(`, `);return X5(`\`${q5(e)}\` matches more than one trusted repository: ${q5(t)}.`)}let i=([...r.values()][0]??[]).find(e=>t.isMainWorktree(e));return i===void 0?X5(`\`${q5(e)}\` resolves only to linked worktrees, with no main worktree among the trusted ones; open the link with \`cwd=\` to say which.`):Z5(i,t)}async function SGe(e,t){if(e.cwd!==void 0){let n=t.realDirectory(e.cwd);return n===void 0?X5(`${q5(e.cwd)} does not exist or is not a directory.`):Z5(n,t)}return e.repo===void 0?X5(`the link names no target.`):xGe(e.repo,t)}function CGe(){return[`config`,`--get`,`remote.origin.url`]}function wGe(e){return async t=>{let n=await e.run(CGe(),{cwd:t,timeoutMs:1e4});if(n.kind!==`exited`||n.exitCode!==0)return;let r=n.stdout.trim();return r.length>0?r:void 0}}const Q5=`open`;function $5(e){return{kind:`refused`,message:e,exitCode:1}}async function TGe(e,t){if(e[2]!==`open`)return{kind:`not-an-open-invocation`};let n=dGe(t.cliName,t.protocolScheme),r=e.slice(3);if(r.includes(`--help`)||r.includes(`-h`))return{kind:`not-an-open-invocation`};let i=r[0];if(i===void 0)return $5(`\`${Q5}\` needs a link.\n${n}`);if(r.slice(1).some(e=>e.toLowerCase().startsWith(`${t.protocolScheme}:`)))return $5(`\`${Q5}\` takes exactly one link; a second one was given.\n${n}`);let a=yGe(i,t.protocolScheme);if(!a.ok)return $5(`Link refused: ${a.reason}`);let o=await SGe(a.intent,t);return o.ok?t.isInteractive()?{kind:`launch`,cwd:o.cwd,initialInput:a.intent.prompt}:$5(`a prefilled session needs an interactive terminal; the prompt is never submitted on its own.`):$5(`Link refused: ${o.reason}`)}function EGe(e){e[2]===`open`&&e.splice(2,2)}function DGe(e){try{let t=Cn(e);return Dn(t).isDirectory()?t:void 0}catch{return}}function OGe(e){try{return Dn(M(e,`.git`)).isDirectory()}catch{return!1}}function kGe(e){let t=sf(pq(e).workspaceTrust),n=of(),r=wGe(Gb());return{protocolScheme:e.config.identity.protocolScheme,cliName:e.vocabulary.cliName,listGrants:async()=>t.listGrants?t.listGrants():void 0,inspectTrust:async e=>{let r;try{r=n.resolve(e)}catch{return`unknown`}return(await t.inspect(r)).state},realDirectory:DGe,readRemoteUrl:r,isMainWorktree:OGe,isInteractive:()=>process.stdout.isTTY===!0&&process.stdin.isTTY===!0}}async function AGe(e){let t=await TGe(process.argv,kGe(e));return t.kind===`not-an-open-invocation`?{kind:`continue`}:t.kind===`refused`?(process.stderr.write(`${t.message}\n`),process.exitCode=t.exitCode,{kind:`refused`}):(process.chdir(t.cwd),EGe(process.argv),{kind:`launched`,initialInput:t.initialInput})}const e7=(e,t=!1,n={})=>new Promise((r,i)=>{if(n.signal?.aborted){i(new DOMException(`Input cancelled.`,`AbortError`));return}process.stdout.write(e);let a=``,o=process.stdin,s=o.isRaw;if(!o.isTTY){i(Error(`Cannot prompt for input: stdin is not a TTY.
2868
+ `.replaceAll(`{{cli}}`,o.config.identity.cliName)),process.exitCode=1,!0;let i,a;try{a=lGe(e),i=rO(e.grantFiles),a!==void 0&&$A({grants:i,trustedProxies:a.trustedProxies})}catch(e){return process.stderr.write(`${e instanceof Error?e.message:`grant refused`}\n`),process.exitCode=1,!0}if(kD(m.projectAccess)&&!(e.restricted&&h4(m.projectAccess)))return process.stderr.write(`${AD(m.projectAccess,n,o.config.identity.cliName)}\n`),process.exitCode=1,!0;try{S1(r,{telemetryServiceName:o.config.identity.telemetryServiceName,serviceVersion:I1(o),surface:`serve`}),(e.restricted||m.projectAccess.status===`restricted`)&&process.stderr.write(`${jD(o.layout.projectSettingsPaths)}\n`),e.restricted&&l.set(n,Rq(n,{productRuntime:o,projectAccess:$d(`untrusted`,n)}).settingsSources);let t=await v3(n,{productRuntime:o,env:u(),...e.name===void 0?{}:{name:e.name},...e.restricted?{restricted:!0}:{},...i.length>0&&a!==void 0?{grants:i,eventEndpoint:a}:{}});process.stdout.write(`Supervised session: ${t}\n`)}catch(e){process.stderr.write(`${e instanceof Error?e.message:`Supervised session could not start.`}\n`),process.exitCode=1}return!0}return t[2]===`eval`?(process.exitCode=await P1(t.slice(3),n,{settingsSources:m.settingsSources,projectAccess:m.projectAccess,environment:o.environment,resolveProviderCredential:(s.providerConnectionHost??gq(o)).resolveCredential}),!0):!1}const W5=[`v`,`prompt`,`cwd`,`repo`];function fGe(e,t){return`Usage: ${e} open '${t}://open?v=1&prompt=<text>[&cwd=<absolute path>|&repo=<owner/name>]'`}function G5(e){return[...e].length}const pGe=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/u,K5=/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/u,mGe=/^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/;function q5(e){let t=[...e].map(e=>K5.test(e)?`\\u{${(e.codePointAt(0)??0).toString(16)}}`:e).join(``),n=[...t];return n.length>80?`${n.slice(0,80).join(``)}\u2026`:t}function J5(e){return{ok:!1,reason:e}}function hGe(e){let t=e.host.toLowerCase(),n=e.pathname;return t.length>0?n===``||n===`/`?t:void 0:n.toLowerCase()}function Y5(e){return typeof e==`object`&&!!e&&!(e instanceof Map)}function gGe(e){let t=new Map;for(let[n,r]of e.searchParams){if(!W5.includes(n))return J5(`\`${q5(n)}\` is not an accepted key; only ${W5.join(`, `)} are.`);if(t.has(n))return J5(`\`${q5(n)}\` appears more than once.`);t.set(n,r)}return t}function _Ge(e){if(e===void 0)return;let t=e.replace(/\r\n/g,`
2869
+ `);return t.includes(`\r`)?J5(`the prompt contains a carriage return.`):pGe.test(t)?J5(`the prompt contains a control or invisible formatting character.`):G5(t)>5e3?J5(`the prompt is longer than 5000 characters.`):t.trimStart().startsWith(`/`)?J5("a link may carry a prompt but not a command: the prompt begins with `/`."):t}function vGe(e){if(e===void 0)return;if(K5.test(e))return J5(`the cwd contains a control or invisible formatting character.`);if(e.startsWith(`\\\\`)||e.startsWith(`//`))return J5(`the cwd is a UNC or network path.`);let t=e.startsWith(`/`),n=/^[A-Za-z]:[\\/]/.test(e);return!t&&!n?J5(`the cwd is not an absolute path.`):e.split(/[\\/]/).includes(`..`)?J5("the cwd contains a `..` segment."):e}function yGe(e){let t=e.get(`v`);if(t===void 0)return J5("the link carries no `v`.");if(t!==`1`)return J5(`\`v=${q5(t)}\` is not version 1.`);let n=_Ge(e.get(`prompt`));if(Y5(n))return n;let r=vGe(e.get(`cwd`));if(Y5(r))return r;let i=e.get(`repo`);return i!==void 0&&!mGe.test(i)?J5(`\`${q5(i)}\` is not an \`owner/name\` slug.`):r===void 0&&i===void 0?J5("the link names no target: pass `cwd` or `repo`."):{ok:!0,intent:{version:t,prompt:n,cwd:r,repo:r===void 0?i:void 0,repoSuperseded:r!==void 0&&i!==void 0}}}function bGe(e,t){if(G5(e)>8192)return J5(`the link is longer than 8192 characters.`);let n;try{n=new URL(e)}catch{return J5(`the link is not a URL.`)}if(n.protocol!==`${t}:`)return J5(`\`${q5(n.protocol)}\` is not the selected protocol scheme.`);if(n.hash.length>0)return J5(`the link carries a fragment.`);if(hGe(n)!==`open`)return J5(`the only accepted launch verb is ${t}://open.`);let r=gGe(n);return Y5(r)?r:yGe(r)}function xGe(e){let t=e.trim().replace(/\.git$/,``),n=/^[^@\s]+@[^:\s]+:(?<owner>[^/\s]+)\/(?<name>[^/\s]+)$/u.exec(t);if(n?.groups)return`${n.groups.owner}/${n.groups.name}`;let r=/^[a-z][a-z0-9+.-]*:\/\/[^/]+\/(?<owner>[^/\s]+)\/(?<name>[^/\s]+)$/iu.exec(t);if(r?.groups)return`${r.groups.owner}/${r.groups.name}`}function X5(e){return{ok:!1,reason:e}}async function Z5(e,t){let n;try{n=await t.inspectTrust(e)}catch(t){return X5(`the workspace trust state of ${q5(e)} could not be read (${q5(String(t))}); the link is refused rather than opened unchecked.`)}return n===`trusted`?{ok:!0,cwd:e}:X5(`${q5(e)} is not a trusted workspace (${n}). A link opens only what you have already trusted — run \`${t.cliName} trust --yes\` there first.`)}async function SGe(e,t){let n;try{n=await t.listGrants()}catch(e){return X5(`the workspace trust store could not be read (${q5(String(e))}).`)}if(n===void 0)return X5("this host cannot list workspace trust grants, so `repo=` cannot be resolved; open the link with `cwd=` instead.");let r=new Map;for(let i of n){if(i.state!==`trusted`)continue;let n=await t.readRemoteUrl(i.worktreeRoot);if(n===void 0||xGe(n)!==e)continue;let a=r.get(i.repositoryKey)??[];a.push(i.worktreeRoot),r.set(i.repositoryKey,a)}if(r.size===0)return X5(`no trusted local clone of \`${q5(e)}\` is recorded. Open the link with \`cwd=<absolute path>\`, or run this CLI in that clone and trust it first.`);if(r.size>1){let t=[...r.values()].flat().join(`, `);return X5(`\`${q5(e)}\` matches more than one trusted repository: ${q5(t)}.`)}let i=([...r.values()][0]??[]).find(e=>t.isMainWorktree(e));return i===void 0?X5(`\`${q5(e)}\` resolves only to linked worktrees, with no main worktree among the trusted ones; open the link with \`cwd=\` to say which.`):Z5(i,t)}async function CGe(e,t){if(e.cwd!==void 0){let n=t.realDirectory(e.cwd);return n===void 0?X5(`${q5(e.cwd)} does not exist or is not a directory.`):Z5(n,t)}return e.repo===void 0?X5(`the link names no target.`):SGe(e.repo,t)}function wGe(){return[`config`,`--get`,`remote.origin.url`]}function TGe(e){return async t=>{let n=await e.run(wGe(),{cwd:t,timeoutMs:1e4});if(n.kind!==`exited`||n.exitCode!==0)return;let r=n.stdout.trim();return r.length>0?r:void 0}}const Q5=`open`;function $5(e){return{kind:`refused`,message:e,exitCode:1}}async function EGe(e,t){if(e[2]!==`open`)return{kind:`not-an-open-invocation`};let n=fGe(t.cliName,t.protocolScheme),r=e.slice(3);if(r.includes(`--help`)||r.includes(`-h`))return{kind:`not-an-open-invocation`};let i=r[0];if(i===void 0)return $5(`\`${Q5}\` needs a link.\n${n}`);if(r.slice(1).some(e=>e.toLowerCase().startsWith(`${t.protocolScheme}:`)))return $5(`\`${Q5}\` takes exactly one link; a second one was given.\n${n}`);let a=bGe(i,t.protocolScheme);if(!a.ok)return $5(`Link refused: ${a.reason}`);let o=await CGe(a.intent,t);return o.ok?t.isInteractive()?{kind:`launch`,cwd:o.cwd,initialInput:a.intent.prompt}:$5(`a prefilled session needs an interactive terminal; the prompt is never submitted on its own.`):$5(`Link refused: ${o.reason}`)}function DGe(e){e[2]===`open`&&e.splice(2,2)}function OGe(e){try{let t=Cn(e);return Dn(t).isDirectory()?t:void 0}catch{return}}function kGe(e){try{return Dn(M(e,`.git`)).isDirectory()}catch{return!1}}function AGe(e){let t=sf(pq(e).workspaceTrust),n=of(),r=TGe(Gb());return{protocolScheme:e.config.identity.protocolScheme,cliName:e.vocabulary.cliName,listGrants:async()=>t.listGrants?t.listGrants():void 0,inspectTrust:async e=>{let r;try{r=n.resolve(e)}catch{return`unknown`}return(await t.inspect(r)).state},realDirectory:OGe,readRemoteUrl:r,isMainWorktree:kGe,isInteractive:()=>process.stdout.isTTY===!0&&process.stdin.isTTY===!0}}async function jGe(e){let t=await EGe(process.argv,AGe(e));return t.kind===`not-an-open-invocation`?{kind:`continue`}:t.kind===`refused`?(process.stderr.write(`${t.message}\n`),process.exitCode=t.exitCode,{kind:`refused`}):(process.chdir(t.cwd),DGe(process.argv),{kind:`launched`,initialInput:t.initialInput})}const e7=(e,t=!1,n={})=>new Promise((r,i)=>{if(n.signal?.aborted){i(new DOMException(`Input cancelled.`,`AbortError`));return}process.stdout.write(e);let a=``,o=process.stdin,s=o.isRaw;if(!o.isTTY){i(Error(`Cannot prompt for input: stdin is not a TTY.
2870
2870
  Set your API key via environment variable instead:
2871
2871
  ANTHROPIC_API_KEY=<key>
2872
2872
  OPENAI_API_KEY=<key>`));return}o.setRawMode(!0),o.resume(),o.setEncoding(`utf8`);let c=!1,l=()=>{c=!0,o.removeListener(`data`,d),n.signal?.removeEventListener(`abort`,u),o.setRawMode(s??!1),o.pause(),process.stdout.write(`
2873
2873
  `)},u=()=>{c||(l(),a=``,i(new DOMException(`Input cancelled.`,`AbortError`)))},d=e=>{for(let i of e)if(i===`\r`||i===`
2874
- `){l(),r(a.trim());return}else if(i===``||i===`\b`)a.length>0&&(a=a.slice(0,-1),process.stdout.write(`\b \b`));else if(i===``){if(n.signal!==void 0){u();return}l(),process.exit(0)}else i.charCodeAt(0)>=32&&(a+=i,process.stdout.write(t?`*`:i))};o.on(`data`,d),n.signal?.addEventListener(`abort`,u,{once:!0})});function jGe(e=e7){return{async ask(t,n){let r=n?.signal??new AbortController().signal,i=t.options??[],a=[`\n ${t.title}`,t.description,...i.map((e,t)=>` ${t+1}. ${e.label}`),i.length>0?` Choose [1-${i.length}] (Ctrl+C to cancel): `:` `].filter(e=>e!==void 0).join(`
2875
- `);try{let n=await e(a,t.masked===!0,{signal:r});if(r.aborted)return{type:`cancelled`};if(t.allowFreeText===!0)return{type:`answer`,values:[],text:n};let o=n.trim().length===0?t.default?.values?.[0]:i[Number(n)-1]?.value??i.find(e=>e.value===n)?.value;return o===void 0?{type:`cancelled`}:{type:`answer`,values:[o]}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return{type:`cancelled`};throw e}}}}const t7=[`sessions/`,`logs/`,`checkpoints/`,`settings.local.json`];function MGe(e,t,n){let r=`${n.layout.projectDirectory}/.gitignore`,i=e.readText(r,`inspect runtime data ignore rules`),a=i===void 0?[]:i.split(`
2874
+ `){l(),r(a.trim());return}else if(i===``||i===`\b`)a.length>0&&(a=a.slice(0,-1),process.stdout.write(`\b \b`));else if(i===``){if(n.signal!==void 0){u();return}l(),process.exit(0)}else i.charCodeAt(0)>=32&&(a+=i,process.stdout.write(t?`*`:i))};o.on(`data`,d),n.signal?.addEventListener(`abort`,u,{once:!0})});function MGe(e=e7){return{async ask(t,n){let r=n?.signal??new AbortController().signal,i=t.options??[],a=[`\n ${t.title}`,t.description,...i.map((e,t)=>` ${t+1}. ${e.label}`),i.length>0?` Choose [1-${i.length}] (Ctrl+C to cancel): `:` `].filter(e=>e!==void 0).join(`
2875
+ `);try{let n=await e(a,t.masked===!0,{signal:r});if(r.aborted)return{type:`cancelled`};if(t.allowFreeText===!0)return{type:`answer`,values:[],text:n};let o=n.trim().length===0?t.default?.values?.[0]:i[Number(n)-1]?.value??i.find(e=>e.value===n)?.value;return o===void 0?{type:`cancelled`}:{type:`answer`,values:[o]}}catch(e){if(e instanceof Error&&e.name===`AbortError`)return{type:`cancelled`};throw e}}}}const t7=[`sessions/`,`logs/`,`checkpoints/`,`settings.local.json`];function NGe(e,t,n){let r=`${n.layout.projectDirectory}/.gitignore`,i=e.readText(r,`inspect runtime data ignore rules`),a=i===void 0?[]:i.split(`
2876
2876
  `),o=new Set(a.map(e=>e.trim())),s=t7.filter(e=>!o.has(e));if(i!==void 0&&s.length===0)return`unchanged`;let c=i===void 0?[`# Agent runtime session data — transcripts, tool output and machine-local settings.`,...t7].join(`
2877
2877
  `):[...a.filter((e,t)=>t<a.length-1||e!==``),...s].join(`
2878
- `);return t.writeBytes(r,new TextEncoder().encode(`${c}\n`),`initialize runtime data ignore rules`),i===void 0?`created`:`updated`}function NGe(e){let t=e.readText(`.claude/settings.json`,`migrate Claude project settings`);if(t===void 0)return{};try{return JSON.parse(t)}catch{return null}}var PGe=class extends Error{constructor(e){super(`Cannot ask "${e}" in a non-interactive shell. Re-run with --yes to accept the defaults.`),this.name=`InitPromptUnavailableError`}};async function n7(e,t,n){if(n.yes||n.ci)return n.terminal.writeLine(`${e} → ${t?`Y`:`N`} (${n.yes?`--yes`:`CI`}: using default)`),t;if(!n.isTTY)throw new PGe(e);let r=await n.promptFn(`${e} [y/N] `);return r.toLowerCase()===`y`||r.toLowerCase()===`yes`}async function FGe(e,t){if(t.projectAccess.status!==`trusted`)throw new U(`Project initialization requires project access.`);if(t.projectMutation===void 0)throw new U(`Project initialization requires project mutation permission.`);let n=Ld(t.projectAccess.authority),r=Zd(t.projectMutation,t.projectAccess.authority),i=t.productRuntime,a=`${i.layout.projectDirectory}/settings.json`,o=`${i.layout.projectDirectory}/.gitignore`,s={permissions:{allow:i.layout.baselinePermissionAllow,deny:[]}};e.writeLine(``),e.writeLine(`${i.vocabulary.cliName} project initialization`),e.writeLine(`─`.repeat(40));let c={yes:t.yes===!0,ci:t.ci??t.productRuntime.environment.CI===`true`,isTTY:t.isTTY??process.stdin.isTTY===!0,promptFn:t.promptFn??e7,terminal:e},l=MGe(n,r,i);e.writeLine(``),e.writeLine(l===`unchanged`?`Unchanged: ${o} (already covers runtime session data)`:`${l===`created`?`Created`:`Updated`}: ${o}`);let u=n.inspectKind(`.claude`,`inspect Claude project settings`)===`directory`,d=n.inspectKind(a,`inspect product project settings`)===`file`,f=n.inspectKind(`AGENTS.md`,`inspect project instructions`)===`file`;if(d&&f&&(e.writeLine(``),e.writeLine(`Both AGENTS.md and ${a} already exist.`),!await n7(`Overwrite existing files?`,!1,c))){e.writeLine(`Init cancelled.`);return}let p={...s};if(u&&(e.writeLine(``),e.writeLine(`Detected .claude/ directory (Claude Code configuration).`),await n7(`Migrate Claude Code settings to ${i.layout.projectDirectory}/?`,!1,c))){let t=NGe(n);if(t===null)e.writeLine(`Warning: .claude/settings.json could not be parsed — skipping migration.`);else{let n=t.permissions;p={...t,permissions:{...typeof t.permissions==`object`&&t.permissions!==null?t.permissions:{},allow:[...s.permissions.allow,...n?.allow??[]],deny:n?.deny??[]}},e.writeLine(`Settings imported from .claude/settings.json.`)}}r.writeBytes(a,new TextEncoder().encode(`${JSON.stringify(p,null,2)}\n`),`initialize product project settings`),e.writeLine(``),e.writeLine(`Created: ${a}`),r.writeBytes(`AGENTS.md`,new TextEncoder().encode(`# AGENTS.md — Project Agent Guidelines
2878
+ `);return t.writeBytes(r,new TextEncoder().encode(`${c}\n`),`initialize runtime data ignore rules`),i===void 0?`created`:`updated`}function PGe(e){let t=e.readText(`.claude/settings.json`,`migrate Claude project settings`);if(t===void 0)return{};try{return JSON.parse(t)}catch{return null}}var FGe=class extends Error{constructor(e){super(`Cannot ask "${e}" in a non-interactive shell. Re-run with --yes to accept the defaults.`),this.name=`InitPromptUnavailableError`}};async function n7(e,t,n){if(n.yes||n.ci)return n.terminal.writeLine(`${e} → ${t?`Y`:`N`} (${n.yes?`--yes`:`CI`}: using default)`),t;if(!n.isTTY)throw new FGe(e);let r=await n.promptFn(`${e} [y/N] `);return r.toLowerCase()===`y`||r.toLowerCase()===`yes`}async function IGe(e,t){if(t.projectAccess.status!==`trusted`)throw new U(`Project initialization requires project access.`);if(t.projectMutation===void 0)throw new U(`Project initialization requires project mutation permission.`);let n=Ld(t.projectAccess.authority),r=Zd(t.projectMutation,t.projectAccess.authority),i=t.productRuntime,a=`${i.layout.projectDirectory}/settings.json`,o=`${i.layout.projectDirectory}/.gitignore`,s={permissions:{allow:i.layout.baselinePermissionAllow,deny:[]}};e.writeLine(``),e.writeLine(`${i.vocabulary.cliName} project initialization`),e.writeLine(`─`.repeat(40));let c={yes:t.yes===!0,ci:t.ci??t.productRuntime.environment.CI===`true`,isTTY:t.isTTY??process.stdin.isTTY===!0,promptFn:t.promptFn??e7,terminal:e},l=NGe(n,r,i);e.writeLine(``),e.writeLine(l===`unchanged`?`Unchanged: ${o} (already covers runtime session data)`:`${l===`created`?`Created`:`Updated`}: ${o}`);let u=n.inspectKind(`.claude`,`inspect Claude project settings`)===`directory`,d=n.inspectKind(a,`inspect product project settings`)===`file`,f=n.inspectKind(`AGENTS.md`,`inspect project instructions`)===`file`;if(d&&f&&(e.writeLine(``),e.writeLine(`Both AGENTS.md and ${a} already exist.`),!await n7(`Overwrite existing files?`,!1,c))){e.writeLine(`Init cancelled.`);return}let p={...s};if(u&&(e.writeLine(``),e.writeLine(`Detected .claude/ directory (Claude Code configuration).`),await n7(`Migrate Claude Code settings to ${i.layout.projectDirectory}/?`,!1,c))){let t=PGe(n);if(t===null)e.writeLine(`Warning: .claude/settings.json could not be parsed — skipping migration.`);else{let n=t.permissions;p={...t,permissions:{...typeof t.permissions==`object`&&t.permissions!==null?t.permissions:{},allow:[...s.permissions.allow,...n?.allow??[]],deny:n?.deny??[]}},e.writeLine(`Settings imported from .claude/settings.json.`)}}r.writeBytes(a,new TextEncoder().encode(`${JSON.stringify(p,null,2)}\n`),`initialize product project settings`),e.writeLine(``),e.writeLine(`Created: ${a}`),r.writeBytes(`AGENTS.md`,new TextEncoder().encode(`# AGENTS.md — Project Agent Guidelines
2879
2879
 
2880
2880
  This file guides the AI agent working in this project. Customize it for your project.
2881
2881
 
@@ -2905,16 +2905,16 @@ npm run build
2905
2905
  ## Important Notes
2906
2906
 
2907
2907
  <!-- Anything the agent should know before making changes -->
2908
- `),`initialize project instructions`),e.writeLine(`Created: AGENTS.md`),e.writeLine(``),e.writeLine(`Initialization complete.`),e.writeLine(``),e.writeLine(`Next steps:`),e.writeLine(` 1. Edit AGENTS.md to describe your project conventions`),e.writeLine(` 2. Run \`${i.vocabulary.cliName} --configure\` to set up your AI provider`),e.writeLine(` 3. Run \`${i.vocabulary.cliName}\` to start the assistant`),e.writeLine(``),t.onProviderSetup!==void 0&&(c.isTTY||c.yes||c.ci)&&await n7(`Would you like to set up a provider now?`,!1,c)&&await t.onProviderSetup()}async function IGe(e){let{cwd:t,args:n,terminal:r,providerDefinitions:i,workspace:a}=e,o=aD(e.startOptions),s={cliName:o.config.identity.cliName,env:o.environment,settingsSources:a.settingsSources,settingsStores:a.settingsStores,connectionHost:e.providerConnectionHost,interaction:jGe(),orgPolicy:e.orgPolicy};if(DD(n)===`init`)return await LGe(e,s),{handled:!0};if(n.configure)return await QK(t,n,e7,r,i,s),{handled:!0};if(await FCe(t,n,r,i,s))return{handled:!0};try{await ICe(t,n,e7,r,i,DD(n)===`mcp`&&n.positional[1]===`serve`||DD(n)===`acp`?!1:void 0,s)}catch(e){if(e instanceof hy&&n.serve)return{handled:!1,setupRequired:e.message};process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(e instanceof hy&&n.printMode?3:1)}return{handled:!1}}async function LGe(e,t){let{cwd:n,args:r,startOptions:i,terminal:a,providerDefinitions:o,workspace:s}=e;try{await FGe(a,{productRuntime:aD(i),projectAccess:s.projectAccess,...i.projectMutation===void 0?{}:{projectMutation:i.projectMutation},yes:r.yes,onProviderSetup:()=>QK(n,r,e7,a,o,t)})}catch(e){a.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}}function RGe(e,t,n=()=>!1){if(e!==void 0)return{initialInput:e,initialInputOrigin:`external-link`};let r=t[0];if(r!==void 0&&n(r))return{};let i=t.join(` `).trim();return i===``?{}:{initialInput:i}}function zGe(e,t){if(!e.serve||e.httpPort===void 0)return;let n=t.PRODUCT_HTTP_TOKEN;if(FD(e)){if(n!==void 0&&n!==``)throw Error(`PRODUCT_HTTP_TOKEN is loopback-only and cannot be combined with remote authorization`);return{port:e.httpPort,remote:ID(e)}}if(LD(e,`--serve --http-port`),n===void 0||n===``)throw Error(`--serve --http-port needs PRODUCT_HTTP_TOKEN: the bearer every HTTP client presents`);if(n.length<32)throw Error(`PRODUCT_HTTP_TOKEN must be at least 32 characters`);return{port:e.httpPort,token:n}}function BGe(){return{sealRecord:_k,chunk:(e,t)=>IEe(e,t),verifyPayload:(e,t)=>vk(e,t),createAssembler:e=>{let t=new LEe(e);return{accept:e=>t.accept(e)}},decodeRecord:Qo}}const VGe=[`-c`,`protocol.allow=never`,`-c`,`core.sshCommand=`,`-c`,`core.hooksPath=/dev/null`,`-c`,`core.fsmonitor=false`],HGe=[`PATH`,`HOME`,`TMPDIR`,`TMP`,`TEMP`,`SystemRoot`,`WINDIR`,`LANG`,`LC_ALL`,`LC_CTYPE`,`XDG_RUNTIME_DIR`];function UGe(e){let t={};for(let n of HGe){let r=e[n];r!==void 0&&(t[n]=r)}return t.GIT_NO_LAZY_FETCH=`1`,t}const r7=(e,t)=>{let n=UGe(process.env);return new Promise(r=>{nn(`git`,[...VGe,...t],{cwd:e,env:n,encoding:`utf8`,timeout:2e3,maxBuffer:64*1024},(e,t)=>{if(e===null)return r({code:0,stdout:t.trim()});let n=e.code;r(typeof n==`number`&&e.killed!==!0?{code:n,stdout:t.trim()}:void 0)})})};function i7(e){try{return Cn(e)}catch{return}}function WGe(e){let t=e.trim(),n=/^(?:[^@/]+@)?([^:/]+):(?!\/)(.*)$/.exec(t),r=``,i=t;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&n!==null)r=n[1]??``,i=n[2]??``;else try{let e=new URL(t);r=e.hostname,i=e.pathname}catch{}let a=i.replace(/\/+$/,``).replace(/\.git$/,``).replace(/^\/+/,``);return`${r.toLowerCase()}/${a}`}function GGe(e){return Vn(`sha256`).update(WGe(e)).digest(`hex`)}async function a7(e,t=r7){let n=i7(e);if(n===void 0)return;let r=await t(n,[`rev-parse`,`--show-toplevel`]),i=r?.code===0&&r.stdout?i7(r.stdout):void 0;if(i===void 0)return;let a=await t(i,[`rev-parse`,`--verify`,`-q`,`HEAD`]);if(a===void 0||a.code!==0&&(a.code!==1||a.stdout!==``))return;let o=[];if(a.code===0){let e=await t(i,[`rev-list`,`--max-parents=0`,`HEAD`]);if(e?.code!==0||e.stdout===``)return;o=e.stdout.split(/\s+/).sort()}let s=await t(i,[`config`,`--get`,`remote.origin.url`]);if(!(s===void 0||s.code!==0&&s.code!==1))return{worktreePath:i,rootCommits:o,...s.code===0&&s.stdout?{originUrlHash:GGe(s.stdout)}:{}}}function KGe(e){let t=e;return typeof t==`object`&&!!t&&typeof t.worktreePath==`string`&&Array.isArray(t.rootCommits)&&t.rootCommits.every(e=>typeof e==`string`)&&(t.originUrlHash===void 0||typeof t.originUrlHash==`string`)}function o7(e,t){return e===void 0||t===void 0?e===t:e.worktreePath===t.worktreePath&&e.originUrlHash===t.originUrlHash&&e.rootCommits.length===t.rootCommits.length&&e.rootCommits.every((e,n)=>e===t.rootCommits[n])}function qGe(e,t){return e.worktreePath===t.worktreePath?`same-worktree`:e.rootCommits.some(e=>t.rootCommits.includes(e))?`same-repo`:e.rootCommits.length>0&&t.rootCommits.length>0?`different-repo`:e.originUrlHash!==void 0&&t.originUrlHash!==void 0?e.originUrlHash===t.originUrlHash?`same-repo`:`different-repo`:`unknown`}async function JGe(e,t,n=a7){if(t===void 0)return{relation:`unknown`,claim:`absent`};if(!KGe(t))return{relation:`unknown`,claim:`mismatched`};let r=await n(t.worktreePath);return r===void 0||!o7(r,t)?{relation:`unknown`,claim:`mismatched`}:e===void 0?{relation:`unknown`,claim:`verified`}:{relation:qGe(e,r),claim:`verified`}}const YGe=new Set([`queued`,`running`,`waiting_permission`,`sleeping`,`paused`]);function s7(e,t){let n=QZ(t.cryptoContext,M(e,`devices`));if(n===void 0)return;let r=n.deviceCertificate;return{userId:n.userId,deviceId:r.deviceId,certificateOf:e=>e===r.deviceId?r:n.roster.devices.find(t=>t.deviceId===e)}}function XGe(e,t){return yt(D(t,e.name))===void 0||(e.apiKey??``)!==``}async function ZGe(e){let t=await r7(e,[`status`,`--porcelain`]);return t!==void 0&&t.code===0&&t.stdout!==``}async function QGe(e,t,n){let r=QZ(n.cryptoContext,M(e,`devices`));if(r===void 0)return;let i=await WZ(t,n.config.credentials.serviceNamespace,r.deviceCertificate);return i===void 0?void 0:{userId:r.userId,signPrivateKey:i.signPrivateKey,deviceId:r.deviceCertificate.deviceId}}function $Ge(e,t){return e.id===t.id&&e.updatedAt===t.updatedAt&&e.messages.length===t.messages.length&&(e.history?.length??0)===(t.history?.length??0)}function c7(e){return{state:`stopped`,reason:e,stillMine:!0}}function eKe(e){return e.phase===`committed`?{state:`done`,stillMine:!1}:c7(e.detail??e.refusal??`the transfer did not complete`)}function tKe(e){let t=e.now??Date.now,n=e.uncommittedChanges??ZGe,r={state:`offered`,stillMine:!0},i=!1,a,o=async()=>{let t=e.getSession();if(t===void 0)return{uncommittedChanges:!1,subprocesses:0};let r=t.listBackgroundTasks?.()??[];return{uncommittedChanges:await n(t.getCwd()),subprocesses:r.filter(e=>YGe.has(e.status)).length}},s=async(n,i)=>{if(a!==void 0&&a.target!==n)return c7(`an earlier hand-off to ${a.target} was not confirmed and may already be saved there; run /handoff ${a.target} to settle it first`);let s=e.getSession(),c=a?.target===n?a.toDevice:e.devices?.list().some(e=>e.deviceId===n)===!0,l=c?void 0:e.openChannel();if(s===void 0||!c&&l===void 0)return c7(`this session cannot reach other sessions yet`);let u=await QGe(e.root,e.store,e.productRuntime);if(u===void 0)return c7("this device has no identity to sign the hand-off with; run `/devices join` to join your other devices, or `/devices init` on your first device");let d=e.sessionStore.load(s.getSessionId());if(d.status!==`valid`)return c7(`this session has nothing saved to hand off yet`);let f=d.record,p=await o(),m=e=>{r={state:e,stillMine:!0},i?.(r)},h={modelCallInFlight:s.isExecuting(),subprocesses:p.subprocesses,uncommittedChanges:p.uncommittedChanges},g=vl(h);if(!g.ready)return c7(g.detail);if(a!==void 0&&!$Ge(a.request.record,f))return a=void 0,r=c7(`this session changed since the hand-off to ${n} that was not confirmed, so ${n} may hold an older copy of it. Check it there; /handoff again sends the current session as a new transfer`),r;let _=a===void 0?{handoffId:N(),sessionId:f.id,sourceDeviceId:c?u.deviceId:e.peers.ownSessionId(),destinationDeviceId:n,record:f,runtime:h,offeredAt:t()}:{...a.request,runtime:h},v={cryptoContext:e.productRuntime.cryptoContext,composition:e.composition,request:_,mintGrant:(n,r)=>sje(e.productRuntime.cryptoContext,u,n,r,t()),onReadOnly:()=>{r={state:`done`,stillMine:!1}},onProgress:m,...e.idleMs===void 0?{}:{idleMs:e.idleMs}},y;if(l!==void 0)({outcome:y}=await zQ({...v,openChannel:()=>l(n),carrierBinding:AQ(n)}));else{let t=e.devices;if(t===void 0)return c7(`${n} is not linked`);try{({outcome:y}=await t.push(n,v))}catch(e){return c7(e instanceof Error?e.message:String(e))}}let b=y.phase===`transferring`||y.phase===`staged`;return a=b?{target:n,request:_,toDevice:c}:void 0,r=b?c7(`${n} did not confirm; it may already have saved the session. Run /handoff ${n} again to settle it`):eKe(y),r.stillMine||e.onHandedOff(),r};return{destinations:async()=>[...e.peers.list().filter(t=>t.sessionId!==e.peers.ownSessionId()&&t.liveness!==`dead`).map(e=>({deviceId:e.sessionId,name:`another session on this machine`})),...(e.devices?.list()??[]).map(e=>({deviceId:e.deviceId,name:`${e.name??`unnamed`}, another of your devices`}))],staysBehind:o,transfer:async(e,t)=>{if(i)return c7(`a hand-off is already in progress`);if(!r.stillMine)return r;i=!0;try{return await s(e,t)}finally{i=!1}},status:()=>r}}function nKe(e,t,n){let r=s7(e.root,e.productRuntime);return{channel:n,carrierBinding:AQ(e.sessionId),destinationId:e.sessionId,sourceId:t.sessionId,signerDeviceId:r?.deviceId??``,senderDirectory:`local-${t.sessionId}`,authority:new gl({sessionId:t.sessionId,locality:`same-host`,capabilities:[`handoff`]},e.approver)}}function l7(e,t,n){if(!t.received)return`[handoff] a session from ${e} was not taken: ${t.detail}.`;let r=t.record?.id??t.manifest.sessionId;return`[handoff] session ${r} from ${e} is saved here and was not started. Resume it with: ${n(r)}`}function rKe(e,t){return`session ${e.sessionId} (${e.integrity.byteLength} bytes) onto ${t}. It is saved here, not started; resumed, it runs with this machine's provider credential, files and shell, and the other machine gives it up once this one has saved it.`}function iKe(e){return async(t,n)=>t.admitted?(await e.authority.authorize(`handoff`,{summary:rKe(n,e.deviceLabel),...e.signal===void 0?{}:{signal:e.signal}})).allowed:!1}const u7=3e4,d7=5e3,aKe=/^[A-Za-z0-9_-]{1,128}$/,oKe=/^[A-Za-z0-9_-]{43}$/,sKe=new Set([`transferred`,`rehydrated`,`source-local`,`never-transferred`]);function f7(e){return typeof e==`string`&&e.length>0&&e.length<=1024}function cKe(e){if(!Array.isArray(e)||e.length>64)return;let t=[];for(let n of e){if(typeof n!=`object`||!n)return;let{kind:e,disposition:r,note:i}=n;if(!f7(e)||typeof r!=`string`||!sKe.has(r)||i!==void 0&&!f7(i))return;t.push({kind:e,disposition:r,...i===void 0?{}:{note:i}})}return t}function lKe(e){if(typeof e!=`object`||!e)return;let t=e,{handoffId:n,sessionId:r,sourceDeviceId:i,destinationDeviceId:a,offeredAt:o,integrity:s}=t;if(typeof n!=`string`||!aKe.test(n)||!f7(r)||!f7(i)||!f7(a)||typeof o!=`number`||!Number.isFinite(o)||typeof s!=`object`||!s)return;let{digest:c,byteLength:l}=s;if(typeof c!=`string`||!oKe.test(c)||typeof l!=`number`||!Number.isSafeInteger(l)||l<0)return;let u=cKe(t.inventory);if(u!==void 0)return{handoffId:n,sessionId:r,sourceDeviceId:i,destinationDeviceId:a,inventory:u,integrity:{digest:c,byteLength:l},offeredAt:o}}var p7=class extends Error{reason;detail;constructor(e,t){super(t),this.reason=e,this.detail=t}},m7=class extends Error{reason;detail;constructor(e,t){super(t),this.reason=e,this.detail=t}};function h7(e){return new p7(e.refusal===`payload-undecodable`||e.refusal===`destination-cannot-resume`?e.refusal:`integrity-failed`,e.detail??`the session was not kept`)}async function uKe(e){let t=NQ(e.channel),n;try{let r=await t.next(u7);if(r.t===`handoff-pull`)throw new p7(`push-only`,`a session is only ever sent by the machine that holds it; its operator starts that with /handoff`);if(r.t!==`handoff-open`)throw new p7(`protocol`,`expected a hand-off to open`);let i=oje();t.send({t:`handoff-binding`,nonce:i});let a=await t.next(u7);if(a.t!==`handoff-offer`)throw new p7(`protocol`,`expected an offer`);let o=lKe(a.manifest);if(o===void 0)throw new p7(`protocol`,`the manifest could not be read`);if(o.destinationDeviceId!==e.destinationId)throw new p7(`unauthorized`,`the transfer is addressed to another destination`);let s=OQ(e.cryptoContext,e.carrierBinding,i),c=!1,l=await JY(vOe(a.grant),{verify:t=>e.verifyGrant(t,o,s),consent:t=>e.committed.has(o.handoffId)?Promise.resolve(!0):(c=!0,e.consent(t,o))});if(!l.admitted)throw new p7(c?`declined`:`unauthorized`,l.reason??`refused`);let u=e.committed.get(o.handoffId);if(u!==void 0)return t.send({t:`handoff-ack`,ack:u}),await t.closedWithin(d7),{received:!0,manifest:o};let d=new sae({composition:e.composition,deviceId:e.destinationId,resolveCredential:e.resolveCredential,persist:e.persist,...e.now===void 0?{}:{now:e.now}});d.receiveManifest(o),t.send({t:`handoff-accept`}),n=await dKe(t,e,o);let f=d.receivePayload(await er(n,`utf8`));if(f.state!==`staged`)throw h7(f);t.send({t:`handoff-staged`});let p;try{p=await d.commit()}catch(e){throw d.discard(`destination-cannot-resume`,e instanceof Error?e.message:String(e)),new p7(`destination-cannot-resume`,`the session could not be saved here`)}let m=d.acknowledgement(),h=d.liveRecord();if(p.state!==`committed`||m===null||h===null)throw h7(p);return e.committed.set(o.handoffId,m),t.send({t:`handoff-ack`,ack:m}),await t.closedWithin(d7),{received:!0,manifest:o,record:h}}catch(e){if(e instanceof m7)return{received:!1,reason:e.reason,detail:e.detail};if(e instanceof p7){try{t.send({t:`handoff-refuse`,reason:e.reason,detail:e.detail})}catch{}return await t.closedWithin(d7),{received:!1,reason:e.reason,detail:e.detail}}return{received:!1,reason:`closed`,detail:e instanceof Error?e.message:String(e)}}finally{n!==void 0&&await ir(n).catch(()=>void 0),t.close()}}async function dKe(e,t,n){let r=Buffer.from(n.integrity.digest,`base64url`).toString(`hex`),i=await oA({channel:e.fileChannel(),...t.maxBytes===void 0?{}:{maxBytes:t.maxBytes},admit:async e=>{if(e.transferId!==n.handoffId||e.size!==n.integrity.byteLength||e.sha256!==r)return{refused:`integrity`,detail:`the payload is not the one the manifest sealed`};let i=await _Q({root:t.root,senderId:t.senderId,name:`${n.handoffId}.json`,area:`handoff`});return`ok`in i?{sink:await vQ(i)}:i}});if(!i.ok)throw new m7(i.reason===`integrity`?`integrity-failed`:`protocol`,yQ(i.reason,i.detail));return i.location}function fKe(e){let t=new Map,n=new Set,r=e.now??Date.now;return async i=>{let a=new AbortController,o=i.channel.onClose(()=>a.abort()),s=iKe({authority:i.authority,deviceLabel:e.deviceLabel,signal:a.signal});try{return await uKe({cryptoContext:e.productRuntime.cryptoContext,channel:i.channel,carrierBinding:i.carrierBinding,destinationId:i.destinationId,senderId:i.senderDirectory,verifyGrant:async(t,a,o)=>{let s=e.identity(),c=s?.certificateOf(i.signerDeviceId);return s===void 0||c===void 0?{admitted:!1,trust:`unproven`,reason:"this device holds no certificate for the sender; run `/devices` to check"}:uje(e.productRuntime.cryptoContext,t,{sender:c,sourceId:i.sourceId,userId:s.userId,manifest:a,destinationId:i.destinationId,channelFingerprint:o,now:r(),seenNonces:n})},consent:s,composition:e.composition,root:e.root,resolveCredential:e.resolveCredential,persist:e.persist,committed:t,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},now:r})}finally{o()}}}const pKe=new Set([`.ssh`,`.gnupg`,`.aws`,`.azure`,`.kube`,`.docker`,`.password-store`,`gcloud`]),mKe=new Set([`.netrc`,`.npmrc`,`.pypirc`,`.git-credentials`,`.htpasswd`,`credentials`,`credentials.json`]),hKe=[/^\.env/i,/^id_(rsa|dsa|ecdsa|ed25519)(\..*)?$/i,/\.(pem|key|p12|pfx|jks|keystore|kdbx)$/i];function g7(e,t){if(t?.protectedPaths.some(t=>j.resolve(t)===j.resolve(e)||_7(j.resolve(t),j.resolve(e))))return!0;let n=j.resolve(e).split(j.sep).filter(e=>e!==``),r=n[n.length-1]??``;return mKe.has(r.toLowerCase())||hKe.some(e=>e.test(r))?!0:n.slice(0,-1).some(e=>pKe.has(e.toLowerCase())||t?.protectedDirectoryNames.includes(e)===!0)}function _7(e,t){let n=j.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!j.isAbsolute(n)}function gKe(e){return new Promise((t,n)=>{let r=Vn(`sha256`);dn(e).on(`data`,e=>r.update(e)).on(`error`,n).on(`end`,()=>t(r.digest(`hex`)))})}async function _Ke(e){let t=e.path.trim();if(t===``)return{ok:!1,reason:`no file was named.`};if((t===`~`||t.startsWith(`~/`))&&e.home===void 0)return{ok:!1,reason:`Home-relative file paths require an explicit home directory.`};let n=t===`~`||t.startsWith(`~/`)?j.join(e.home,t.slice(1)):t,r=j.resolve(e.cwd,n),i;try{i=await nr(r)}catch{return{ok:!1,reason:`${r} does not exist or cannot be read.`}}let a=await rr(i);if(!a.isFile())return{ok:!1,reason:`${r} is not a regular file.`};if(a.size>e.maxBytes)return{ok:!1,reason:`${r} is ${a.size} bytes, over the ${e.maxBytes}-byte limit.`};if(e.origin===`model`){if(!_7(await nr(e.cwd).catch(()=>j.resolve(e.cwd)),i)||!_7(j.resolve(e.cwd),r))return{ok:!1,reason:`${r} is outside the workspace. Only the operator can send it, with /peers send-file.`};if(g7(r,e.pathProtection)||g7(i,e.pathProtection))return{ok:!1,reason:`${r} looks like it holds secrets. Only the operator can send it, with /peers send-file.`}}let o=await gKe(i),s=a.size;return{ok:!0,file:{path:r,name:j.basename(r),size:s,sha256:o,source:{size:s,read:()=>dn(i)}}}}const v7=1e3,y7=5e3;function vKe(e){let t=Mze(e);if(!t.admitted||t.binding===void 0)throw Error(`local peer presence: the rendezvous directory was not admitted, so this session cannot be announced as same-user-same-host. ${t.reason??`No reason was given.`}`);return t.binding.guardedDirectory}function yKe(e,t,n,r){let i,a=!1,o=e=>{a||(a=!0,process.emitWarning(`Local peer liveness certification delayed: ${e}`))},s=e=>{i=setTimeout(()=>{if(!r())try{c(t(!0))}catch(e){o(e instanceof Error?e.message:String(e)),s(y7)}},e),i.unref?.()},c=t=>{if(t.startTimePrecision!==`seconds`)return;let n=t.startSecondMs;if(typeof n!=`number`){o(`The process birth second is unavailable.`),s(y7);return}if(t.announcedAt>=n+v7)return;let r=Math.max(1,Math.min(v7,n+v7+1-(e.now??Date.now)()));s(r)};return c(n),()=>{i&&clearTimeout(i)}}function bKe(e){let t=e.guardedDirectory??vKe(e.productRuntime),n={guardedDirectory:t,...e.registry};jze(n);let r={sessionId:e.sessionId,...e.name===void 0?{}:{name:e.name}},i=!1,a,o,s,c=(e=!1)=>(o=kze(n,{...r,...s===void 0?{}:{workspace:s},...a===void 0?{}:{status:a},...e?{requireStartTime:!0}:{}}),o),l=yKe(n,c,c(),()=>i),u,d=()=>(u??=a7(e.workspaceDirectory??process.cwd()).then(e=>{i||o7(e,s)||(s=e,c())}).catch(e=>{process.emitWarning(`Local peer workspace refresh failed: ${String(e)}`)}).finally(()=>{u=void 0}),u);d();let f=setInterval(()=>{if(!i&&(d(),a!==void 0))try{c(!0)}catch(e){process.emitWarning(`Local peer status refresh failed: ${String(e)}`)}},1e4);f.unref?.();let p=()=>{i||(i=!0,l(),clearInterval(f),Aze(n,e.sessionId,o))};(e.on??((e,t)=>process.on(e,t)))(`exit`,p);let m=(e,t)=>({sessionId:e.entry.sessionId,...e.entry.name===void 0?{}:{name:e.entry.name},liveness:e.liveness,status:e.status,...t===void 0?{}:{workspaceRelation:t.relation,workspaceClaim:t.claim}}),h=new Map,g=t=>{if(t.entry.sessionId===e.sessionId||t.liveness===`dead`)return;let n=JSON.stringify([t.entry.announcedAt,t.entry.workspace??null,s??null]),r=h.get(t.entry.sessionId);if(r?.key===n)return r.verdict;let i=JGe(s,t.entry.workspace);return h.set(t.entry.sessionId,{key:n,verdict:i}),i};return{sessionId:e.sessionId,guardedDirectory:t,list:()=>E4(n).map(e=>m(e)),listWithWorkspace:()=>Promise.all(E4(n).map(async e=>m(e,await g(e)))),relate:async e=>{let t=E4(n).find(t=>t.entry.sessionId===e);return t===void 0?void 0:g(t)},refreshWorkspace:d,publishStatus:e=>{i||(a=e,c(!0))},withdraw:()=>{p(),(e.off??((e,t)=>process.off(e,t)))(`exit`,p)}}}function xKe(e,t,n=e=>process.emitWarning(e)){let r,i=!1,a=!1,o=t=>{if(!(t===r&&!a))try{e.publishStatus(t),r=t,a=!1,i=!1}catch(e){if(a=!0,i)return;i=!0,n(`Local peer activity publication failed: ${String(e)}`)}},s=()=>{if(!t.isActiveForPeerStatus){o(void 0);return}try{o(t.getSession().getLocalActivityStatus())}catch(e){if(o(void 0),i)return;i=!0,n(`Local peer activity observation failed: ${String(e)}`)}};s();let c=setInterval(s,250);return c.unref?.(),()=>{clearInterval(c);try{e.publishStatus(void 0)}catch(e){n(`Local peer activity reset failed: ${String(e)}`)}}}function b7(e){return{receive:t=>new $fe({submit:(n,r,i)=>e().submit(n,void 0,void 0,{turnSource:`peer`,...r.driverId===void 0?{}:{driverId:r.driverId},onAccepted:i,peer:{messageId:t.message.id,replyTo:r.sessionId}})}).receive(t)}}function SKe(e){return typeof e.getLocalActivityStatus==`function`}function CKe(e){return{getStatus:()=>e.getStatus(),describeKeyStorage:()=>e.describeKeyStorage(),listDevices:()=>e.listDevices().map(e=>({deviceId:e.deviceId,label:e.label,lastSeenAt:e.lastSeenAt})),revokeDevice:t=>e.revokeDevice(t),enable:()=>e.enable(),stop:()=>e.stop()}}function wKe(e,t,n){return{list:()=>e.list(),listWithWorkspace:()=>e.listWithWorkspace(),ownSessionId:()=>e.sessionId,...t===void 0?{}:{listDevices:()=>t.devices(),...x7(void 0,t,n)}}}function x7(e,t,n){let r={state:`failed`,reason:`this session cannot reach other sessions yet`};return{send:async(n,i,a)=>{let o=t?.isLinked(n)===!0?await t.send(n,i,a):e===void 0?r:await e.send(n,i,a);return{state:o.state,...o.reason===void 0?{}:{reason:o.reason}}},prepareFile:async(i,a,{origin:o,cwd:s})=>{let c=await _Ke({path:a,cwd:s,home:n.userHome??(()=>{throw Error(`File paths using home require an explicit host home.`)})(),origin:o,maxBytes:33554432,pathProtection:n.layout.pathProtection});if(!c.ok)return c;let{file:l}=c;return{ok:!0,file:{path:l.path,size:l.size,sha256:l.sha256,send:async()=>t?.isLinked(i)===!0?t.sendFile(i,l):e===void 0?r:e.sendFile(i,l)}}}}}function TKe(e,t,n,r){return{list:()=>[],ownSessionId:()=>t,localDiscoveryOff:n,listDevices:()=>e.devices(),...x7(void 0,e,r)}}function EKe(e,t,n,r=bKe,i){let a=N();try{let t=r({sessionId:a,productRuntime:n});return e.localPeers=wKe(t,i,n),t}catch(r){let o=r instanceof Error?r.message:String(r);t.writeError(`Local peer discovery is off for this session: ${o}`),i!==void 0&&(e.localPeers=TKe(i,a,o,n));return}}function DKe(e,t,n,r,i,a=n$,o,s,c,l){let u=e.localPeers;return t===void 0||u===void 0?Promise.resolve(void 0):OKe(o,r).then(()=>kKe(u,t,n,r,a,s,c,l,i))}async function OKe(e,t){if(e!==void 0)try{await(await e)?.close()}catch(e){t.writeError(`A previous local peer listener could not be closed: ${e instanceof Error?e.message:String(e)}`)}}function kKe(e,t,n,r,i,a,o,s,c){return i({...a===void 0?{}:{files:a},...o===void 0?{}:{onHandoff:o},guardedDirectory:t.guardedDirectory,sessionId:t.sessionId,list:()=>t.list(),relate:async e=>(await t.relate(e))?.relation,report:e=>r.writeError(e),ingress:b7(n)}).then(t=>(Object.assign(e,x7(t,s,c)),t),e=>{r.writeError(`Local peer messaging is off for this session, though discovery is on: ${e instanceof Error?e.message:String(e)}`)})}function AKe(e,t,n,r,i,a,o){e.remoteControl=CKe(t);let s=EKe(e,n,r,i,o),c={},l=a!==void 0&&(s!==void 0||o!==void 0)?jKe(e,s,t,n,a,()=>c,o,r):void 0,u,d;return i=>{if(d?.(),d=void 0,s!==void 0){let e=i.getSession();SKe(e)&&typeof i.isActiveForPeerStatus==`boolean`&&(d=xKe(s,{getSession:()=>e,get isActiveForPeerStatus(){return i.isActiveForPeerStatus===!0}},e=>n.writeError(e)))}c={session:i.getSession()};let a=c;o?.bind({ingress:b7(()=>i.getSession())}),u=DKe(e,s,()=>i.getSession(),n,r,n$,u,{root:mq(r),...t.operatorApprover===void 0?{}:{approver:t.operatorApprover}},l,o),u.then(e=>{c===a&&e!==void 0&&(c={...a,messaging:e})})}}function S7(e){let t=e;return t!==void 0&&typeof t.getSessionId==`function`&&typeof t.getCwd==`function`&&typeof t.isExecuting==`function`?t:void 0}function jKe(e,t,n,r,i,a,o,s){let c=mq(s),l=sq({root:c,serviceNamespace:s.config.credentials.serviceNamespace,notify:()=>{}}),u=BGe();e.handoff=tKe({productRuntime:s,root:c,store:l.store,composition:u,sessionStore:i.sessionStore,getSession:()=>S7(a().session),peers:{list:()=>t?.list()??[],ownSessionId:()=>t?.sessionId??e.localPeers?.ownSessionId()??``},openChannel:()=>{let e=a().messaging;return e===void 0?void 0:t=>e.openHandoffChannel(t)},...o===void 0?{}:{devices:{list:()=>o.devices(),push:(e,t)=>o.handoff(e,t)}},onHandedOff:i.onHandedOff});let d=fKe({productRuntime:s,root:c,composition:u,identity:()=>s7(c,s),resolveCredential:i.hasOwnProvider,persist:e=>{let t=S7(a().session)?.getCwd()??e.cwd;return i.sessionStore.save({...e,cwd:t}),!0},deviceLabel:`this session`});return o?.bind({handoff:{receive:d,onOutcome:(e,t)=>r.writeError(l7(`device ${e}`,t,s.vocabulary.resumeCommand))}}),(e,i)=>{if(t===void 0){i.close();return}let a=nKe({sessionId:t.sessionId,productRuntime:s,root:c,...n.operatorApprover===void 0?{}:{approver:n.operatorApprover}},e,i);d(a).then(t=>r.writeError(l7(e.sessionId,t,s.vocabulary.resumeCommand)))}}function MKe(){let e=()=>{setTimeout(()=>process.kill(process.pid,`SIGTERM`),500).unref?.()};return{requestExit:()=>e(),requestRestart:()=>e()}}function NKe(e,t){if(!t||xq(e).includes(`--safe-mode`))return[...e];let n=e.indexOf(`--`);return n===-1?[...e,Iq]:[...e.slice(0,n),Iq,...e.slice(n)]}async function PKe(e,t){return e.restricted?$d(`untrusted`,e.targetCwd):t(e.targetCwd)}function FKe(e){let t=e.resolveAccess??(t=>Lq(t,{productRuntime:e.productRuntime})),n=e.onProcessExit??(e=>void process.once(`exit`,e)),r=e.runSync??sn;return{async move(i){let a=await PKe(i,t),o=zq({productRuntime:e.productRuntime,cwd:i.targetCwd,userHome:e.userHome,projectAccess:a}),s=Tg(i.record,o.sessionStore);o.sessionStore.save(s);let c=Uve(e.argv,{resumeId:s.id,movedFrom:i.fromCwd,restricted:a.status===`restricted`}),l=T1();n(()=>{let t=r(l.execPath,[...l.execArgv??[],...l.args,...c],{cwd:i.targetCwd,stdio:`inherit`,env:{...x4(e.productRuntime,o.settingsSources,e.providerDefinitions??[]),...e.environment}});process.exitCode=t.status??1}),e.requestExit()}}}function C7(e){return{...e.commandProductVocabulary===void 0?{}:{commandProductVocabulary:e.commandProductVocabulary},...e.pathProtection===void 0?{}:{pathProtection:e.pathProtection},...e.cliAppendSystemPrompt===void 0?{}:{appendSystemPrompt:e.cliAppendSystemPrompt},...e.allowedTools===void 0?{}:{allowedTools:e.allowedTools},...e.deniedTools===void 0?{}:{deniedTools:e.deniedTools}}}async function IKe(e,t,n,r,i,a,o,s,c,l,u,d={},f={},p={},m,h,g,_,v,y,b,x,S,C,w,T,E,ee,te,ne,re,ie,ae){let oe=n.goal?.trim(),se=n.positional.join(` `).trim();if(!oe&&!se&&!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);se=Buffer.concat(e).toString(`utf-8`).trim()}!oe&&!se&&(process.stderr.write(`Print mode (-p) requires a prompt argument (or --goal <objective>).
2908
+ `),`initialize project instructions`),e.writeLine(`Created: AGENTS.md`),e.writeLine(``),e.writeLine(`Initialization complete.`),e.writeLine(``),e.writeLine(`Next steps:`),e.writeLine(` 1. Edit AGENTS.md to describe your project conventions`),e.writeLine(` 2. Run \`${i.vocabulary.cliName} --configure\` to set up your AI provider`),e.writeLine(` 3. Run \`${i.vocabulary.cliName}\` to start the assistant`),e.writeLine(``),t.onProviderSetup!==void 0&&(c.isTTY||c.yes||c.ci)&&await n7(`Would you like to set up a provider now?`,!1,c)&&await t.onProviderSetup()}async function LGe(e){let{cwd:t,args:n,terminal:r,providerDefinitions:i,workspace:a}=e,o=aD(e.startOptions),s={cliName:o.config.identity.cliName,env:o.environment,settingsSources:a.settingsSources,settingsStores:a.settingsStores,connectionHost:e.providerConnectionHost,interaction:MGe(),orgPolicy:e.orgPolicy};if(DD(n)===`init`)return await RGe(e,s),{handled:!0};if(n.configure)return await QK(t,n,e7,r,i,s),{handled:!0};if(await FCe(t,n,r,i,s))return{handled:!0};try{await ICe(t,n,e7,r,i,DD(n)===`mcp`&&n.positional[1]===`serve`||DD(n)===`acp`?!1:void 0,s)}catch(e){if(e instanceof hy&&n.serve)return{handled:!1,setupRequired:e.message};process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(e instanceof hy&&n.printMode?3:1)}return{handled:!1}}async function RGe(e,t){let{cwd:n,args:r,startOptions:i,terminal:a,providerDefinitions:o,workspace:s}=e;try{await IGe(a,{productRuntime:aD(i),projectAccess:s.projectAccess,...i.projectMutation===void 0?{}:{projectMutation:i.projectMutation},yes:r.yes,onProviderSetup:()=>QK(n,r,e7,a,o,t)})}catch(e){a.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}}function zGe(e,t,n=()=>!1){if(e!==void 0)return{initialInput:e,initialInputOrigin:`external-link`};let r=t[0];if(r!==void 0&&n(r))return{};let i=t.join(` `).trim();return i===``?{}:{initialInput:i}}function BGe(e,t){if(!e.serve||e.httpPort===void 0)return;let n=t.PRODUCT_HTTP_TOKEN;if(FD(e)){if(n!==void 0&&n!==``)throw Error(`PRODUCT_HTTP_TOKEN is loopback-only and cannot be combined with remote authorization`);return{port:e.httpPort,remote:ID(e)}}if(LD(e,`--serve --http-port`),n===void 0||n===``)throw Error(`--serve --http-port needs PRODUCT_HTTP_TOKEN: the bearer every HTTP client presents`);if(n.length<32)throw Error(`PRODUCT_HTTP_TOKEN must be at least 32 characters`);return{port:e.httpPort,token:n}}function VGe(){return{sealRecord:_k,chunk:(e,t)=>IEe(e,t),verifyPayload:(e,t)=>vk(e,t),createAssembler:e=>{let t=new LEe(e);return{accept:e=>t.accept(e)}},decodeRecord:Qo}}const HGe=[`-c`,`protocol.allow=never`,`-c`,`core.sshCommand=`,`-c`,`core.hooksPath=/dev/null`,`-c`,`core.fsmonitor=false`],UGe=[`PATH`,`HOME`,`TMPDIR`,`TMP`,`TEMP`,`SystemRoot`,`WINDIR`,`LANG`,`LC_ALL`,`LC_CTYPE`,`XDG_RUNTIME_DIR`];function WGe(e){let t={};for(let n of UGe){let r=e[n];r!==void 0&&(t[n]=r)}return t.GIT_NO_LAZY_FETCH=`1`,t}const r7=(e,t)=>{let n=WGe(process.env);return new Promise(r=>{nn(`git`,[...HGe,...t],{cwd:e,env:n,encoding:`utf8`,timeout:2e3,maxBuffer:64*1024},(e,t)=>{if(e===null)return r({code:0,stdout:t.trim()});let n=e.code;r(typeof n==`number`&&e.killed!==!0?{code:n,stdout:t.trim()}:void 0)})})};function i7(e){try{return Cn(e)}catch{return}}function GGe(e){let t=e.trim(),n=/^(?:[^@/]+@)?([^:/]+):(?!\/)(.*)$/.exec(t),r=``,i=t;if(!/^[a-z][a-z0-9+.-]*:\/\//i.test(t)&&n!==null)r=n[1]??``,i=n[2]??``;else try{let e=new URL(t);r=e.hostname,i=e.pathname}catch{}let a=i.replace(/\/+$/,``).replace(/\.git$/,``).replace(/^\/+/,``);return`${r.toLowerCase()}/${a}`}function KGe(e){return Vn(`sha256`).update(GGe(e)).digest(`hex`)}async function a7(e,t=r7){let n=i7(e);if(n===void 0)return;let r=await t(n,[`rev-parse`,`--show-toplevel`]),i=r?.code===0&&r.stdout?i7(r.stdout):void 0;if(i===void 0)return;let a=await t(i,[`rev-parse`,`--verify`,`-q`,`HEAD`]);if(a===void 0||a.code!==0&&(a.code!==1||a.stdout!==``))return;let o=[];if(a.code===0){let e=await t(i,[`rev-list`,`--max-parents=0`,`HEAD`]);if(e?.code!==0||e.stdout===``)return;o=e.stdout.split(/\s+/).sort()}let s=await t(i,[`config`,`--get`,`remote.origin.url`]);if(!(s===void 0||s.code!==0&&s.code!==1))return{worktreePath:i,rootCommits:o,...s.code===0&&s.stdout?{originUrlHash:KGe(s.stdout)}:{}}}function qGe(e){let t=e;return typeof t==`object`&&!!t&&typeof t.worktreePath==`string`&&Array.isArray(t.rootCommits)&&t.rootCommits.every(e=>typeof e==`string`)&&(t.originUrlHash===void 0||typeof t.originUrlHash==`string`)}function o7(e,t){return e===void 0||t===void 0?e===t:e.worktreePath===t.worktreePath&&e.originUrlHash===t.originUrlHash&&e.rootCommits.length===t.rootCommits.length&&e.rootCommits.every((e,n)=>e===t.rootCommits[n])}function JGe(e,t){return e.worktreePath===t.worktreePath?`same-worktree`:e.rootCommits.some(e=>t.rootCommits.includes(e))?`same-repo`:e.rootCommits.length>0&&t.rootCommits.length>0?`different-repo`:e.originUrlHash!==void 0&&t.originUrlHash!==void 0?e.originUrlHash===t.originUrlHash?`same-repo`:`different-repo`:`unknown`}async function YGe(e,t,n=a7){if(t===void 0)return{relation:`unknown`,claim:`absent`};if(!qGe(t))return{relation:`unknown`,claim:`mismatched`};let r=await n(t.worktreePath);return r===void 0||!o7(r,t)?{relation:`unknown`,claim:`mismatched`}:e===void 0?{relation:`unknown`,claim:`verified`}:{relation:JGe(e,r),claim:`verified`}}const XGe=new Set([`queued`,`running`,`waiting_permission`,`sleeping`,`paused`]);function s7(e,t){let n=QZ(t.cryptoContext,M(e,`devices`));if(n===void 0)return;let r=n.deviceCertificate;return{userId:n.userId,deviceId:r.deviceId,certificateOf:e=>e===r.deviceId?r:n.roster.devices.find(t=>t.deviceId===e)}}function ZGe(e,t){return yt(D(t,e.name))===void 0||(e.apiKey??``)!==``}async function QGe(e){let t=await r7(e,[`status`,`--porcelain`]);return t!==void 0&&t.code===0&&t.stdout!==``}async function $Ge(e,t,n){let r=QZ(n.cryptoContext,M(e,`devices`));if(r===void 0)return;let i=await WZ(t,n.config.credentials.serviceNamespace,r.deviceCertificate);return i===void 0?void 0:{userId:r.userId,signPrivateKey:i.signPrivateKey,deviceId:r.deviceCertificate.deviceId}}function eKe(e,t){return e.id===t.id&&e.updatedAt===t.updatedAt&&e.messages.length===t.messages.length&&(e.history?.length??0)===(t.history?.length??0)}function c7(e){return{state:`stopped`,reason:e,stillMine:!0}}function tKe(e){return e.phase===`committed`?{state:`done`,stillMine:!1}:c7(e.detail??e.refusal??`the transfer did not complete`)}function nKe(e){let t=e.now??Date.now,n=e.uncommittedChanges??QGe,r={state:`offered`,stillMine:!0},i=!1,a,o=async()=>{let t=e.getSession();if(t===void 0)return{uncommittedChanges:!1,subprocesses:0};let r=t.listBackgroundTasks?.()??[];return{uncommittedChanges:await n(t.getCwd()),subprocesses:r.filter(e=>XGe.has(e.status)).length}},s=async(n,i)=>{if(a!==void 0&&a.target!==n)return c7(`an earlier hand-off to ${a.target} was not confirmed and may already be saved there; run /handoff ${a.target} to settle it first`);let s=e.getSession(),c=a?.target===n?a.toDevice:e.devices?.list().some(e=>e.deviceId===n)===!0,l=c?void 0:e.openChannel();if(s===void 0||!c&&l===void 0)return c7(`this session cannot reach other sessions yet`);let u=await $Ge(e.root,e.store,e.productRuntime);if(u===void 0)return c7("this device has no identity to sign the hand-off with; run `/devices join` to join your other devices, or `/devices init` on your first device");let d=e.sessionStore.load(s.getSessionId());if(d.status!==`valid`)return c7(`this session has nothing saved to hand off yet`);let f=d.record,p=await o(),m=e=>{r={state:e,stillMine:!0},i?.(r)},h={modelCallInFlight:s.isExecuting(),subprocesses:p.subprocesses,uncommittedChanges:p.uncommittedChanges},g=vl(h);if(!g.ready)return c7(g.detail);if(a!==void 0&&!eKe(a.request.record,f))return a=void 0,r=c7(`this session changed since the hand-off to ${n} that was not confirmed, so ${n} may hold an older copy of it. Check it there; /handoff again sends the current session as a new transfer`),r;let _=a===void 0?{handoffId:N(),sessionId:f.id,sourceDeviceId:c?u.deviceId:e.peers.ownSessionId(),destinationDeviceId:n,record:f,runtime:h,offeredAt:t()}:{...a.request,runtime:h},v={cryptoContext:e.productRuntime.cryptoContext,composition:e.composition,request:_,mintGrant:(n,r)=>sje(e.productRuntime.cryptoContext,u,n,r,t()),onReadOnly:()=>{r={state:`done`,stillMine:!1}},onProgress:m,...e.idleMs===void 0?{}:{idleMs:e.idleMs}},y;if(l!==void 0)({outcome:y}=await zQ({...v,openChannel:()=>l(n),carrierBinding:AQ(n)}));else{let t=e.devices;if(t===void 0)return c7(`${n} is not linked`);try{({outcome:y}=await t.push(n,v))}catch(e){return c7(e instanceof Error?e.message:String(e))}}let b=y.phase===`transferring`||y.phase===`staged`;return a=b?{target:n,request:_,toDevice:c}:void 0,r=b?c7(`${n} did not confirm; it may already have saved the session. Run /handoff ${n} again to settle it`):tKe(y),r.stillMine||e.onHandedOff(),r};return{destinations:async()=>[...e.peers.list().filter(t=>t.sessionId!==e.peers.ownSessionId()&&t.liveness!==`dead`).map(e=>({deviceId:e.sessionId,name:`another session on this machine`})),...(e.devices?.list()??[]).map(e=>({deviceId:e.deviceId,name:`${e.name??`unnamed`}, another of your devices`}))],staysBehind:o,transfer:async(e,t)=>{if(i)return c7(`a hand-off is already in progress`);if(!r.stillMine)return r;i=!0;try{return await s(e,t)}finally{i=!1}},status:()=>r}}function rKe(e,t,n){let r=s7(e.root,e.productRuntime);return{channel:n,carrierBinding:AQ(e.sessionId),destinationId:e.sessionId,sourceId:t.sessionId,signerDeviceId:r?.deviceId??``,senderDirectory:`local-${t.sessionId}`,authority:new gl({sessionId:t.sessionId,locality:`same-host`,capabilities:[`handoff`]},e.approver)}}function l7(e,t,n){if(!t.received)return`[handoff] a session from ${e} was not taken: ${t.detail}.`;let r=t.record?.id??t.manifest.sessionId;return`[handoff] session ${r} from ${e} is saved here and was not started. Resume it with: ${n(r)}`}function iKe(e,t){return`session ${e.sessionId} (${e.integrity.byteLength} bytes) onto ${t}. It is saved here, not started; resumed, it runs with this machine's provider credential, files and shell, and the other machine gives it up once this one has saved it.`}function aKe(e){return async(t,n)=>t.admitted?(await e.authority.authorize(`handoff`,{summary:iKe(n,e.deviceLabel),...e.signal===void 0?{}:{signal:e.signal}})).allowed:!1}const u7=3e4,d7=5e3,oKe=/^[A-Za-z0-9_-]{1,128}$/,sKe=/^[A-Za-z0-9_-]{43}$/,cKe=new Set([`transferred`,`rehydrated`,`source-local`,`never-transferred`]);function f7(e){return typeof e==`string`&&e.length>0&&e.length<=1024}function lKe(e){if(!Array.isArray(e)||e.length>64)return;let t=[];for(let n of e){if(typeof n!=`object`||!n)return;let{kind:e,disposition:r,note:i}=n;if(!f7(e)||typeof r!=`string`||!cKe.has(r)||i!==void 0&&!f7(i))return;t.push({kind:e,disposition:r,...i===void 0?{}:{note:i}})}return t}function uKe(e){if(typeof e!=`object`||!e)return;let t=e,{handoffId:n,sessionId:r,sourceDeviceId:i,destinationDeviceId:a,offeredAt:o,integrity:s}=t;if(typeof n!=`string`||!oKe.test(n)||!f7(r)||!f7(i)||!f7(a)||typeof o!=`number`||!Number.isFinite(o)||typeof s!=`object`||!s)return;let{digest:c,byteLength:l}=s;if(typeof c!=`string`||!sKe.test(c)||typeof l!=`number`||!Number.isSafeInteger(l)||l<0)return;let u=lKe(t.inventory);if(u!==void 0)return{handoffId:n,sessionId:r,sourceDeviceId:i,destinationDeviceId:a,inventory:u,integrity:{digest:c,byteLength:l},offeredAt:o}}var p7=class extends Error{reason;detail;constructor(e,t){super(t),this.reason=e,this.detail=t}},m7=class extends Error{reason;detail;constructor(e,t){super(t),this.reason=e,this.detail=t}};function h7(e){return new p7(e.refusal===`payload-undecodable`||e.refusal===`destination-cannot-resume`?e.refusal:`integrity-failed`,e.detail??`the session was not kept`)}async function dKe(e){let t=NQ(e.channel),n;try{let r=await t.next(u7);if(r.t===`handoff-pull`)throw new p7(`push-only`,`a session is only ever sent by the machine that holds it; its operator starts that with /handoff`);if(r.t!==`handoff-open`)throw new p7(`protocol`,`expected a hand-off to open`);let i=oje();t.send({t:`handoff-binding`,nonce:i});let a=await t.next(u7);if(a.t!==`handoff-offer`)throw new p7(`protocol`,`expected an offer`);let o=uKe(a.manifest);if(o===void 0)throw new p7(`protocol`,`the manifest could not be read`);if(o.destinationDeviceId!==e.destinationId)throw new p7(`unauthorized`,`the transfer is addressed to another destination`);let s=OQ(e.cryptoContext,e.carrierBinding,i),c=!1,l=await JY(vOe(a.grant),{verify:t=>e.verifyGrant(t,o,s),consent:t=>e.committed.has(o.handoffId)?Promise.resolve(!0):(c=!0,e.consent(t,o))});if(!l.admitted)throw new p7(c?`declined`:`unauthorized`,l.reason??`refused`);let u=e.committed.get(o.handoffId);if(u!==void 0)return t.send({t:`handoff-ack`,ack:u}),await t.closedWithin(d7),{received:!0,manifest:o};let d=new sae({composition:e.composition,deviceId:e.destinationId,resolveCredential:e.resolveCredential,persist:e.persist,...e.now===void 0?{}:{now:e.now}});d.receiveManifest(o),t.send({t:`handoff-accept`}),n=await fKe(t,e,o);let f=d.receivePayload(await er(n,`utf8`));if(f.state!==`staged`)throw h7(f);t.send({t:`handoff-staged`});let p;try{p=await d.commit()}catch(e){throw d.discard(`destination-cannot-resume`,e instanceof Error?e.message:String(e)),new p7(`destination-cannot-resume`,`the session could not be saved here`)}let m=d.acknowledgement(),h=d.liveRecord();if(p.state!==`committed`||m===null||h===null)throw h7(p);return e.committed.set(o.handoffId,m),t.send({t:`handoff-ack`,ack:m}),await t.closedWithin(d7),{received:!0,manifest:o,record:h}}catch(e){if(e instanceof m7)return{received:!1,reason:e.reason,detail:e.detail};if(e instanceof p7){try{t.send({t:`handoff-refuse`,reason:e.reason,detail:e.detail})}catch{}return await t.closedWithin(d7),{received:!1,reason:e.reason,detail:e.detail}}return{received:!1,reason:`closed`,detail:e instanceof Error?e.message:String(e)}}finally{n!==void 0&&await ir(n).catch(()=>void 0),t.close()}}async function fKe(e,t,n){let r=Buffer.from(n.integrity.digest,`base64url`).toString(`hex`),i=await oA({channel:e.fileChannel(),...t.maxBytes===void 0?{}:{maxBytes:t.maxBytes},admit:async e=>{if(e.transferId!==n.handoffId||e.size!==n.integrity.byteLength||e.sha256!==r)return{refused:`integrity`,detail:`the payload is not the one the manifest sealed`};let i=await _Q({root:t.root,senderId:t.senderId,name:`${n.handoffId}.json`,area:`handoff`});return`ok`in i?{sink:await vQ(i)}:i}});if(!i.ok)throw new m7(i.reason===`integrity`?`integrity-failed`:`protocol`,yQ(i.reason,i.detail));return i.location}function pKe(e){let t=new Map,n=new Set,r=e.now??Date.now;return async i=>{let a=new AbortController,o=i.channel.onClose(()=>a.abort()),s=aKe({authority:i.authority,deviceLabel:e.deviceLabel,signal:a.signal});try{return await dKe({cryptoContext:e.productRuntime.cryptoContext,channel:i.channel,carrierBinding:i.carrierBinding,destinationId:i.destinationId,senderId:i.senderDirectory,verifyGrant:async(t,a,o)=>{let s=e.identity(),c=s?.certificateOf(i.signerDeviceId);return s===void 0||c===void 0?{admitted:!1,trust:`unproven`,reason:"this device holds no certificate for the sender; run `/devices` to check"}:uje(e.productRuntime.cryptoContext,t,{sender:c,sourceId:i.sourceId,userId:s.userId,manifest:a,destinationId:i.destinationId,channelFingerprint:o,now:r(),seenNonces:n})},consent:s,composition:e.composition,root:e.root,resolveCredential:e.resolveCredential,persist:e.persist,committed:t,...e.maxBytes===void 0?{}:{maxBytes:e.maxBytes},now:r})}finally{o()}}}const mKe=new Set([`.ssh`,`.gnupg`,`.aws`,`.azure`,`.kube`,`.docker`,`.password-store`,`gcloud`]),hKe=new Set([`.netrc`,`.npmrc`,`.pypirc`,`.git-credentials`,`.htpasswd`,`credentials`,`credentials.json`]),gKe=[/^\.env/i,/^id_(rsa|dsa|ecdsa|ed25519)(\..*)?$/i,/\.(pem|key|p12|pfx|jks|keystore|kdbx)$/i];function g7(e,t){if(t?.protectedPaths.some(t=>j.resolve(t)===j.resolve(e)||_7(j.resolve(t),j.resolve(e))))return!0;let n=j.resolve(e).split(j.sep).filter(e=>e!==``),r=n[n.length-1]??``;return hKe.has(r.toLowerCase())||gKe.some(e=>e.test(r))?!0:n.slice(0,-1).some(e=>mKe.has(e.toLowerCase())||t?.protectedDirectoryNames.includes(e)===!0)}function _7(e,t){let n=j.relative(e,t);return n!==``&&!n.startsWith(`..`)&&!j.isAbsolute(n)}function _Ke(e){return new Promise((t,n)=>{let r=Vn(`sha256`);dn(e).on(`data`,e=>r.update(e)).on(`error`,n).on(`end`,()=>t(r.digest(`hex`)))})}async function vKe(e){let t=e.path.trim();if(t===``)return{ok:!1,reason:`no file was named.`};if((t===`~`||t.startsWith(`~/`))&&e.home===void 0)return{ok:!1,reason:`Home-relative file paths require an explicit home directory.`};let n=t===`~`||t.startsWith(`~/`)?j.join(e.home,t.slice(1)):t,r=j.resolve(e.cwd,n),i;try{i=await nr(r)}catch{return{ok:!1,reason:`${r} does not exist or cannot be read.`}}let a=await rr(i);if(!a.isFile())return{ok:!1,reason:`${r} is not a regular file.`};if(a.size>e.maxBytes)return{ok:!1,reason:`${r} is ${a.size} bytes, over the ${e.maxBytes}-byte limit.`};if(e.origin===`model`){if(!_7(await nr(e.cwd).catch(()=>j.resolve(e.cwd)),i)||!_7(j.resolve(e.cwd),r))return{ok:!1,reason:`${r} is outside the workspace. Only the operator can send it, with /peers send-file.`};if(g7(r,e.pathProtection)||g7(i,e.pathProtection))return{ok:!1,reason:`${r} looks like it holds secrets. Only the operator can send it, with /peers send-file.`}}let o=await _Ke(i),s=a.size;return{ok:!0,file:{path:r,name:j.basename(r),size:s,sha256:o,source:{size:s,read:()=>dn(i)}}}}const v7=1e3,y7=5e3;function yKe(e){let t=Mze(e);if(!t.admitted||t.binding===void 0)throw Error(`local peer presence: the rendezvous directory was not admitted, so this session cannot be announced as same-user-same-host. ${t.reason??`No reason was given.`}`);return t.binding.guardedDirectory}function bKe(e,t,n,r){let i,a=!1,o=e=>{a||(a=!0,process.emitWarning(`Local peer liveness certification delayed: ${e}`))},s=e=>{i=setTimeout(()=>{if(!r())try{c(t(!0))}catch(e){o(e instanceof Error?e.message:String(e)),s(y7)}},e),i.unref?.()},c=t=>{if(t.startTimePrecision!==`seconds`)return;let n=t.startSecondMs;if(typeof n!=`number`){o(`The process birth second is unavailable.`),s(y7);return}if(t.announcedAt>=n+v7)return;let r=Math.max(1,Math.min(v7,n+v7+1-(e.now??Date.now)()));s(r)};return c(n),()=>{i&&clearTimeout(i)}}function xKe(e){let t=e.guardedDirectory??yKe(e.productRuntime),n={guardedDirectory:t,...e.registry};jze(n);let r={sessionId:e.sessionId,...e.name===void 0?{}:{name:e.name}},i=!1,a,o,s,c=(e=!1)=>(o=kze(n,{...r,...s===void 0?{}:{workspace:s},...a===void 0?{}:{status:a},...e?{requireStartTime:!0}:{}}),o),l=bKe(n,c,c(),()=>i),u,d=()=>(u??=a7(e.workspaceDirectory??process.cwd()).then(e=>{i||o7(e,s)||(s=e,c())}).catch(e=>{process.emitWarning(`Local peer workspace refresh failed: ${String(e)}`)}).finally(()=>{u=void 0}),u);d();let f=setInterval(()=>{if(!i&&(d(),a!==void 0))try{c(!0)}catch(e){process.emitWarning(`Local peer status refresh failed: ${String(e)}`)}},1e4);f.unref?.();let p=()=>{i||(i=!0,l(),clearInterval(f),Aze(n,e.sessionId,o))};(e.on??((e,t)=>process.on(e,t)))(`exit`,p);let m=(e,t)=>({sessionId:e.entry.sessionId,...e.entry.name===void 0?{}:{name:e.entry.name},liveness:e.liveness,status:e.status,...t===void 0?{}:{workspaceRelation:t.relation,workspaceClaim:t.claim}}),h=new Map,g=t=>{if(t.entry.sessionId===e.sessionId||t.liveness===`dead`)return;let n=JSON.stringify([t.entry.announcedAt,t.entry.workspace??null,s??null]),r=h.get(t.entry.sessionId);if(r?.key===n)return r.verdict;let i=YGe(s,t.entry.workspace);return h.set(t.entry.sessionId,{key:n,verdict:i}),i};return{sessionId:e.sessionId,guardedDirectory:t,list:()=>E4(n).map(e=>m(e)),listWithWorkspace:()=>Promise.all(E4(n).map(async e=>m(e,await g(e)))),relate:async e=>{let t=E4(n).find(t=>t.entry.sessionId===e);return t===void 0?void 0:g(t)},refreshWorkspace:d,publishStatus:e=>{i||(a=e,c(!0))},withdraw:()=>{p(),(e.off??((e,t)=>process.off(e,t)))(`exit`,p)}}}function SKe(e,t,n=e=>process.emitWarning(e)){let r,i=!1,a=!1,o=t=>{if(!(t===r&&!a))try{e.publishStatus(t),r=t,a=!1,i=!1}catch(e){if(a=!0,i)return;i=!0,n(`Local peer activity publication failed: ${String(e)}`)}},s=()=>{if(!t.isActiveForPeerStatus){o(void 0);return}try{o(t.getSession().getLocalActivityStatus())}catch(e){if(o(void 0),i)return;i=!0,n(`Local peer activity observation failed: ${String(e)}`)}};s();let c=setInterval(s,250);return c.unref?.(),()=>{clearInterval(c);try{e.publishStatus(void 0)}catch(e){n(`Local peer activity reset failed: ${String(e)}`)}}}function b7(e){return{receive:t=>new $fe({submit:(n,r,i)=>e().submit(n,void 0,void 0,{turnSource:`peer`,...r.driverId===void 0?{}:{driverId:r.driverId},onAccepted:i,peer:{messageId:t.message.id,replyTo:r.sessionId}})}).receive(t)}}function CKe(e){return typeof e.getLocalActivityStatus==`function`}function wKe(e){return{getStatus:()=>e.getStatus(),describeKeyStorage:()=>e.describeKeyStorage(),listDevices:()=>e.listDevices().map(e=>({deviceId:e.deviceId,label:e.label,lastSeenAt:e.lastSeenAt})),revokeDevice:t=>e.revokeDevice(t),enable:()=>e.enable(),stop:()=>e.stop()}}function TKe(e,t,n){return{list:()=>e.list(),listWithWorkspace:()=>e.listWithWorkspace(),ownSessionId:()=>e.sessionId,...t===void 0?{}:{listDevices:()=>t.devices(),...x7(void 0,t,n)}}}function x7(e,t,n){let r={state:`failed`,reason:`this session cannot reach other sessions yet`};return{send:async(n,i,a)=>{let o=t?.isLinked(n)===!0?await t.send(n,i,a):e===void 0?r:await e.send(n,i,a);return{state:o.state,...o.reason===void 0?{}:{reason:o.reason}}},prepareFile:async(i,a,{origin:o,cwd:s})=>{let c=await vKe({path:a,cwd:s,home:n.userHome??(()=>{throw Error(`File paths using home require an explicit host home.`)})(),origin:o,maxBytes:33554432,pathProtection:n.layout.pathProtection});if(!c.ok)return c;let{file:l}=c;return{ok:!0,file:{path:l.path,size:l.size,sha256:l.sha256,send:async()=>t?.isLinked(i)===!0?t.sendFile(i,l):e===void 0?r:e.sendFile(i,l)}}}}}function EKe(e,t,n,r){return{list:()=>[],ownSessionId:()=>t,localDiscoveryOff:n,listDevices:()=>e.devices(),...x7(void 0,e,r)}}function DKe(e,t,n,r=xKe,i){let a=N();try{let t=r({sessionId:a,productRuntime:n});return e.localPeers=TKe(t,i,n),t}catch(r){let o=r instanceof Error?r.message:String(r);t.writeError(`Local peer discovery is off for this session: ${o}`),i!==void 0&&(e.localPeers=EKe(i,a,o,n));return}}function OKe(e,t,n,r,i,a=n$,o,s,c,l){let u=e.localPeers;return t===void 0||u===void 0?Promise.resolve(void 0):kKe(o,r).then(()=>AKe(u,t,n,r,a,s,c,l,i))}async function kKe(e,t){if(e!==void 0)try{await(await e)?.close()}catch(e){t.writeError(`A previous local peer listener could not be closed: ${e instanceof Error?e.message:String(e)}`)}}function AKe(e,t,n,r,i,a,o,s,c){return i({...a===void 0?{}:{files:a},...o===void 0?{}:{onHandoff:o},guardedDirectory:t.guardedDirectory,sessionId:t.sessionId,list:()=>t.list(),relate:async e=>(await t.relate(e))?.relation,report:e=>r.writeError(e),ingress:b7(n)}).then(t=>(Object.assign(e,x7(t,s,c)),t),e=>{r.writeError(`Local peer messaging is off for this session, though discovery is on: ${e instanceof Error?e.message:String(e)}`)})}function jKe(e,t,n,r,i,a,o){e.remoteControl=wKe(t);let s=DKe(e,n,r,i,o),c={},l=a!==void 0&&(s!==void 0||o!==void 0)?MKe(e,s,t,n,a,()=>c,o,r):void 0,u,d;return i=>{if(d?.(),d=void 0,s!==void 0){let e=i.getSession();CKe(e)&&typeof i.isActiveForPeerStatus==`boolean`&&(d=SKe(s,{getSession:()=>e,get isActiveForPeerStatus(){return i.isActiveForPeerStatus===!0}},e=>n.writeError(e)))}c={session:i.getSession()};let a=c;o?.bind({ingress:b7(()=>i.getSession())}),u=OKe(e,s,()=>i.getSession(),n,r,n$,u,{root:mq(r),...t.operatorApprover===void 0?{}:{approver:t.operatorApprover}},l,o),u.then(e=>{c===a&&e!==void 0&&(c={...a,messaging:e})})}}function S7(e){let t=e;return t!==void 0&&typeof t.getSessionId==`function`&&typeof t.getCwd==`function`&&typeof t.isExecuting==`function`?t:void 0}function MKe(e,t,n,r,i,a,o,s){let c=mq(s),l=sq({root:c,serviceNamespace:s.config.credentials.serviceNamespace,notify:()=>{}}),u=VGe();e.handoff=nKe({productRuntime:s,root:c,store:l.store,composition:u,sessionStore:i.sessionStore,getSession:()=>S7(a().session),peers:{list:()=>t?.list()??[],ownSessionId:()=>t?.sessionId??e.localPeers?.ownSessionId()??``},openChannel:()=>{let e=a().messaging;return e===void 0?void 0:t=>e.openHandoffChannel(t)},...o===void 0?{}:{devices:{list:()=>o.devices(),push:(e,t)=>o.handoff(e,t)}},onHandedOff:i.onHandedOff});let d=pKe({productRuntime:s,root:c,composition:u,identity:()=>s7(c,s),resolveCredential:i.hasOwnProvider,persist:e=>{let t=S7(a().session)?.getCwd()??e.cwd;return i.sessionStore.save({...e,cwd:t}),!0},deviceLabel:`this session`});return o?.bind({handoff:{receive:d,onOutcome:(e,t)=>r.writeError(l7(`device ${e}`,t,s.vocabulary.resumeCommand))}}),(e,i)=>{if(t===void 0){i.close();return}let a=rKe({sessionId:t.sessionId,productRuntime:s,root:c,...n.operatorApprover===void 0?{}:{approver:n.operatorApprover}},e,i);d(a).then(t=>r.writeError(l7(e.sessionId,t,s.vocabulary.resumeCommand)))}}function NKe(){let e=()=>{setTimeout(()=>process.kill(process.pid,`SIGTERM`),500).unref?.()};return{requestExit:()=>e(),requestRestart:()=>e()}}function PKe(e,t){if(!t||xq(e).includes(`--safe-mode`))return[...e];let n=e.indexOf(`--`);return n===-1?[...e,Iq]:[...e.slice(0,n),Iq,...e.slice(n)]}async function FKe(e,t){return e.restricted?$d(`untrusted`,e.targetCwd):t(e.targetCwd)}function IKe(e){let t=e.resolveAccess??(t=>Lq(t,{productRuntime:e.productRuntime})),n=e.onProcessExit??(e=>void process.once(`exit`,e)),r=e.runSync??sn;return{async move(i){let a=await FKe(i,t),o=zq({productRuntime:e.productRuntime,cwd:i.targetCwd,userHome:e.userHome,projectAccess:a}),s=Tg(i.record,o.sessionStore);o.sessionStore.save(s);let c=Uve(e.argv,{resumeId:s.id,movedFrom:i.fromCwd,restricted:a.status===`restricted`}),l=T1();n(()=>{let t=r(l.execPath,[...l.execArgv??[],...l.args,...c],{cwd:i.targetCwd,stdio:`inherit`,env:{...x4(e.productRuntime,o.settingsSources,e.providerDefinitions??[]),...e.environment}});process.exitCode=t.status??1}),e.requestExit()}}}function C7(e){return{...e.commandProductVocabulary===void 0?{}:{commandProductVocabulary:e.commandProductVocabulary},...e.pathProtection===void 0?{}:{pathProtection:e.pathProtection},...e.cliAppendSystemPrompt===void 0?{}:{appendSystemPrompt:e.cliAppendSystemPrompt},...e.allowedTools===void 0?{}:{allowedTools:e.allowedTools},...e.deniedTools===void 0?{}:{deniedTools:e.deniedTools}}}async function LKe(e,t,n,r,i,a,o,s,c,l,u,d={},f={},p={},m,h,g,_,v,y,b,x,S,C,w,T,E,ee,te,ne,re,ie,ae){let oe=n.goal?.trim(),se=n.positional.join(` `).trim();if(!oe&&!se&&!process.stdin.isTTY){let e=[];for await(let t of process.stdin)e.push(t);se=Buffer.concat(e).toString(`utf-8`).trim()}!oe&&!se&&(process.stderr.write(`Print mode (-p) requires a prompt argument (or --goal <objective>).
2909
2909
  `),await h?.(),process.exit(1)),u.process={requestExit:()=>{},requestRestart:(e,t)=>{process.stderr.write(`Restart requested (${t}) — print mode cannot restart itself; run the command again.\n`)}};let ce=new Wpe({cwd:t,...re?{livePromptTrace:re}:{},provider:r,shellExec:(t,n)=>kq(t,Pq(e.environment),n),..._===void 0?{}:{providerErrorGuidance:_},...T===void 0?{}:{promptFileReferenceTag:T},...E===void 0?{}:{modelCommandToolPrefix:E},...ee===void 0?{}:{subagentHookEnvironmentNames:ee},...te===void 0?{}:{observerFailureWarningCode:te},...ne===void 0?{}:{commandHookShell:ne},...g===void 0?{}:{orgPolicy:g},...ae===void 0?{}:{resolveProviderCredential:ae},...m===void 0?{}:{projectAccess:m},...b===void 0?{}:{projectSettingsPaths:b},...x===void 0?{}:{userSettingsSources:x},environment:e.environment,...S===void 0?{}:{contributionSources:S},...C===void 0?{}:{skillRoots:C},...w===void 0?{}:{taskContext:w},outputFormat:n.outputFormat??`text`,...f.model===void 0?{}:{model:f.model},...f.outputStyle===void 0?{}:{outputStyle:f.outputStyle},permissionMode:n.permissionMode??f.permissionMode??`default`,baselinePermissionAllow:e.layout.baselinePermissionAllow,maxTurns:n.maxTurns,sessionStore:n.noSessionPersistence?void 0:i,disableSessionLoops:d4(e.environment),resolveDefaultLoopPrompt:l4({productRuntime:e,projectAccess:m,userHome:e.userHome??e.layout.userRoot}),resumeSessionId:d.resumeSessionId,forkSession:d.forkSession,sessionName:n.sessionName,bare:n.bare||n.safeMode||void 0,...n.safeMode?{skipConfiguredHooks:!0}:{},...C7(f),...f.persona===void 0?{}:{persona:f.persona},...f.agentName===void 0?{}:{agentName:f.agentName},...f.activePresetId===void 0?{}:{activePresetId:f.activePresetId},...f.enableParallelSubagents===void 0?{}:{enableParallelSubagents:f.enableParallelSubagents},...f.effort===void 0?{}:{effort:f.effort},...f.effortResolution!==void 0&&!n.bare?{effortResolution:f.effortResolution}:{},...f.temperature===void 0?{}:{temperature:f.temperature},...f.maxOutputTokens===void 0?{}:{maxOutputTokens:f.maxOutputTokens},...f.responseFormat===void 0?{}:{responseFormat:f.responseFormat},...f.language===void 0?{}:{language:f.language},...f.systemPrompt===void 0?{}:{presetSystemPrompt:f.systemPrompt},...f.selfVerification===void 0?{}:{selfVerification:f.selfVerification},...n.systemPrompt?{systemPrompt:n.systemPrompt}:{},backgroundTaskRunners:a,subagentRunnerFactory:o,...s.length>0?{agentDefinitions:s}:{},...v===void 0?{}:{agentDefinitionRoots:v},...y===void 0?{}:{pluginDirectories:y},...c.additionalTools===void 0?{}:{additionalTools:c.additionalTools},...c.defaultTools===void 0?{}:{defaultTools:c.defaultTools},...c.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:c.toolExecutionPolicy},...c.sandboxClient===void 0?{}:{sandboxClient:c.sandboxClient},commandModules:l,commandHostAdapters:u,...p,...ie===void 0?{}:{editCheckpointStore:ie}});try{oe?await ce.runGoal(oe,n.goalMaxIterations?{maxIterations:n.goalMaxIterations}:{}):await ce.run(se)}catch(e){process.stderr.write((e instanceof Error?e.message:String(e))+`
2910
- `),await h?.(),await w7(1)}await h?.(),await w7(ce.getExitCode())}async function w7(e,t=[process.stdout,process.stderr]){await Promise.all(t.map(e=>new Promise(t=>{if(e.writableLength===0)return t();e.once(`error`,()=>t()),e.write(``,()=>t())}))),process.exit(e)}const T7=`127.0.0.1`,LKe={".html":`text/html; charset=utf-8`,".js":`text/javascript; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".css":`text/css; charset=utf-8`,".json":`application/json; charset=utf-8`,".svg":`image/svg+xml`,".png":`image/png`,".ico":`image/x-icon`,".woff2":`font/woff2`,".map":`application/json; charset=utf-8`};function RKe(e,t){return`${t.config.identity.displayName} is open at ${e}\n`}function zKe(){let e=Nee(new URL(`../web`,import.meta.url));return fn(M(e,`index.html`))?e:null}function BKe(e){return e.artifact===void 0?zKe():e.artifact.webRoot??null}const VKe=new Set([`localhost`,`127.0.0.1`,`::1`,`[::1]`]);function HKe(e){if(!e)return!1;let t=e.startsWith(`[`)?e.slice(0,e.indexOf(`]`)+1):e.slice(0,e.lastIndexOf(`:`)===-1?e.length:e.lastIndexOf(`:`));return VKe.has(t)}function UKe(e,t,n){let r=`<meta name="ws-url" content="${t}" /><script id="product-config" type="application/json">${JSON.stringify(Oge(n.config)).replaceAll(`<`,`\\u003c`)}<\/script>`;return e.includes(`</head>`)?e.replace(`</head>`,` ${r}\n </head>`):`${r}\n${e}`}async function WKe(e,t,n){let r=Cn(e),i=Wn(32).toString(`base64url`),a=Wn(32).toString(`base64url`),o=`/${Wn(24).toString(`base64url`)}/`,s=hr((e,s)=>{if(s.setHeader(`Referrer-Policy`,`no-referrer`),s.setHeader(`Cache-Control`,`no-store`),!HKe(e.headers.host)){s.writeHead(403).end(`Forbidden host`);return}if(e.method===`POST`&&e.url===`/__monitor_login`){let t=``,n=setTimeout(()=>e.destroy(),1e4);n.unref(),e.once(`close`,()=>clearTimeout(n)),e.setEncoding(`utf8`),e.setTimeout(1e4,()=>e.destroy()),e.on(`error`,()=>{}),e.on(`data`,n=>{t+=n,t.length>1024&&e.destroy()}),e.on(`end`,()=>{let e=new URLSearchParams(t).get(`code`)??``,n=Buffer.from(i),r=Buffer.from(e);if(r.length!==n.length||!Kn(r,n)){s.writeHead(403).end(`Invalid access code`);return}s.writeHead(303,{Location:o,"Set-Cookie":`robota_monitor=${a}; HttpOnly; SameSite=Strict; Path=${o}`}).end()});return}if(e.method!==`GET`&&e.method!==`HEAD`){s.writeHead(405).end(`Method not allowed`);return}if(e.url===`/`){s.writeHead(200,{"content-type":`text/html; charset=utf-8`,"content-security-policy":`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,"x-frame-options":`DENY`}).end(`<!doctype html><title>Monitor access</title><form method="post" action="/__monitor_login"><label>Access code from your terminal <input name="code" type="password" required autocomplete="off"></label><button type="submit">Open monitor</button></form>`);return}let c=(e.url??`/`).split(`?`)[0].startsWith(o);if(c){let t=(e.headers.cookie??``).split(`;`).map(e=>e.trim()).filter(e=>e.startsWith(`robota_monitor=`)),n=Buffer.from(t[0]?.slice(15)??``),r=Buffer.from(a);if(t.length!==1||n.length!==r.length||!Kn(n,r)){s.writeHead(403).end(`Forbidden`);return}}let l;try{l=decodeURIComponent((e.url??`/`).split(`?`)[0])}catch{s.writeHead(400).end(`Bad request`);return}let u=(c?l===o?`/index.html`:`/${l.slice(o.length)}`:l).split(`/`).filter(e=>e.length>0);if(u.length===0||!u.every(e=>e!==`.`&&e!==`..`&&!e.includes(Rn)&&!e.includes(`\\`))){s.writeHead(403).end(`Forbidden`);return}let d=M(r,...u),f;try{f=Cn(d)}catch{s.writeHead(404).end(`Not found`);return}if(!$t(r,f)){s.writeHead(403).end(`Forbidden`);return}let p=f.endsWith(`${Rn}index.html`);if(p&&!c){s.writeHead(403).end(`Forbidden`);return}let m=LKe[Nn(f)]??`application/octet-stream`,h,g;try{g=bn(f,`r`)}catch{s.writeHead(404).end(`Not found`);return}try{if(!pn(g).isFile()){s.writeHead(404).end(`Not found`);return}h=p?UKe(A(g,`utf8`),t,n):A(g)}catch{s.writeHead(404).end(`Not found`);return}finally{un(g)}s.writeHead(200,{"content-type":m,...f===M(r,`app-sandbox.html`)?{"Connection-Allowlist":`()`}:{}}),s.end(h)});await new Promise((e,t)=>{s.once(`error`,t),s.listen(0,T7,()=>{s.off(`error`,t),e()})});let c=s.address(),l=typeof c==`object`&&c?c.port:0;return{url:`http://${T7}:${l}`,accessCode:i,close:()=>new Promise((e,t)=>{s.close(n=>n?t(n):e()),s.closeAllConnections()})}}function GKe(e){let t=process.platform===`darwin`?`open`:process.platform===`win32`?`start`:`xdg-open`;try{let n=on(t,[e],{stdio:`ignore`,detached:!0,shell:process.platform===`win32`});n.on(`error`,()=>{}),n.unref()}catch{}}async function KKe(e,t,n){try{let r=await e.waitForFailure();if(!r)return;t.setExitCode(r.outcome.exitCode),t.writeError(`transport failed: ${r.name} exited ${r.outcome.exitCode}\n`),n(`a transport failed`)}catch(e){t.setExitCode(1);let r=e instanceof Error?e.message:String(e);t.writeError(`transport failed: ${r}\n`),n(`a transport failed`)}}const qKe=/^[0-9a-f-]{36}$/u;function JKe(e){return`${JSON.stringify({at:e.at,...e.grantId===void 0?{}:{grantId:e.grantId},...`refusal`in e?{refusal:e.refusal}:{settlement:e.settlement},...e.remote===void 0?{}:{remote:e.remote},...e.throttled===void 0?{}:{throttled:e.throttled}})}\n`}function YKe(e){let t=Sn(e).filter(e=>e.endsWith(`.jsonl`)).map(t=>{try{return{name:t,at:_n(M(e,t)).mtimeMs}}catch{return}}).filter(e=>e!==void 0).sort((e,t)=>t.at-e.at);for(let n of t.slice(64))Tn(M(e,n.name),{force:!0})}function E7(e,t){let n=0;for(;n<t.length;)n+=An(e,t,n,t.length-n)}function XKe(e,t){Tn(t,{force:!0});let n=bn(t,k.O_WRONLY|k.O_CREAT|k.O_EXCL|k.O_NOFOLLOW,384);try{let t=Buffer.alloc(64*1024),r=0;for(;;){let i=xn(e,t,0,t.length,r);if(i===0)break;E7(n,t.subarray(0,i)),r+=i}}finally{un(n)}hn(e,0)}function ZKe(e,t){if(!qKe.test(t))throw Error(`Invalid supervised session ID.`);let n=M(e,`${t}.jsonl`),r=M(e,`${t}.1.jsonl`);try{YKe(e)}catch{}return e=>{let t=JKe(e);try{let e=bn(n,k.O_RDWR|k.O_APPEND|k.O_CREAT|k.O_NOFOLLOW,384);try{let n=Buffer.from(t);pn(e).size+n.length>262144&&XKe(e,r),E7(e,n)}finally{un(e)}}catch{}}}function QKe(){let e=new Map;return{record(t,n){let r=e.get(t);r===void 0&&(r=new Map,e.set(t,r)),r.set(n.event.id,n)},forget(t,n){e.get(t)?.delete(n)},list:t=>[...e.get(t)?.values()??[]],find:(t,n)=>e.get(t)?.get(n),clear(t){e.delete(t)}}}function $Ke(e){return async t=>{let n=await e.sessionFactory(t),r=e.claims.keyFor(n);return t.json({prompts:r===void 0?[]:e.openPrompts.list(r)})}}function eqe(e){let{sessionFactory:t,claims:n,openPrompts:r,attribution:i}=e;return async e=>{let a=await t(e),o=e.req.param(`id`)??``,s;try{s=await e.req.json()}catch{return e.json({error:`the body must be a JSON object`},400)}let c=n.keyFor(a),l=c===void 0?void 0:r.find(c,o);if(c===void 0||l===void 0)return e.json({error:`no open prompt with this id`},404);if(l.type===`permission_request`){let t=tJ({type:`permission-response`,id:o,result:s?.result});if(!t.ok||t.message.type!==`permission-response`)return e.json({error:`result must be true, false, "allow-session" or "allow-project"`},400);a.resolvePermission(o,t.message.result,i?.driverId)}else{let t=tJ({type:`ask-response`,id:o,response:s?.response});if(!t.ok||t.message.type!==`ask-response`)return e.json({error:`response must be { "type": "answer", "values": string[], "text"?: string } or { "type": "cancelled" }`},400);a.resolveAsk(o,t.message.response,i?.driverId)}return r.find(c,o)===void 0?e.json({ok:!0}):e.json({error:`the session did not accept this answer`},409)}}function tqe(e,t,n,r,i){let a=(t,r)=>{e.on(t,r),n.push(()=>e.off(t,r))},o=(e,n)=>t.writeSSE({event:e,data:JSON.stringify(n)}).catch(()=>{}),s,c=new Promise(e=>{s=e});return a(`text_delta`,e=>void o(`text_delta`,{delta:e})),a(`tool_start`,e=>void o(`tool_start`,e)),a(`tool_end`,e=>void o(`tool_end`,e)),a(`thinking`,e=>void o(`thinking`,{isThinking:e})),i!==void 0&&nqe(a,o,i),a(`complete`,async e=>{await o(`complete`,e),s()}),a(`interrupted`,async e=>{await o(`interrupted`,e),s()}),a(`error`,async e=>{await o(`error`,{message:e.message}),s()}),t.onAbort(()=>rqe(e,r,s)),c}function nqe(e,t,n){e(`permission_request`,e=>{n.record({type:`permission_request`,event:e}),t(`permission_request`,e)}),e(`ask_request`,e=>{n.record({type:`ask_request`,event:e}),t(`ask_request`,e)}),e(`prompt_resolved`,e=>{n.forget(e.id),t(`prompt_resolved`,e)})}function rqe(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function iqe(e,t){for(let t of e)try{t()}catch{}t()}function aqe(e,t,n,r,i,a){return async o=>{try{let s=[];try{let n=tqe(e,o,s,r,a);await(i===void 0?e.submit(t):e.submit(t,void 0,void 0,{...i})),await n}finally{iqe(s,n)}}catch(e){await oqe(e instanceof Error?e:Error(String(e)),o,r)}}}async function oqe(e,t,n){try{n?.(e)}catch{}await t.writeSSE({event:`error`,data:JSON.stringify({message:`the stream failed on the server after it opened — the turn may not have run`})}).catch(()=>{})}function sqe(e,t,n){let r=n.keyFor(t);return r===void 0?e.json({error:`concurrent-turn tracking is unavailable for this session, so this request cannot be served safely. Refusing rather than starting a turn that cannot be guaranteed to be yours.`},500):n.isHeld(r)||t.isExecuting()?e.json({error:`session busy — a turn is already in flight`},409):(n.hold(r),{claim:r})}function cqe(e){let{sessionFactory:t,claims:n,openPrompts:r,onStreamFailure:i,attribution:a}=e;return async e=>{let o=await t(e),s=await e.req.json();if(!s.prompt||typeof s.prompt!=`string`)return e.json({error:`prompt is required`},400);if(s.receivePrompts!==void 0&&typeof s.receivePrompts!=`boolean`)return e.json({error:`receivePrompts must be a boolean`},400);if(o.whenInitialized!==void 0)try{await o.whenInitialized()}catch{return e.json({error:`the session could not be started`},500)}let c=sqe(e,o,n);if(c instanceof Response)return c;let{claim:l}=c,u=!1,d=()=>{u||(u=!0,r.clear(l),n.release(l))},f=s.receivePrompts===!0?{record:e=>r.record(l,e),forget:e=>r.forget(l,e)}:void 0;try{return await yte(e,aqe(o,s.prompt,d,i,a,f))}catch(e){throw d(),e}}}function lqe(){let e=new Set;return{keyFor(e){try{let t=e.getSession().getSessionId();return typeof t==`string`&&t!==``?t:void 0}catch{return}},isHeld:t=>e.has(t),hold:t=>void e.add(t),release:t=>void e.delete(t)}}function uqe(e){let{sessionFactory:t,onStreamFailure:n,attribution:r}=e,i=new _te,a=lqe(),o=QKe(),s=e.maxJsonBodyBytes??65536;if(!Number.isSafeInteger(s)||s<1)throw Error(`maxJsonBodyBytes must be a positive integer`);let c=vte({maxSize:s,onError:e=>e.json({error:`request body too large`},413)}),l=mk(e.admission);return i.use(`*`,async(e,t)=>l.token===null||hk(l.token,gk(e.req.header(`authorization`)))?t():e.json({error:`unauthorized`},401)),i.post(`/submit`,c,cqe({sessionFactory:t,claims:a,openPrompts:o,onStreamFailure:n,attribution:r})),i.get(`/prompts`,$Ke({sessionFactory:t,claims:a,openPrompts:o,attribution:r})),i.post(`/prompts/:id`,c,eqe({sessionFactory:t,claims:a,openPrompts:o,attribution:r})),i.post(`/command`,c,async e=>{let n=await t(e),r=await e.req.json();if(!r.name||typeof r.name!=`string`)return e.json({error:`name is required`},400);let i=await n.executeCommand(r.name,r.args??``,`remote`);return i?e.json(i):e.json({error:`Unknown command: ${r.name}`},404)}),i.post(`/abort`,async e=>((await t(e)).abort(),e.json({ok:!0}))),i.post(`/cancel-queue`,async e=>((await t(e)).cancelQueue(),e.json({ok:!0}))),i.get(`/messages`,async e=>{let n=await t(e);return e.json(n.getMessages())}),i.get(`/context`,async e=>{let n=await t(e);return e.json(n.getContextState())}),i.get(`/executing`,async e=>{let n=await t(e),r=a.keyFor(n),i=r!==void 0&&a.isHeld(r);return e.json({executing:i||n.isExecuting()})}),i.get(`/pending`,async e=>{let n=await t(e);return e.json({pending:n.getPendingPrompt()})}),i}const D7={type:`cancelled`},O7=`decision`,k7=`allow_once`,A7=`answer`,j7=`text`,M7=2e3;function N7(e){return e.length>M7?`${e.slice(0,M7)}…`:e}function dqe(e){let t=NJ(e.toolArgs),n=`Allow ${e.toolName}${t===void 0?``:`: ${N7(t)}`}?`,r=[e.requester?`${e.requester.label} asks: ${n}`:n];return r.push(`Arguments: ${N7(JSON.stringify(e.toolArgs))}`),e.cwd!==void 0&&r.push(`Working directory: ${e.cwd}`),r.join(`
2911
- `)}function fqe(e){return{message:dqe(e),requestedSchema:{type:`object`,properties:{[O7]:{type:`string`,title:`Decision`,description:`Allow this one call, or deny it. Nothing is remembered.`,enum:[k7,`deny`],enumNames:[`Allow once`,`Deny`]}},required:[O7]}}}function pqe(e){return e.action===`accept`&&e.content?.decision===k7}function P7(e){let t=Math.max(1,Math.floor(e.maxSelect??1));return{min:Math.min(t,Math.max(0,Math.floor(e.minSelect??1))),max:t}}function mqe(e,t){let{min:n,max:r}=P7(e),i=t.map(e=>e.value),a=t.filter(e=>e.description!==void 0||e.label!==e.value).map(e=>e.description===void 0?`${e.value}: ${e.label}`:`${e.value}: ${e.label} — ${e.description}`),o=a.length>0?a.join(`
2912
- `):void 0,s=e.default?.values?.filter(e=>i.includes(e));return r>1?{type:`array`,title:`Answer`,...o===void 0?{}:{description:o},minItems:n,maxItems:r,items:{type:`string`,enum:i},...s!==void 0&&s.length>0?{default:s}:{}}:{type:`string`,title:`Answer`,...o===void 0?{}:{description:o},enum:i,enumNames:t.map(e=>e.label),...s?.[0]===void 0?{}:{default:s[0]}}}function hqe(e){if(e.masked===!0)return;let t=e.options??[],n=e.allowFreeText===!0;if(t.length===0&&!n)return;let r={},i=[];if(t.length>0&&(r[A7]=mqe(e,t),!n&&P7(e).min>0&&i.push(A7)),n){let n=e.default?.text;r[j7]={type:`string`,title:t.length>0?`Other answer`:`Answer`,...e.placeholder===void 0?{}:{description:e.placeholder},...e.allowEmpty===!0?{}:{minLength:1},...n===void 0?{}:{default:n}},t.length===0&&e.allowEmpty!==!0&&i.push(j7)}return{message:[e.title,e.description].filter(e=>e).join(`
2913
- `),requestedSchema:{type:`object`,properties:r,...i.length>0?{required:i}:{}}}}function gqe(e,t){if(t.action!==`accept`)return D7;let n=t.content??{},r=new Set((e.options??[]).map(e=>e.value)),{min:i,max:a}=P7(e),o=n[A7],s=[];if(o!==void 0){let e=Array.isArray(o)?o:[o];for(let t of e){if(typeof t!=`string`||!r.has(t)||s.includes(t))return D7;s.push(t)}}if(s.length>a)return D7;let c=n[j7];if(c!==void 0&&(typeof c!=`string`||e.allowFreeText!==!0))return D7;let l=c!==void 0&&c!==``;return s.length<i&&!l||s.length===0&&!l&&e.allowEmpty!==!0?D7:{type:`answer`,values:s,...c===void 0?{}:{text:c}}}function F7(e){return e.kind===`permission`?fqe(e.event):hqe(e.event.request)}function _qe(e){let t=e?.elicitation;return typeof t!=`object`||!t?!1:t.form!==void 0||t.url===void 0}let vqe=0;function I7(){return`mcp:${++vqe}`}var L7=class{session;driverId;queue=[];waiter;settledHooks=new Map;seen=new Set;open=new Map;settledIds=new Set;listening=!1;closed=!1;constructor(e,t){this.session=e,this.driverId=t,e.on(`turn_source`,this.onTurnStart),e.on(`prompt_resolved`,this.onPromptResolved)}followActiveDriver(){if(this.closed)return;let e=this.session.getActiveDriverId()===this.driverId;e&&!this.listening?(this.listening=!0,this.session.on(`permission_request`,this.onPermissionRequest),this.session.on(`ask_request`,this.onAskRequest)):!e&&this.listening&&this.stopListening()}onTurnStart=()=>this.followActiveDriver();stopListening(){this.listening&&(this.listening=!1,this.session.off(`permission_request`,this.onPermissionRequest),this.session.off(`ask_request`,this.onAskRequest))}onPermissionRequest=e=>{e.requesterDriverId===this.driverId&&this.push({kind:`permission`,event:e})};onAskRequest=e=>{e.requesterDriverId===this.driverId&&this.push({kind:`ask`,event:e})};onPromptResolved=e=>{if(!this.seen.has(e.id))return;this.settledIds.add(e.id),this.open.delete(e.id);let t=this.queue.findIndex(t=>t.event.id===e.id);t>=0&&this.queue.splice(t,1),this.runSettledHooks(e.id)};push(e){if(this.closed)return;this.seen.add(e.event.id),this.open.set(e.event.id,e);let t=this.waiter;if(t===void 0){this.queue.push(e);return}this.waiter=void 0,t.signal.removeEventListener(`abort`,t.onAbort),t.resolve(e)}next(e){let t=this.queue.shift();return t===void 0?this.closed?Promise.reject(Error(`The call has ended`)):e.aborted?Promise.reject(Error(`No longer waiting for a prompt`)):this.waiter===void 0?new Promise((t,n)=>{let r=()=>{this.waiter=void 0,n(Error(`No longer waiting for a prompt`))};this.waiter={resolve:t,reject:n,signal:e,onAbort:r},e.addEventListener(`abort`,r,{once:!0})}):Promise.reject(Error(`Already waiting for a prompt`)):Promise.resolve(t)}whenSettled(e,t){if(this.closed||this.settledIds.has(e))return t(),()=>void 0;let n=this.settledHooks.get(e);return n===void 0&&(n=new Set,this.settledHooks.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&this.settledHooks.delete(e)}}settle(e,t){try{if(e.kind===`permission`){let n=t!==void 0&&pqe(t);this.session.resolvePermission(e.event.id,n,this.driverId);return}let n=t===void 0?{type:`cancelled`}:gqe(e.event.request,t);this.session.resolveAsk(e.event.id,n,this.driverId)}catch{}}settleOutstanding(){for(let e of[...this.open.values()])this.settle(e,void 0)}close(){if(this.closed)return;this.closed=!0;for(let e of[...this.settledHooks.keys()])this.runSettledHooks(e);let e=this.waiter;e!==void 0&&(this.waiter=void 0,e.signal.removeEventListener(`abort`,e.onAbort),e.reject(Error(`The call has ended`))),this.queue.length=0,this.session.off(`turn_source`,this.onTurnStart),this.stopListening(),this.session.off(`prompt_resolved`,this.onPromptResolved)}runSettledHooks(e){let t=this.settledHooks.get(e);if(t!==void 0){this.settledHooks.delete(e);for(let e of t)e()}}};function R7(e){e.prompts.settleOutstanding(),e.abort.abort()}var yqe=class{deadlineMs;parked=new Map;stopped=!1;constructor(e=18e5){this.deadlineMs=e}has(e){return this.parked.has(e)}park(e){if(this.stopped||this.parked.size>=16)return;let t=Wn(32).toString(`base64url`),n=setTimeout(()=>{this.parked.get(t)?.call===e&&(this.parked.delete(t),R7(e))},this.deadlineMs);return n.unref?.(),this.parked.set(t,{call:e,timer:n}),t}take(e){let t=this.parked.get(e);if(t!==void 0)return this.parked.delete(e),clearTimeout(t.timer),t.call}abortAll(){this.stopped=!0;for(let{call:e,timer:t}of this.parked.values())clearTimeout(t),R7(e);this.parked.clear()}};const bqe={name:`agent_submit`,description:`Submit a prompt to the agent and await its turn`};function z7(e){let t=Cte.Tool[`~standard`].validate(JSON.parse(JSON.stringify(e)));if(t.issues!==void 0){let e=t.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).map(String).join(`.`);return t?`${t}: ${e.message}`:e.message});throw Error(`Invalid MCP tool: ${e.join(`; `)}`)}return t.value}function B7(e=bqe){if(typeof e.name!=`string`||!/^[A-Za-z0-9._-]{1,128}$/.test(e.name))throw Error(`MCP submit tool name must contain 1–128 ASCII letters, digits, dots, hyphens, or underscores`);return z7({name:e.name,description:e.description,inputSchema:{type:`object`,properties:{prompt:{type:`string`,minLength:1}},required:[`prompt`],additionalProperties:!1}})}async function V7(e,t){let n=new Set([t]);return(await e.listRuntimeTools()).map(e=>{if(n.has(e.name))throw Error(`Duplicate or reserved MCP tool name: ${e.name}`);return n.add(e.name),z7({name:e.name,description:e.description,inputSchema:e.parameters})})}function H7(e){return{content:[{type:`text`,text:e}],isError:!0}}function U7(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(U7):typeof e==`object`&&Object.values(e).every(U7)}function xqe(e){return Object.values(e).every(U7)}async function Sqe(e,t,n,r,i){let a;try{r.throwIfAborted(),a=await V7(e,i)}catch(e){return H7(e instanceof Error?e.message:String(e))}if(t===i){let t=n.prompt;return typeof t!=`string`||t.length===0||Object.keys(n).some(e=>e!==`prompt`)?H7(`${i} requires a non-empty string prompt and no other arguments`):async(n,r)=>{try{let i=await e.submit(t,void 0,void 0,{signal:n,...r===void 0?{}:{driverId:r.driverId}});return r?.holding(),{content:[{type:`text`,text:(await i.completed).response}]}}catch(e){if(!ao(e)&&!n.aborted)throw e;return H7(e instanceof Error?e.message:String(e))}}}if(!a.some(e=>e.name===t))return H7(`Unknown tool: ${t}`);if(!xqe(n))return H7(`Tool arguments must contain JSON values`);let o=n;return async(n,r)=>{try{let i=e.invokeRuntimeTool(t,o,{signal:n,...r===void 0?{}:{driverId:r.driverId,permissionInteraction:`interactive`}});r?.holding();let a=await i;return{content:[{type:`text`,text:JSON.stringify(a)}],isError:!a.success}}catch(e){return H7(e instanceof Error?e.message:String(e))}}}async function Cqe(e,t,n,r,i,a){if(a?.kind===`rounds`&&a.requestState!==void 0)return Dqe(a.pending,a.requestState,a.inputResponses,r);let o=await Sqe(e,t,n,r,i);return typeof o==`function`?a===void 0?o(r,void 0):a.kind===`elicit`?Tqe(e,o,r,a.elicit):Eqe(e,o,r,a.pending):o}function W7(e){return{driverId:e.driverId,holding:()=>e.followActiveDriver()}}async function wqe(e,t,n,r){let i=F7(t);if(i===void 0){e.settle(t,void 0);return}let a=new AbortController,o=!1,s=e.whenSettled(t.event.id,()=>{o=!0,a.abort()}),c=()=>a.abort();r.addEventListener(`abort`,c,{once:!0});let l;try{l=await n(i,a.signal)}catch{l=void 0}finally{s(),r.removeEventListener(`abort`,c)}o||e.settle(t,l)}async function Tqe(e,t,n,r){let i=new L7(e,I7()),a=new AbortController,o=new Set,s=(async()=>{for(;;){let e=await i.next(a.signal),t=wqe(i,e,r,n).catch(()=>void 0).finally(()=>{o.delete(t)});o.add(t)}})().catch(()=>void 0);try{return await t(n,W7(i))}finally{a.abort(),await s,i.close(),await Promise.all(o)}}function Eqe(e,t,n,r){let i=new AbortController,a=new L7(e,I7());return G7({prompts:a,outcome:t(i.signal,W7(a)).finally(()=>a.close()),abort:i},n,r)}function Dqe(e,t,n,r){let i=e.take(t);if(i===void 0)return Promise.resolve(H7(`Unknown or expired request state`));let a=Ste(n,i.prompt.event.id);return i.prompts.settle(i.prompt,a.kind===`elicit`?Oqe(a):void 0),G7(i,r,e)}function Oqe(e){let t={};for(let[n,r]of Object.entries(e.content??{}))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`))&&(t[n]=r);return{action:e.action,...e.content===void 0?{}:{content:t}}}async function G7(e,t,n){let r=()=>R7(e);t.addEventListener(`abort`,r,{once:!0}),t.aborted&&r();let i=new AbortController;try{for(;;){let a=await Promise.race([e.outcome.then(e=>({result:e})),e.prompts.next(i.signal).then(e=>({prompt:e}),()=>e.outcome.then(e=>({result:e})))]);if(`result`in a)return a.result;let o=F7(a.prompt),s=o===void 0?void 0:n.park({...e,prompt:a.prompt});if(o===void 0||s===void 0){e.prompts.settle(a.prompt,void 0);continue}return t.removeEventListener(`abort`,r),ii({inputRequests:{[a.prompt.event.id]:ii.elicit(o)},requestState:s})}}finally{i.abort(),t.removeEventListener(`abort`,r)}}function K7(e,t,n={kind:`none`}){let{name:r,version:i,session:a}=e,o=e.askClient===!0,s=o&&n.kind===`rounds`?n.pending:void 0,c=new bte({name:r,version:i},{capabilities:{tools:{}},...s===void 0?{}:{requestState:{verify:e=>{if(!s.has(e))throw Error(`Unknown or expired MCP request state`)}}}}),l=e=>{if(s!==void 0){let t=e.mcpReq.requestState();if(t!==void 0)return{kind:`rounds`,pending:s,requestState:t,inputResponses:e.mcpReq.inputResponses}}if(!(!o||!_qe(c.getClientCapabilities()))){if(n.kind===`connection`)return{kind:`elicit`,elicit:(e,t)=>c.elicitInput(e,{signal:t,timeout:36e5})};if(s!==void 0)return{kind:`rounds`,pending:s,requestState:void 0,inputResponses:void 0}}};return c.setRequestHandler(`tools/list`,async()=>({tools:[...await V7(a,t.name),t]})),c.setRequestHandler(`tools/call`,async(e,n)=>Cqe(a,e.params.name,e.params.arguments??{},n.mcpReq.signal,t.name,l(n))),c}async function kqe(e){let t=B7(e.submitTool);return await V7(e.session,t.name),K7(e,t,{kind:`connection`})}function Aqe(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=e.stdin??process.stdin,c=e.stdout??process.stdout,l=null,u=null,d=Promise.resolve(),f=()=>{d=new Promise((e,t)=>{l=e,u=t}),d.catch(()=>void 0)},p=()=>{l?.(),o?.(Error(`MCP input closed during startup`))},m=()=>{l?.(),o?.(Error(`MCP output closed during startup`))},h=e=>{u?.(e),o?.(e)},g=()=>{a?.release(),a=null},_=e=>Object.assign(Error(`MCP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`mcp`});return{name:`mcp`,lifecycle:Object.freeze({kind:`service`}),attach(e){if(n||r||i)throw _(`already-started`);t=e,f()},async start(){if(!t)throw _(`not-attached`);if(n||r||i)throw _(`already-started`);let d=t,f=new Promise((e,t)=>{o=t}),v=cA(s,c,{onInputClose:p,onOutputClose:m,onOutputError:h});a=v,r=(async()=>{let t=null,r=setTimeout(()=>o?.(Error(`MCP carrier startup timed out`)),15e3);try{t=await Promise.race([kqe({name:e.name,version:e.version,session:d,...e.submitTool===void 0?{}:{submitTool:e.submitTool},...e.askClient===void 0?{}:{askClient:e.askClient}}),f]);let r=new wte(v.bridge,c,{maxBufferSize:10485760});r.onclose=()=>l?.(),r.onerror=e=>u?.(e),await t.connect(r),n=t,t=null}catch(e){throw g(),t&&await t.close().catch(()=>void 0),e}finally{clearTimeout(r),o=null}})();try{await r}finally{r=null}},stop(){return i||(i=(async()=>{try{o?.(Error(`MCP carrier startup stopped`)),r&&await r.catch(()=>void 0),n&&await n.close()}finally{g(),n=null,t=null,l?.()}})().finally(()=>{i=null}),i)},getServer(){if(!n)throw Error(`Transport not started. Call start() first.`);return n},waitForClose(){return d}}}const q7=`MCP HTTP`;function jqe(e,t=()=>performance.now()){let n=Hk({resource:e.publicUrl,issuer:e.issuer,scopes:e.scopes,label:q7}),r=Vk({publicUrl:e.publicUrl,...e.trustedProxies===void 0?{}:{trustedProxies:e.trustedProxies},label:q7,now:t}),i=r.url.pathname;function a(t,i,a){Gk(t,i,r,n,a,e.audit)}return{endpointPath:i,async admit(t,o){if(!r.checkNames(t,o))return!1;if(t.url===n.wellKnownPath)return Uk(t,o,n),!1;if(t.url!==i)return o.writeHead(404).end(),!1;let s=gk(t.headers.authorization);if(s===void 0)return a(t,o,`missing-token`),!1;let c=await e.verifier.verify(s);return c.admitted?!0:(a(t,o,c.refusal),!1)}}}const J7=`127.0.0.1`,Y7=1024*1024;function X7(e){if(e!==void 0&&(!Number.isInteger(e)||e<0||e>65535))throw Error(`MCP HTTP port must be an integer in 0..65535`)}function Z7(e,t,n){let r=B7(e.submitTool),i=new yqe,a,o,s,c=!1,l=!1,u=0,d,f,p=new Promise((e,t)=>{d=e,f=t});return p.catch(()=>void 0),{async start(){if(c||s)throw Error(`MCP HTTP host already started`);if(c=!0,await V7(e.session,r.name),l)throw Error(`MCP HTTP host stopped during startup`);o=xte(t=>K7(e,r,t.era===`modern`?{kind:`rounds`,pending:i}:{kind:`none`}),{maxSubscriptions:0});let p=Tte(o),m=(e,t)=>{if(u>=16){t.writeHead(503).end();return}u+=1,(async()=>{try{let n;if(e.method===`POST`){let r=Number(e.headers[`content-length`]);if(Number.isFinite(r)&&r>Y7){t.writeHead(413).end();return}let i=[],a=0;for await(let n of e){let r=Buffer.isBuffer(n)?n:Buffer.from(n);if(a+=r.length,a>Y7){t.writeHead(413).end(),e.destroy();return}i.push(r)}try{n=JSON.parse(Buffer.concat(i).toString(`utf8`))}catch{t.writeHead(400).end();return}}await p(e,t,n)}catch{t.headersSent?t.destroy():t.writeHead(500).end()}finally{--u}})()},h=hr({maxHeaderSize:16*1024},(e,t)=>{let r=h.address();if(!r||typeof r==`string`){t.writeHead(503).end();return}let i=n(e,t,r.port);i===!0?m(e,t):i!==!1&&i.then(n=>{n&&m(e,t)},()=>{t.headersSent?t.destroy():t.writeHead(500).end()})});h.maxConnections=32,h.headersTimeout=5e3,h.requestTimeout=15e3,h.on(`error`,e=>f?.(e)),h.on(`close`,()=>d?.());try{await new Promise((n,r)=>{h.once(`error`,r),h.listen(e.port??0,t,()=>{h.off(`error`,r),n()})})}catch(e){throw await o.close(),e}if(l)throw await new Promise(e=>h.close(()=>e())),await o.close(),Error(`MCP HTTP host stopped during startup`);return a=h,h.address()},stop(){return s||(l=!0,s=(async()=>{let e=o,t=a;if(i.abortAll(),!t){await e?.close(),d?.();return}let n=new Promise((e,n)=>{t.close(t=>t?n(t):e()),t.closeAllConnections()}),r;try{await Promise.race([Promise.all([e?.close(),n]).then(()=>void 0),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`MCP HTTP close timed out`)),5e3)})])}finally{r&&clearTimeout(r)}})(),s)},waitForClose(){return p}}}function Mqe(e){if(e.host!==void 0&&e.host!==J7)throw Error(`MCP HTTP host must bind numeric IPv4 loopback`);X7(e.port);let t=pk(),n=Z7(e,J7,(e,n,r)=>{let i=`${J7}:${r}`,a=`http://${i}`;if(e.url!==`/mcp`||e.headers.host!==i||e.headers.origin!==void 0&&e.headers.origin!==a)return n.writeHead(403).end(),!1;let o=e.headers.authorization;return typeof o!=`string`||!hk(t,gk(o))?(n.writeHead(401).end(),!1):!0});return{async start(){let e=await n.start();return{url:`http://${J7}:${e.port}/mcp`,token:t}},stop:n.stop,waitForClose:n.waitForClose}}function Nqe(e){let t=e.host??J7;if(pr(t)===0)throw Error(`MCP HTTP host must bind a literal IP address`);X7(e.port);let n=jqe(e.authorization),r=Z7(e,t,(e,t)=>n.admit(e,t));return{async start(){let t=await r.start();return{listening:`${t.family===`IPv6`?`[${t.address}]`:t.address}:${t.port}`,url:e.authorization.publicUrl}},stop:r.stop,waitForClose:r.waitForClose}}async function Q7(e,t,n){let r;try{await Promise.race([e.shutdown({reason:`other`,message:t}),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`${n} session shutdown timed out`)),5e3)})])}finally{r!==void 0&&clearTimeout(r)}}const $7=[`RS256`,`ES256`,`EdDSA`];function e9(e){return{name:`${e.config.identity.cliName}_submit`,description:`Submit a prompt to the agent and await its own turn`}}async function t9(e,t,n,r){let i,a=new Promise(e=>{i=e}),o=()=>i?.();process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{let e=await Promise.race([t.start(),a.then(()=>void 0)]);if(!e)return;await n(e),await Promise.race([t.waitForClose(),a])}finally{process.off(`SIGINT`,o),process.off(`SIGTERM`,o);try{await t.stop()}finally{try{await r()}finally{await Q7(e,`MCP HTTP carrier closed`,`MCP`)}}}}function Pqe(e){process.stderr.write(`MCP HTTP refused: ${e.refusal} (${e.remote}${e.throttled?`, throttled`:``})\n`)}async function Fqe(e,t,n,r,i={},a=!1){if(i.remote!==void 0){if(i.tokenFile!==void 0)throw Error(`MCP HTTP token file is not accepted with remote authorization`);let r=i.remote,o=wk({issuer:r.issuer,resource:r.publicUrl,algorithms:$7,requiredScopes:r.scopes,allowedSubjects:r.allowedSubjects}),s=px(t),c;try{c=Nqe({name:e.config.identity.mcpClientName,version:n,session:s,host:r.host,port:i.port,submitTool:e9(e),...a?{askClient:!0}:{},authorization:{publicUrl:r.publicUrl,issuer:r.issuer,scopes:r.scopes,verifier:o,trustedProxies:r.trustedProxies,audit:Pqe}})}catch(e){throw await Q7(s,`MCP HTTP carrier refused its configuration`,`MCP`),e}return t9(s,c,async e=>{process.stderr.write(`MCP HTTP listening on ${e.listening} for ${e.url}; authorization server: ${r.issuer}\n`)},async()=>void 0)}if(i.tokenFile!==void 0&&!Pn(i.tokenFile))throw Error(`MCP HTTP token file must be an absolute path`);if(i.port!==void 0&&i.tokenFile===void 0)throw Error(`MCP HTTP port requires a token file`);let o=px(t);if(i.tokenFile!==void 0){let t=i.tokenFile,r=Mqe({name:e.config.identity.mcpClientName,version:n,session:o,port:i.port,submitTool:e9(e),...a?{askClient:!0}:{}}),s;await t9(o,r,async e=>{let n=await $n(t,`wx`,384);try{await n.chmod(384);let t=await n.stat();s={dev:t.dev,ino:t.ino},await n.writeFile(`${e.token}\n`,`utf8`)}finally{await n.close()}process.stderr.write(`MCP HTTP listening at ${e.url}; bearer token file: ${t}\n`)},async()=>{if(!s)return;let e=await Zn(t).catch(e=>{if(e.code!==`ENOENT`)throw e});e?.dev===s.dev&&e.ino===s.ino&&await ir(t)});return}let s=Aqe({name:e.config.identity.mcpClientName,version:n,stdout:r,submitTool:e9(e),...a?{askClient:!0}:{}});s.attach(o);let c,l=new Promise(e=>{c=e}),u=()=>c?.();process.once(`SIGINT`,u),process.once(`SIGTERM`,u);try{await Promise.race([s.start(),s.waitForClose(),l]),await Promise.race([s.waitForClose(),l])}finally{process.off(`SIGINT`,u),process.off(`SIGTERM`,u);try{await s.stop()}finally{await Q7(o,`MCP stdio carrier closed`,`MCP`)}}}const n9=`127.0.0.1`,r9=`HTTP API`,Iqe={driverId:`remote:http`,surface:`remote`},Lqe={open:!0,openReason:`admitted by the OAuth resource-server gate in front of these routes`};async function Rqe(e){if(e.token===void 0==(e.remote===void 0))throw Error(`HTTP API needs exactly one of a loopback bearer and remote authorization`);let t=e.remote,n=gte(uqe({sessionFactory:e.session,admission:t===void 0?{token:e.token??``}:Lqe,attribution:Iqe,...e.onStreamFailure===void 0?{}:{onStreamFailure:e.onStreamFailure}}).fetch),r=t===void 0?n:zqe(t,n,e),i=t?.host??n9,a=hr(r);a.requestTimeout=3e4,a.headersTimeout=1e4,await Bqe(a,e.port,i);let o=a.address();if(o===null||typeof o==`string`)throw await i9(a),Error(`HTTP API listener has no port.`);let s=o.family===`IPv6`?`[${o.address}]`:o.address;return{url:t?.publicUrl??`http://${n9}:${o.port}`,listening:`${s}:${o.port}`,stop:async()=>{a.closeAllConnections(),await i9(a)}}}function zqe(e,t,n){let r=Hk({resource:e.publicUrl,issuer:e.issuer,scopes:e.scopes,label:r9}),i=Vk({publicUrl:e.publicUrl,trustedProxies:e.trustedProxies,label:r9}),a=wk({issuer:e.issuer,resource:e.publicUrl,algorithms:$7,requiredScopes:e.scopes,allowedSubjects:e.allowedSubjects}),o=i.url.pathname.replace(/\/$/,``);function s(e,t,a){Gk(e,t,i,r,a,n.onRefusal)}async function c(e,n){if(!i.checkNames(e,n))return;let c=e.url??``;if(c===r.wellKnownPath){Uk(e,n,r);return}if(!(c.split(`?`)[0]??``).startsWith(`${o}/`)){n.writeHead(404).end();return}let l=gk(e.headers.authorization);if(l===void 0){s(e,n,`missing-token`);return}let u=await a.verify(l);if(!u.admitted){s(e,n,u.refusal);return}e.url=c.slice(o.length),await t(e,n)}return(e,t)=>{c(e,t).catch(()=>{t.headersSent||t.writeHead(500),t.end()})}}function Bqe(e,t,n){return new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.off(`error`,a),r()})})}function i9(e){return new Promise(t=>e.close(()=>t()))}function a9(e){let{args:t,preset:n}=e;return{cwd:e.cwd,...e.livePromptTrace?{livePromptTrace:e.livePromptTrace}:{},provider:e.provider,...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.providerErrorGuidance===void 0?{}:{providerErrorGuidance:e.providerErrorGuidance},...e.promptFileReferenceTag===void 0?{}:{promptFileReferenceTag:e.promptFileReferenceTag},...e.modelCommandToolPrefix===void 0?{}:{modelCommandToolPrefix:e.modelCommandToolPrefix},...e.subagentHookEnvironmentNames===void 0?{}:{subagentHookEnvironmentNames:e.subagentHookEnvironmentNames},...e.observerFailureWarningCode===void 0?{}:{observerFailureWarningCode:e.observerFailureWarningCode},...e.commandHookShell===void 0?{}:{commandHookShell:e.commandHookShell},...e.bare===!0?{bare:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...o9(e),...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},environment:e.productRuntime.environment,...e.contributionSources===void 0?{}:{contributionSources:e.contributionSources},...e.skillRoots===void 0?{}:{skillRoots:e.skillRoots},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.model===void 0?{}:{model:e.model},...n.outputStyle===void 0?{}:{outputStyle:n.outputStyle},permissionMode:t.permissionMode??n.permissionMode,...t.supervisedExternalEventGrants===!0?{externalEventVerifierFactory:lA,externalEventGrantHistory:e.externalEventGrantHistory??Nb()}:{},baselinePermissionAllow:e.productRuntime.layout.baselinePermissionAllow,maxTurns:t.maxTurns,sessionStore:t.noSessionPersistence?void 0:e.sessionStore,disableSessionLoops:d4(e.productRuntime.environment),resolveDefaultLoopPrompt:l4({productRuntime:e.productRuntime,projectAccess:e.projectAccess,userHome:e.productRuntime.userHome??e.productRuntime.layout.userRoot}),resumeSessionId:e.resumeSessionId,forkSession:t.forkSession,sessionName:t.sessionName,autoName:!0,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,...e.remoteCommandPolicy?{remoteCommandPolicy:e.remoteCommandPolicy}:{},language:t.language,...C7(n),...t.systemPrompt?{systemPrompt:t.systemPrompt}:{},...n.agentName===void 0?{}:{agentName:n.agentName},...n.activePresetId===void 0?{}:{activePresetId:n.activePresetId},...n.persona===void 0?{}:{persona:n.persona},...n.enableParallelSubagents===void 0?{}:{enableParallelSubagents:n.enableParallelSubagents},...n.selfVerification===void 0?{}:{selfVerification:n.selfVerification},...n.effort===void 0?{}:{effort:n.effort},...n.temperature===void 0?{}:{temperature:n.temperature},...n.maxOutputTokens===void 0?{}:{maxOutputTokens:n.maxOutputTokens},...n.responseFormat===void 0?{}:{responseFormat:n.responseFormat},...n.language===void 0?{}:{language:n.language},...n.systemPrompt===void 0?{}:{presetSystemPrompt:n.systemPrompt},...e.memorySessionOptions??{},...e.setupRequired===!0?{setupRequired:!0}:{}}}function o9(e){return e.createEditCheckpointStore===void 0?{}:{editCheckpointStore:e.createEditCheckpointStore()}}function s9(e,t,n){return{...e,...o9(t),resumeSessionId:n,forkSession:void 0,sessionName:void 0}}function Vqe(e){let t=e.map(e=>e.getLocalActivityStatus());if(t.includes(`needs-input`))return`needs-input`;if(t.includes(`working`))return`working`;if(!t.includes(void 0))return t.length>0?`idle`:void 0}function Hqe(e,t){let n;for(let r of e){if(r.phase!==`waiting`||r.nextAllowedAt===void 0)continue;let e=Date.parse(r.nextAllowedAt),i=Date.parse(r.expiresAt);!Number.isFinite(e)||!Number.isFinite(i)||new Date(e).toISOString()!==r.nextAllowedAt||i<=t||e>=i||(n===void 0||e<n.millis)&&(n={at:r.nextAllowedAt,millis:e})}return n?.at}function Uqe(e){return{requestExit:()=>{throw Error(`A command does not stop the workspace daemon, which serves every client attached to it. Detach this client to leave. To stop the daemon, run ${e.config.identity.cliName} daemon stop; anything this command changed applies when you next run ${e.config.identity.cliName} daemon start.`)},requestRestart:()=>{throw Error(`A command does not restart the workspace daemon, which serves every client attached to it. The change is saved and applies once you restart the daemon: run ${e.config.identity.cliName} daemon stop, then ${e.config.identity.cliName} daemon start.`)}}}function Wqe(e,t){return{requestExit:()=>{throw Error(`A command does not stop this supervised session, which serves every client attached to it. Detach this client to leave. To stop the session, run ${t.config.identity.cliName} session stop ${e}; anything this command changed applies to the next session you start with ${t.config.identity.cliName} session start --background.`)},requestRestart:()=>{throw Error(`A command does not restart this supervised session, which serves every client attached to it. The change is saved and applies to a new session started with ${t.config.identity.cliName} session start --background; to end this one, run ${t.config.identity.cliName} session stop ${e}.`)}}}async function Gqe(e){let{args:t}=e;if(t.open&&!process.stdout.isTTY)throw Error(`Opening the monitor requires an interactive terminal for its access code.`);let n,r,i=e=>{r?r(`received ${e}`):n??=e};process.once(`SIGTERM`,i),process.once(`SIGINT`,i);let a=e=>{if(e.code!==`EPIPE`)throw e};t.supervisedSessionId!==void 0&&process.stderr.on(`error`,a);try{let i=a9(t.supervisedExternalEventGrants===!0&&e.externalEventGrantHistory===void 0?{...e,externalEventGrantHistory:Nb(LA(e.productRuntime.layout.userRoot))}:e),a=!1,o,s,c=e.sessionDirectory,l=await Mfe({session:i,transportRegistry:e.transportRegistry,bindTransports:t=>{if(c!==void 0&&i.sessionStore!==void 0){let n=t.current,r=new ux({primary:n,build:t=>px(s9(i,e,t)),maxLive:4});s=r,c.attach({pool:r,primary:n,store:i.sessionStore,cwd:e.cwd,isStopping:()=>a})}e.bindTransports?.(t)}}),u;if(e.http!==void 0){try{u=await Rqe({port:e.http.port,...e.http.remote===void 0?{token:e.http.token}:{remote:e.http.remote},session:()=>l.session.current,onStreamFailure:e=>{process.stderr.write(`HTTP API stream failed: ${e.message}\n`)},onRefusal:e=>{process.stderr.write(`HTTP API refused: ${e.refusal} (${e.remote}${e.throttled?`, throttled`:``})\n`)}})}catch(t){throw await l.shutdown(`HTTP API could not be served`).catch(()=>void 0),await s?.shutdownAll(`HTTP API could not be served`)?.catch(()=>void 0),Error(`HTTP API could not be served on ${e.http.remote?.host??`127.0.0.1`}:${e.http.port}: ${t instanceof Error?t.message:String(t)}`)}process.stderr.write(e.http.remote===void 0?`HTTP API served at ${u.url}\n`:`HTTP API listening on ${u.listening} for ${u.url}; authorization server: ${e.http.remote.issuer}\n`)}let d=()=>{let e=l.session.current;return[e,...(s?.listLive()??[]).map(e=>e.session).filter(t=>t!==e)]},f=null;try{if(t.open){let t=e.getMonitorWsUrl?.(),n=BKe(e.productRuntime);t&&n?(f=await WKe(n,t,e.productRuntime),process.stdout.write(RKe(f.url,e.productRuntime)),process.stdout.write(`Monitor access code: ${f.accessCode}\n`),GKe(f.url)):n||process.stderr.write(`${e.productRuntime.config.identity.displayName} web assets not found (dist/web) — run a full CLI build.\n`)}}catch(e){throw await f?.close().catch(()=>void 0),await u?.stop().catch(()=>void 0),await l.shutdown(`Monitor could not be served`).catch(()=>void 0),await s?.shutdownAll(`Monitor could not be served`)?.catch(()=>void 0),e}let p,m,h=()=>void 0,g=new AbortController,_=new Promise(n=>{let i=e=>{a||(a=!0,g.abort(),Promise.resolve(f?.close()).catch(()=>{}).then(()=>u?.stop()).catch(()=>void 0).then(()=>m?.stop()).catch(()=>void 0).then(()=>o?.close()).then(()=>l.shutdown(e)).catch(()=>void 0).then(()=>s?.shutdownAll(e)).catch(()=>void 0).then(()=>p?.close()).finally(()=>n()))};h=i,r=i,KKe(l,{setExitCode:e=>{process.exitCode=e},writeError:e=>{process.stderr.write(e)}},i);let c=e=>{setTimeout(()=>i(e),500).unref?.()};e.commandHostAdapters.process=t.daemon===!0?Uqe(e.productRuntime):t.supervisedSessionId===void 0?{requestExit:e=>c(`command exit${e?` (${e})`:``}`),requestRestart:(e,t)=>c(`command restart: ${t}`)}:Wqe(t.supervisedSessionId,e.productRuntime)});if(n!==void 0&&h(`received ${n}`),t.supervisedSessionId!==void 0&&!a)try{if(t.daemon===!0&&e.getMonitorWsUrl?.()===void 0)throw new l9;let n=Cn(e.cwd),r;if(t.supervisedExternalEventGrants===!0){let n=e.supervisedRoot??Y4(e.productRuntime),r=sBe(n,t.supervisedSessionId),i=ZKe(nBe(n),t.supervisedSessionId),a=WA(r,e=>{`settlement`in e&&i(e)});await a.bind(l.session.current),o=a;try{let e=ij({grants:r,receive:(e,t)=>a.receive(e,t),countRefusal:(e,t)=>a.countRefusal(e,t),port:t.externalEventPort??0,...t.externalEventTrustedProxies===void 0?{}:{trustedProxies:t.externalEventTrustedProxies},audit:i});await e.start(),m=e}catch{throw new c9}}let u=o;if(u!==void 0&&(e.commandHostAdapters.externalEvents={list:()=>u.adapter.list(),revoke:e=>u.adapter.revoke(e)}),p=await cBe(t.supervisedSessionId,()=>h(`supervised session stopped`),e.supervisedRoot??Y4(e.productRuntime),()=>a?void 0:Vqe(d()),()=>a?void 0:n,()=>a||i.disableSessionLoops?void 0:Hqe(d().flatMap(e=>e.listSelfPacedLoops()),Date.now()),()=>a?void 0:l.session.current.getName(),e=>{if(a)throw Error(`Supervised runtime is stopping.`);l.session.current.setName(e)},{get:()=>a?void 0:r,set:e=>{if(a)throw Error(`Supervised runtime is stopping.`);r=e}},u===void 0?void 0:{list:()=>u.adapter.list(),revoke:e=>{if(a)throw Error(`Supervised runtime is stopping.`);return u.adapter.revoke(e)}},s!==void 0&&c!==void 0?{binder:c}:{session:l.session},t.daemon===!0?{url:()=>a?void 0:e.getMonitorWsUrl?.(),restricted:e.projectAccess?.status===`restricted`}:void 0),a)throw Error(`Supervised runtime stopped before readiness.`);if(await qqe(t.supervisedSessionId,g.signal,void 0,u?.adapter.list().map(e=>e.grantId)),a)throw Error(`Supervised runtime stopped during readiness.`)}catch(e){if(process.connected&&process.send)try{let n=e instanceof RA?{code:`grant-refused`,grant:e.grantId}:e instanceof c9?{code:`events-endpoint-failed`}:e instanceof l9?{code:`daemon-no-endpoint`}:e instanceof $4?{code:`control-path-too-long`,directory:e.directory}:{code:`startup-failed`};process.send({kind:`error`,id:t.supervisedSessionId,...n},()=>{})}catch{}throw h(`supervised session startup failed`),await p?.close(),await _,e}await _}finally{process.off(`SIGTERM`,i),process.off(`SIGINT`,i),t.supervisedSessionId!==void 0&&process.stderr.off(`error`,a)}}var c9=class extends Error{constructor(){super(`External event endpoint could not be served on its port.`),this.name=`ExternalEventEndpointError`}},l9=class extends Error{constructor(){super(`The daemon has no WebSocket endpoint.`),this.name=`DaemonNoEndpointError`}};function Kqe(){if(!process.send)throw Error(`Supervised serve mode requires a parent readiness channel.`);return{send:(e,t)=>{process.send?.(e,t)},onMessage:e=>{process.on(`message`,e)},offMessage:e=>{process.off(`message`,e)},onDisconnect:e=>{process.on(`disconnect`,e)},offDisconnect:e=>{process.off(`disconnect`,e)}}}async function qqe(e,t,n=Kqe(),r){if(t.aborted)throw Error(`Supervised runtime stopped before readiness.`);await new Promise((i,a)=>{let o=!1,s=e=>{o||(o=!0,clearTimeout(d),n.offMessage(c),n.offDisconnect(u),t.removeEventListener(`abort`,l),e())},c=r=>{if(t.aborted){s(()=>a(Error(`Supervised runtime stopped during readiness.`)));return}if(typeof r!=`object`||!r||!(`kind`in r)||!(`id`in r)||r.kind!==`ack`||r.id!==e){s(()=>a(Error(`Supervised startup acknowledgement was invalid.`)));return}n.send({kind:`acknowledged`,id:e},e=>{t.aborted||e?s(()=>a(Error(`Supervised startup acknowledgement could not be sent.`))):s(i)})},l=()=>s(()=>a(Error(`Supervised runtime stopped during readiness.`))),u=()=>s(()=>a(Error(`Supervised launcher closed before acknowledgement.`))),d=setTimeout(()=>s(()=>a(Error(`Supervised launcher did not acknowledge startup.`))),1e4);n.onMessage(c),n.onDisconnect(u),t.addEventListener(`abort`,l,{once:!0}),n.send({kind:`ready`,id:e,...r===void 0?{}:{grants:r}},e=>{e&&s(()=>a(Error(`Supervised readiness could not be sent.`)))})})}const u9=`This runtime is stopping.`;function Jqe(){let e,t=()=>{if(e===void 0)throw Error(`Sessions are not available yet.`);return e},n=(e,t)=>{let n=new Map(e.pool.listLive().map(e=>[e.sessionId,e.clients])),r=_x(e.store,e.cwd).map(e=>{let t=n.get(e.id);return{...e,live:t!==void 0,clients:t??0}});return{currentSessionId:t.getSession().getSessionId(),sessions:r,unreadableSessionIds:vx(e.store,e.cwd).map(e=>e.id)}},r=e=>{try{return e.slot.current.getSession().getSessionId()}catch{return}},i=(e,t)=>{let n=new Map(e.pool.listLive().map(e=>[e.sessionId,e.clients])),i=r(t);return e=>{let t=n.get(e);return t===void 0?0:t-+(e===i)}},a=e=>{let t=new Map(e.pool.listLive().map(e=>[e.sessionId,e.session]));return e=>{let n=t.get(e);return n!==void 0&&cx(n)}},o=(e,t)=>{let o=e.pool.bind(t),s=!1,c=()=>{if(e.isStopping?.()===!0)return new ix(`stopping`,u9);if(o.isLastDriver()&&o.slot.current.getLocalActivityStatus()===`needs-input`)return new ix(`prompt_pending`,`Answer or dismiss the pending prompt first: no other client driving this session could answer it.`)},l=async t=>{if(e.isStopping?.()===!0)throw new ix(`stopping`,u9);if(s)throw new ix(`in_progress`,`Another session change is already under way.`);let n=c();if(n!==void 0)throw n;s=!0;try{let n=await e.pool.acquire(t),r=c();if(r!==void 0)throw n.cancel(),r;o.moveTo(n)}finally{s=!1}};return{session:o.slot,directory:{listSessions:()=>n(e,o.slot.current),async switchSession(t){if(t!==o.slot.current.getSession().getSessionId()){if(vx(e.store,e.cwd).some(e=>e.id===t))throw new ix(`unreadable`,`Session ${t} was saved in a form this version cannot read.`);if(!_x(e.store,e.cwd).some(e=>e.id===t))throw new ix(`unknown_session`,`No session ${t} in this workspace.`);await l(t)}},async newSession(){let t=yx(e.store,e.cwd,{otherClientsOf:i(e,o),isBusy:a(e)});await l(t)},async renameSession(t,n){if(!_x(e.store,e.cwd).some(e=>e.id===t))throw Error(`No session ${t} in this workspace.`);if(e.pool.listLive().some(e=>e.sessionId===t))throw Error(`Session ${t} is open now; renaming it here would be overwritten the next time it saves. Switch to it to rename it, or wait for it to close.`);xy(e.store,t,n)},async deleteSession(t){if(e.isStopping?.()===!0)throw new ax(`stopping`,u9);if(!_x(e.store,e.cwd).some(e=>e.id===t))throw new ax(`unknown_session`,`No session ${t} in this workspace.`);let n=t===r(o),i=e.pool.listLive().find(e=>e.sessionId===t);if(i!==void 0){if(i.clients-+!!n>0)throw new ax(`live_elsewhere`,`Another client is on this session; it cannot be deleted while someone else is using it.`);if(cx(i.session))throw new ax(`running`,`This session has work in progress; wait for it to finish, then delete it.`)}if(n){let n=_x(e.store,e.cwd).find(e=>e.id!==t)?.id;await l(n)}e.store.delete(t)}},release:()=>o.release()}};return{attach(t){e=t},bind(e){return o(t(),e)},listSessions(){let e=t();return n(e,e.primary)}}}function d9(e){return e===void 0?void 0:{cancellationSignal:e}}function f9(e){if(!(e instanceof ai))return e instanceof Error?e:Error(String(e));let t=e.data,n=typeof t==`object`&&t&&`details`in t&&typeof t.details==`string`?t.details:void 0;return Error(n===void 0?e.message:`${e.message}: ${n}`)}function p9(e){if(!Pn(e))throw Error(`the editor is given absolute paths only: ${e}`)}function Yqe(e,t,n){let r=e?.readTextFile===!0,i=e?.writeTextFile===!0;if(!r&&!i)return;let a=()=>{let e=n();if(e===void 0)throw Error(`the editor has no session to read or write for`);return e};return{...r?{readTextFile:async(e,n)=>{p9(e);try{return(await t.request(`fs/read_text_file`,{sessionId:a(),path:e},d9(n))).content}catch(e){throw f9(e)}}}:{},...i?{writeTextFile:async(e,n,r)=>{p9(e);try{await t.request(`fs/write_text_file`,{sessionId:a(),path:e,content:n},d9(r))}catch(e){throw f9(e)}}}:{}}}function Xqe(e){let t=Math.max(0,...[...e.matchAll(/`+/g)].map(e=>e[0].length));return"`".repeat(Math.max(3,t+1))}function Zqe(e){let t=``,n=[],r=[];for(let i of e)if(i.type===`text`)t+=i.text;else if(i.type===`resource`&&`text`in i.resource){let e=Xqe(i.resource.text);n.push(`Context from ${i.resource.uri}:\n${e}\n${i.resource.text}\n${e}`)}else i.type===`resource_link`&&r.push(`- ${i.uri}`);return r.length>0&&n.push(`Referenced resources:\n${r.join(`
2910
+ `),await h?.(),await w7(1)}await h?.(),await w7(ce.getExitCode())}async function w7(e,t=[process.stdout,process.stderr]){await Promise.all(t.map(e=>new Promise(t=>{if(e.writableLength===0)return t();e.once(`error`,()=>t()),e.write(``,()=>t())}))),process.exit(e)}const T7=`127.0.0.1`,RKe={".html":`text/html; charset=utf-8`,".js":`text/javascript; charset=utf-8`,".mjs":`text/javascript; charset=utf-8`,".css":`text/css; charset=utf-8`,".json":`application/json; charset=utf-8`,".svg":`image/svg+xml`,".png":`image/png`,".ico":`image/x-icon`,".woff2":`font/woff2`,".map":`application/json; charset=utf-8`};function zKe(e,t){return`${t.config.identity.displayName} is open at ${e}\n`}function BKe(){let e=Nee(new URL(`../web`,import.meta.url));return fn(M(e,`index.html`))?e:null}function VKe(e){return e.artifact===void 0?BKe():e.artifact.webRoot??null}const HKe=new Set([`localhost`,`127.0.0.1`,`::1`,`[::1]`]);function UKe(e){if(!e)return!1;let t=e.startsWith(`[`)?e.slice(0,e.indexOf(`]`)+1):e.slice(0,e.lastIndexOf(`:`)===-1?e.length:e.lastIndexOf(`:`));return HKe.has(t)}function WKe(e,t,n){let r=`<meta name="ws-url" content="${t}" /><script id="product-config" type="application/json">${JSON.stringify(Oge(n.config)).replaceAll(`<`,`\\u003c`)}<\/script>`;return e.includes(`</head>`)?e.replace(`</head>`,` ${r}\n </head>`):`${r}\n${e}`}async function GKe(e,t,n){let r=Cn(e),i=Wn(32).toString(`base64url`),a=Wn(32).toString(`base64url`),o=`/${Wn(24).toString(`base64url`)}/`,s=hr((e,s)=>{if(s.setHeader(`Referrer-Policy`,`no-referrer`),s.setHeader(`Cache-Control`,`no-store`),!UKe(e.headers.host)){s.writeHead(403).end(`Forbidden host`);return}if(e.method===`POST`&&e.url===`/__monitor_login`){let t=``,n=setTimeout(()=>e.destroy(),1e4);n.unref(),e.once(`close`,()=>clearTimeout(n)),e.setEncoding(`utf8`),e.setTimeout(1e4,()=>e.destroy()),e.on(`error`,()=>{}),e.on(`data`,n=>{t+=n,t.length>1024&&e.destroy()}),e.on(`end`,()=>{let e=new URLSearchParams(t).get(`code`)??``,n=Buffer.from(i),r=Buffer.from(e);if(r.length!==n.length||!Kn(r,n)){s.writeHead(403).end(`Invalid access code`);return}s.writeHead(303,{Location:o,"Set-Cookie":`robota_monitor=${a}; HttpOnly; SameSite=Strict; Path=${o}`}).end()});return}if(e.method!==`GET`&&e.method!==`HEAD`){s.writeHead(405).end(`Method not allowed`);return}if(e.url===`/`){s.writeHead(200,{"content-type":`text/html; charset=utf-8`,"content-security-policy":`default-src 'none'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,"x-frame-options":`DENY`}).end(`<!doctype html><title>Monitor access</title><form method="post" action="/__monitor_login"><label>Access code from your terminal <input name="code" type="password" required autocomplete="off"></label><button type="submit">Open monitor</button></form>`);return}let c=(e.url??`/`).split(`?`)[0].startsWith(o);if(c){let t=(e.headers.cookie??``).split(`;`).map(e=>e.trim()).filter(e=>e.startsWith(`robota_monitor=`)),n=Buffer.from(t[0]?.slice(15)??``),r=Buffer.from(a);if(t.length!==1||n.length!==r.length||!Kn(n,r)){s.writeHead(403).end(`Forbidden`);return}}let l;try{l=decodeURIComponent((e.url??`/`).split(`?`)[0])}catch{s.writeHead(400).end(`Bad request`);return}let u=(c?l===o?`/index.html`:`/${l.slice(o.length)}`:l).split(`/`).filter(e=>e.length>0);if(u.length===0||!u.every(e=>e!==`.`&&e!==`..`&&!e.includes(Rn)&&!e.includes(`\\`))){s.writeHead(403).end(`Forbidden`);return}let d=M(r,...u),f;try{f=Cn(d)}catch{s.writeHead(404).end(`Not found`);return}if(!$t(r,f)){s.writeHead(403).end(`Forbidden`);return}let p=f.endsWith(`${Rn}index.html`);if(p&&!c){s.writeHead(403).end(`Forbidden`);return}let m=RKe[Nn(f)]??`application/octet-stream`,h,g;try{g=bn(f,`r`)}catch{s.writeHead(404).end(`Not found`);return}try{if(!pn(g).isFile()){s.writeHead(404).end(`Not found`);return}h=p?WKe(A(g,`utf8`),t,n):A(g)}catch{s.writeHead(404).end(`Not found`);return}finally{un(g)}s.writeHead(200,{"content-type":m,...f===M(r,`app-sandbox.html`)?{"Connection-Allowlist":`()`}:{}}),s.end(h)});await new Promise((e,t)=>{s.once(`error`,t),s.listen(0,T7,()=>{s.off(`error`,t),e()})});let c=s.address(),l=typeof c==`object`&&c?c.port:0;return{url:`http://${T7}:${l}`,accessCode:i,close:()=>new Promise((e,t)=>{s.close(n=>n?t(n):e()),s.closeAllConnections()})}}function KKe(e){let t=process.platform===`darwin`?`open`:process.platform===`win32`?`start`:`xdg-open`;try{let n=on(t,[e],{stdio:`ignore`,detached:!0,shell:process.platform===`win32`});n.on(`error`,()=>{}),n.unref()}catch{}}async function qKe(e,t,n){try{let r=await e.waitForFailure();if(!r)return;t.setExitCode(r.outcome.exitCode),t.writeError(`transport failed: ${r.name} exited ${r.outcome.exitCode}\n`),n(`a transport failed`)}catch(e){t.setExitCode(1);let r=e instanceof Error?e.message:String(e);t.writeError(`transport failed: ${r}\n`),n(`a transport failed`)}}const JKe=/^[0-9a-f-]{36}$/u;function YKe(e){return`${JSON.stringify({at:e.at,...e.grantId===void 0?{}:{grantId:e.grantId},...`refusal`in e?{refusal:e.refusal}:{settlement:e.settlement},...e.remote===void 0?{}:{remote:e.remote},...e.throttled===void 0?{}:{throttled:e.throttled}})}\n`}function XKe(e){let t=Sn(e).filter(e=>e.endsWith(`.jsonl`)).map(t=>{try{return{name:t,at:_n(M(e,t)).mtimeMs}}catch{return}}).filter(e=>e!==void 0).sort((e,t)=>t.at-e.at);for(let n of t.slice(64))Tn(M(e,n.name),{force:!0})}function E7(e,t){let n=0;for(;n<t.length;)n+=An(e,t,n,t.length-n)}function ZKe(e,t){Tn(t,{force:!0});let n=bn(t,k.O_WRONLY|k.O_CREAT|k.O_EXCL|k.O_NOFOLLOW,384);try{let t=Buffer.alloc(64*1024),r=0;for(;;){let i=xn(e,t,0,t.length,r);if(i===0)break;E7(n,t.subarray(0,i)),r+=i}}finally{un(n)}hn(e,0)}function QKe(e,t){if(!JKe.test(t))throw Error(`Invalid supervised session ID.`);let n=M(e,`${t}.jsonl`),r=M(e,`${t}.1.jsonl`);try{XKe(e)}catch{}return e=>{let t=YKe(e);try{let e=bn(n,k.O_RDWR|k.O_APPEND|k.O_CREAT|k.O_NOFOLLOW,384);try{let n=Buffer.from(t);pn(e).size+n.length>262144&&ZKe(e,r),E7(e,n)}finally{un(e)}}catch{}}}function $Ke(){let e=new Map;return{record(t,n){let r=e.get(t);r===void 0&&(r=new Map,e.set(t,r)),r.set(n.event.id,n)},forget(t,n){e.get(t)?.delete(n)},list:t=>[...e.get(t)?.values()??[]],find:(t,n)=>e.get(t)?.get(n),clear(t){e.delete(t)}}}function eqe(e){return async t=>{let n=await e.sessionFactory(t),r=e.claims.keyFor(n);return t.json({prompts:r===void 0?[]:e.openPrompts.list(r)})}}function tqe(e){let{sessionFactory:t,claims:n,openPrompts:r,attribution:i}=e;return async e=>{let a=await t(e),o=e.req.param(`id`)??``,s;try{s=await e.req.json()}catch{return e.json({error:`the body must be a JSON object`},400)}let c=n.keyFor(a),l=c===void 0?void 0:r.find(c,o);if(c===void 0||l===void 0)return e.json({error:`no open prompt with this id`},404);if(l.type===`permission_request`){let t=tJ({type:`permission-response`,id:o,result:s?.result});if(!t.ok||t.message.type!==`permission-response`)return e.json({error:`result must be true, false, "allow-session" or "allow-project"`},400);a.resolvePermission(o,t.message.result,i?.driverId)}else{let t=tJ({type:`ask-response`,id:o,response:s?.response});if(!t.ok||t.message.type!==`ask-response`)return e.json({error:`response must be { "type": "answer", "values": string[], "text"?: string } or { "type": "cancelled" }`},400);a.resolveAsk(o,t.message.response,i?.driverId)}return r.find(c,o)===void 0?e.json({ok:!0}):e.json({error:`the session did not accept this answer`},409)}}function nqe(e,t,n,r,i){let a=(t,r)=>{e.on(t,r),n.push(()=>e.off(t,r))},o=(e,n)=>t.writeSSE({event:e,data:JSON.stringify(n)}).catch(()=>{}),s,c=new Promise(e=>{s=e});return a(`text_delta`,e=>void o(`text_delta`,{delta:e})),a(`tool_start`,e=>void o(`tool_start`,e)),a(`tool_end`,e=>void o(`tool_end`,e)),a(`thinking`,e=>void o(`thinking`,{isThinking:e})),i!==void 0&&rqe(a,o,i),a(`complete`,async e=>{await o(`complete`,e),s()}),a(`interrupted`,async e=>{await o(`interrupted`,e),s()}),a(`error`,async e=>{await o(`error`,{message:e.message}),s()}),t.onAbort(()=>iqe(e,r,s)),c}function rqe(e,t,n){e(`permission_request`,e=>{n.record({type:`permission_request`,event:e}),t(`permission_request`,e)}),e(`ask_request`,e=>{n.record({type:`ask_request`,event:e}),t(`ask_request`,e)}),e(`prompt_resolved`,e=>{n.forget(e.id),t(`prompt_resolved`,e)})}function iqe(e,t,n){try{e.abort()}catch(e){try{t?.(e instanceof Error?e:Error(String(e)))}catch{}}finally{n()}}function aqe(e,t){for(let t of e)try{t()}catch{}t()}function oqe(e,t,n,r,i,a){return async o=>{try{let s=[];try{let n=nqe(e,o,s,r,a);await(i===void 0?e.submit(t):e.submit(t,void 0,void 0,{...i})),await n}finally{aqe(s,n)}}catch(e){await sqe(e instanceof Error?e:Error(String(e)),o,r)}}}async function sqe(e,t,n){try{n?.(e)}catch{}await t.writeSSE({event:`error`,data:JSON.stringify({message:`the stream failed on the server after it opened — the turn may not have run`})}).catch(()=>{})}function cqe(e,t,n){let r=n.keyFor(t);return r===void 0?e.json({error:`concurrent-turn tracking is unavailable for this session, so this request cannot be served safely. Refusing rather than starting a turn that cannot be guaranteed to be yours.`},500):n.isHeld(r)||t.isExecuting()?e.json({error:`session busy — a turn is already in flight`},409):(n.hold(r),{claim:r})}function lqe(e){let{sessionFactory:t,claims:n,openPrompts:r,onStreamFailure:i,attribution:a}=e;return async e=>{let o=await t(e),s=await e.req.json();if(!s.prompt||typeof s.prompt!=`string`)return e.json({error:`prompt is required`},400);if(s.receivePrompts!==void 0&&typeof s.receivePrompts!=`boolean`)return e.json({error:`receivePrompts must be a boolean`},400);if(o.whenInitialized!==void 0)try{await o.whenInitialized()}catch{return e.json({error:`the session could not be started`},500)}let c=cqe(e,o,n);if(c instanceof Response)return c;let{claim:l}=c,u=!1,d=()=>{u||(u=!0,r.clear(l),n.release(l))},f=s.receivePrompts===!0?{record:e=>r.record(l,e),forget:e=>r.forget(l,e)}:void 0;try{return await yte(e,oqe(o,s.prompt,d,i,a,f))}catch(e){throw d(),e}}}function uqe(){let e=new Set;return{keyFor(e){try{let t=e.getSession().getSessionId();return typeof t==`string`&&t!==``?t:void 0}catch{return}},isHeld:t=>e.has(t),hold:t=>void e.add(t),release:t=>void e.delete(t)}}function dqe(e){let{sessionFactory:t,onStreamFailure:n,attribution:r}=e,i=new _te,a=uqe(),o=$Ke(),s=e.maxJsonBodyBytes??65536;if(!Number.isSafeInteger(s)||s<1)throw Error(`maxJsonBodyBytes must be a positive integer`);let c=vte({maxSize:s,onError:e=>e.json({error:`request body too large`},413)}),l=mk(e.admission);return i.use(`*`,async(e,t)=>l.token===null||hk(l.token,gk(e.req.header(`authorization`)))?t():e.json({error:`unauthorized`},401)),i.post(`/submit`,c,lqe({sessionFactory:t,claims:a,openPrompts:o,onStreamFailure:n,attribution:r})),i.get(`/prompts`,eqe({sessionFactory:t,claims:a,openPrompts:o,attribution:r})),i.post(`/prompts/:id`,c,tqe({sessionFactory:t,claims:a,openPrompts:o,attribution:r})),i.post(`/command`,c,async e=>{let n=await t(e),r=await e.req.json();if(!r.name||typeof r.name!=`string`)return e.json({error:`name is required`},400);let i=await n.executeCommand(r.name,r.args??``,`remote`);return i?e.json(i):e.json({error:`Unknown command: ${r.name}`},404)}),i.post(`/abort`,async e=>((await t(e)).abort(),e.json({ok:!0}))),i.post(`/cancel-queue`,async e=>((await t(e)).cancelQueue(),e.json({ok:!0}))),i.get(`/messages`,async e=>{let n=await t(e);return e.json(n.getMessages())}),i.get(`/context`,async e=>{let n=await t(e);return e.json(n.getContextState())}),i.get(`/executing`,async e=>{let n=await t(e),r=a.keyFor(n),i=r!==void 0&&a.isHeld(r);return e.json({executing:i||n.isExecuting()})}),i.get(`/pending`,async e=>{let n=await t(e);return e.json({pending:n.getPendingPrompt()})}),i}const D7={type:`cancelled`},O7=`decision`,k7=`allow_once`,A7=`answer`,j7=`text`,M7=2e3;function N7(e){return e.length>M7?`${e.slice(0,M7)}…`:e}function fqe(e){let t=NJ(e.toolArgs),n=`Allow ${e.toolName}${t===void 0?``:`: ${N7(t)}`}?`,r=[e.requester?`${e.requester.label} asks: ${n}`:n];return r.push(`Arguments: ${N7(JSON.stringify(e.toolArgs))}`),e.cwd!==void 0&&r.push(`Working directory: ${e.cwd}`),r.join(`
2911
+ `)}function pqe(e){return{message:fqe(e),requestedSchema:{type:`object`,properties:{[O7]:{type:`string`,title:`Decision`,description:`Allow this one call, or deny it. Nothing is remembered.`,enum:[k7,`deny`],enumNames:[`Allow once`,`Deny`]}},required:[O7]}}}function mqe(e){return e.action===`accept`&&e.content?.decision===k7}function P7(e){let t=Math.max(1,Math.floor(e.maxSelect??1));return{min:Math.min(t,Math.max(0,Math.floor(e.minSelect??1))),max:t}}function hqe(e,t){let{min:n,max:r}=P7(e),i=t.map(e=>e.value),a=t.filter(e=>e.description!==void 0||e.label!==e.value).map(e=>e.description===void 0?`${e.value}: ${e.label}`:`${e.value}: ${e.label} — ${e.description}`),o=a.length>0?a.join(`
2912
+ `):void 0,s=e.default?.values?.filter(e=>i.includes(e));return r>1?{type:`array`,title:`Answer`,...o===void 0?{}:{description:o},minItems:n,maxItems:r,items:{type:`string`,enum:i},...s!==void 0&&s.length>0?{default:s}:{}}:{type:`string`,title:`Answer`,...o===void 0?{}:{description:o},enum:i,enumNames:t.map(e=>e.label),...s?.[0]===void 0?{}:{default:s[0]}}}function gqe(e){if(e.masked===!0)return;let t=e.options??[],n=e.allowFreeText===!0;if(t.length===0&&!n)return;let r={},i=[];if(t.length>0&&(r[A7]=hqe(e,t),!n&&P7(e).min>0&&i.push(A7)),n){let n=e.default?.text;r[j7]={type:`string`,title:t.length>0?`Other answer`:`Answer`,...e.placeholder===void 0?{}:{description:e.placeholder},...e.allowEmpty===!0?{}:{minLength:1},...n===void 0?{}:{default:n}},t.length===0&&e.allowEmpty!==!0&&i.push(j7)}return{message:[e.title,e.description].filter(e=>e).join(`
2913
+ `),requestedSchema:{type:`object`,properties:r,...i.length>0?{required:i}:{}}}}function _qe(e,t){if(t.action!==`accept`)return D7;let n=t.content??{},r=new Set((e.options??[]).map(e=>e.value)),{min:i,max:a}=P7(e),o=n[A7],s=[];if(o!==void 0){let e=Array.isArray(o)?o:[o];for(let t of e){if(typeof t!=`string`||!r.has(t)||s.includes(t))return D7;s.push(t)}}if(s.length>a)return D7;let c=n[j7];if(c!==void 0&&(typeof c!=`string`||e.allowFreeText!==!0))return D7;let l=c!==void 0&&c!==``;return s.length<i&&!l||s.length===0&&!l&&e.allowEmpty!==!0?D7:{type:`answer`,values:s,...c===void 0?{}:{text:c}}}function F7(e){return e.kind===`permission`?pqe(e.event):gqe(e.event.request)}function vqe(e){let t=e?.elicitation;return typeof t!=`object`||!t?!1:t.form!==void 0||t.url===void 0}let yqe=0;function I7(){return`mcp:${++yqe}`}var L7=class{session;driverId;queue=[];waiter;settledHooks=new Map;seen=new Set;open=new Map;settledIds=new Set;listening=!1;closed=!1;constructor(e,t){this.session=e,this.driverId=t,e.on(`turn_source`,this.onTurnStart),e.on(`prompt_resolved`,this.onPromptResolved)}followActiveDriver(){if(this.closed)return;let e=this.session.getActiveDriverId()===this.driverId;e&&!this.listening?(this.listening=!0,this.session.on(`permission_request`,this.onPermissionRequest),this.session.on(`ask_request`,this.onAskRequest)):!e&&this.listening&&this.stopListening()}onTurnStart=()=>this.followActiveDriver();stopListening(){this.listening&&(this.listening=!1,this.session.off(`permission_request`,this.onPermissionRequest),this.session.off(`ask_request`,this.onAskRequest))}onPermissionRequest=e=>{e.requesterDriverId===this.driverId&&this.push({kind:`permission`,event:e})};onAskRequest=e=>{e.requesterDriverId===this.driverId&&this.push({kind:`ask`,event:e})};onPromptResolved=e=>{if(!this.seen.has(e.id))return;this.settledIds.add(e.id),this.open.delete(e.id);let t=this.queue.findIndex(t=>t.event.id===e.id);t>=0&&this.queue.splice(t,1),this.runSettledHooks(e.id)};push(e){if(this.closed)return;this.seen.add(e.event.id),this.open.set(e.event.id,e);let t=this.waiter;if(t===void 0){this.queue.push(e);return}this.waiter=void 0,t.signal.removeEventListener(`abort`,t.onAbort),t.resolve(e)}next(e){let t=this.queue.shift();return t===void 0?this.closed?Promise.reject(Error(`The call has ended`)):e.aborted?Promise.reject(Error(`No longer waiting for a prompt`)):this.waiter===void 0?new Promise((t,n)=>{let r=()=>{this.waiter=void 0,n(Error(`No longer waiting for a prompt`))};this.waiter={resolve:t,reject:n,signal:e,onAbort:r},e.addEventListener(`abort`,r,{once:!0})}):Promise.reject(Error(`Already waiting for a prompt`)):Promise.resolve(t)}whenSettled(e,t){if(this.closed||this.settledIds.has(e))return t(),()=>void 0;let n=this.settledHooks.get(e);return n===void 0&&(n=new Set,this.settledHooks.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&this.settledHooks.delete(e)}}settle(e,t){try{if(e.kind===`permission`){let n=t!==void 0&&mqe(t);this.session.resolvePermission(e.event.id,n,this.driverId);return}let n=t===void 0?{type:`cancelled`}:_qe(e.event.request,t);this.session.resolveAsk(e.event.id,n,this.driverId)}catch{}}settleOutstanding(){for(let e of[...this.open.values()])this.settle(e,void 0)}close(){if(this.closed)return;this.closed=!0;for(let e of[...this.settledHooks.keys()])this.runSettledHooks(e);let e=this.waiter;e!==void 0&&(this.waiter=void 0,e.signal.removeEventListener(`abort`,e.onAbort),e.reject(Error(`The call has ended`))),this.queue.length=0,this.session.off(`turn_source`,this.onTurnStart),this.stopListening(),this.session.off(`prompt_resolved`,this.onPromptResolved)}runSettledHooks(e){let t=this.settledHooks.get(e);if(t!==void 0){this.settledHooks.delete(e);for(let e of t)e()}}};function R7(e){e.prompts.settleOutstanding(),e.abort.abort()}var bqe=class{deadlineMs;parked=new Map;stopped=!1;constructor(e=18e5){this.deadlineMs=e}has(e){return this.parked.has(e)}park(e){if(this.stopped||this.parked.size>=16)return;let t=Wn(32).toString(`base64url`),n=setTimeout(()=>{this.parked.get(t)?.call===e&&(this.parked.delete(t),R7(e))},this.deadlineMs);return n.unref?.(),this.parked.set(t,{call:e,timer:n}),t}take(e){let t=this.parked.get(e);if(t!==void 0)return this.parked.delete(e),clearTimeout(t.timer),t.call}abortAll(){this.stopped=!0;for(let{call:e,timer:t}of this.parked.values())clearTimeout(t),R7(e);this.parked.clear()}};const xqe={name:`agent_submit`,description:`Submit a prompt to the agent and await its turn`};function z7(e){let t=Cte.Tool[`~standard`].validate(JSON.parse(JSON.stringify(e)));if(t.issues!==void 0){let e=t.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).map(String).join(`.`);return t?`${t}: ${e.message}`:e.message});throw Error(`Invalid MCP tool: ${e.join(`; `)}`)}return t.value}function B7(e=xqe){if(typeof e.name!=`string`||!/^[A-Za-z0-9._-]{1,128}$/.test(e.name))throw Error(`MCP submit tool name must contain 1–128 ASCII letters, digits, dots, hyphens, or underscores`);return z7({name:e.name,description:e.description,inputSchema:{type:`object`,properties:{prompt:{type:`string`,minLength:1}},required:[`prompt`],additionalProperties:!1}})}async function V7(e,t){let n=new Set([t]);return(await e.listRuntimeTools()).map(e=>{if(n.has(e.name))throw Error(`Duplicate or reserved MCP tool name: ${e.name}`);return n.add(e.name),z7({name:e.name,description:e.description,inputSchema:e.parameters})})}function H7(e){return{content:[{type:`text`,text:e}],isError:!0}}function U7(e){return e===null||typeof e==`string`||typeof e==`boolean`?!0:typeof e==`number`?Number.isFinite(e):Array.isArray(e)?e.every(U7):typeof e==`object`&&Object.values(e).every(U7)}function Sqe(e){return Object.values(e).every(U7)}async function Cqe(e,t,n,r,i){let a;try{r.throwIfAborted(),a=await V7(e,i)}catch(e){return H7(e instanceof Error?e.message:String(e))}if(t===i){let t=n.prompt;return typeof t!=`string`||t.length===0||Object.keys(n).some(e=>e!==`prompt`)?H7(`${i} requires a non-empty string prompt and no other arguments`):async(n,r)=>{try{let i=await e.submit(t,void 0,void 0,{signal:n,...r===void 0?{}:{driverId:r.driverId}});return r?.holding(),{content:[{type:`text`,text:(await i.completed).response}]}}catch(e){if(!ao(e)&&!n.aborted)throw e;return H7(e instanceof Error?e.message:String(e))}}}if(!a.some(e=>e.name===t))return H7(`Unknown tool: ${t}`);if(!Sqe(n))return H7(`Tool arguments must contain JSON values`);let o=n;return async(n,r)=>{try{let i=e.invokeRuntimeTool(t,o,{signal:n,...r===void 0?{}:{driverId:r.driverId,permissionInteraction:`interactive`}});r?.holding();let a=await i;return{content:[{type:`text`,text:JSON.stringify(a)}],isError:!a.success}}catch(e){return H7(e instanceof Error?e.message:String(e))}}}async function wqe(e,t,n,r,i,a){if(a?.kind===`rounds`&&a.requestState!==void 0)return Oqe(a.pending,a.requestState,a.inputResponses,r);let o=await Cqe(e,t,n,r,i);return typeof o==`function`?a===void 0?o(r,void 0):a.kind===`elicit`?Eqe(e,o,r,a.elicit):Dqe(e,o,r,a.pending):o}function W7(e){return{driverId:e.driverId,holding:()=>e.followActiveDriver()}}async function Tqe(e,t,n,r){let i=F7(t);if(i===void 0){e.settle(t,void 0);return}let a=new AbortController,o=!1,s=e.whenSettled(t.event.id,()=>{o=!0,a.abort()}),c=()=>a.abort();r.addEventListener(`abort`,c,{once:!0});let l;try{l=await n(i,a.signal)}catch{l=void 0}finally{s(),r.removeEventListener(`abort`,c)}o||e.settle(t,l)}async function Eqe(e,t,n,r){let i=new L7(e,I7()),a=new AbortController,o=new Set,s=(async()=>{for(;;){let e=await i.next(a.signal),t=Tqe(i,e,r,n).catch(()=>void 0).finally(()=>{o.delete(t)});o.add(t)}})().catch(()=>void 0);try{return await t(n,W7(i))}finally{a.abort(),await s,i.close(),await Promise.all(o)}}function Dqe(e,t,n,r){let i=new AbortController,a=new L7(e,I7());return G7({prompts:a,outcome:t(i.signal,W7(a)).finally(()=>a.close()),abort:i},n,r)}function Oqe(e,t,n,r){let i=e.take(t);if(i===void 0)return Promise.resolve(H7(`Unknown or expired request state`));let a=Ste(n,i.prompt.event.id);return i.prompts.settle(i.prompt,a.kind===`elicit`?kqe(a):void 0),G7(i,r,e)}function kqe(e){let t={};for(let[n,r]of Object.entries(e.content??{}))(typeof r==`string`||typeof r==`number`||typeof r==`boolean`||Array.isArray(r)&&r.every(e=>typeof e==`string`))&&(t[n]=r);return{action:e.action,...e.content===void 0?{}:{content:t}}}async function G7(e,t,n){let r=()=>R7(e);t.addEventListener(`abort`,r,{once:!0}),t.aborted&&r();let i=new AbortController;try{for(;;){let a=await Promise.race([e.outcome.then(e=>({result:e})),e.prompts.next(i.signal).then(e=>({prompt:e}),()=>e.outcome.then(e=>({result:e})))]);if(`result`in a)return a.result;let o=F7(a.prompt),s=o===void 0?void 0:n.park({...e,prompt:a.prompt});if(o===void 0||s===void 0){e.prompts.settle(a.prompt,void 0);continue}return t.removeEventListener(`abort`,r),ii({inputRequests:{[a.prompt.event.id]:ii.elicit(o)},requestState:s})}}finally{i.abort(),t.removeEventListener(`abort`,r)}}function K7(e,t,n={kind:`none`}){let{name:r,version:i,session:a}=e,o=e.askClient===!0,s=o&&n.kind===`rounds`?n.pending:void 0,c=new bte({name:r,version:i},{capabilities:{tools:{}},...s===void 0?{}:{requestState:{verify:e=>{if(!s.has(e))throw Error(`Unknown or expired MCP request state`)}}}}),l=e=>{if(s!==void 0){let t=e.mcpReq.requestState();if(t!==void 0)return{kind:`rounds`,pending:s,requestState:t,inputResponses:e.mcpReq.inputResponses}}if(!(!o||!vqe(c.getClientCapabilities()))){if(n.kind===`connection`)return{kind:`elicit`,elicit:(e,t)=>c.elicitInput(e,{signal:t,timeout:36e5})};if(s!==void 0)return{kind:`rounds`,pending:s,requestState:void 0,inputResponses:void 0}}};return c.setRequestHandler(`tools/list`,async()=>({tools:[...await V7(a,t.name),t]})),c.setRequestHandler(`tools/call`,async(e,n)=>wqe(a,e.params.name,e.params.arguments??{},n.mcpReq.signal,t.name,l(n))),c}async function Aqe(e){let t=B7(e.submitTool);return await V7(e.session,t.name),K7(e,t,{kind:`connection`})}function jqe(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=e.stdin??process.stdin,c=e.stdout??process.stdout,l=null,u=null,d=Promise.resolve(),f=()=>{d=new Promise((e,t)=>{l=e,u=t}),d.catch(()=>void 0)},p=()=>{l?.(),o?.(Error(`MCP input closed during startup`))},m=()=>{l?.(),o?.(Error(`MCP output closed during startup`))},h=e=>{u?.(e),o?.(e)},g=()=>{a?.release(),a=null},_=e=>Object.assign(Error(`MCP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`mcp`});return{name:`mcp`,lifecycle:Object.freeze({kind:`service`}),attach(e){if(n||r||i)throw _(`already-started`);t=e,f()},async start(){if(!t)throw _(`not-attached`);if(n||r||i)throw _(`already-started`);let d=t,f=new Promise((e,t)=>{o=t}),v=cA(s,c,{onInputClose:p,onOutputClose:m,onOutputError:h});a=v,r=(async()=>{let t=null,r=setTimeout(()=>o?.(Error(`MCP carrier startup timed out`)),15e3);try{t=await Promise.race([Aqe({name:e.name,version:e.version,session:d,...e.submitTool===void 0?{}:{submitTool:e.submitTool},...e.askClient===void 0?{}:{askClient:e.askClient}}),f]);let r=new wte(v.bridge,c,{maxBufferSize:10485760});r.onclose=()=>l?.(),r.onerror=e=>u?.(e),await t.connect(r),n=t,t=null}catch(e){throw g(),t&&await t.close().catch(()=>void 0),e}finally{clearTimeout(r),o=null}})();try{await r}finally{r=null}},stop(){return i||(i=(async()=>{try{o?.(Error(`MCP carrier startup stopped`)),r&&await r.catch(()=>void 0),n&&await n.close()}finally{g(),n=null,t=null,l?.()}})().finally(()=>{i=null}),i)},getServer(){if(!n)throw Error(`Transport not started. Call start() first.`);return n},waitForClose(){return d}}}const q7=`MCP HTTP`;function Mqe(e,t=()=>performance.now()){let n=Hk({resource:e.publicUrl,issuer:e.issuer,scopes:e.scopes,label:q7}),r=Vk({publicUrl:e.publicUrl,...e.trustedProxies===void 0?{}:{trustedProxies:e.trustedProxies},label:q7,now:t}),i=r.url.pathname;function a(t,i,a){Gk(t,i,r,n,a,e.audit)}return{endpointPath:i,async admit(t,o){if(!r.checkNames(t,o))return!1;if(t.url===n.wellKnownPath)return Uk(t,o,n),!1;if(t.url!==i)return o.writeHead(404).end(),!1;let s=gk(t.headers.authorization);if(s===void 0)return a(t,o,`missing-token`),!1;let c=await e.verifier.verify(s);return c.admitted?!0:(a(t,o,c.refusal),!1)}}}const J7=`127.0.0.1`,Y7=1024*1024;function X7(e){if(e!==void 0&&(!Number.isInteger(e)||e<0||e>65535))throw Error(`MCP HTTP port must be an integer in 0..65535`)}function Z7(e,t,n){let r=B7(e.submitTool),i=new bqe,a,o,s,c=!1,l=!1,u=0,d,f,p=new Promise((e,t)=>{d=e,f=t});return p.catch(()=>void 0),{async start(){if(c||s)throw Error(`MCP HTTP host already started`);if(c=!0,await V7(e.session,r.name),l)throw Error(`MCP HTTP host stopped during startup`);o=xte(t=>K7(e,r,t.era===`modern`?{kind:`rounds`,pending:i}:{kind:`none`}),{maxSubscriptions:0});let p=Tte(o),m=(e,t)=>{if(u>=16){t.writeHead(503).end();return}u+=1,(async()=>{try{let n;if(e.method===`POST`){let r=Number(e.headers[`content-length`]);if(Number.isFinite(r)&&r>Y7){t.writeHead(413).end();return}let i=[],a=0;for await(let n of e){let r=Buffer.isBuffer(n)?n:Buffer.from(n);if(a+=r.length,a>Y7){t.writeHead(413).end(),e.destroy();return}i.push(r)}try{n=JSON.parse(Buffer.concat(i).toString(`utf8`))}catch{t.writeHead(400).end();return}}await p(e,t,n)}catch{t.headersSent?t.destroy():t.writeHead(500).end()}finally{--u}})()},h=hr({maxHeaderSize:16*1024},(e,t)=>{let r=h.address();if(!r||typeof r==`string`){t.writeHead(503).end();return}let i=n(e,t,r.port);i===!0?m(e,t):i!==!1&&i.then(n=>{n&&m(e,t)},()=>{t.headersSent?t.destroy():t.writeHead(500).end()})});h.maxConnections=32,h.headersTimeout=5e3,h.requestTimeout=15e3,h.on(`error`,e=>f?.(e)),h.on(`close`,()=>d?.());try{await new Promise((n,r)=>{h.once(`error`,r),h.listen(e.port??0,t,()=>{h.off(`error`,r),n()})})}catch(e){throw await o.close(),e}if(l)throw await new Promise(e=>h.close(()=>e())),await o.close(),Error(`MCP HTTP host stopped during startup`);return a=h,h.address()},stop(){return s||(l=!0,s=(async()=>{let e=o,t=a;if(i.abortAll(),!t){await e?.close(),d?.();return}let n=new Promise((e,n)=>{t.close(t=>t?n(t):e()),t.closeAllConnections()}),r;try{await Promise.race([Promise.all([e?.close(),n]).then(()=>void 0),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`MCP HTTP close timed out`)),5e3)})])}finally{r&&clearTimeout(r)}})(),s)},waitForClose(){return p}}}function Nqe(e){if(e.host!==void 0&&e.host!==J7)throw Error(`MCP HTTP host must bind numeric IPv4 loopback`);X7(e.port);let t=pk(),n=Z7(e,J7,(e,n,r)=>{let i=`${J7}:${r}`,a=`http://${i}`;if(e.url!==`/mcp`||e.headers.host!==i||e.headers.origin!==void 0&&e.headers.origin!==a)return n.writeHead(403).end(),!1;let o=e.headers.authorization;return typeof o!=`string`||!hk(t,gk(o))?(n.writeHead(401).end(),!1):!0});return{async start(){let e=await n.start();return{url:`http://${J7}:${e.port}/mcp`,token:t}},stop:n.stop,waitForClose:n.waitForClose}}function Pqe(e){let t=e.host??J7;if(pr(t)===0)throw Error(`MCP HTTP host must bind a literal IP address`);X7(e.port);let n=Mqe(e.authorization),r=Z7(e,t,(e,t)=>n.admit(e,t));return{async start(){let t=await r.start();return{listening:`${t.family===`IPv6`?`[${t.address}]`:t.address}:${t.port}`,url:e.authorization.publicUrl}},stop:r.stop,waitForClose:r.waitForClose}}async function Q7(e,t,n){let r;try{await Promise.race([e.shutdown({reason:`other`,message:t}),new Promise((e,t)=>{r=setTimeout(()=>t(Error(`${n} session shutdown timed out`)),5e3)})])}finally{r!==void 0&&clearTimeout(r)}}const $7=[`RS256`,`ES256`,`EdDSA`];function e9(e){return{name:`${e.config.identity.cliName}_submit`,description:`Submit a prompt to the agent and await its own turn`}}async function t9(e,t,n,r){let i,a=new Promise(e=>{i=e}),o=()=>i?.();process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{let e=await Promise.race([t.start(),a.then(()=>void 0)]);if(!e)return;await n(e),await Promise.race([t.waitForClose(),a])}finally{process.off(`SIGINT`,o),process.off(`SIGTERM`,o);try{await t.stop()}finally{try{await r()}finally{await Q7(e,`MCP HTTP carrier closed`,`MCP`)}}}}function Fqe(e){process.stderr.write(`MCP HTTP refused: ${e.refusal} (${e.remote}${e.throttled?`, throttled`:``})\n`)}async function Iqe(e,t,n,r,i={},a=!1){if(i.remote!==void 0){if(i.tokenFile!==void 0)throw Error(`MCP HTTP token file is not accepted with remote authorization`);let r=i.remote,o=wk({issuer:r.issuer,resource:r.publicUrl,algorithms:$7,requiredScopes:r.scopes,allowedSubjects:r.allowedSubjects}),s=px(t),c;try{c=Pqe({name:e.config.identity.mcpClientName,version:n,session:s,host:r.host,port:i.port,submitTool:e9(e),...a?{askClient:!0}:{},authorization:{publicUrl:r.publicUrl,issuer:r.issuer,scopes:r.scopes,verifier:o,trustedProxies:r.trustedProxies,audit:Fqe}})}catch(e){throw await Q7(s,`MCP HTTP carrier refused its configuration`,`MCP`),e}return t9(s,c,async e=>{process.stderr.write(`MCP HTTP listening on ${e.listening} for ${e.url}; authorization server: ${r.issuer}\n`)},async()=>void 0)}if(i.tokenFile!==void 0&&!Pn(i.tokenFile))throw Error(`MCP HTTP token file must be an absolute path`);if(i.port!==void 0&&i.tokenFile===void 0)throw Error(`MCP HTTP port requires a token file`);let o=px(t);if(i.tokenFile!==void 0){let t=i.tokenFile,r=Nqe({name:e.config.identity.mcpClientName,version:n,session:o,port:i.port,submitTool:e9(e),...a?{askClient:!0}:{}}),s;await t9(o,r,async e=>{let n=await $n(t,`wx`,384);try{await n.chmod(384);let t=await n.stat();s={dev:t.dev,ino:t.ino},await n.writeFile(`${e.token}\n`,`utf8`)}finally{await n.close()}process.stderr.write(`MCP HTTP listening at ${e.url}; bearer token file: ${t}\n`)},async()=>{if(!s)return;let e=await Zn(t).catch(e=>{if(e.code!==`ENOENT`)throw e});e?.dev===s.dev&&e.ino===s.ino&&await ir(t)});return}let s=jqe({name:e.config.identity.mcpClientName,version:n,stdout:r,submitTool:e9(e),...a?{askClient:!0}:{}});s.attach(o);let c,l=new Promise(e=>{c=e}),u=()=>c?.();process.once(`SIGINT`,u),process.once(`SIGTERM`,u);try{await Promise.race([s.start(),s.waitForClose(),l]),await Promise.race([s.waitForClose(),l])}finally{process.off(`SIGINT`,u),process.off(`SIGTERM`,u);try{await s.stop()}finally{await Q7(o,`MCP stdio carrier closed`,`MCP`)}}}const n9=`127.0.0.1`,r9=`HTTP API`,Lqe={driverId:`remote:http`,surface:`remote`},Rqe={open:!0,openReason:`admitted by the OAuth resource-server gate in front of these routes`};async function zqe(e){if(e.token===void 0==(e.remote===void 0))throw Error(`HTTP API needs exactly one of a loopback bearer and remote authorization`);let t=e.remote,n=gte(dqe({sessionFactory:e.session,admission:t===void 0?{token:e.token??``}:Rqe,attribution:Lqe,...e.onStreamFailure===void 0?{}:{onStreamFailure:e.onStreamFailure}}).fetch),r=t===void 0?n:Bqe(t,n,e),i=t?.host??n9,a=hr(r);a.requestTimeout=3e4,a.headersTimeout=1e4,await Vqe(a,e.port,i);let o=a.address();if(o===null||typeof o==`string`)throw await i9(a),Error(`HTTP API listener has no port.`);let s=o.family===`IPv6`?`[${o.address}]`:o.address;return{url:t?.publicUrl??`http://${n9}:${o.port}`,listening:`${s}:${o.port}`,stop:async()=>{a.closeAllConnections(),await i9(a)}}}function Bqe(e,t,n){let r=Hk({resource:e.publicUrl,issuer:e.issuer,scopes:e.scopes,label:r9}),i=Vk({publicUrl:e.publicUrl,trustedProxies:e.trustedProxies,label:r9}),a=wk({issuer:e.issuer,resource:e.publicUrl,algorithms:$7,requiredScopes:e.scopes,allowedSubjects:e.allowedSubjects}),o=i.url.pathname.replace(/\/$/,``);function s(e,t,a){Gk(e,t,i,r,a,n.onRefusal)}async function c(e,n){if(!i.checkNames(e,n))return;let c=e.url??``;if(c===r.wellKnownPath){Uk(e,n,r);return}if(!(c.split(`?`)[0]??``).startsWith(`${o}/`)){n.writeHead(404).end();return}let l=gk(e.headers.authorization);if(l===void 0){s(e,n,`missing-token`);return}let u=await a.verify(l);if(!u.admitted){s(e,n,u.refusal);return}e.url=c.slice(o.length),await t(e,n)}return(e,t)=>{c(e,t).catch(()=>{t.headersSent||t.writeHead(500),t.end()})}}function Vqe(e,t,n){return new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.off(`error`,a),r()})})}function i9(e){return new Promise(t=>e.close(()=>t()))}function a9(e){let{args:t,preset:n}=e;return{cwd:e.cwd,...e.livePromptTrace?{livePromptTrace:e.livePromptTrace}:{},provider:e.provider,...e.providerDefinitions?{providerDefinitions:e.providerDefinitions}:{},...e.resolveProviderCredential===void 0?{}:{resolveProviderCredential:e.resolveProviderCredential},...e.providerErrorGuidance===void 0?{}:{providerErrorGuidance:e.providerErrorGuidance},...e.promptFileReferenceTag===void 0?{}:{promptFileReferenceTag:e.promptFileReferenceTag},...e.modelCommandToolPrefix===void 0?{}:{modelCommandToolPrefix:e.modelCommandToolPrefix},...e.subagentHookEnvironmentNames===void 0?{}:{subagentHookEnvironmentNames:e.subagentHookEnvironmentNames},...e.observerFailureWarningCode===void 0?{}:{observerFailureWarningCode:e.observerFailureWarningCode},...e.commandHookShell===void 0?{}:{commandHookShell:e.commandHookShell},...e.bare===!0?{bare:!0}:{},...e.skipConfiguredHooks===!0?{skipConfiguredHooks:!0}:{},...e.projectAccess===void 0?{}:{projectAccess:e.projectAccess},...o9(e),...e.projectSettingsPaths===void 0?{}:{projectSettingsPaths:e.projectSettingsPaths},...e.userSettingsSources===void 0?{}:{userSettingsSources:e.userSettingsSources},environment:e.productRuntime.environment,...e.contributionSources===void 0?{}:{contributionSources:e.contributionSources},...e.skillRoots===void 0?{}:{skillRoots:e.skillRoots},...e.taskContext===void 0?{}:{taskContext:e.taskContext},...e.orgPolicy===void 0?{}:{orgPolicy:e.orgPolicy},...e.model===void 0?{}:{model:e.model},...n.outputStyle===void 0?{}:{outputStyle:n.outputStyle},permissionMode:t.permissionMode??n.permissionMode,...t.supervisedExternalEventGrants===!0?{externalEventVerifierFactory:lA,externalEventGrantHistory:e.externalEventGrantHistory??Nb()}:{},baselinePermissionAllow:e.productRuntime.layout.baselinePermissionAllow,maxTurns:t.maxTurns,sessionStore:t.noSessionPersistence?void 0:e.sessionStore,disableSessionLoops:d4(e.productRuntime.environment),resolveDefaultLoopPrompt:l4({productRuntime:e.productRuntime,projectAccess:e.projectAccess,userHome:e.productRuntime.userHome??e.productRuntime.layout.userRoot}),resumeSessionId:e.resumeSessionId,forkSession:t.forkSession,sessionName:t.sessionName,autoName:!0,backgroundTaskRunners:e.backgroundTaskRunners,subagentRunnerFactory:e.subagentRunnerFactory,...e.agentDefinitions===void 0?{}:{agentDefinitions:e.agentDefinitions},...e.agentDefinitionRoots===void 0?{}:{agentDefinitionRoots:e.agentDefinitionRoots},...e.pluginDirectories===void 0?{}:{pluginDirectories:e.pluginDirectories},...e.additionalTools===void 0?{}:{additionalTools:e.additionalTools},...e.defaultTools===void 0?{}:{defaultTools:e.defaultTools},...e.toolExecutionPolicy===void 0?{}:{toolExecutionPolicy:e.toolExecutionPolicy},...e.sandboxClient===void 0?{}:{sandboxClient:e.sandboxClient},...e.toolCallHandoff===void 0?{}:{toolCallHandoff:e.toolCallHandoff},commandModules:e.commandModules,commandHostAdapters:e.commandHostAdapters,...e.remoteCommandPolicy?{remoteCommandPolicy:e.remoteCommandPolicy}:{},language:t.language,...C7(n),...t.systemPrompt?{systemPrompt:t.systemPrompt}:{},...n.agentName===void 0?{}:{agentName:n.agentName},...n.activePresetId===void 0?{}:{activePresetId:n.activePresetId},...n.persona===void 0?{}:{persona:n.persona},...n.enableParallelSubagents===void 0?{}:{enableParallelSubagents:n.enableParallelSubagents},...n.selfVerification===void 0?{}:{selfVerification:n.selfVerification},...n.effort===void 0?{}:{effort:n.effort},...n.temperature===void 0?{}:{temperature:n.temperature},...n.maxOutputTokens===void 0?{}:{maxOutputTokens:n.maxOutputTokens},...n.responseFormat===void 0?{}:{responseFormat:n.responseFormat},...n.language===void 0?{}:{language:n.language},...n.systemPrompt===void 0?{}:{presetSystemPrompt:n.systemPrompt},...e.memorySessionOptions??{},...e.setupRequired===!0?{setupRequired:!0}:{}}}function o9(e){return e.createEditCheckpointStore===void 0?{}:{editCheckpointStore:e.createEditCheckpointStore()}}function s9(e,t,n){return{...e,...o9(t),resumeSessionId:n,forkSession:void 0,sessionName:void 0}}function Hqe(e){let t=e.map(e=>e.getLocalActivityStatus());if(t.includes(`needs-input`))return`needs-input`;if(t.includes(`working`))return`working`;if(!t.includes(void 0))return t.length>0?`idle`:void 0}function Uqe(e,t){let n;for(let r of e){if(r.phase!==`waiting`||r.nextAllowedAt===void 0)continue;let e=Date.parse(r.nextAllowedAt),i=Date.parse(r.expiresAt);!Number.isFinite(e)||!Number.isFinite(i)||new Date(e).toISOString()!==r.nextAllowedAt||i<=t||e>=i||(n===void 0||e<n.millis)&&(n={at:r.nextAllowedAt,millis:e})}return n?.at}function Wqe(e){return{requestExit:()=>{throw Error(`A command does not stop the workspace daemon, which serves every client attached to it. Detach this client to leave. To stop the daemon, run ${e.config.identity.cliName} daemon stop; anything this command changed applies when you next run ${e.config.identity.cliName} daemon start.`)},requestRestart:()=>{throw Error(`A command does not restart the workspace daemon, which serves every client attached to it. The change is saved and applies once you restart the daemon: run ${e.config.identity.cliName} daemon stop, then ${e.config.identity.cliName} daemon start.`)}}}function Gqe(e,t){return{requestExit:()=>{throw Error(`A command does not stop this supervised session, which serves every client attached to it. Detach this client to leave. To stop the session, run ${t.config.identity.cliName} session stop ${e}; anything this command changed applies to the next session you start with ${t.config.identity.cliName} session start --background.`)},requestRestart:()=>{throw Error(`A command does not restart this supervised session, which serves every client attached to it. The change is saved and applies to a new session started with ${t.config.identity.cliName} session start --background; to end this one, run ${t.config.identity.cliName} session stop ${e}.`)}}}async function Kqe(e){let{args:t}=e;if(t.open&&!process.stdout.isTTY)throw Error(`Opening the monitor requires an interactive terminal for its access code.`);let n,r,i=e=>{r?r(`received ${e}`):n??=e};process.once(`SIGTERM`,i),process.once(`SIGINT`,i);let a=e=>{if(e.code!==`EPIPE`)throw e};t.supervisedSessionId!==void 0&&process.stderr.on(`error`,a);try{let i=a9(t.supervisedExternalEventGrants===!0&&e.externalEventGrantHistory===void 0?{...e,externalEventGrantHistory:Nb(LA(e.productRuntime.layout.userRoot))}:e),a=!1,o,s,c=e.sessionDirectory,l=await Mfe({session:i,transportRegistry:e.transportRegistry,bindTransports:t=>{if(c!==void 0&&i.sessionStore!==void 0){let n=t.current,r=new ux({primary:n,build:t=>px(s9(i,e,t)),maxLive:4});s=r,c.attach({pool:r,primary:n,store:i.sessionStore,cwd:e.cwd,isStopping:()=>a})}e.bindTransports?.(t)}}),u;if(e.http!==void 0){try{u=await zqe({port:e.http.port,...e.http.remote===void 0?{token:e.http.token}:{remote:e.http.remote},session:()=>l.session.current,onStreamFailure:e=>{process.stderr.write(`HTTP API stream failed: ${e.message}\n`)},onRefusal:e=>{process.stderr.write(`HTTP API refused: ${e.refusal} (${e.remote}${e.throttled?`, throttled`:``})\n`)}})}catch(t){throw await l.shutdown(`HTTP API could not be served`).catch(()=>void 0),await s?.shutdownAll(`HTTP API could not be served`)?.catch(()=>void 0),Error(`HTTP API could not be served on ${e.http.remote?.host??`127.0.0.1`}:${e.http.port}: ${t instanceof Error?t.message:String(t)}`)}process.stderr.write(e.http.remote===void 0?`HTTP API served at ${u.url}\n`:`HTTP API listening on ${u.listening} for ${u.url}; authorization server: ${e.http.remote.issuer}\n`)}let d=()=>{let e=l.session.current;return[e,...(s?.listLive()??[]).map(e=>e.session).filter(t=>t!==e)]},f=null;try{if(t.open){let t=e.getMonitorWsUrl?.(),n=VKe(e.productRuntime);t&&n?(f=await GKe(n,t,e.productRuntime),process.stdout.write(zKe(f.url,e.productRuntime)),process.stdout.write(`Monitor access code: ${f.accessCode}\n`),KKe(f.url)):n||process.stderr.write(`${e.productRuntime.config.identity.displayName} web assets not found (dist/web) — run a full CLI build.\n`)}}catch(e){throw await f?.close().catch(()=>void 0),await u?.stop().catch(()=>void 0),await l.shutdown(`Monitor could not be served`).catch(()=>void 0),await s?.shutdownAll(`Monitor could not be served`)?.catch(()=>void 0),e}let p,m,h=()=>void 0,g=new AbortController,_=new Promise(n=>{let i=e=>{a||(a=!0,g.abort(),Promise.resolve(f?.close()).catch(()=>{}).then(()=>u?.stop()).catch(()=>void 0).then(()=>m?.stop()).catch(()=>void 0).then(()=>o?.close()).then(()=>l.shutdown(e)).catch(()=>void 0).then(()=>s?.shutdownAll(e)).catch(()=>void 0).then(()=>p?.close()).finally(()=>n()))};h=i,r=i,qKe(l,{setExitCode:e=>{process.exitCode=e},writeError:e=>{process.stderr.write(e)}},i);let c=e=>{setTimeout(()=>i(e),500).unref?.()};e.commandHostAdapters.process=t.daemon===!0?Wqe(e.productRuntime):t.supervisedSessionId===void 0?{requestExit:e=>c(`command exit${e?` (${e})`:``}`),requestRestart:(e,t)=>c(`command restart: ${t}`)}:Gqe(t.supervisedSessionId,e.productRuntime)});if(n!==void 0&&h(`received ${n}`),t.supervisedSessionId!==void 0&&!a)try{if(t.daemon===!0&&e.getMonitorWsUrl?.()===void 0)throw new l9;let n=Cn(e.cwd),r;if(t.supervisedExternalEventGrants===!0){let n=e.supervisedRoot??Y4(e.productRuntime),r=sBe(n,t.supervisedSessionId),i=QKe(nBe(n),t.supervisedSessionId),a=WA(r,e=>{`settlement`in e&&i(e)});await a.bind(l.session.current),o=a;try{let e=ij({grants:r,receive:(e,t)=>a.receive(e,t),countRefusal:(e,t)=>a.countRefusal(e,t),port:t.externalEventPort??0,...t.externalEventTrustedProxies===void 0?{}:{trustedProxies:t.externalEventTrustedProxies},audit:i});await e.start(),m=e}catch{throw new c9}}let u=o;if(u!==void 0&&(e.commandHostAdapters.externalEvents={list:()=>u.adapter.list(),revoke:e=>u.adapter.revoke(e)}),p=await cBe(t.supervisedSessionId,()=>h(`supervised session stopped`),e.supervisedRoot??Y4(e.productRuntime),()=>a?void 0:Hqe(d()),()=>a?void 0:n,()=>a||i.disableSessionLoops?void 0:Uqe(d().flatMap(e=>e.listSelfPacedLoops()),Date.now()),()=>a?void 0:l.session.current.getName(),e=>{if(a)throw Error(`Supervised runtime is stopping.`);l.session.current.setName(e)},{get:()=>a?void 0:r,set:e=>{if(a)throw Error(`Supervised runtime is stopping.`);r=e}},u===void 0?void 0:{list:()=>u.adapter.list(),revoke:e=>{if(a)throw Error(`Supervised runtime is stopping.`);return u.adapter.revoke(e)}},s!==void 0&&c!==void 0?{binder:c}:{session:l.session},t.daemon===!0?{url:()=>a?void 0:e.getMonitorWsUrl?.(),restricted:e.projectAccess?.status===`restricted`}:void 0),a)throw Error(`Supervised runtime stopped before readiness.`);if(await Jqe(t.supervisedSessionId,g.signal,void 0,u?.adapter.list().map(e=>e.grantId)),a)throw Error(`Supervised runtime stopped during readiness.`)}catch(e){if(process.connected&&process.send)try{let n=e instanceof RA?{code:`grant-refused`,grant:e.grantId}:e instanceof c9?{code:`events-endpoint-failed`}:e instanceof l9?{code:`daemon-no-endpoint`}:e instanceof $4?{code:`control-path-too-long`,directory:e.directory}:{code:`startup-failed`};process.send({kind:`error`,id:t.supervisedSessionId,...n},()=>{})}catch{}throw h(`supervised session startup failed`),await p?.close(),await _,e}await _}finally{process.off(`SIGTERM`,i),process.off(`SIGINT`,i),t.supervisedSessionId!==void 0&&process.stderr.off(`error`,a)}}var c9=class extends Error{constructor(){super(`External event endpoint could not be served on its port.`),this.name=`ExternalEventEndpointError`}},l9=class extends Error{constructor(){super(`The daemon has no WebSocket endpoint.`),this.name=`DaemonNoEndpointError`}};function qqe(){if(!process.send)throw Error(`Supervised serve mode requires a parent readiness channel.`);return{send:(e,t)=>{process.send?.(e,t)},onMessage:e=>{process.on(`message`,e)},offMessage:e=>{process.off(`message`,e)},onDisconnect:e=>{process.on(`disconnect`,e)},offDisconnect:e=>{process.off(`disconnect`,e)}}}async function Jqe(e,t,n=qqe(),r){if(t.aborted)throw Error(`Supervised runtime stopped before readiness.`);await new Promise((i,a)=>{let o=!1,s=e=>{o||(o=!0,clearTimeout(d),n.offMessage(c),n.offDisconnect(u),t.removeEventListener(`abort`,l),e())},c=r=>{if(t.aborted){s(()=>a(Error(`Supervised runtime stopped during readiness.`)));return}if(typeof r!=`object`||!r||!(`kind`in r)||!(`id`in r)||r.kind!==`ack`||r.id!==e){s(()=>a(Error(`Supervised startup acknowledgement was invalid.`)));return}n.send({kind:`acknowledged`,id:e},e=>{t.aborted||e?s(()=>a(Error(`Supervised startup acknowledgement could not be sent.`))):s(i)})},l=()=>s(()=>a(Error(`Supervised runtime stopped during readiness.`))),u=()=>s(()=>a(Error(`Supervised launcher closed before acknowledgement.`))),d=setTimeout(()=>s(()=>a(Error(`Supervised launcher did not acknowledge startup.`))),1e4);n.onMessage(c),n.onDisconnect(u),t.addEventListener(`abort`,l,{once:!0}),n.send({kind:`ready`,id:e,...r===void 0?{}:{grants:r}},e=>{e&&s(()=>a(Error(`Supervised readiness could not be sent.`)))})})}const u9=`This runtime is stopping.`;function Yqe(){let e,t=()=>{if(e===void 0)throw Error(`Sessions are not available yet.`);return e},n=(e,t)=>{let n=new Map(e.pool.listLive().map(e=>[e.sessionId,e.clients])),r=_x(e.store,e.cwd).map(e=>{let t=n.get(e.id);return{...e,live:t!==void 0,clients:t??0}});return{currentSessionId:t.getSession().getSessionId(),sessions:r,unreadableSessionIds:vx(e.store,e.cwd).map(e=>e.id)}},r=e=>{try{return e.slot.current.getSession().getSessionId()}catch{return}},i=(e,t)=>{let n=new Map(e.pool.listLive().map(e=>[e.sessionId,e.clients])),i=r(t);return e=>{let t=n.get(e);return t===void 0?0:t-+(e===i)}},a=e=>{let t=new Map(e.pool.listLive().map(e=>[e.sessionId,e.session]));return e=>{let n=t.get(e);return n!==void 0&&cx(n)}},o=(e,t)=>{let o=e.pool.bind(t),s=!1,c=()=>{if(e.isStopping?.()===!0)return new ix(`stopping`,u9);if(o.isLastDriver()&&o.slot.current.getLocalActivityStatus()===`needs-input`)return new ix(`prompt_pending`,`Answer or dismiss the pending prompt first: no other client driving this session could answer it.`)},l=async t=>{if(e.isStopping?.()===!0)throw new ix(`stopping`,u9);if(s)throw new ix(`in_progress`,`Another session change is already under way.`);let n=c();if(n!==void 0)throw n;s=!0;try{let n=await e.pool.acquire(t),r=c();if(r!==void 0)throw n.cancel(),r;o.moveTo(n)}finally{s=!1}};return{session:o.slot,directory:{listSessions:()=>n(e,o.slot.current),async switchSession(t){if(t!==o.slot.current.getSession().getSessionId()){if(vx(e.store,e.cwd).some(e=>e.id===t))throw new ix(`unreadable`,`Session ${t} was saved in a form this version cannot read.`);if(!_x(e.store,e.cwd).some(e=>e.id===t))throw new ix(`unknown_session`,`No session ${t} in this workspace.`);await l(t)}},async newSession(){let t=yx(e.store,e.cwd,{otherClientsOf:i(e,o),isBusy:a(e)});await l(t)},async renameSession(t,n){if(!_x(e.store,e.cwd).some(e=>e.id===t))throw Error(`No session ${t} in this workspace.`);if(e.pool.listLive().some(e=>e.sessionId===t))throw Error(`Session ${t} is open now; renaming it here would be overwritten the next time it saves. Switch to it to rename it, or wait for it to close.`);xy(e.store,t,n)},async deleteSession(t){if(e.isStopping?.()===!0)throw new ax(`stopping`,u9);if(!_x(e.store,e.cwd).some(e=>e.id===t))throw new ax(`unknown_session`,`No session ${t} in this workspace.`);let n=t===r(o),i=e.pool.listLive().find(e=>e.sessionId===t);if(i!==void 0){if(i.clients-+!!n>0)throw new ax(`live_elsewhere`,`Another client is on this session; it cannot be deleted while someone else is using it.`);if(cx(i.session))throw new ax(`running`,`This session has work in progress; wait for it to finish, then delete it.`)}if(n){let n=_x(e.store,e.cwd).find(e=>e.id!==t)?.id;await l(n)}e.store.delete(t)}},release:()=>o.release()}};return{attach(t){e=t},bind(e){return o(t(),e)},listSessions(){let e=t();return n(e,e.primary)}}}function d9(e){return e===void 0?void 0:{cancellationSignal:e}}function f9(e){if(!(e instanceof ai))return e instanceof Error?e:Error(String(e));let t=e.data,n=typeof t==`object`&&t&&`details`in t&&typeof t.details==`string`?t.details:void 0;return Error(n===void 0?e.message:`${e.message}: ${n}`)}function p9(e){if(!Pn(e))throw Error(`the editor is given absolute paths only: ${e}`)}function Xqe(e,t,n){let r=e?.readTextFile===!0,i=e?.writeTextFile===!0;if(!r&&!i)return;let a=()=>{let e=n();if(e===void 0)throw Error(`the editor has no session to read or write for`);return e};return{...r?{readTextFile:async(e,n)=>{p9(e);try{return(await t.request(`fs/read_text_file`,{sessionId:a(),path:e},d9(n))).content}catch(e){throw f9(e)}}}:{},...i?{writeTextFile:async(e,n,r)=>{p9(e);try{await t.request(`fs/write_text_file`,{sessionId:a(),path:e,content:n},d9(r))}catch(e){throw f9(e)}}}:{}}}function Zqe(e){let t=Math.max(0,...[...e.matchAll(/`+/g)].map(e=>e[0].length));return"`".repeat(Math.max(3,t+1))}function Qqe(e){let t=``,n=[],r=[];for(let i of e)if(i.type===`text`)t+=i.text;else if(i.type===`resource`&&`text`in i.resource){let e=Zqe(i.resource.text);n.push(`Context from ${i.resource.uri}:\n${e}\n${i.resource.text}\n${e}`)}else i.type===`resource_link`&&r.push(`- ${i.uri}`);return r.length>0&&n.push(`Referenced resources:\n${r.join(`
2914
2914
  `)}`),{typed:t,full:n.length===0?t:`${t}\n\n${n.join(`
2915
2915
 
2916
- `)}`}}const Qqe={Read:`read`,Glob:`search`,Grep:`search`,Edit:`edit`,Write:`edit`,Shell:`execute`,Bash:`execute`,WebFetch:`fetch`,WebSearch:`fetch`};function m9(e){return Qqe[e]??`other`}function $qe(e,t){let n=t?.replace(/\s+/g,` `).trim();return n?`${e}: ${n.length>120?`${n.slice(0,119)}…`:n}`:e}function eJe(e,t){let n=t?.trim();return n?`${e}: ${n}`:e}function h9(e){return $qe(e.toolName,e.displayPath??e.firstArg)}function g9(e){return e.result===`success`?`completed`:`failed`}function tJe(e){let t=[],n=new Set,r=(e,r,i)=>{n.has(e)||(n.add(e),t.push({name:e,description:r,...i?{input:{hint:i}}:{}}))};for(let t of e.listCommands?.()??[])t.runner===`runtime`&&r(t.name,t.description,t.argumentHint);for(let t of e.listSkills?.()??[])t.userInvocable&&r(t.name,t.description,t.argumentHint);return t}function nJe(e,t,n){for(let r of e){if(r.type===`text`){if(r.content===``)continue;t.send({sessionUpdate:r.role===`user`?`user_message_chunk`:`agent_message_chunk`,content:{type:`text`,text:r.content}});continue}let{tool:e}=r;if(e.internal)continue;let i=n(e.executionId);t.send({sessionUpdate:`tool_call`,toolCallId:i,title:h9(e),kind:m9(e.toolName),status:g9(e)})}}const _9={allowOnce:`allow-once`,allowSession:`allow-session`,allowProject:`allow-project`,reject:`reject`};function rJe(e){return[{optionId:_9.allowOnce,name:`Allow once`,kind:`allow_once`},{optionId:_9.allowSession,name:`Allow for this session`,kind:`allow_always`},...e?[{optionId:_9.allowProject,name:`Allow for this project`,kind:`allow_always`}]:[],{optionId:_9.reject,name:`Reject`,kind:`reject_once`}]}function iJe(e){let t=eJe(e.toolName,e.diffFile??NJ(e.toolArgs));return e.requester?`${e.requester.label}: ${t}`:t}function aJe(e){return e.cwd===void 0||`cwd`in e.toolArgs?e.toolArgs:{...e.toolArgs,cwd:e.cwd}}const oJe=/^@@ /;function sJe(e){let t=[],n=[],r=`context`;for(let i of e){if(i.type===`hunk`){if(oJe.test(i.text))continue;r!==`add`&&t.push(i.text),r!==`remove`&&n.push(i.text);continue}r=i.type,i.type!==`add`&&t.push(i.text),i.type!==`remove`&&n.push(i.text)}return{...t.length>0?{oldText:t.join(`
2916
+ `)}`}}const $qe={Read:`read`,Glob:`search`,Grep:`search`,Edit:`edit`,Write:`edit`,Shell:`execute`,Bash:`execute`,WebFetch:`fetch`,WebSearch:`fetch`};function m9(e){return $qe[e]??`other`}function eJe(e,t){let n=t?.replace(/\s+/g,` `).trim();return n?`${e}: ${n.length>120?`${n.slice(0,119)}…`:n}`:e}function tJe(e,t){let n=t?.trim();return n?`${e}: ${n}`:e}function h9(e){return eJe(e.toolName,e.displayPath??e.firstArg)}function g9(e){return e.result===`success`?`completed`:`failed`}function nJe(e){let t=[],n=new Set,r=(e,r,i)=>{n.has(e)||(n.add(e),t.push({name:e,description:r,...i?{input:{hint:i}}:{}}))};for(let t of e.listCommands?.()??[])t.runner===`runtime`&&r(t.name,t.description,t.argumentHint);for(let t of e.listSkills?.()??[])t.userInvocable&&r(t.name,t.description,t.argumentHint);return t}function rJe(e,t,n){for(let r of e){if(r.type===`text`){if(r.content===``)continue;t.send({sessionUpdate:r.role===`user`?`user_message_chunk`:`agent_message_chunk`,content:{type:`text`,text:r.content}});continue}let{tool:e}=r;if(e.internal)continue;let i=n(e.executionId);t.send({sessionUpdate:`tool_call`,toolCallId:i,title:h9(e),kind:m9(e.toolName),status:g9(e)})}}const _9={allowOnce:`allow-once`,allowSession:`allow-session`,allowProject:`allow-project`,reject:`reject`};function iJe(e){return[{optionId:_9.allowOnce,name:`Allow once`,kind:`allow_once`},{optionId:_9.allowSession,name:`Allow for this session`,kind:`allow_always`},...e?[{optionId:_9.allowProject,name:`Allow for this project`,kind:`allow_always`}]:[],{optionId:_9.reject,name:`Reject`,kind:`reject_once`}]}function aJe(e){let t=tJe(e.toolName,e.diffFile??NJ(e.toolArgs));return e.requester?`${e.requester.label}: ${t}`:t}function oJe(e){return e.cwd===void 0||`cwd`in e.toolArgs?e.toolArgs:{...e.toolArgs,cwd:e.cwd}}const sJe=/^@@ /;function cJe(e){let t=[],n=[],r=`context`;for(let i of e){if(i.type===`hunk`){if(sJe.test(i.text))continue;r!==`add`&&t.push(i.text),r!==`remove`&&n.push(i.text);continue}r=i.type,i.type!==`add`&&t.push(i.text),i.type!==`remove`&&n.push(i.text)}return{...t.length>0?{oldText:t.join(`
2917
2917
  `)}:{},newText:n.join(`
2918
- `)}}function v9(e,t,n){let r=e.diffFile===void 0?void 0:Ln(n,e.diffFile);return{toolCallId:t,title:iJe(e),kind:m9(e.toolName),status:`pending`,rawInput:aJe(e),...r!==void 0&&e.diffLines!==void 0?{content:[{type:`diff`,path:r,...sJe(e.diffLines)}]}:{},...r===void 0?{}:{locations:[{path:r}]}}}function cJe(e,t){if(e.outcome!==`selected`||!t.some(t=>t.optionId===e.optionId))return!1;switch(e.optionId){case _9.allowOnce:return!0;case _9.allowSession:return`allow-session`;case _9.allowProject:return`allow-project`;default:return!1}}function lJe(e,t){let n=Object.keys(t);for(let r of n)e.on(r,t[r]);return()=>{for(let r of n)e.off(r,t[r])}}function uJe(e){let{updates:t}=e,n=[],r=new Map,i=new Map,a=!1,o=e=>{if(e===void 0)return;let t=r.get(e);return r.delete(e),t},s=(e,n)=>t.send({sessionUpdate:`tool_call_update`,toolCallId:e,status:n?`completed`:`failed`});return{start(r){if(r.internal)return;let i=o(r.executionId),a=i?.id??e.nextToolCallId(r.executionId);n.push({id:a,toolName:r.toolName,executionId:r.executionId});let s={toolCallId:a,title:h9(r),kind:m9(r.toolName),status:`in_progress`};i===void 0?t.send({sessionUpdate:`tool_call`,...s}):t.send({sessionUpdate:`tool_call_update`,...s,rawInput:i.rawInput})},end(r){if(r.internal)return;let i=g9(r),a=n.findIndex(e=>r.executionId===void 0?e.executionId===void 0&&e.toolName===r.toolName:e.executionId===r.executionId);if(a>=0){let[e]=n.splice(a,1);t.send({sessionUpdate:`tool_call_update`,toolCallId:e.id,status:i});return}let s=o(r.executionId);if(s!==void 0){t.send({sessionUpdate:`tool_call_update`,toolCallId:s.id,status:i});return}t.send({sessionUpdate:`tool_call`,toolCallId:e.nextToolCallId(r.executionId),title:h9(r),kind:m9(r.toolName),status:i})},requested(t){let{executionId:a}=t;if(a===void 0){let n=v9(t,e.nextToolCallId(`permission-${t.id}`),e.cwd);return i.set(t.id,n.toolCallId),n}let o=n.find(e=>e.executionId===a),s=r.get(a),c=o?.id??s?.id??e.nextToolCallId(a),l=v9(t,c,e.cwd);return o===void 0&&s===void 0&&r.set(a,{id:c,rawInput:l.rawInput,background:t.requester!==void 0}),l},answered(e,t){if(e.executionId!==void 0){let n=r.get(e.executionId);n!==void 0&&(n.allowed=t);return}let n=i.get(e.id);n===void 0||a||(i.delete(e.id),s(n,t))},finish(){a=!0;for(let e of r.values())s(e.id,e.background&&e.allowed===!0);for(let e of i.values())s(e,!1);r.clear(),i.clear()}}}const y9={stopReason:`cancelled`},dJe={stopReason:`end_turn`};function b9(e){return e instanceof Error?e:Error(String(e))}async function x9(e,t){let{session:n,sessionId:r,client:i,updates:a}=e,o=uJe({updates:a,nextToolCallId:e.nextToolCallId,cwd:e.cwd}),s=!1,c=lJe(n,{text_delta:e=>{e!==``&&(s=!0,a.text(e))},thinking_delta:e=>{e!==``&&a.thought(e)},tool_start:o.start,tool_end:o.end,permission_request:t=>{let a=rJe(t.canPersistProjectPermission===!0),s=o.requested(t);(async()=>{let c=!1;try{c=cJe((await i.request(`session/request_permission`,{sessionId:r,toolCall:s,options:a})).outcome,a)}catch(t){e.report(b9(t),`session/request_permission`)}o.answered(t,c!==!1);try{n.resolvePermission(t.id,c,e.driverId)}catch(t){e.report(b9(t),`resolvePermission`)}})()}});try{let n=await t.run();return e.wasCancelled()||e.signal.aborted||n.interrupted?y9:(!s&&n.reply!==``&&a.text(n.reply),dJe)}catch(n){return e.wasCancelled()||e.signal.aborted||t.isCancellation?.(n)===!0?y9:t.fail(n)}finally{c(),o.finish(),await a.drained()}}function fJe(e,t){return x9(e,{async run(){let n=await(await e.session.submit(t,void 0,void 0,{signal:e.signal,driverId:e.driverId,...e.surface===void 0?{}:{surface:e.surface}})).completed;return{interrupted:n.interrupted===!0,reply:n.response}},isCancellation:e=>ao(e)&&e.reason===`cancelled`,fail(t){throw e.report(b9(t),`turn`),new ai(-32603,ao(t)?`Turn was not run`:`Turn failed`)}})}function pJe(e,t,n){return x9(e,{async run(){return{interrupted:!1,reply:await n(t,e.signal)}},fail(t){throw e.report(b9(t),`command`),new ai(-32603,`Command failed`)}})}function S9(e,t,n){let r=Promise.resolve(),i=!1,a=a=>{r=r.then(async()=>{if(!i)try{await e.notify(`session/update`,{sessionId:t,update:a})}catch(e){i=!0,n(e instanceof Error?e:Error(String(e)),`session/update`)}})};return{send:a,text:e=>a({sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:e}}),thought:e=>a({sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:e}}),drained:()=>r}}const C9=-32603,mJe=()=>Promise.resolve(`Slash commands are not available in this host.`);function hJe(e,t){if(Ln(e)===Ln(t))return!0;try{return Cn(e)===Cn(t)}catch{return!1}}function w9(e){return e instanceof Error?e:Error(String(e))}function gJe(e,t){let n=t.driverId??io,r=(e,n)=>t.onDeliveryError?.(e,n),i,a=!1,o,s=0,c=new Set,l=e=>{let t=e;for(;t===void 0||c.has(t);)t=`tool-${s+=1}`;return c.add(t),t},u,d=e=>{if(!Pn(e.cwd)||!hJe(e.cwd,t.cwd))throw ai.invalidParams(void 0,`cwd must be the directory this agent was started in: ${t.cwd}`);if(e.mcpServers.length>0)throw ai.invalidParams(void 0,`mcpServers are not accepted by this agent`);if((e.additionalDirectories??[]).length>0)throw ai.invalidParams(void 0,`additionalDirectories are not accepted by this agent`);let n=t.admitWorkspace();if(!n.admitted)throw new ai(-32001,n.message,{reason:`workspace-not-trusted`})},f=async t=>{try{return await e.whenInitialized?.(),e.getStatusSnapshot().sessionId}catch(e){throw r(w9(e),t),new ai(C9,`The session could not be started`)}},p=(t,n)=>{if(e.listCommands===void 0&&e.listSkills===void 0)return;let i;try{i=tJe(e)}catch(e){r(w9(e),`available_commands_update`);return}let a=JSON.stringify(i);a!==u&&(u=a,t.notify(`session/update`,{sessionId:n,update:{sessionUpdate:`available_commands_update`,availableCommands:i}}).catch(e=>r(w9(e),`available_commands_update`)))},m=(e,t)=>{setImmediate(()=>p(e,t))},h,g=!1,_=e=>{let n=Yqe(h,e,()=>i);n!==void 0&&(g=!0,t.onEditorFileAccess?.(n))};return{app:Dte({name:t.agentInfo.name}).onRequest(`initialize`,({params:n})=>(h=n.clientCapabilities?.fs,{protocolVersion:Ete,agentCapabilities:{loadSession:t.loadSession!==void 0&&e.getMessagesDisplay!==void 0,promptCapabilities:{image:!1,audio:!1,embeddedContext:!0}},agentInfo:{name:t.agentInfo.name,version:t.agentInfo.version}})).onRequest(`session/new`,async({params:e,client:t})=>{if(i!==void 0||a)throw ai.invalidParams(void 0,`one session per connection`);d(e),a=!0;try{i=await f(`session/new`)}finally{a=!1}return _(t),m(t,i),{sessionId:i}}).onRequest(`session/load`,async({params:n,client:s})=>{let c=t.loadSession;if(c===void 0||e.getMessagesDisplay===void 0)throw ai.methodNotFound(`session/load`);if(a)throw ai.invalidParams(void 0,`a session is already being opened`);if(o!==void 0)throw ai.invalidParams(void 0,`a prompt is running`);d(n),a=!0;try{let t;try{t=await c(n.sessionId)}catch(e){throw r(w9(e),`session/load`),new ai(C9,`The session could not be loaded`)}if(!t.loaded)throw ai.invalidParams(void 0,t.message);i=await f(`session/load`),_(s);let a=S9(s,i,r);try{nJe(e.getMessagesDisplay(),a,l)}catch(e){throw r(w9(e),`session/load`),new ai(C9,`The session history could not be shown`)}await a.drained()}finally{a=!1}return u=void 0,m(s,i),{}}).onRequest(`session/prompt`,async({params:s,signal:c,client:u})=>{if(s.sessionId!==i||a)throw ai.invalidParams(void 0,`unknown session`);if(o!==void 0)throw ai.invalidParams(void 0,`a prompt is already running`);let d=Zqe(s.prompt);if(d.full.trim()===``)throw ai.invalidParams(void 0,`the prompt has no text`);let f=new AbortController,m=!1;o={cancel(){m=!0,f.abort(),e.abort()}};let h={session:e,sessionId:s.sessionId,client:u,updates:S9(u,s.sessionId,r),signal:AbortSignal.any([c,f.signal]),driverId:n,surface:t.surface??`unknown`,cwd:t.cwd,nextToolCallId:l,wasCancelled:()=>m,report:r};try{return d.typed.trimStart().startsWith(`/`)?await pJe(h,d.typed,t.executeCommand??mJe):await fJe(h,d.full)}finally{o=void 0,p(u,s.sessionId)}}).onNotification(`session/cancel`,({params:e})=>{e.sessionId===i&&o?.cancel()}),cancelActive:()=>o?.cancel(),withdrawEditorFiles:()=>{g&&(g=!1,t.onEditorFileAccess?.(void 0))}}}function _Je(e){return new WritableStream({write:t=>new Promise((n,r)=>{e.write(t,e=>e?r(e):n())})})}function vJe(e){let t=null,n=!1,r=null,i=null,a=null,o=null,s=null,c=null,l=null,u=Promise.resolve(),d=()=>{u=new Promise((e,t)=>{c=e,l=t}),u.catch(()=>void 0)},f=()=>{try{s?.(),o?.(),a?.close()}finally{i?.release(),i=null,a=null,o=null,s=null}},p=e=>Object.assign(Error(`ACP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`acp`});return{name:`acp`,lifecycle:Object.freeze({kind:`service`}),attach(e){if(n||r)throw p(`already-started`);t=e,d()},async start(){if(!t)throw p(`not-attached`);if(n||r)throw p(`already-started`);n=!0;try{let n=gJe(t,e);o=n.cancelActive,s=n.withdrawEditorFiles;let r=cA(e.input,e.output,{onInputClose:()=>c?.(),onOutputClose:()=>c?.(),onOutputError:e=>l?.(e)});i=r;let u=n.app.connect(Ote(_Je(e.output),kee.toWeb(r.bridge)));a=u,u.closed.then(()=>c?.())}catch(e){throw f(),n=!1,e}},stop(){return r||(r=(async()=>{try{f()}finally{t=null,n=!1,c?.()}})().finally(()=>{r=null}),r)},waitForClose(){return u}}}async function yJe(e,t,n){n.throwIfAborted();let[r=``,...i]=t.trimStart().slice(1).split(/\s+/);if(r===``)return`Type a command name after "/".`;let a=``,o=e=>{a=e.response};e.on(`complete`,o);try{let t=await e.executeCommand(r,i.join(` `),`remote`,io,`local`,{signal:n});return t===null?`Unknown command "/${r}".`:t.data?.sessionExecution===!0?a:t.message}finally{e.off(`complete`,o)}}var bJe=class extends sx{whenInitialized(){return this.current.whenInitialized()}};function xJe(e,t,n){return e.goal?.status===`active`||(e.sessionLoops??[]).some(e=>e.phase!==`stopped`&&e.phase!==`expired`&&Date.parse(e.expiresAt)>t)||(e.backgroundTasks??[]).some(e=>Ql(e,t,n)===`rearm`)}function SJe(e,t){let n=e.sessionOptions.sessionStore;if(n===void 0)return;let r=!1,i=Promise.resolve(),a=e=>({loaded:!1,message:e}),o=async i=>{if(await t.whenInitialized(),t.current.getStatusSnapshot().sessionId===i)return{loaded:!0};if(cx(t.current))return a(`The current session has work in progress; load another once it finishes.`);if(vx(n,e.cwd).some(e=>e.id===i))return a(`Session ${i} was saved in a form this version cannot read.`);let o=n.list().flatMap(e=>e.outcome.status===`valid`?[e.outcome.record]:[]).find(t=>t.id===i&&t.cwd===e.cwd);if(o===void 0)return a(`No session ${i} in this workspace.`);if(xJe(o,Date.now(),e.sessionOptions.disableSessionLoops??!1))return a(`Session ${i} has a goal, loop or schedule that would run on its own; resume it in the terminal to stop that first.`);let s=px(s9(e.sessionOptions,{createEditCheckpointStore:e.createEditCheckpointStore},i));try{await s.whenInitialized()}catch(e){throw await Q7(s,`ACP session load failed`,`ACP`),e}return r?(await Q7(s,`ACP carrier closed during a session load`,`ACP`),a(`The agent is shutting down.`)):(await t.replace(s,`ACP session loaded`),{loaded:!0})};return{load(e){if(r)return Promise.resolve(a(`The agent is shutting down.`));let t=o(e);return i=t.catch(()=>void 0),t},async close(){r=!0,await i}}}async function CJe(e){let t=new bJe(px(e.sessionOptions)),n=SJe(e,t),r=vJe({input:e.input,output:e.output,agentInfo:{name:e.productRuntime.config.identity.cliName,version:e.version},cwd:e.cwd,admitWorkspace:e.admitWorkspace,executeCommand:(e,n)=>yJe(t,e,n),...n===void 0?{}:{loadSession:n.load},...e.editorFiles===void 0?{}:{onEditorFileAccess:e.editorFiles.set},onDeliveryError:(e,t)=>{process.stderr.write(`ACP ${t}: ${e.message}\n`)}});r.attach(t);let i,a=new Promise(e=>{i=e}),o=()=>i?.();process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{await Promise.race([r.start(),r.waitForClose(),a]),await Promise.race([r.waitForClose(),a])}finally{process.off(`SIGINT`,o),process.off(`SIGTERM`,o);try{await r.stop()}finally{await n?.close(),await Q7(t.current,`ACP stdio carrier closed`,`ACP`)}}}function wJe(){let e=process.stdout.write,t=new Aee({write(t,n,r){e.call(process.stdout,t,n,r)}});return process.stdout.write=process.stderr.write.bind(process.stderr),{protocol:t,restore(){process.stdout.write=e}}}function TJe(){let e=new Map;return{list:()=>[...e.values()],put:t=>{e.set(t.namespace,{...t})},remove:t=>{e.delete(t)}}}var T9=class extends Error{reason;constructor(e){super(`MCP skill activation refused: ${e}${e===`approval-required`?`. Ask the user to run /mcp skill-inspect <server> <uri>, then approve its reviewed fingerprint.`:``}`),this.reason=e,this.name=`McpSkillActivationError`}};function E9(e,t,n){return`mcp-skill:${Buffer.from(JSON.stringify([e.serverId,e.securityIdentity,t,n])).toString(`base64url`)}`}function D9(e,t){return Vn(`sha256`).update(JSON.stringify([e,t.manifestFingerprint])).digest(`hex`)}function EJe(e){if(e.text!==void 0)return e.text;if(e.blob===void 0)throw new T9(`invalid-frontmatter`);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.from(e.blob,`base64`))}catch{throw new T9(`invalid-frontmatter`)}}var DJe=class{resolveSource;approvals;scope;revisions=new Map;catalog=new Map;listMetadata(){return[...this.catalog.values()].flat()}key(e,t){return JSON.stringify([e,t])}advance(e,t){let n=this.key(e,t),r=(this.revisions.get(n)??0)+1;return this.revisions.set(n,r),r}advanceServer(e){for(let[t,n]of this.revisions)JSON.parse(t)[0]===e&&this.revisions.set(t,n+1)}constructor(e,t=TJe(),n=`user`){this.resolveSource=e,this.approvals=t,this.scope=n}revoke(e,t){for(let n of this.approvals.list())n.scope===this.scope&&n.serverId===e&&n.uri===t&&this.approvals.remove(n.namespace)}async source(e,t){t?.throwIfAborted();let n=await this.resolveSource(e);if(t?.throwIfAborted(),!n||n.serverId!==e)throw new T9(`unavailable`);if(!await n.isCurrent())throw new T9(`source-changed`);return n}async list(e,t,n){return(await this.refreshMetadata(e,t,n)).map(e=>e.entry)}async refreshMetadata(e,t,n){let r,i;try{if(r=await this.source(e,n),i=await r.skills.list({maxPages:t,signal:n}),!await r.isCurrent())throw new T9(`source-changed`)}catch(t){if(!n?.aborted){this.catalog.delete(e),this.advanceServer(e);for(let t of this.approvals.list())t.scope===this.scope&&t.serverId===e&&this.approvals.remove(t.namespace)}throw t}this.advanceServer(e);for(let t of i){this.advance(e,t.uri);let n=E9(r,t.uri,this.scope),i=D9(n,t);for(let r of this.approvals.list())r.scope===this.scope&&r.serverId===e&&r.uri===t.uri&&(r.namespace!==n||r.fingerprint!==i)&&this.approvals.remove(r.namespace)}for(let t of this.approvals.list())t.scope===this.scope&&t.serverId===e&&!i.some(e=>e.uri===t.uri)&&(this.advance(e,t.uri),this.approvals.remove(t.namespace));let a=i.map(t=>{let n=E9(r,t.uri,this.scope);return{serverId:e,namespace:n,fingerprint:D9(n,t),entry:t}});return this.catalog.set(e,a),a}async inspect(e,t,n){let r=this.advance(e,t);try{let i=await this.source(e,n),a=await i.skills.get(t,{signal:n});if(a.identity.serverId!==e)throw new T9(`source-changed`);let o=EJe(await i.skills.read(a,t,{signal:n})),s=tpe(t,o);if(!s?.ok)throw new T9(`invalid-frontmatter`);if(!_r(JSON.parse(JSON.stringify(s.frontmatter)),a.frontmatter))throw new T9(`frontmatter-mismatch`);if(!await i.isCurrent())throw new T9(`source-changed`);if(this.revisions.get(this.key(e,t))!==r)throw new T9(`content-changed`);let c=E9(i,t,this.scope),l=D9(c,a);for(let n of this.approvals.list())n.serverId===e&&n.scope===this.scope&&n.uri===t&&(n.namespace!==c||n.fingerprint!==l)&&this.approvals.remove(n.namespace);return{serverId:e,namespace:c,fingerprint:l,entry:a,body:s.body,content:o}}catch(n){throw this.revisions.get(this.key(e,t))===r&&this.revoke(e,t),n}}async approve(e,t,n,r){if(r!==`user`)throw new T9(`user-only`);let i=await this.inspect(e,t);if(i.fingerprint!==n)throw new T9(`content-changed`);return this.approvals.put({scope:this.scope,namespace:i.namespace,serverId:e,uri:t,fingerprint:n}),i}withdraw(e,t,n){if(n!==`user`)throw new T9(`user-only`);this.advance(e,t),this.revoke(e,t)}requireApproval(e){if(!this.approvals.list().some(t=>t.namespace===e.namespace&&t.scope===this.scope&&t.serverId===e.serverId&&t.uri===e.entry.uri&&t.fingerprint===e.fingerprint))throw new T9(`approval-required`)}async activate(e,t,n){let r=await this.inspect(e,t,n);this.requireApproval(r);let i=!1,a=new AbortController,o=n?AbortSignal.any([n,a.signal]):a.signal,s=e=>{if(i)throw new T9(`activation-ended`);e.throwIfAborted(),this.requireApproval(r)},c=async n=>{s(n);let i=await this.source(e,n);if(E9(i,t,this.scope)!==r.namespace)throw new T9(`source-changed`);let a=await i.skills.get(t,{signal:n});if(a.identity.serverId!==e)throw new T9(`source-changed`);if(a.identity.catalogGeneration!==r.entry.identity.catalogGeneration)throw new T9(`activation-ended`);if(D9(r.namespace,a)!==r.fingerprint)throw new T9(`content-changed`);return s(n),{source:i,current:a}},l=(n,r)=>{let o=r.aborted;throw i=!0,a.abort(),!o&&!(n instanceof T9&&n.reason===`activation-ended`)&&this.revoke(e,t),n};return{...r,close:()=>{i=!0,a.abort()},validate:async()=>{try{let{source:e}=await c(o);if(!await e.isCurrent())throw new T9(`source-changed`);s(o)}catch(e){l(e,o)}},read:async(e,t)=>{let n=t?AbortSignal.any([t,o]):o;if(i)throw new T9(`activation-ended`);try{let{source:t,current:a}=await c(n),o=await t.skills.read(a,e,{signal:n});if(i)throw new T9(`activation-ended`);if(this.requireApproval(r),!await t.isCurrent())throw new T9(`source-changed`);return s(n),o}catch(e){return l(e,n)}}}}};function OJe(e){return`mcp-skill-${Vn(`sha256`).update(e).digest(`hex`)}`}function O9(e,t){let{serverId:n,entry:r,namespace:i,fingerprint:a}=e,o=OJe(i),s=Il({source:i,content:`---\n${JSON.stringify(r.frontmatter)}\n---\n`,profile:`skill`});return s.ok?{command:{...ag(s.metadata,``,o,void 0),name:o,source:`host-skill`,description:`${r.frontmatter.name} (${n}): ${r.frontmatter.description}`,skillContentLoader:{acquire:async e=>{let o;try{let s=await t.activate(n,r.uri,e);if(o=s,s.namespace!==i||s.fingerprint!==a)throw new T9(`content-changed`);return{content:s.content,...s.entry.resources===`dynamic`?{}:{resources:{manifest:s.entry.resources,read:(e,t)=>s.read(e,t)}},validate:()=>s.validate(),close:()=>s.close()}}catch(e){throw o?.close(),e instanceof T9&&e.reason===`approval-required`?Error(`Skill content consent is required. Ask the local user to run /mcp skill-inspect ${JSON.stringify([n,r.uri])} and approve the reviewed fingerprint.`):e}}}},invocationName:o}:{unavailableReason:s.diagnostics.map(e=>`${e.code}: ${e.field??`frontmatter`}`).join(`; `)}}function kJe(e){return{name:`mcp-skills`,getCommands:()=>e.listMetadata().flatMap(t=>{let n=O9(t,e);return n.command?[n.command]:[]}),describe:t=>{let{invocationName:n,unavailableReason:r}=O9(t,e);return{...n?{invocationName:n}:{},...r?{unavailableReason:r}:{}}}}}const k9={startupMs:1e4,perCallMs:3e4,globalDefaultMs:6e4,idleMs:3e5,toolCallMs:3e4};function AJe(e){return{...k9,toolCallMs:e}}function jJe(e,t,n){return{source:e.source,origin:e.origin,reason:e.reason,blockedServerNames:e.source===t?n:[]}}function A9(e,t){let n=t===void 0||!e.allowed?void 0:t.discovered.has(e.serverId)?`connected`:t.connectionFailures.has(e.serverId)?`failed`:void 0,r=t===void 0?void 0:[...t.connectedToolProvenance.entries()].filter(([,t])=>t.serverId===e.serverId).map(([e])=>e);return{serverId:e.serverId,...e.displayName===void 0?{}:{displayName:e.displayName},source:e.source,status:e.status,allowed:e.allowed,reason:e.reason,provenanceId:e.provenanceId,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,...n===void 0?{}:{connection:n},...n===`failed`?{connectionFailureReason:t?.connectionFailures.get(e.serverId)??`unknown`}:{},...r===void 0?{}:{toolNames:r}}}function j9(e){return e instanceof Error?e.message:String(e)}function MJe(e){if(e===`pending`||e===`stale`)return`approve`;if(e===`untrusted`)return`trust-workspace`}function NJe(e){let t,n=!1,r=()=>(t??=e(),n&&t.close(),t);return{authenticator:{authorize:e=>r().authorize(e),onRejected:e=>r().onRejected(e)},renew:()=>{t?.close(),t=void 0},close:()=>{n=!0,t?.close()}}}function M9(e,t,n,r,i,a,o){return{serverId:e.serverId,awaitOpenCleanupOnTimeout:n.kind===`stdio`,openSession:async s=>{o?.();let c=await cWe({serverId:e.serverId,...t.protocolVersion===void 0?{}:{protocolVersion:t.protocolVersion},...t.skills===!0?{skills:!0}:{},...a.elicitation===!0?{elicitation:!0}:{},...a.apps===!0?{apps:!0}:{},transport:n.construct(r),timeouts:{startupMs:i.startupMs,perCallMs:i.perCallMs},...a.clientInfo===void 0?{}:{clientInfo:a.clientInfo},signal:s});for(let t of c.compatibilityDiagnostics??[])a.reportDiagnostic(`MCP server "${e.serverId}" capability "${t.capability}" unavailable: ${t.reason}`);return c},timeouts:i,...a.backoff===void 0?{}:{backoff:a.backoff},...a.clock===void 0?{}:{clock:a.clock},...a.discovery===void 0?{}:{discovery:a.discovery}}}async function N9(e,t,n,r){let{admission:i,createSupervisor:a,timeouts:o,deps:s,signal:c}=r;if(s.isDefinitionCurrent){let e=!1;try{e=await s.isDefinitionCurrent(t)}catch{}if(!e)return s.reportDiagnostic(`MCP connection refused: admission or installed source changed; restart with the current source.`),`not-admitted`}let l=i.admit(e);if(!l.allowed){s.reportDiagnostic(`MCP server "${e.serverId}" was not admitted (${l.status}): ${l.reason}`);let t=MJe(l.status);return t!==void 0&&r.unavailable.set(e.serverId,t),`not-admitted`}let u,d=t.transport===`stdio`?`stdio`:`streamable-http`;if(t.transport===`stdio`){let n=s.stdioAuthorities!==void 0&&Object.hasOwn(s.stdioAuthorities,e.serverId)?s.stdioAuthorities[e.serverId]:void 0;if(n===void 0){s.reportDiagnostic(`MCP server "${e.serverId}" stdio was refused: missing host authority.`),r.connectionFailures.set(e.serverId,`missing host authority`);return}let a=aUe({admission:i,authority:n}),c=await a.admit({definition:t,activation:e});if(!c.ok){s.reportDiagnostic(`MCP server "${e.serverId}" stdio was refused (${c.reason}).`),r.connectionFailures.set(e.serverId,c.reason);return}u=M9(e,t,a,c.admitted,o,s)}else{let n=gHe(s.transport),i=t.headersHelper,a,c;if(t.oauth!==void 0){let n=s.oauth;if(n===void 0){s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (oauth-unavailable).`),r.connectionFailures.set(e.serverId,`OAuth is not available`);return}let i=r.oauthAuthenticators.get(e.serverId);if(i===void 0){try{i=n.authenticatorFor(e,t)}catch{s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (oauth-unavailable).`),r.connectionFailures.set(e.serverId,`OAuth is not available`);return}r.oauthAuthenticators.set(e.serverId,i)}a=i}else if(i===void 0)a=s.authenticatorFor?.(e);else{let n=s.headersHelpers,o=yHe(i,e.source,e.workspace,n?.allowed??[]);if(n===void 0||o!==void 0){s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (${o??`headers-helper-not-allowed`}).`),r.connectionFailures.set(e.serverId,o??`headers-helper-not-allowed`);return}let l=NJe(()=>EHe(r=>n.run({request:e,definition:t,helper:i},r)));r.helperSlots.get(e.serverId)?.close(),r.helperSlots.set(e.serverId,l),c=l,a=l.authenticator}let l=await n.admit({url:t.url??``,...i===void 0&&t.oauth===void 0?{}:{authenticationRequired:!0},...t.headers===void 0?{}:{headers:t.headers},...t.unsupportedAuthentication===void 0?{}:{unsupportedAuthentication:t.unsupportedAuthentication},...a===void 0?{}:{authentication:{serverId:e.serverId,securityIdentity:e.securityIdentity,authenticator:a}}});if(!l.ok){s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (${l.reason}): ${l.message}`),r.connectionFailures.set(e.serverId,`${l.reason}: ${l.message}`);return}u=M9(e,t,n,l.admitted,o,s,c===void 0?void 0:()=>c.renew())}let f=a(u);try{let t=await f.discover(c);return r.connectionFailures.delete(e.serverId),{catalogInput:{serverId:e.serverId,origin:n,transport:d,discovery:t},connection:f}}catch(i){let a=d===`stdio`?`stdio connection failed`:j9(i);return s.reportDiagnostic(`MCP server "${e.serverId}" discovery failed: ${a}`),r.connectionFailures.set(e.serverId,a),t.oauth!==void 0&&O5(i)===`auth`&&r.unavailable.set(e.serverId,`sign-in`),{catalogInput:{serverId:e.serverId,origin:n,transport:d},connection:f}}}function PJe(e,t,n,r){let i=f6[0];return{list:()=>e.list().map(e=>A9(e,r)),sourceProblems:()=>{let e=n.filter(h6).map(e=>e.name);return t.map(t=>jJe(t,i,e))},approve:t=>A9(e.approve(t)),reject:t=>A9(e.reject(t)),revoke:t=>A9(e.revoke(t))}}function FJe(e,t,n,r,i,a){if(n===void 0)return{};let o=new Set,s=()=>e.list().flatMap(e=>{let n=t.find(t=>t.name===e.serverId)?.definition;return n?.transport===`http`&&n.oauth!==void 0?[{request:e,definition:n}]:[]}),{state:c,signOut:l,signIn:u}=n;return{...u===void 0?{}:{oauthLogin:async e=>{let{serverId:t}=e,r=s().find(e=>e.request.serverId===t),a=r?.definition.oauth?.clientId!==void 0,c=e=>({serverId:t,failure:e,preRegisteredClient:a,tools:[]});if(r===void 0||u===void 0)return c(`not-oauth`);if(r.definition.unsetVariables.some(e=>e.field===`url`))return c(`url-unset`);if(e.noBrowser&&e.readRedirect===void 0)return c(`prompt-unavailable`);if(o.has(t))return c(`sign-in-in-progress`);o.add(t);try{await u.call(n,r.request,r.definition,{noBrowser:e.noBrowser,...e.readRedirect===void 0?{}:{readRedirect:e.readRedirect},...e.confirmBrowser===void 0?{}:{confirmBrowser:e.confirmBrowser},...e.signal===void 0?{}:{signal:e.signal}})}catch(e){return c(e instanceof $?e.reason:`unexpected-error`)}finally{o.delete(t)}return{serverId:t,preRegisteredClient:a,...await i(t)}},oauthToolsAdded:a},...c===void 0?{}:{oauthStatus:()=>Promise.all(s().map(async({request:e,definition:t})=>({serverId:e.serverId,state:await c.call(n,e,t)})))},...l===void 0?{}:{oauthLogout:async e=>{let t=s().find(({request:t})=>t.serverId===e);if(t===void 0)throw Error(`MCP server ${e} does not declare OAuth.`);let i=await l.call(n,t.request,t.definition);return r.get(e)?.forget?.(),{serverId:e,...i}}}}}function IJe(e,t,n,r){return n===void 0?{}:Object.fromEntries(Object.entries(fUe(e,t)).filter(([e,i])=>{let a=r.get(i);return a?.serverId===t&&a.sourceName===e&&a.securityIdentity===n}))}function P9(e,t,n,r,i,a,o,s,c){let l=[];for(let u of[...e.adopted,...e.adapted]){if(u.kind!==`tool`)continue;let d=t.get(u.provenance.serverId);if(d===void 0)continue;let f=o.get(u.provenance.serverId),p=n.get(u.provenance.serverId),m=qWe(u,d,{admission:a,get appCallableTools(){return IJe(e,u.provenance.serverId,p,i)},isDispatchAdmitted:()=>s(u.provenance.serverId,d),...f===void 0?{}:{authFailureNotice:f},...u.ui?.resourceUri===void 0?{}:{reportAppViewProblem:e=>c(`MCP server "${u.provenance.serverId}" tool "${u.canonicalName}" app view omitted: ${e}`)}});l.push(m),p!==void 0&&r.set(m.getName(),{serverId:u.provenance.serverId,sourceName:u.sourceName,securityIdentity:p})}return l}function LJe(e){let t=new C6(e.resolvedEntries,{...e.workspace===void 0?{}:{workspace:e.workspace}}),n=new eHe(e.approvalStore,e.now),r=new tHe(t,n,t.displayNames()),i=new Map,a=[],o=new Map,s=new Map;async function c(t,n){let i=e.resolvedEntries.find(e=>e.name===t)?.definition;if(!i)return!1;try{if(e.isDefinitionCurrent&&!await e.isDefinitionCurrent(i))return!1}catch{return!1}return s.get(t)===n&&r.list().some(e=>e.serverId===t&&e.allowed)}let l=new DJe(async n=>{let r=s.get(n),i=e.resolvedEntries.find(e=>e.name===n)?.definition,a=t.list().find(e=>e.serverId===n);if(!r?.getSkillsSession||!a||i?.skills!==!0||!await c(n,r))return;let o=await r.getSkillsSession();if(!(!o||!await c(n,r)))return{serverId:n,securityIdentity:JSON.stringify([a.securityIdentity,a.definitionFingerprint,a.source,a.provenance,a.workspace?.repositoryKey??null,a.workspace?.generation??null]),skills:o,isCurrent:()=>c(n,r)}},e.skillApprovalStore,e.workspace?.repositoryKey??`user`),u=e.timeouts??k9,d=e.createSupervisor??(e=>new BWe(e)),f=new Map,p=new Map,m=new Set,h=new Map,g=kJe(l),_={skills:{commandSource:g,list:async e=>(await l.refreshMetadata(e,32)).map(t=>({serverId:e,uri:t.entry.uri,name:t.entry.frontmatter.name,description:t.entry.frontmatter.description,...g.describe(t)})),inspect:async(e,t)=>v(await l.inspect(e,t)),approve:async(e,t,n,r)=>v(await l.approve(e,t,n,r)),withdraw:(e,t,n)=>l.withdraw(e,t,n)},...PJe(r,e.sourceProblems??[],e.resolvedEntries,{discovered:m,connectedToolProvenance:f,connectionFailures:h}),...FJe(t,e.resolvedEntries,e.oauth,i,ne,re),reload:se,reloadToolsAdded:le,...e.userActionSurface===void 0?{}:{userActionSurface:e.userActionSurface}};function v(e){return{serverId:e.serverId,uri:e.entry.uri,namespace:e.namespace,fingerprint:e.fingerprint,name:e.entry.frontmatter.name,description:e.entry.frontmatter.description,frontmatter:e.entry.frontmatter,content:e.content}}let y=new Map,b,x=0,S,C,w={...e.resultAdmissionLimits,...e.createResultSpillStore?{spillStore:{write:t=>(C??=e.createResultSpillStore(),C.write(t))}}:{},onWarning:({resultChars:t,warningChars:n})=>e.reportDiagnostic(`MCP tool result warning: ${t} characters exceeds ${n}`)},T=!1,E=t=>t.length===0||!e.createResultSpillStore||T?t:(T=!0,[...t,ue()]),ee=t=>({admission:n,createSupervisor:d,timeouts:u,deps:e,signal:t,helperSlots:o,oauthAuthenticators:i,unavailable:p,connectionFailures:h}),te=t=>JU(t,`sign-in`,e.userActionSurface??`session`,e.cliName);async function ne(r){i.get(r)?.forget?.();let o=t.list().find(e=>e.serverId===r),l=e.resolvedEntries.find(e=>e.name===r);if(o===void 0||l?.definition===void 0)return{connection:`not-connected`,tools:[]};let u=n.admit(o);if(!u.allowed)return e.reportDiagnostic(`MCP server "${r}" was not admitted (${u.status}): ${u.reason}`),{connection:`not-admitted`,tools:[]};let d=s.get(r);if(d!==void 0&&m.has(r)){if(d.retry===void 0)return{connection:`not-connected`,tools:[]};try{return await d.retry(),{connection:`recovered`,tools:[]}}catch(t){return e.reportDiagnostic(`MCP server "${r}" did not reconnect after sign-in: ${j9(t)}`),{connection:`not-connected`,tools:[]}}}let p=await N9(o,l.definition,l.origin,ee(void 0));if(p===`not-admitted`)return{connection:`not-admitted`,tools:[]};if(p?.connection===void 0||(a.push(p.connection),s.set(r,p.connection),d!==void 0&&(a.splice(a.indexOf(d),1),await d.shutdown().catch(()=>void 0)),p.catalogInput.discovery===void 0))return{connection:`not-connected`,tools:[]};m.add(r);let h=ie([p.catalogInput]),g=new Map,_=P9(h,new Map([[r,p.connection]]),new Map([[r,o.securityIdentity]]),g,f,w,l.definition.oauth===void 0?new Map:new Map([[r,te(r)]]),c,e.reportDiagnostic);return y.set(r,g),{connection:`connected`,tools:E(_)}}function re(t,n){let r=y.get(t);if(y.delete(t),r===void 0)return;let i=new Set(n);for(let[n,a]of r)i.has(n)?f.set(n,a):e.reportDiagnostic(`MCP tool "${n}" from "${t}" was not added: the session already has a tool by that name.`)}function ie(t){let n=AWe(t,{report:(t,n)=>e.reportDiagnostic(`MCP tool "${t}" has an unenforceable schema subtree: ${n.join(`, `)}`),reportResultSizeProblem:t=>e.reportDiagnostic(`MCP result-size metadata ignored (${t})`),reportUiMetadataProblem:(t,n)=>e.reportDiagnostic(`MCP tool "${t}" UI metadata ignored (${n})`)});for(let t of n.rejected)e.reportDiagnostic(`MCP ${t.kind} "${t.name}" on "${t.serverId}" was rejected: ${t.reason}`);return n}function ae(t,n){if(n.transport===`http`||n.transport===`stdio`)return!0;let r=`unsupported transport: ${n.transport}; use Streamable HTTP (type: "http")`;return h.set(t.serverId,r),e.reportDiagnostic(`MCP server "${t.serverId}" was refused: ${r}.`),!1}async function oe(n){s.clear(),p.clear(),m.clear(),h.clear();let r=[],i=new Map,o=new Map,l=new Map,u=ee(n);for(let n of t.list()){let t=e.resolvedEntries.find(e=>e.name===n.serverId);if(t===void 0||t.definition===void 0)continue;let c=t.definition;if(!ae(n,c))continue;let d=await N9(n,c,t.origin,u);d!==void 0&&d!==`not-admitted`&&(r.push(d.catalogInput),d.connection!==void 0&&(a.push(d.connection),i.set(n.serverId,d.connection),s.set(n.serverId,d.connection),d.catalogInput.discovery!==void 0&&m.add(n.serverId),o.set(n.serverId,n.securityIdentity),c.oauth!==void 0&&l.set(n.serverId,te(n.serverId))))}let d=ie(r);f.clear(),T=!1;let g=P9(d,i,o,f,f,w,l,c,e.reportDiagnostic);return E(g)}function se(){if(S!==void 0)return S;let e=ce();return S=e,e.then(e=>{e.reloadToken===void 0&&(S=void 0)},()=>{S=void 0}),e}async function ce(){let n=ee(void 0),r=[],i=[],o=[],l=new Map,u=new Map,d=new Map;for(let c of t.list()){if(m.has(c.serverId))continue;let t=e.resolvedEntries.find(e=>e.name===c.serverId);if(t===void 0||t.definition===void 0)continue;let f=t.definition;if(!ae(c,f)){i.push(c.serverId);continue}let p=s.get(c.serverId);if(p!==void 0){let e=a.indexOf(p);e!==-1&&a.splice(e,1),await p.shutdown().catch(()=>void 0),s.delete(c.serverId)}let h=await N9(c,f,t.origin,n);if(h!==void 0&&h!==`not-admitted`){if(h.connection===void 0){i.push(c.serverId);continue}if(a.push(h.connection),s.set(c.serverId,h.connection),h.catalogInput.discovery===void 0){i.push(c.serverId);continue}o.push(h.catalogInput),l.set(c.serverId,h.connection),u.set(c.serverId,c.securityIdentity),f.oauth!==void 0&&d.set(c.serverId,te(c.serverId)),m.add(c.serverId),r.push(c.serverId)}}if(o.length===0)return{tools:[],connectedServerIds:r,failedServerIds:i};let p=ie(o),h=new Map,g=P9(p,l,u,h,f,w,d,c,e.reportDiagnostic),_=`reload-${++x}`;return b={token:_,provenance:h},{tools:E(g),connectedServerIds:r,failedServerIds:i,reloadToken:_}}function le(t,n){if(b===void 0||b.token!==t)return;let{provenance:r}=b;b=void 0,S=void 0;let i=new Set(n);for(let[t,n]of r)i.has(t)?f.set(t,n):e.reportDiagnostic(`MCP tool "${t}" from "${n.serverId}" was not added: the session already has a tool by that name.`)}function ue(){return new wt({name:e.resultReadToolName??`agent_read_mcp_result`,description:`Read up to 4,000 characters of a saved MCP tool result using its opaque tool-result reference and a zero-based character offset.`,parameters:{type:`object`,properties:{reference:{type:`string`,description:`The exact tool-result reference`},offset:{type:`number`,description:`Zero-based character offset, default 0`}},required:[`reference`]}},async t=>{let n=t.reference,r=t.offset??0;if(typeof n!=`string`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0)throw Error(`Tool result read arguments invalid`);if(!C)throw Error(`Tool result reference unavailable`);let i;try{i=await C.read(n)}catch{throw Error(`Tool result reference unavailable`)}let a=Math.min(r,i.length),o=e.resultAdmissionLimits?.hardChars??25e3,s=-1,c=Math.min(4e3,i.length-a)+1;for(;c-s>1;){let e=Math.floor((s+c)/2),t={content:i.slice(a,a+e),totalChars:i.length,nextOffset:a+e};JSON.stringify(t).length<=o?s=e:c=e}if(s<0||s===0&&a<i.length)throw Error(`Tool result read limit too small`);return{content:i.slice(a,a+s),totalChars:i.length,nextOffset:a+s}})}async function de(){s.clear();try{await Promise.all([...a.map(e=>e.shutdown()),...C?[C.shutdown()]:[]])}finally{for(let e of o.values())e.close();o.clear();for(let e of i.values())e.close();i.clear()}}return{activationAdapter:_,skillRegistry:l,connect:oe,shutdown:de,connectedToolProvenance:f,unavailableServers:p}}function RJe(e){let t=S6(e),n=e.definition;if(!t||!n||e.status!==`resolved`)return;let r=n.transport===`stdio`||n.transport===`http`,i=[`mcp-client`,...n.transport===`stdio`?[`stdio-authority`]:n.transport===`http`?[`http-transport`]:[]];return{schemaVersion:1,identity:e.name,installedRevision:t.definitionFingerprint,generation:JSON.stringify([t.securityIdentity,t.definitionFingerprint]),source:{kind:`mcp`,location:e.origin},requiredCapabilities:i,contributions:[{identity:`${e.name}:mcp:${e.name}`,kind:`mcp`,source:e.origin,requiredCapabilities:i,disposition:r?`supported`:`unsupported`,...r?{}:{reason:`Unsupported MCP transport`}}],lifecycle:{activation:`unadmitted`,activeCalls:`host-owned`},diagnostics:r?[]:[{component:`mcp`,code:`unsupported-transport`}]}}function F9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I9(e,t){return typeof e==`string`?e.replaceAll("${CLAUDE_PLUGIN_ROOT}",t):Array.isArray(e)?e.map(e=>I9(e,t)):F9(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I9(n,t)])):e}function L9(e,t,n){let r=[],i=new Set;for(let a of ly(sC(t,e,n),{settingsPath:rC(e)})){for(let e of a.skipped){if(e.reason===`disabled`)continue;let t=e.manifestPath;r.push({source:`plugin`,origin:t,definitions:[],problems:[{name:``,source:`plugin`,origin:t,reason:`bundle ${e.reason}${e.detail?`: ${e.detail}`:``}`}]})}for(let e of a.loaded){if(i.has(e.manifest.name)||(i.add(e.manifest.name),e.mcpConfig===void 0))continue;let t=e.mcpConfig;if(!F9(t)||!F9(t.mcpServers)){let n=e.pluginDir;r.push({...G3(t,`plugin`,n),source:`plugin`,origin:n});continue}for(let[n,i]of Object.entries(t.mcpServers)){let t=`${e.manifest.name}:${n}`,a=e.mcpSourcePaths&&Object.hasOwn(e.mcpSourcePaths,n)?e.mcpSourcePaths[n]:e.pluginDir,o=F9(i)&&i.type===void 0?{...i,type:typeof i.command==`string`?`stdio`:typeof i.url==`string`?`http`:void 0}:i;r.push({...G3({mcpServers:{[t]:I9(o,e.pluginDir)}},`plugin`,a),source:`plugin`,origin:a})}}}return r}const R9=`mcpHeaderHelpers`;function z9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zJe(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function BJe(e){if(!z9(e)||Object.keys(e).some(e=>e!==`command`&&e!==`args`))return;let t=e.command,n=e.args??[];if(!(typeof t!=`string`||!Pn(t)||!zJe(n)))return{command:t,args:[...n]}}function VJe(e){let t=[],n=[];for(let r of e){let e=Yp(r,`resolve MCP header helper allowlist`);if(e===void 0||e.trim()===``)continue;let i;try{i=JSON.parse(e)}catch{continue}if(!z9(i)||i.mcpHeaderHelpers===void 0)continue;if(r.kind!==`host`||r.scope!==`user`){n.push(`"${R9}" in ${r.displayName} was ignored: only user settings may allow a header helper.`);continue}let a=i[R9],o=Array.isArray(a)?a.map(BJe):void 0;if(o===void 0||o.some(e=>e===void 0)){n.push(`"${R9}" in ${r.displayName} was refused: it must be an array of {"command": "/absolute/path", "args": [...]} objects.`);continue}t.push(...o)}return{allowed:t,diagnostics:n}}function HJe(e,t,n,r){let i=X6(t),a={};for(let[t,n]of Object.entries(e))n===void 0||OHe(t)||i&&K3(t)||(a[t]=n);return a.PRODUCT_MCP_SERVER_NAME=n,a.PRODUCT_MCP_SERVER_URL=r,a}const B9=process.platform===`win32`;function V9(e,t=!1){if(typeof e.pid==`number`){if(B9){let n=[`/pid`,String(e.pid),`/T`,`/F`],r={stdio:`ignore`,windowsHide:!0};if(t){sn(`taskkill`,n,r);return}let i=on(`taskkill`,n,r);i.on(`error`,()=>void 0),i.unref();return}try{process.kill(-e.pid,`SIGKILL`)}catch{try{e.kill(`SIGKILL`)}catch{}}}}const H9=new Set;let U9=!1;function UJe(e){H9.add(e),!U9&&(U9=!0,process.once(`exit`,()=>{for(let e of H9)V9(e,!0);H9.clear()}))}function WJe(e){let t=e.timeoutMs??1e4,n=e.maxStdoutBytes??65536;return new Promise((r,i)=>{if(e.signal.aborted){i(new Y6(`cancelled`));return}let a;try{a=on(e.helper.command,[...e.helper.args],{cwd:e.cwd,env:e.env,shell:!1,stdio:[`ignore`,`pipe`,`ignore`],detached:!B9,windowsHide:!0})}catch{i(new Y6(`spawn-failed`));return}UJe(a);let o=[],s=0,c=!1,l=()=>{c=!0,H9.delete(a),clearTimeout(f),e.signal.removeEventListener(`abort`,d)},u=(e,t=!0)=>{c||(l(),t&&V9(a),a.stdout?.destroy(),i(new Y6(e)))},d=()=>u(`cancelled`),f=setTimeout(()=>u(`timeout`),t);e.signal.addEventListener(`abort`,d,{once:!0}),a.stdout?.on(`data`,e=>{if(s+=e.byteLength,s>n){u(`output-too-large`);return}o.push(e)}),a.stdout?.on(`error`,()=>u(`spawn-failed`)),a.on(`error`,()=>u(`spawn-failed`)),a.on(`close`,e=>{if(H9.delete(a),!c){if(e!==0){u(`exit-status`,!1);return}l();try{r(new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.concat(o)))}catch{i(new Y6(`output-malformed`))}}})})}const GJe=[`autoBackgroundMs`,`callTimeoutMs`],KJe=[...f6].reverse();function W9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qJe(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function JJe(e){let t=Yp(e,`resolve MCP background-handoff settings`);if(t===void 0||t.trim()===``)return;let n=I5(e),r=e.displayName,i;try{i=JSON.parse(t)}catch(e){return{key:`*`,source:n,origin:r,reason:F5(e)}}if(!W9(i)||i.mcp===void 0)return;let a=i.mcp;return W9(a)?{source:n,origin:r,mcp:a}:{key:`*`,source:n,origin:r,reason:`"mcp" must be an object, got ${typeof a}`}}function YJe(e){let t=[],n=[];for(let r of e){let e=JJe(r);e!==void 0&&(`mcp`in e?n.push(e):t.push(e))}let r=e=>KJe.indexOf(e),i=[...n].sort((e,t)=>r(e.source)-r(t.source)),a=12e4,o=6e5;for(let e of i){let n={},r=!1;for(let i of GJe){let a=e.mcp[i];if(a!==void 0){if(!qJe(a)){r=!0,t.push({key:i,source:e.source,origin:e.origin,reason:`"${i}" must be a non-negative integer, got ${JSON.stringify(a)}`});continue}n[i]=a}}r||(n.autoBackgroundMs!==void 0&&(a=n.autoBackgroundMs),n.callTimeoutMs!==void 0&&(o=n.callTimeoutMs))}let s=[],c=a>0;return c&&a>=o&&(c=!1,s.push(`MCP tool-call handoff disabled: "mcp.autoBackgroundMs" (${a}) must be less than "mcp.callTimeoutMs" (${o}).`)),{autoBackgroundMs:a,callTimeoutMs:o,handoffEnabled:c,problems:t,diagnostics:s}}function G9(e){if(typeof e!=`object`||!e)return!1;let t=e;return[`scope`,`namespace`,`serverId`,`uri`].every(e=>typeof t[e]==`string`)&&typeof t.fingerprint==`string`&&/^[a-f0-9]{64}$/.test(t.fingerprint)}function XJe(e){function t(t=!1){try{Qt(e);let t=JSON.parse(A(e,`utf8`));if(!t||t.version!==1||!Array.isArray(t.records)||!t.records.every(G9)||new Set(t.records.map(e=>e.namespace)).size!==t.records.length)throw Error(`Unrecognised store`);return t.records}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return[];if(t)throw Error(`Refusing to write unreadable or unrecognised MCP skill approval store.`);return[]}}function n(n){vn(Mn(e),{recursive:!0,mode:448});let r=`${e}.lock`,i;try{i=bn(r,`wx`,384)}catch{throw Error(`Refusing to write MCP skill approval store: another writer holds its lock.`)}try{Jt(e,`${JSON.stringify({version:1,records:n(t(!0))},null,2)}\n`)}finally{un(i),On(r)}}return{list:()=>t(),put:e=>{if(!G9(e))throw Error(`Invalid MCP skill approval.`);n(t=>[...t.filter(t=>t.namespace!==e.namespace),e])},remove:e=>n(t=>t.filter(t=>t.namespace!==e))}}function ZJe(e){return XJe(M(e.layout.userRoot,`mcp-skill-approvals.json`))}function K9(e){switch(e){case`trusted`:return`trusted`;case`untrusted`:return`untrusted`;case`revoked`:return`revoked`;case`stale/replaced`:return`stale/replaced`;case`identity-unavailable`:return`identity-unavailable`;case`store-unavailable`:return`store-unavailable`}}function QJe(e,t){return e.status===`trusted`?{repositoryKey:e.identity.repositoryKey,trustState:K9(t.state),generation:t.generation}:e.identity===void 0?{repositoryKey:`identity-unavailable`,trustState:K9(e.trustState),generation:t.generation}:{repositoryKey:e.identity.repositoryKey,trustState:K9(t.state),generation:t.generation}}async function q9(e,t){return sf(pq(t).workspaceTrust).inspect(e)}function $Je(e,...t){return HJe(Pq(e),...t)}async function eYe(e){let{entries:t,problems:n,sourceProblems:r}=L5(e.settingsSources,e.env,L9(e.productRuntime,e.cwd,e.projectAccess));for(let t of n)e.reportDiagnostic(t.name===``?`MCP source ${t.source} (${t.origin}) could not be read: ${t.reason}`:`MCP definition "${t.name}" from ${t.source} (${t.origin}) was refused: ${t.reason}`);for(let n of t)h6(n)&&e.reportDiagnostic(`MCP server "${n.name}" was not activated: the managed source could not be read, so a lower-trust definition cannot be trusted to be the real winner.`);let i=YJe(e.settingsSources);for(let t of i.problems)e.reportDiagnostic(`MCP setting "${t.key}" from ${t.source} (${t.origin}) was refused: ${t.reason}`);for(let t of i.diagnostics)e.reportDiagnostic(t);e.mode===`print`&&i.autoBackgroundMs>0&&e.reportDiagnostic(`MCP tool-call handoff ("mcp.autoBackgroundMs") is ignored in print mode; a long MCP tool call runs to completion in the foreground, bounded only by "mcp.callTimeoutMs".`);let a=e.projectAccess.identity,o=a===void 0?{state:`identity-unavailable`,generation:0}:await(e.inspectTrust??(()=>q9(a,e.productRuntime)))(e.cwd),s=QJe(e.projectAccess,o),c=new C6(t,{workspace:s}).list();async function l(t){if(T6(t.source)){if(!a)return!1;let t=await(e.inspectTrust??(()=>q9(a,e.productRuntime)))(e.cwd);if(t.state!==`trusted`||t.generation!==o.generation)return!1}let n=L5(e.settingsSources,e.env,L9(e.productRuntime,e.cwd,e.projectAccess)).entries,r=new C6(n,{workspace:s}).list().find(e=>e.serverId===t.name),i=c.find(e=>e.serverId===t.name);return!!r&&!!i&&r.securityIdentity===i.securityIdentity&&r.definitionFingerprint===i.definitionFingerprint}let u=VJe(e.settingsSources);for(let t of u.diagnostics)e.reportDiagnostic(t);let d={allowed:u.allowed,run:async({request:t,definition:n,helper:r},i)=>{let o=X6(t.source),s=n.url??``,c;if(o){if(a===void 0)throw new Y6(`spawn-failed`);c=a.worktreeRoot}else c=mq(e.productRuntime),vn(c,{recursive:!0});return WJe({helper:r,cwd:c,env:$Je(e.env,t.source,t.serverId,o?BVe(n,`url`,s):s),signal:i})}},f=LJe({skillApprovalStore:ZJe(e.productRuntime),resolvedEntries:t,isDefinitionCurrent:l,resultReadToolName:`${e.productRuntime.config.identity.modelCommandToolPrefix}read_mcp_result`,sourceProblems:r,workspace:s,clientInfo:{name:e.productRuntime.config.identity.mcpClientName,version:`0.0.0`},...e.stdioAuthorities===void 0?{}:{stdioAuthorities:e.stdioAuthorities},...e.approvalStore===void 0?{}:{approvalStore:e.approvalStore},...e.httpTransportDeps===void 0?{}:{transport:e.httpTransportDeps},headersHelpers:d,oauth:eGe({productRuntime:e.productRuntime,network:{...e.httpTransportDeps?.policy===void 0?{}:{policy:e.httpTransportDeps.policy},...e.httpTransportDeps?.lookup===void 0?{}:{lookup:e.httpTransportDeps.lookup},...e.httpTransportDeps?.fetch===void 0?{}:{fetch:e.httpTransportDeps.fetch}},reportDiagnostic:e.reportDiagnostic}),timeouts:AJe(i.callTimeoutMs),createResultSpillStore:()=>Vfe({onCleanupFailure:t=>e.reportDiagnostic(`MCP tool-result retention cleanup failed (${t})`)}),...e.resultAdmissionLimits?{resultAdmissionLimits:e.resultAdmissionLimits}:{},reportDiagnostic:e.reportDiagnostic,userActionSurface:nYe(e.mode),elicitation:rYe(e.mode,e.askSurface),apps:iYe(e.mode,e.appSurface),cliName:e.productRuntime.vocabulary.cliName});function p(t){if(e.mode!==`interactive`&&e.mode!==`serve`||!i.handoffEnabled)return;let n=t??`default`,r=[],a={};for(let[e,t]of f.connectedToolProvenance)r.push(e),a[e]={serverId:t.serverId,sourceName:t.sourceName,securityIdentity:t.securityIdentity,permissionMode:n};return{thresholdMs:i.autoBackgroundMs,budgetMs:i.callTimeoutMs,toolNames:r,provenance:a}}let m=t.flatMap(e=>{let t=RJe(e);return t?[t]:[]});return{...f,buildToolCallHandoff:p,contributionDescriptors:m}}function tYe(e,t,n){return e===`interactive`?YU(t,n):void 0}function nYe(e){return e===`interactive`?`session`:`terminal`}function rYe(e,t){return e!==`print`&&t!==!1}function iYe(e,t){return e===`serve`&&t===!0}function aYe(e){return e.serve&&!e.mcpServe&&!e.acp}const oYe=new Set([`approved`,`rejected`,`revoked`]),J9=new Set([`managed`,`user`,`project`,`plugin`,`local`]);function Y9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sYe(e){if(!Y9(e))return!1;let t=e.provenance;return typeof e.serverId==`string`&&typeof e.source==`string`&&J9.has(e.source)&&Y9(t)&&typeof t.kind==`string`&&typeof t.id==`string`&&typeof e.definitionFingerprint==`string`&&typeof e.securityIdentity==`string`&&typeof e.approvalAuthority==`string`&&J9.has(e.approvalAuthority)&&typeof e.decision==`string`&&oYe.has(e.decision)&&typeof e.decidedAt==`string`&&(e.repositoryKey===void 0||typeof e.repositoryKey==`string`)&&(e.workspaceGeneration===void 0||typeof e.workspaceGeneration==`number`)}function cYe(e){return Y9(e)&&typeof e.action==`string`&&typeof e.serverId==`string`&&typeof e.decision==`string`&&typeof e.at==`string`}function X9(e,t){return e.serverId===t.serverId&&e.approvalAuthority===t.approvalAuthority&&(e.repositoryKey??``)===(t.repositoryKey??``)}function lYe(e){function t(t=!1){try{Qt(e);let t=JSON.parse(A(e,`utf8`));if(!Y9(t)||t.version!==1||!Array.isArray(t.records)||!t.records.every(sYe)||!Array.isArray(t.audit)||!t.audit.every(cYe))throw Error(`Unrecognised approval store`);return{version:1,records:t.records,audit:t.audit}}catch(n){if(Y9(n)&&n.code===`ENOENT`)return{version:1,records:[],audit:[]};if(t)throw Error(`Refusing to write unreadable or unrecognised MCP approval store ${e}; repair or move it aside first.`);return{version:1,records:[],audit:[]}}}function n(n){vn(Mn(e),{recursive:!0,mode:448});let r=`${e}.lock`,i;try{i=bn(r,`wx`,384)}catch{throw Error(`Refusing to write MCP approval store ${e}: another writer holds ${r}. Retry after it finishes; remove a stale lock only after that process has stopped.`)}try{Jt(e,`${JSON.stringify(n(t(!0)),null,2)}\n`)}finally{un(i),On(r)}}return{list:()=>t().records,put(e){n(t=>({...t,records:[...t.records.filter(t=>!X9(t,e)),e]}))},putWithAudit(e,t){n(n=>({...n,records:[...n.records.filter(t=>!X9(t,e)),e],audit:[...n.audit,t].slice(-500)}))},listAudit:()=>t().audit,appendAudit(e){n(t=>({...t,audit:[...t.audit,e].slice(-500)}))}}}function uYe(e,t){return e??lYe(pq(t).mcpApprovals)}const Z9=`advisorConsentDestinations`;function Q9(e){let t=e.PRODUCT_DISABLE_ADVISOR?.trim().toLowerCase();return t===`1`||t===`true`}function dYe(e){let t=()=>{let t=Yg(e)[Z9];return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]};return{has:e=>t().includes(e),grant:n=>{let r=t();r.includes(n)||Xg(e,{...Yg(e),[Z9]:[...r,n]})}}}function fYe(e,t,n){return r=>{let i={providerOverride:r.profile,providerDefinitions:t,env:n},a=vy(e,i),o=r.model??a.model;return{provider:yy(e,o,i),model:o,destination:vu(a,t)}}}function pYe(e){let t=$pe(e.flag,e.safeMode?void 0:e.userSettings.advisorModel),n=e.orgPolicy?.allowedProviders;bu(e.mainProvider.provider,vu(e.mainProvider.config,e.providerDefinitions));let r=new sme({...t===void 0?{}:{spec:t},resolveTarget:fYe(e.settingsSources,e.providerDefinitions,e.env),...e.resolveProviderCredential===void 0?{}:{validateTarget:t=>{vy(e.settingsSources,{providerOverride:t.profile,providerDefinitions:e.providerDefinitions,env:e.env})},resolveTargetAsync:async t=>{let n=vy(e.settingsSources,{providerOverride:t.profile,providerDefinitions:e.providerDefinitions,env:e.env}),r=t.model??n.model;return{provider:Tt(await e.resolveProviderCredential({...n,model:r}),e.providerDefinitions),model:r,destination:vu(n,e.providerDefinitions)}}},consent:dYe(e.userSettingsPath),...n===void 0?{}:{allowedProfiles:n},killSwitch:Q9(e.env)});return r.isRegistered()?{controller:r,tool:zoe(r)}:t===void 0||Q9(e.env)?{controller:r}:{controller:r,notice:`Advisor "${$x(t)}" is not allowed by your organization policy; starting without it.`}}const mYe={maxTopics:5,maxTopicChars:2e3};function hYe(e){let t=e?.memory;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r={};return typeof n.enabled==`boolean`&&(r.enabled=n.enabled),typeof n.autoSave==`boolean`&&(r.autoSave=n.autoSave),r}function gYe(e){let t=e.settings?.enabled??!1;e.flagEnabled!==void 0&&(t=e.flagEnabled);let n=e.env?.trim();n===`1`?t=!0:n===`0`&&(t=!1);let r=(e.settings?.autoSave??!1)||e.flagAutoSave===!0;return{enabled:t,autoSave:r}}function _Ye(e,t){if(!e.enabled)return{};if(t===void 0)throw new U(`Project memory requires an explicit workspace-authority-backed memory store.`);return{memoryStore:t,recallMemory:{budget:mYe},automaticMemory:{policy:e.autoSave?`auto_save`:`approval_required`}}}function vYe(e){let t=gYe({settings:hYe(e.settings),flagEnabled:e.args.memory,flagAutoSave:e.args.memoryAutoSave,env:e.productRuntime.environment.PRODUCT_MEMORY}),n=e.platform??process.platform;if(t.enabled&&e.memoryStore===void 0&&!Bd(n))return bYe(n,e.productRuntime,e.write),{};let r=_Ye(t,e.memoryStore);return t.enabled&&yYe(e.cwd,e.productRuntime,e.write),r}function $9(e){process.stderr.write(e)}function yYe(e,t,n=$9){n(`Memory is ON (opt-in): capturing and recalling durable memory in ${M(e,t.layout.projectStateDirectories.memory)}. Inspect with /memory; disable with --no-memory or "memory": { "enabled": false } in settings.json.\n`)}function bYe(e,t,n=$9){n(`Memory is OFF: project memory is kept in ${t.layout.projectStateDirectories.memory}, and on this host (${e}) The agent cannot prove a write stays inside the project, so nothing is captured or recalled.\n`)}async function xYe(e,t,n){let r=aD(e);if(nC(r),gD(r.environment)!==void 0)return oye(e,r.environment,r.config.identity.cliName);let i={...e,productRuntime:r},a={...r.environment};delete a.PRODUCT_TELEMETRY_SERVICE_NAME;let o=bNe(a);Mq([...new Set([...Object.keys(r.environment),...Object.keys(process.env)])].filter(e=>e===`PRODUCT_TELEMETRY_SERVICE_NAME`||e===`${r.config.identity.envPrefix}TELEMETRY_SERVICE_NAME`?!1:e.startsWith(`PRODUCT_TELEMETRY_`)||e.startsWith(`${r.config.identity.envPrefix}TELEMETRY_`)));let s=await AGe(r);if(s.kind===`refused`)return;let c=s.kind===`launched`?s.initialInput:void 0,l=Jve(process.argv.slice(2))??Gve(process.argv.slice(2)),u=l===void 0?void 0:wJe();try{await SYe(i,t,n,c,u?.protocol,l,o)}finally{u?.restore()}}async function SYe(e,t,n,r,i,a,o={}){let s=aD(e),c=process.cwd(),l=xq(process.argv).includes(`--safe-mode`)||e.safeMode===!0,u=await Nwe(process.argv,c,{...e,safeMode:l}),d={...e,projectAccess:u,...l?{safeMode:!0}:{}};if(await uGe(d,process.argv,c,o,n?.renderSupervisedSessionView,n))return;let f;try{f=a??OD(),f={...f,safeMode:l}}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let p=I1(s),{mcpServe:m,http:h,askClient:g}=RD(f,s.config.identity.cliName),{acp:_}=MD(f,s.config.identity.cliName),v=zGe(f,s.environment);if(Mq([`PRODUCT_HTTP_TOKEN`,`${s.config.identity.envPrefix}HTTP_TOKEN`]),f.help){process.stdout.write(Ave(s));return}if(f.version){process.stdout.write(`${s.config.identity.cliName} ${p}\n`);return}if(f.checkUpdate){let e=await _q({productRuntime:s,currentVersion:p,force:!0}),t=fwe(e);e.status===`error`&&(process.stderr.write(`${t}\n`),process.exit(1)),process.stdout.write(`${t}\n`);return}let y=l?{bare:!0,skipConfiguredHooks:!0}:{},b=e=>cC(e,s,c,u,!l),x=new ZD;if(f.reset){process.exitCode=await uPe(x,{productRuntime:s,yes:f.yes,isTTY:process.stdin.isTTY===!0});return}if((f.printMode||f.goal!==void 0||f.serve||m)&&!l&&!xq(process.argv).includes(`--restricted-workspace`)&&kD(u))if(f.serve&&f.open&&v4(u)){let e=await y4(u,c,{productRuntime:s});if(e.decision===`quit`){process.exitCode=1;return}u=e.access}else{process.stderr.write(`${AD(u,c,s.config.identity.cliName)}\n`),process.exitCode=1;return}if((f.printMode||f.goal!==void 0||f.serve||m)&&!l&&!xq(process.argv).includes(`--restricted-workspace`)&&kD(u))if(f.serve&&f.open&&v4(u)){let e=await y4(u,c,{productRuntime:s});if(e.decision===`quit`){process.exitCode=1;return}u=e.access}else{process.stderr.write(`${AD(u,c,s.config.identity.cliName)}\n`),process.exitCode=1;return}if((f.printMode||f.goal!==void 0||f.serve||m||_)&&u.status===`restricted`&&process.stderr.write(`${jD(s.layout.projectSettingsPaths)}\n`),DD(f)===`eval`){let t=Rq(c,d);process.exitCode=await P1(process.argv.slice(3),c,{settingsSources:t.settingsSources,projectAccess:t.projectAccess,environment:s.environment,resolveProviderCredential:(e.providerConnectionHost??gq(s)).resolveCredential});return}if(DD(f)===`session`&&f.positional[1]===`analyze`){await N1(process.argv.slice(4),c,void 0,gx(s.layout.userPaths.sessions));return}try{if(await QNe(f,c,x,s))return}catch(e){x.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}if(f.serve&&f.open&&!process.stdout.isTTY)throw Error(`Opening the monitor requires an interactive terminal for its access code.`);u=await yze(u,c,{productRuntime:s,interactive:_ze(f)&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0,accessFixed:l||xq(process.argv).includes(`--restricted-workspace`)||e.projectAccess!==void 0}),zwe(d,u,c);let S=Oq(s),C=Sq({args:f,settings:S,productRuntime:s,safeMode:l,writeError:e=>x.writeError(e)}),w=C.options,T=C.presetId,E=k1(s.environment),ee=Cq({productRuntime:s,cwd:c,settingsSources:Rq(c,d).settingsSources}),te=Dq(ee);if(te!==void 0&&(process.stderr.write(`${te.message}\n`),te.fatal)){process.exitCode=1;return}let ne=ee.client,re=_?ZNe():void 0,{packContext:ie,packs:ae,packCommandModules:oe}=JNe(c,s,{shellExecutable:E,...ne===void 0?{}:{sandboxClient:ne,sandboxType:`os`},...re===void 0?{}:{editorFiles:re.current}}),se=n===void 0?void 0:P3(n,{enabled:!(f.printMode||f.goal!==void 0||f.serve||m||_),cwd:c,productRuntime:s,projectAccess:u,settings:S,reducedMotionFlag:f.reducedMotion,env:s.environment}),ce=se?.keybindingsSource,le=se?.theme,ue=f.printMode||f.goal?`print`:f.serve||m||_?`serve`:`interactive`,de=!(f.printMode||f.goal||m||_),fe=aYe({serve:f.serve,mcpServe:m,acp:_}),D=e.mcpActivationAdapter===void 0&&!l?await eYe({productRuntime:s,settingsSources:Rq(c,d).settingsSources,projectAccess:u,cwd:c,env:s.environment,mode:ue,askSurface:de,appSurface:fe,...e.mcpStdioAuthorities===void 0?{}:{stdioAuthorities:e.mcpStdioAuthorities},approvalStore:uYe(e.mcpApprovalStore,s),...e.mcpHttpTransportDeps===void 0?{}:{httpTransportDeps:e.mcpHttpTransportDeps},...e.mcpResultAdmissionLimits===void 0?{}:{resultAdmissionLimits:e.mcpResultAdmissionLimits},reportDiagnostic:e=>x.writeError(e)}):void 0;D!==void 0&&(d.mcpActivationAdapter=D.activationAdapter);let pe=Kje({productRuntime:s,report:e=>x.writeError(e)}),{commandHostAdapters:me,outputStyleRegistry:he,outputStyleLoadErrors:ge,providerDefinitions:_e,callerSuppliedProviderDefinitions:ve,baseCommandModules:ye,fixedCommandModules:be,startupUpdateNoticePromise:xe,remoteCommandPolicy:Se,workspaceComposition:O,orgPolicy:Ce,providerConnectionHost:we}=pze(c,f,d,p,oe,ce,le?.cataloguePort,ee,{status:()=>pe.status(),identityChanged:()=>void pe.identityChanged()});for(let{file:e,error:t}of ge)x.writeError(`Skipped output style "${e}": ${t}`);for(let{fileName:e,reason:t}of le?.skipped??[])x.writeError(`Skipped theme "${e}": ${t}`);let Te=Jwe(f,l?void 0:S.outputStyle),Ee;try{Ee=Ywe(he,Te)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}if(f.outputStyle!==void 0||!l&&S.outputStyle!==void 0){let e=`Output style: ${Ee.name} (${Ee.id}; input cost ${Ee.tokenCost})`;f.printMode?process.stderr.write(`${e}\n`):x.writeLine(e)}let De=f.serve&&!f.noSessionPersistence?Jqe():void 0,Oe=UDe({commandHostAdapters:me,settingsSources:O.settingsSources,settingsStores:O.settingsStores,providerDefinitions:_e,orgPolicy:Ce,environment:s.environment}),{registry:ke,wsTransport:Ae,bindTransports:je,usageReporters:Me}=iMe(s,O.sessionStore,O.projectAccess.status===`trusted`,f.open,De,f.daemon===!0,Oe),Ne,Pe=[];if((f.externalEventGrantFiles?.length??0)>0){try{Pe=rO(f.externalEventGrantFiles??[]),Ne=UA(Pe,e=>x.writeLine(e))}catch(e){process.stderr.write(`${e instanceof Error?e.message:`grant refused`}\n`),process.exit(1)}me.externalEvents=Ne.adapter}let Fe;if(Ne!==void 0){let e=Ne;try{Fe=ij({grants:Pe,receive:(t,n)=>e.receive(t,n),countRefusal:(t,n)=>e.countRefusal(t,n),port:f.externalEventPort??0,...f.externalEventTrustedProxies===void 0?{}:{trustedProxies:f.externalEventTrustedProxies},audit:HA(e=>x.writeLine(e))}),await Fe.start()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`External event endpoint could not start.`}\n`),process.exit(1)}}let Ie=Ne,Le=async e=>{if(je(e),Ie!==void 0){if(!(e instanceof rx))throw Error(`External event grants require an InteractiveSession runtime`);await Ie.bind(e)}},{controller:Re,setChannel:ze}=xAe(ke,Me,s);me.costBudget=qj(c,s),me.sandbox=Owe(ee,{read:()=>Yg(rC(s)),write:e=>Xg(rC(s),e)});let Be=AKe(me,Re,x,s,void 0,{sessionStore:O.sessionStore,hasOwnProvider:()=>XGe(Ue,_e),onHandedOff:()=>me.process?.requestExit(`other`)},pe);zDe(e=>x.writeError(e),ye,oe,w);let Ve=await IGe({cwd:c,args:f,startOptions:d,terminal:x,providerDefinitions:_e,workspace:O,providerConnectionHost:we,orgPolicy:Ce});if(Ve.handled){we.shutdown();return}let He=Ve.setupRequired!==void 0,Ue=He?{name:`setup-placeholder`,model:`setup-required`}:await we.resolveCredential(NCe(s,O.settingsSources,_e,f.provider)),We=w.model??Ue.model,Ge;try{Ge=Kwe(f,s.environment,gy(O.settingsSources),w)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}if(me.effort=qwe(Ge),l&&(f.printMode?process.stderr.write(`Safe mode: project and user instruction files, skills, commands, agents, output styles, plugins, hooks and MCP servers are off. Provider, model, built-in tools and permissions work as usual.
2918
+ `)}}function v9(e,t,n){let r=e.diffFile===void 0?void 0:Ln(n,e.diffFile);return{toolCallId:t,title:aJe(e),kind:m9(e.toolName),status:`pending`,rawInput:oJe(e),...r!==void 0&&e.diffLines!==void 0?{content:[{type:`diff`,path:r,...cJe(e.diffLines)}]}:{},...r===void 0?{}:{locations:[{path:r}]}}}function lJe(e,t){if(e.outcome!==`selected`||!t.some(t=>t.optionId===e.optionId))return!1;switch(e.optionId){case _9.allowOnce:return!0;case _9.allowSession:return`allow-session`;case _9.allowProject:return`allow-project`;default:return!1}}function uJe(e,t){let n=Object.keys(t);for(let r of n)e.on(r,t[r]);return()=>{for(let r of n)e.off(r,t[r])}}function dJe(e){let{updates:t}=e,n=[],r=new Map,i=new Map,a=!1,o=e=>{if(e===void 0)return;let t=r.get(e);return r.delete(e),t},s=(e,n)=>t.send({sessionUpdate:`tool_call_update`,toolCallId:e,status:n?`completed`:`failed`});return{start(r){if(r.internal)return;let i=o(r.executionId),a=i?.id??e.nextToolCallId(r.executionId);n.push({id:a,toolName:r.toolName,executionId:r.executionId});let s={toolCallId:a,title:h9(r),kind:m9(r.toolName),status:`in_progress`};i===void 0?t.send({sessionUpdate:`tool_call`,...s}):t.send({sessionUpdate:`tool_call_update`,...s,rawInput:i.rawInput})},end(r){if(r.internal)return;let i=g9(r),a=n.findIndex(e=>r.executionId===void 0?e.executionId===void 0&&e.toolName===r.toolName:e.executionId===r.executionId);if(a>=0){let[e]=n.splice(a,1);t.send({sessionUpdate:`tool_call_update`,toolCallId:e.id,status:i});return}let s=o(r.executionId);if(s!==void 0){t.send({sessionUpdate:`tool_call_update`,toolCallId:s.id,status:i});return}t.send({sessionUpdate:`tool_call`,toolCallId:e.nextToolCallId(r.executionId),title:h9(r),kind:m9(r.toolName),status:i})},requested(t){let{executionId:a}=t;if(a===void 0){let n=v9(t,e.nextToolCallId(`permission-${t.id}`),e.cwd);return i.set(t.id,n.toolCallId),n}let o=n.find(e=>e.executionId===a),s=r.get(a),c=o?.id??s?.id??e.nextToolCallId(a),l=v9(t,c,e.cwd);return o===void 0&&s===void 0&&r.set(a,{id:c,rawInput:l.rawInput,background:t.requester!==void 0}),l},answered(e,t){if(e.executionId!==void 0){let n=r.get(e.executionId);n!==void 0&&(n.allowed=t);return}let n=i.get(e.id);n===void 0||a||(i.delete(e.id),s(n,t))},finish(){a=!0;for(let e of r.values())s(e.id,e.background&&e.allowed===!0);for(let e of i.values())s(e,!1);r.clear(),i.clear()}}}const y9={stopReason:`cancelled`},fJe={stopReason:`end_turn`};function b9(e){return e instanceof Error?e:Error(String(e))}async function x9(e,t){let{session:n,sessionId:r,client:i,updates:a}=e,o=dJe({updates:a,nextToolCallId:e.nextToolCallId,cwd:e.cwd}),s=!1,c=uJe(n,{text_delta:e=>{e!==``&&(s=!0,a.text(e))},thinking_delta:e=>{e!==``&&a.thought(e)},tool_start:o.start,tool_end:o.end,permission_request:t=>{let a=iJe(t.canPersistProjectPermission===!0),s=o.requested(t);(async()=>{let c=!1;try{c=lJe((await i.request(`session/request_permission`,{sessionId:r,toolCall:s,options:a})).outcome,a)}catch(t){e.report(b9(t),`session/request_permission`)}o.answered(t,c!==!1);try{n.resolvePermission(t.id,c,e.driverId)}catch(t){e.report(b9(t),`resolvePermission`)}})()}});try{let n=await t.run();return e.wasCancelled()||e.signal.aborted||n.interrupted?y9:(!s&&n.reply!==``&&a.text(n.reply),fJe)}catch(n){return e.wasCancelled()||e.signal.aborted||t.isCancellation?.(n)===!0?y9:t.fail(n)}finally{c(),o.finish(),await a.drained()}}function pJe(e,t){return x9(e,{async run(){let n=await(await e.session.submit(t,void 0,void 0,{signal:e.signal,driverId:e.driverId,...e.surface===void 0?{}:{surface:e.surface}})).completed;return{interrupted:n.interrupted===!0,reply:n.response}},isCancellation:e=>ao(e)&&e.reason===`cancelled`,fail(t){throw e.report(b9(t),`turn`),new ai(-32603,ao(t)?`Turn was not run`:`Turn failed`)}})}function mJe(e,t,n){return x9(e,{async run(){return{interrupted:!1,reply:await n(t,e.signal)}},fail(t){throw e.report(b9(t),`command`),new ai(-32603,`Command failed`)}})}function S9(e,t,n){let r=Promise.resolve(),i=!1,a=a=>{r=r.then(async()=>{if(!i)try{await e.notify(`session/update`,{sessionId:t,update:a})}catch(e){i=!0,n(e instanceof Error?e:Error(String(e)),`session/update`)}})};return{send:a,text:e=>a({sessionUpdate:`agent_message_chunk`,content:{type:`text`,text:e}}),thought:e=>a({sessionUpdate:`agent_thought_chunk`,content:{type:`text`,text:e}}),drained:()=>r}}const C9=-32603,hJe=()=>Promise.resolve(`Slash commands are not available in this host.`);function gJe(e,t){if(Ln(e)===Ln(t))return!0;try{return Cn(e)===Cn(t)}catch{return!1}}function w9(e){return e instanceof Error?e:Error(String(e))}function _Je(e,t){let n=t.driverId??io,r=(e,n)=>t.onDeliveryError?.(e,n),i,a=!1,o,s=0,c=new Set,l=e=>{let t=e;for(;t===void 0||c.has(t);)t=`tool-${s+=1}`;return c.add(t),t},u,d=e=>{if(!Pn(e.cwd)||!gJe(e.cwd,t.cwd))throw ai.invalidParams(void 0,`cwd must be the directory this agent was started in: ${t.cwd}`);if(e.mcpServers.length>0)throw ai.invalidParams(void 0,`mcpServers are not accepted by this agent`);if((e.additionalDirectories??[]).length>0)throw ai.invalidParams(void 0,`additionalDirectories are not accepted by this agent`);let n=t.admitWorkspace();if(!n.admitted)throw new ai(-32001,n.message,{reason:`workspace-not-trusted`})},f=async t=>{try{return await e.whenInitialized?.(),e.getStatusSnapshot().sessionId}catch(e){throw r(w9(e),t),new ai(C9,`The session could not be started`)}},p=(t,n)=>{if(e.listCommands===void 0&&e.listSkills===void 0)return;let i;try{i=nJe(e)}catch(e){r(w9(e),`available_commands_update`);return}let a=JSON.stringify(i);a!==u&&(u=a,t.notify(`session/update`,{sessionId:n,update:{sessionUpdate:`available_commands_update`,availableCommands:i}}).catch(e=>r(w9(e),`available_commands_update`)))},m=(e,t)=>{setImmediate(()=>p(e,t))},h,g=!1,_=e=>{let n=Xqe(h,e,()=>i);n!==void 0&&(g=!0,t.onEditorFileAccess?.(n))};return{app:Dte({name:t.agentInfo.name}).onRequest(`initialize`,({params:n})=>(h=n.clientCapabilities?.fs,{protocolVersion:Ete,agentCapabilities:{loadSession:t.loadSession!==void 0&&e.getMessagesDisplay!==void 0,promptCapabilities:{image:!1,audio:!1,embeddedContext:!0}},agentInfo:{name:t.agentInfo.name,version:t.agentInfo.version}})).onRequest(`session/new`,async({params:e,client:t})=>{if(i!==void 0||a)throw ai.invalidParams(void 0,`one session per connection`);d(e),a=!0;try{i=await f(`session/new`)}finally{a=!1}return _(t),m(t,i),{sessionId:i}}).onRequest(`session/load`,async({params:n,client:s})=>{let c=t.loadSession;if(c===void 0||e.getMessagesDisplay===void 0)throw ai.methodNotFound(`session/load`);if(a)throw ai.invalidParams(void 0,`a session is already being opened`);if(o!==void 0)throw ai.invalidParams(void 0,`a prompt is running`);d(n),a=!0;try{let t;try{t=await c(n.sessionId)}catch(e){throw r(w9(e),`session/load`),new ai(C9,`The session could not be loaded`)}if(!t.loaded)throw ai.invalidParams(void 0,t.message);i=await f(`session/load`),_(s);let a=S9(s,i,r);try{rJe(e.getMessagesDisplay(),a,l)}catch(e){throw r(w9(e),`session/load`),new ai(C9,`The session history could not be shown`)}await a.drained()}finally{a=!1}return u=void 0,m(s,i),{}}).onRequest(`session/prompt`,async({params:s,signal:c,client:u})=>{if(s.sessionId!==i||a)throw ai.invalidParams(void 0,`unknown session`);if(o!==void 0)throw ai.invalidParams(void 0,`a prompt is already running`);let d=Qqe(s.prompt);if(d.full.trim()===``)throw ai.invalidParams(void 0,`the prompt has no text`);let f=new AbortController,m=!1;o={cancel(){m=!0,f.abort(),e.abort()}};let h={session:e,sessionId:s.sessionId,client:u,updates:S9(u,s.sessionId,r),signal:AbortSignal.any([c,f.signal]),driverId:n,surface:t.surface??`unknown`,cwd:t.cwd,nextToolCallId:l,wasCancelled:()=>m,report:r};try{return d.typed.trimStart().startsWith(`/`)?await mJe(h,d.typed,t.executeCommand??hJe):await pJe(h,d.full)}finally{o=void 0,p(u,s.sessionId)}}).onNotification(`session/cancel`,({params:e})=>{e.sessionId===i&&o?.cancel()}),cancelActive:()=>o?.cancel(),withdrawEditorFiles:()=>{g&&(g=!1,t.onEditorFileAccess?.(void 0))}}}function vJe(e){return new WritableStream({write:t=>new Promise((n,r)=>{e.write(t,e=>e?r(e):n())})})}function yJe(e){let t=null,n=!1,r=null,i=null,a=null,o=null,s=null,c=null,l=null,u=Promise.resolve(),d=()=>{u=new Promise((e,t)=>{c=e,l=t}),u.catch(()=>void 0)},f=()=>{try{s?.(),o?.(),a?.close()}finally{i?.release(),i=null,a=null,o=null,s=null}},p=e=>Object.assign(Error(`ACP transport ${e}.`),{name:`TransportLifecycleError`,code:e,transportName:`acp`});return{name:`acp`,lifecycle:Object.freeze({kind:`service`}),attach(e){if(n||r)throw p(`already-started`);t=e,d()},async start(){if(!t)throw p(`not-attached`);if(n||r)throw p(`already-started`);n=!0;try{let n=_Je(t,e);o=n.cancelActive,s=n.withdrawEditorFiles;let r=cA(e.input,e.output,{onInputClose:()=>c?.(),onOutputClose:()=>c?.(),onOutputError:e=>l?.(e)});i=r;let u=n.app.connect(Ote(vJe(e.output),kee.toWeb(r.bridge)));a=u,u.closed.then(()=>c?.())}catch(e){throw f(),n=!1,e}},stop(){return r||(r=(async()=>{try{f()}finally{t=null,n=!1,c?.()}})().finally(()=>{r=null}),r)},waitForClose(){return u}}}async function bJe(e,t,n){n.throwIfAborted();let[r=``,...i]=t.trimStart().slice(1).split(/\s+/);if(r===``)return`Type a command name after "/".`;let a=``,o=e=>{a=e.response};e.on(`complete`,o);try{let t=await e.executeCommand(r,i.join(` `),`remote`,io,`local`,{signal:n});return t===null?`Unknown command "/${r}".`:t.data?.sessionExecution===!0?a:t.message}finally{e.off(`complete`,o)}}var xJe=class extends sx{whenInitialized(){return this.current.whenInitialized()}};function SJe(e,t,n){return e.goal?.status===`active`||(e.sessionLoops??[]).some(e=>e.phase!==`stopped`&&e.phase!==`expired`&&Date.parse(e.expiresAt)>t)||(e.backgroundTasks??[]).some(e=>Ql(e,t,n)===`rearm`)}function CJe(e,t){let n=e.sessionOptions.sessionStore;if(n===void 0)return;let r=!1,i=Promise.resolve(),a=e=>({loaded:!1,message:e}),o=async i=>{if(await t.whenInitialized(),t.current.getStatusSnapshot().sessionId===i)return{loaded:!0};if(cx(t.current))return a(`The current session has work in progress; load another once it finishes.`);if(vx(n,e.cwd).some(e=>e.id===i))return a(`Session ${i} was saved in a form this version cannot read.`);let o=n.list().flatMap(e=>e.outcome.status===`valid`?[e.outcome.record]:[]).find(t=>t.id===i&&t.cwd===e.cwd);if(o===void 0)return a(`No session ${i} in this workspace.`);if(SJe(o,Date.now(),e.sessionOptions.disableSessionLoops??!1))return a(`Session ${i} has a goal, loop or schedule that would run on its own; resume it in the terminal to stop that first.`);let s=px(s9(e.sessionOptions,{createEditCheckpointStore:e.createEditCheckpointStore},i));try{await s.whenInitialized()}catch(e){throw await Q7(s,`ACP session load failed`,`ACP`),e}return r?(await Q7(s,`ACP carrier closed during a session load`,`ACP`),a(`The agent is shutting down.`)):(await t.replace(s,`ACP session loaded`),{loaded:!0})};return{load(e){if(r)return Promise.resolve(a(`The agent is shutting down.`));let t=o(e);return i=t.catch(()=>void 0),t},async close(){r=!0,await i}}}async function wJe(e){let t=new xJe(px(e.sessionOptions)),n=CJe(e,t),r=yJe({input:e.input,output:e.output,agentInfo:{name:e.productRuntime.config.identity.cliName,version:e.version},cwd:e.cwd,admitWorkspace:e.admitWorkspace,executeCommand:(e,n)=>bJe(t,e,n),...n===void 0?{}:{loadSession:n.load},...e.editorFiles===void 0?{}:{onEditorFileAccess:e.editorFiles.set},onDeliveryError:(e,t)=>{process.stderr.write(`ACP ${t}: ${e.message}\n`)}});r.attach(t);let i,a=new Promise(e=>{i=e}),o=()=>i?.();process.once(`SIGINT`,o),process.once(`SIGTERM`,o);try{await Promise.race([r.start(),r.waitForClose(),a]),await Promise.race([r.waitForClose(),a])}finally{process.off(`SIGINT`,o),process.off(`SIGTERM`,o);try{await r.stop()}finally{await n?.close(),await Q7(t.current,`ACP stdio carrier closed`,`ACP`)}}}function TJe(){let e=process.stdout.write,t=new Aee({write(t,n,r){e.call(process.stdout,t,n,r)}});return process.stdout.write=process.stderr.write.bind(process.stderr),{protocol:t,restore(){process.stdout.write=e}}}function EJe(){let e=new Map;return{list:()=>[...e.values()],put:t=>{e.set(t.namespace,{...t})},remove:t=>{e.delete(t)}}}var T9=class extends Error{reason;constructor(e){super(`MCP skill activation refused: ${e}${e===`approval-required`?`. Ask the user to run /mcp skill-inspect <server> <uri>, then approve its reviewed fingerprint.`:``}`),this.reason=e,this.name=`McpSkillActivationError`}};function E9(e,t,n){return`mcp-skill:${Buffer.from(JSON.stringify([e.serverId,e.securityIdentity,t,n])).toString(`base64url`)}`}function D9(e,t){return Vn(`sha256`).update(JSON.stringify([e,t.manifestFingerprint])).digest(`hex`)}function DJe(e){if(e.text!==void 0)return e.text;if(e.blob===void 0)throw new T9(`invalid-frontmatter`);try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.from(e.blob,`base64`))}catch{throw new T9(`invalid-frontmatter`)}}var OJe=class{resolveSource;approvals;scope;revisions=new Map;catalog=new Map;listMetadata(){return[...this.catalog.values()].flat()}key(e,t){return JSON.stringify([e,t])}advance(e,t){let n=this.key(e,t),r=(this.revisions.get(n)??0)+1;return this.revisions.set(n,r),r}advanceServer(e){for(let[t,n]of this.revisions)JSON.parse(t)[0]===e&&this.revisions.set(t,n+1)}constructor(e,t=EJe(),n=`user`){this.resolveSource=e,this.approvals=t,this.scope=n}revoke(e,t){for(let n of this.approvals.list())n.scope===this.scope&&n.serverId===e&&n.uri===t&&this.approvals.remove(n.namespace)}async source(e,t){t?.throwIfAborted();let n=await this.resolveSource(e);if(t?.throwIfAborted(),!n||n.serverId!==e)throw new T9(`unavailable`);if(!await n.isCurrent())throw new T9(`source-changed`);return n}async list(e,t,n){return(await this.refreshMetadata(e,t,n)).map(e=>e.entry)}async refreshMetadata(e,t,n){let r,i;try{if(r=await this.source(e,n),i=await r.skills.list({maxPages:t,signal:n}),!await r.isCurrent())throw new T9(`source-changed`)}catch(t){if(!n?.aborted){this.catalog.delete(e),this.advanceServer(e);for(let t of this.approvals.list())t.scope===this.scope&&t.serverId===e&&this.approvals.remove(t.namespace)}throw t}this.advanceServer(e);for(let t of i){this.advance(e,t.uri);let n=E9(r,t.uri,this.scope),i=D9(n,t);for(let r of this.approvals.list())r.scope===this.scope&&r.serverId===e&&r.uri===t.uri&&(r.namespace!==n||r.fingerprint!==i)&&this.approvals.remove(r.namespace)}for(let t of this.approvals.list())t.scope===this.scope&&t.serverId===e&&!i.some(e=>e.uri===t.uri)&&(this.advance(e,t.uri),this.approvals.remove(t.namespace));let a=i.map(t=>{let n=E9(r,t.uri,this.scope);return{serverId:e,namespace:n,fingerprint:D9(n,t),entry:t}});return this.catalog.set(e,a),a}async inspect(e,t,n){let r=this.advance(e,t);try{let i=await this.source(e,n),a=await i.skills.get(t,{signal:n});if(a.identity.serverId!==e)throw new T9(`source-changed`);let o=DJe(await i.skills.read(a,t,{signal:n})),s=tpe(t,o);if(!s?.ok)throw new T9(`invalid-frontmatter`);if(!_r(JSON.parse(JSON.stringify(s.frontmatter)),a.frontmatter))throw new T9(`frontmatter-mismatch`);if(!await i.isCurrent())throw new T9(`source-changed`);if(this.revisions.get(this.key(e,t))!==r)throw new T9(`content-changed`);let c=E9(i,t,this.scope),l=D9(c,a);for(let n of this.approvals.list())n.serverId===e&&n.scope===this.scope&&n.uri===t&&(n.namespace!==c||n.fingerprint!==l)&&this.approvals.remove(n.namespace);return{serverId:e,namespace:c,fingerprint:l,entry:a,body:s.body,content:o}}catch(n){throw this.revisions.get(this.key(e,t))===r&&this.revoke(e,t),n}}async approve(e,t,n,r){if(r!==`user`)throw new T9(`user-only`);let i=await this.inspect(e,t);if(i.fingerprint!==n)throw new T9(`content-changed`);return this.approvals.put({scope:this.scope,namespace:i.namespace,serverId:e,uri:t,fingerprint:n}),i}withdraw(e,t,n){if(n!==`user`)throw new T9(`user-only`);this.advance(e,t),this.revoke(e,t)}requireApproval(e){if(!this.approvals.list().some(t=>t.namespace===e.namespace&&t.scope===this.scope&&t.serverId===e.serverId&&t.uri===e.entry.uri&&t.fingerprint===e.fingerprint))throw new T9(`approval-required`)}async activate(e,t,n){let r=await this.inspect(e,t,n);this.requireApproval(r);let i=!1,a=new AbortController,o=n?AbortSignal.any([n,a.signal]):a.signal,s=e=>{if(i)throw new T9(`activation-ended`);e.throwIfAborted(),this.requireApproval(r)},c=async n=>{s(n);let i=await this.source(e,n);if(E9(i,t,this.scope)!==r.namespace)throw new T9(`source-changed`);let a=await i.skills.get(t,{signal:n});if(a.identity.serverId!==e)throw new T9(`source-changed`);if(a.identity.catalogGeneration!==r.entry.identity.catalogGeneration)throw new T9(`activation-ended`);if(D9(r.namespace,a)!==r.fingerprint)throw new T9(`content-changed`);return s(n),{source:i,current:a}},l=(n,r)=>{let o=r.aborted;throw i=!0,a.abort(),!o&&!(n instanceof T9&&n.reason===`activation-ended`)&&this.revoke(e,t),n};return{...r,close:()=>{i=!0,a.abort()},validate:async()=>{try{let{source:e}=await c(o);if(!await e.isCurrent())throw new T9(`source-changed`);s(o)}catch(e){l(e,o)}},read:async(e,t)=>{let n=t?AbortSignal.any([t,o]):o;if(i)throw new T9(`activation-ended`);try{let{source:t,current:a}=await c(n),o=await t.skills.read(a,e,{signal:n});if(i)throw new T9(`activation-ended`);if(this.requireApproval(r),!await t.isCurrent())throw new T9(`source-changed`);return s(n),o}catch(e){return l(e,n)}}}}};function kJe(e){return`mcp-skill-${Vn(`sha256`).update(e).digest(`hex`)}`}function O9(e,t){let{serverId:n,entry:r,namespace:i,fingerprint:a}=e,o=kJe(i),s=Il({source:i,content:`---\n${JSON.stringify(r.frontmatter)}\n---\n`,profile:`skill`});return s.ok?{command:{...ag(s.metadata,``,o,void 0),name:o,source:`host-skill`,description:`${r.frontmatter.name} (${n}): ${r.frontmatter.description}`,skillContentLoader:{acquire:async e=>{let o;try{let s=await t.activate(n,r.uri,e);if(o=s,s.namespace!==i||s.fingerprint!==a)throw new T9(`content-changed`);return{content:s.content,...s.entry.resources===`dynamic`?{}:{resources:{manifest:s.entry.resources,read:(e,t)=>s.read(e,t)}},validate:()=>s.validate(),close:()=>s.close()}}catch(e){throw o?.close(),e instanceof T9&&e.reason===`approval-required`?Error(`Skill content consent is required. Ask the local user to run /mcp skill-inspect ${JSON.stringify([n,r.uri])} and approve the reviewed fingerprint.`):e}}}},invocationName:o}:{unavailableReason:s.diagnostics.map(e=>`${e.code}: ${e.field??`frontmatter`}`).join(`; `)}}function AJe(e){return{name:`mcp-skills`,getCommands:()=>e.listMetadata().flatMap(t=>{let n=O9(t,e);return n.command?[n.command]:[]}),describe:t=>{let{invocationName:n,unavailableReason:r}=O9(t,e);return{...n?{invocationName:n}:{},...r?{unavailableReason:r}:{}}}}}const k9={startupMs:1e4,perCallMs:3e4,globalDefaultMs:6e4,idleMs:3e5,toolCallMs:3e4};function jJe(e){return{...k9,toolCallMs:e}}function MJe(e,t,n){return{source:e.source,origin:e.origin,reason:e.reason,blockedServerNames:e.source===t?n:[]}}function A9(e,t){let n=t===void 0||!e.allowed?void 0:t.discovered.has(e.serverId)?`connected`:t.connectionFailures.has(e.serverId)?`failed`:void 0,r=t===void 0?void 0:[...t.connectedToolProvenance.entries()].filter(([,t])=>t.serverId===e.serverId).map(([e])=>e);return{serverId:e.serverId,...e.displayName===void 0?{}:{displayName:e.displayName},source:e.source,status:e.status,allowed:e.allowed,reason:e.reason,provenanceId:e.provenanceId,definitionFingerprint:e.definitionFingerprint,securityIdentity:e.securityIdentity,...n===void 0?{}:{connection:n},...n===`failed`?{connectionFailureReason:t?.connectionFailures.get(e.serverId)??`unknown`}:{},...r===void 0?{}:{toolNames:r}}}function j9(e){return e instanceof Error?e.message:String(e)}function NJe(e){if(e===`pending`||e===`stale`)return`approve`;if(e===`untrusted`)return`trust-workspace`}function PJe(e){let t,n=!1,r=()=>(t??=e(),n&&t.close(),t);return{authenticator:{authorize:e=>r().authorize(e),onRejected:e=>r().onRejected(e)},renew:()=>{t?.close(),t=void 0},close:()=>{n=!0,t?.close()}}}function M9(e,t,n,r,i,a,o){return{serverId:e.serverId,awaitOpenCleanupOnTimeout:n.kind===`stdio`,openSession:async s=>{o?.();let c=await lWe({serverId:e.serverId,...t.protocolVersion===void 0?{}:{protocolVersion:t.protocolVersion},...t.skills===!0?{skills:!0}:{},...a.elicitation===!0?{elicitation:!0}:{},...a.apps===!0?{apps:!0}:{},transport:n.construct(r),timeouts:{startupMs:i.startupMs,perCallMs:i.perCallMs},...a.clientInfo===void 0?{}:{clientInfo:a.clientInfo},signal:s});for(let t of c.compatibilityDiagnostics??[])a.reportDiagnostic(`MCP server "${e.serverId}" capability "${t.capability}" unavailable: ${t.reason}`);return c},timeouts:i,...a.backoff===void 0?{}:{backoff:a.backoff},...a.clock===void 0?{}:{clock:a.clock},...a.discovery===void 0?{}:{discovery:a.discovery}}}async function N9(e,t,n,r){let{admission:i,createSupervisor:a,timeouts:o,deps:s,signal:c}=r;if(s.isDefinitionCurrent){let e=!1;try{e=await s.isDefinitionCurrent(t)}catch{}if(!e)return s.reportDiagnostic(`MCP connection refused: admission or installed source changed; restart with the current source.`),`not-admitted`}let l=i.admit(e);if(!l.allowed){s.reportDiagnostic(`MCP server "${e.serverId}" was not admitted (${l.status}): ${l.reason}`);let t=NJe(l.status);return t!==void 0&&r.unavailable.set(e.serverId,t),`not-admitted`}let u,d=t.transport===`stdio`?`stdio`:`streamable-http`;if(t.transport===`stdio`){let n=s.stdioAuthorities!==void 0&&Object.hasOwn(s.stdioAuthorities,e.serverId)?s.stdioAuthorities[e.serverId]:void 0;if(n===void 0){s.reportDiagnostic(`MCP server "${e.serverId}" stdio was refused: missing host authority.`),r.connectionFailures.set(e.serverId,`missing host authority`);return}let a=oUe({admission:i,authority:n}),c=await a.admit({definition:t,activation:e});if(!c.ok){s.reportDiagnostic(`MCP server "${e.serverId}" stdio was refused (${c.reason}).`),r.connectionFailures.set(e.serverId,c.reason);return}u=M9(e,t,a,c.admitted,o,s)}else{let n=_He(s.transport),i=t.headersHelper,a,c;if(t.oauth!==void 0){let n=s.oauth;if(n===void 0){s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (oauth-unavailable).`),r.connectionFailures.set(e.serverId,`OAuth is not available`);return}let i=r.oauthAuthenticators.get(e.serverId);if(i===void 0){try{i=n.authenticatorFor(e,t)}catch{s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (oauth-unavailable).`),r.connectionFailures.set(e.serverId,`OAuth is not available`);return}r.oauthAuthenticators.set(e.serverId,i)}a=i}else if(i===void 0)a=s.authenticatorFor?.(e);else{let n=s.headersHelpers,o=bHe(i,e.source,e.workspace,n?.allowed??[]);if(n===void 0||o!==void 0){s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (${o??`headers-helper-not-allowed`}).`),r.connectionFailures.set(e.serverId,o??`headers-helper-not-allowed`);return}let l=PJe(()=>DHe(r=>n.run({request:e,definition:t,helper:i},r)));r.helperSlots.get(e.serverId)?.close(),r.helperSlots.set(e.serverId,l),c=l,a=l.authenticator}let l=await n.admit({url:t.url??``,...i===void 0&&t.oauth===void 0?{}:{authenticationRequired:!0},...t.headers===void 0?{}:{headers:t.headers},...t.unsupportedAuthentication===void 0?{}:{unsupportedAuthentication:t.unsupportedAuthentication},...a===void 0?{}:{authentication:{serverId:e.serverId,securityIdentity:e.securityIdentity,authenticator:a}}});if(!l.ok){s.reportDiagnostic(`MCP server "${e.serverId}" endpoint was refused (${l.reason}): ${l.message}`),r.connectionFailures.set(e.serverId,`${l.reason}: ${l.message}`);return}u=M9(e,t,n,l.admitted,o,s,c===void 0?void 0:()=>c.renew())}let f=a(u);try{let t=await f.discover(c);return r.connectionFailures.delete(e.serverId),{catalogInput:{serverId:e.serverId,origin:n,transport:d,discovery:t},connection:f}}catch(i){let a=d===`stdio`?`stdio connection failed`:j9(i);return s.reportDiagnostic(`MCP server "${e.serverId}" discovery failed: ${a}`),r.connectionFailures.set(e.serverId,a),t.oauth!==void 0&&O5(i)===`auth`&&r.unavailable.set(e.serverId,`sign-in`),{catalogInput:{serverId:e.serverId,origin:n,transport:d},connection:f}}}function FJe(e,t,n,r){let i=f6[0];return{list:()=>e.list().map(e=>A9(e,r)),sourceProblems:()=>{let e=n.filter(h6).map(e=>e.name);return t.map(t=>MJe(t,i,e))},approve:t=>A9(e.approve(t)),reject:t=>A9(e.reject(t)),revoke:t=>A9(e.revoke(t))}}function IJe(e,t,n,r,i,a){if(n===void 0)return{};let o=new Set,s=()=>e.list().flatMap(e=>{let n=t.find(t=>t.name===e.serverId)?.definition;return n?.transport===`http`&&n.oauth!==void 0?[{request:e,definition:n}]:[]}),{state:c,signOut:l,signIn:u}=n;return{...u===void 0?{}:{oauthLogin:async e=>{let{serverId:t}=e,r=s().find(e=>e.request.serverId===t),a=r?.definition.oauth?.clientId!==void 0,c=e=>({serverId:t,failure:e,preRegisteredClient:a,tools:[]});if(r===void 0||u===void 0)return c(`not-oauth`);if(r.definition.unsetVariables.some(e=>e.field===`url`))return c(`url-unset`);if(e.noBrowser&&e.readRedirect===void 0)return c(`prompt-unavailable`);if(o.has(t))return c(`sign-in-in-progress`);o.add(t);try{await u.call(n,r.request,r.definition,{noBrowser:e.noBrowser,...e.readRedirect===void 0?{}:{readRedirect:e.readRedirect},...e.confirmBrowser===void 0?{}:{confirmBrowser:e.confirmBrowser},...e.signal===void 0?{}:{signal:e.signal}})}catch(e){return c(e instanceof $?e.reason:`unexpected-error`)}finally{o.delete(t)}return{serverId:t,preRegisteredClient:a,...await i(t)}},oauthToolsAdded:a},...c===void 0?{}:{oauthStatus:()=>Promise.all(s().map(async({request:e,definition:t})=>({serverId:e.serverId,state:await c.call(n,e,t)})))},...l===void 0?{}:{oauthLogout:async e=>{let t=s().find(({request:t})=>t.serverId===e);if(t===void 0)throw Error(`MCP server ${e} does not declare OAuth.`);let i=await l.call(n,t.request,t.definition);return r.get(e)?.forget?.(),{serverId:e,...i}}}}}function LJe(e,t,n,r){return n===void 0?{}:Object.fromEntries(Object.entries(pUe(e,t)).filter(([e,i])=>{let a=r.get(i);return a?.serverId===t&&a.sourceName===e&&a.securityIdentity===n}))}function P9(e,t,n,r,i,a,o,s,c){let l=[];for(let u of[...e.adopted,...e.adapted]){if(u.kind!==`tool`)continue;let d=t.get(u.provenance.serverId);if(d===void 0)continue;let f=o.get(u.provenance.serverId),p=n.get(u.provenance.serverId),m=JWe(u,d,{admission:a,get appCallableTools(){return LJe(e,u.provenance.serverId,p,i)},isDispatchAdmitted:()=>s(u.provenance.serverId,d),...f===void 0?{}:{authFailureNotice:f},...u.ui?.resourceUri===void 0?{}:{reportAppViewProblem:e=>c(`MCP server "${u.provenance.serverId}" tool "${u.canonicalName}" app view omitted: ${e}`)}});l.push(m),p!==void 0&&r.set(m.getName(),{serverId:u.provenance.serverId,sourceName:u.sourceName,securityIdentity:p})}return l}function RJe(e){let t=new C6(e.resolvedEntries,{...e.workspace===void 0?{}:{workspace:e.workspace}}),n=new tHe(e.approvalStore,e.now),r=new nHe(t,n,t.displayNames()),i=new Map,a=[],o=new Map,s=new Map;async function c(t,n){let i=e.resolvedEntries.find(e=>e.name===t)?.definition;if(!i)return!1;try{if(e.isDefinitionCurrent&&!await e.isDefinitionCurrent(i))return!1}catch{return!1}return s.get(t)===n&&r.list().some(e=>e.serverId===t&&e.allowed)}let l=new OJe(async n=>{let r=s.get(n),i=e.resolvedEntries.find(e=>e.name===n)?.definition,a=t.list().find(e=>e.serverId===n);if(!r?.getSkillsSession||!a||i?.skills!==!0||!await c(n,r))return;let o=await r.getSkillsSession();if(!(!o||!await c(n,r)))return{serverId:n,securityIdentity:JSON.stringify([a.securityIdentity,a.definitionFingerprint,a.source,a.provenance,a.workspace?.repositoryKey??null,a.workspace?.generation??null]),skills:o,isCurrent:()=>c(n,r)}},e.skillApprovalStore,e.workspace?.repositoryKey??`user`),u=e.timeouts??k9,d=e.createSupervisor??(e=>new VWe(e)),f=new Map,p=new Map,m=new Set,h=new Map,g=AJe(l),_={skills:{commandSource:g,list:async e=>(await l.refreshMetadata(e,32)).map(t=>({serverId:e,uri:t.entry.uri,name:t.entry.frontmatter.name,description:t.entry.frontmatter.description,...g.describe(t)})),inspect:async(e,t)=>v(await l.inspect(e,t)),approve:async(e,t,n,r)=>v(await l.approve(e,t,n,r)),withdraw:(e,t,n)=>l.withdraw(e,t,n)},...FJe(r,e.sourceProblems??[],e.resolvedEntries,{discovered:m,connectedToolProvenance:f,connectionFailures:h}),...IJe(t,e.resolvedEntries,e.oauth,i,ne,re),reload:se,reloadToolsAdded:le,...e.userActionSurface===void 0?{}:{userActionSurface:e.userActionSurface}};function v(e){return{serverId:e.serverId,uri:e.entry.uri,namespace:e.namespace,fingerprint:e.fingerprint,name:e.entry.frontmatter.name,description:e.entry.frontmatter.description,frontmatter:e.entry.frontmatter,content:e.content}}let y=new Map,b,x=0,S,C,w={...e.resultAdmissionLimits,...e.createResultSpillStore?{spillStore:{write:t=>(C??=e.createResultSpillStore(),C.write(t))}}:{},onWarning:({resultChars:t,warningChars:n})=>e.reportDiagnostic(`MCP tool result warning: ${t} characters exceeds ${n}`)},T=!1,E=t=>t.length===0||!e.createResultSpillStore||T?t:(T=!0,[...t,ue()]),ee=t=>({admission:n,createSupervisor:d,timeouts:u,deps:e,signal:t,helperSlots:o,oauthAuthenticators:i,unavailable:p,connectionFailures:h}),te=t=>JU(t,`sign-in`,e.userActionSurface??`session`,e.cliName);async function ne(r){i.get(r)?.forget?.();let o=t.list().find(e=>e.serverId===r),l=e.resolvedEntries.find(e=>e.name===r);if(o===void 0||l?.definition===void 0)return{connection:`not-connected`,tools:[]};let u=n.admit(o);if(!u.allowed)return e.reportDiagnostic(`MCP server "${r}" was not admitted (${u.status}): ${u.reason}`),{connection:`not-admitted`,tools:[]};let d=s.get(r);if(d!==void 0&&m.has(r)){if(d.retry===void 0)return{connection:`not-connected`,tools:[]};try{return await d.retry(),{connection:`recovered`,tools:[]}}catch(t){return e.reportDiagnostic(`MCP server "${r}" did not reconnect after sign-in: ${j9(t)}`),{connection:`not-connected`,tools:[]}}}let p=await N9(o,l.definition,l.origin,ee(void 0));if(p===`not-admitted`)return{connection:`not-admitted`,tools:[]};if(p?.connection===void 0||(a.push(p.connection),s.set(r,p.connection),d!==void 0&&(a.splice(a.indexOf(d),1),await d.shutdown().catch(()=>void 0)),p.catalogInput.discovery===void 0))return{connection:`not-connected`,tools:[]};m.add(r);let h=ie([p.catalogInput]),g=new Map,_=P9(h,new Map([[r,p.connection]]),new Map([[r,o.securityIdentity]]),g,f,w,l.definition.oauth===void 0?new Map:new Map([[r,te(r)]]),c,e.reportDiagnostic);return y.set(r,g),{connection:`connected`,tools:E(_)}}function re(t,n){let r=y.get(t);if(y.delete(t),r===void 0)return;let i=new Set(n);for(let[n,a]of r)i.has(n)?f.set(n,a):e.reportDiagnostic(`MCP tool "${n}" from "${t}" was not added: the session already has a tool by that name.`)}function ie(t){let n=jWe(t,{report:(t,n)=>e.reportDiagnostic(`MCP tool "${t}" has an unenforceable schema subtree: ${n.join(`, `)}`),reportResultSizeProblem:t=>e.reportDiagnostic(`MCP result-size metadata ignored (${t})`),reportUiMetadataProblem:(t,n)=>e.reportDiagnostic(`MCP tool "${t}" UI metadata ignored (${n})`)});for(let t of n.rejected)e.reportDiagnostic(`MCP ${t.kind} "${t.name}" on "${t.serverId}" was rejected: ${t.reason}`);return n}function ae(t,n){if(n.transport===`http`||n.transport===`stdio`)return!0;let r=`unsupported transport: ${n.transport}; use Streamable HTTP (type: "http")`;return h.set(t.serverId,r),e.reportDiagnostic(`MCP server "${t.serverId}" was refused: ${r}.`),!1}async function oe(n){s.clear(),p.clear(),m.clear(),h.clear();let r=[],i=new Map,o=new Map,l=new Map,u=ee(n);for(let n of t.list()){let t=e.resolvedEntries.find(e=>e.name===n.serverId);if(t===void 0||t.definition===void 0)continue;let c=t.definition;if(!ae(n,c))continue;let d=await N9(n,c,t.origin,u);d!==void 0&&d!==`not-admitted`&&(r.push(d.catalogInput),d.connection!==void 0&&(a.push(d.connection),i.set(n.serverId,d.connection),s.set(n.serverId,d.connection),d.catalogInput.discovery!==void 0&&m.add(n.serverId),o.set(n.serverId,n.securityIdentity),c.oauth!==void 0&&l.set(n.serverId,te(n.serverId))))}let d=ie(r);f.clear(),T=!1;let g=P9(d,i,o,f,f,w,l,c,e.reportDiagnostic);return E(g)}function se(){if(S!==void 0)return S;let e=ce();return S=e,e.then(e=>{e.reloadToken===void 0&&(S=void 0)},()=>{S=void 0}),e}async function ce(){let n=ee(void 0),r=[],i=[],o=[],l=new Map,u=new Map,d=new Map;for(let c of t.list()){if(m.has(c.serverId))continue;let t=e.resolvedEntries.find(e=>e.name===c.serverId);if(t===void 0||t.definition===void 0)continue;let f=t.definition;if(!ae(c,f)){i.push(c.serverId);continue}let p=s.get(c.serverId);if(p!==void 0){let e=a.indexOf(p);e!==-1&&a.splice(e,1),await p.shutdown().catch(()=>void 0),s.delete(c.serverId)}let h=await N9(c,f,t.origin,n);if(h!==void 0&&h!==`not-admitted`){if(h.connection===void 0){i.push(c.serverId);continue}if(a.push(h.connection),s.set(c.serverId,h.connection),h.catalogInput.discovery===void 0){i.push(c.serverId);continue}o.push(h.catalogInput),l.set(c.serverId,h.connection),u.set(c.serverId,c.securityIdentity),f.oauth!==void 0&&d.set(c.serverId,te(c.serverId)),m.add(c.serverId),r.push(c.serverId)}}if(o.length===0)return{tools:[],connectedServerIds:r,failedServerIds:i};let p=ie(o),h=new Map,g=P9(p,l,u,h,f,w,d,c,e.reportDiagnostic),_=`reload-${++x}`;return b={token:_,provenance:h},{tools:E(g),connectedServerIds:r,failedServerIds:i,reloadToken:_}}function le(t,n){if(b===void 0||b.token!==t)return;let{provenance:r}=b;b=void 0,S=void 0;let i=new Set(n);for(let[t,n]of r)i.has(t)?f.set(t,n):e.reportDiagnostic(`MCP tool "${t}" from "${n.serverId}" was not added: the session already has a tool by that name.`)}function ue(){return new wt({name:e.resultReadToolName??`agent_read_mcp_result`,description:`Read up to 4,000 characters of a saved MCP tool result using its opaque tool-result reference and a zero-based character offset.`,parameters:{type:`object`,properties:{reference:{type:`string`,description:`The exact tool-result reference`},offset:{type:`number`,description:`Zero-based character offset, default 0`}},required:[`reference`]}},async t=>{let n=t.reference,r=t.offset??0;if(typeof n!=`string`||typeof r!=`number`||!Number.isSafeInteger(r)||r<0)throw Error(`Tool result read arguments invalid`);if(!C)throw Error(`Tool result reference unavailable`);let i;try{i=await C.read(n)}catch{throw Error(`Tool result reference unavailable`)}let a=Math.min(r,i.length),o=e.resultAdmissionLimits?.hardChars??25e3,s=-1,c=Math.min(4e3,i.length-a)+1;for(;c-s>1;){let e=Math.floor((s+c)/2),t={content:i.slice(a,a+e),totalChars:i.length,nextOffset:a+e};JSON.stringify(t).length<=o?s=e:c=e}if(s<0||s===0&&a<i.length)throw Error(`Tool result read limit too small`);return{content:i.slice(a,a+s),totalChars:i.length,nextOffset:a+s}})}async function de(){s.clear();try{await Promise.all([...a.map(e=>e.shutdown()),...C?[C.shutdown()]:[]])}finally{for(let e of o.values())e.close();o.clear();for(let e of i.values())e.close();i.clear()}}return{activationAdapter:_,skillRegistry:l,connect:oe,shutdown:de,connectedToolProvenance:f,unavailableServers:p}}function zJe(e){let t=S6(e),n=e.definition;if(!t||!n||e.status!==`resolved`)return;let r=n.transport===`stdio`||n.transport===`http`,i=[`mcp-client`,...n.transport===`stdio`?[`stdio-authority`]:n.transport===`http`?[`http-transport`]:[]];return{schemaVersion:1,identity:e.name,installedRevision:t.definitionFingerprint,generation:JSON.stringify([t.securityIdentity,t.definitionFingerprint]),source:{kind:`mcp`,location:e.origin},requiredCapabilities:i,contributions:[{identity:`${e.name}:mcp:${e.name}`,kind:`mcp`,source:e.origin,requiredCapabilities:i,disposition:r?`supported`:`unsupported`,...r?{}:{reason:`Unsupported MCP transport`}}],lifecycle:{activation:`unadmitted`,activeCalls:`host-owned`},diagnostics:r?[]:[{component:`mcp`,code:`unsupported-transport`}]}}function F9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function I9(e,t){return typeof e==`string`?e.replaceAll("${CLAUDE_PLUGIN_ROOT}",t):Array.isArray(e)?e.map(e=>I9(e,t)):F9(e)?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,I9(n,t)])):e}function L9(e,t,n){let r=[],i=new Set;for(let a of ly(sC(t,e,n),{settingsPath:rC(e)})){for(let e of a.skipped){if(e.reason===`disabled`)continue;let t=e.manifestPath;r.push({source:`plugin`,origin:t,definitions:[],problems:[{name:``,source:`plugin`,origin:t,reason:`bundle ${e.reason}${e.detail?`: ${e.detail}`:``}`}]})}for(let e of a.loaded){if(i.has(e.manifest.name)||(i.add(e.manifest.name),e.mcpConfig===void 0))continue;let t=e.mcpConfig;if(!F9(t)||!F9(t.mcpServers)){let n=e.pluginDir;r.push({...G3(t,`plugin`,n),source:`plugin`,origin:n});continue}for(let[n,i]of Object.entries(t.mcpServers)){let t=`${e.manifest.name}:${n}`,a=e.mcpSourcePaths&&Object.hasOwn(e.mcpSourcePaths,n)?e.mcpSourcePaths[n]:e.pluginDir,o=F9(i)&&i.type===void 0?{...i,type:typeof i.command==`string`?`stdio`:typeof i.url==`string`?`http`:void 0}:i;r.push({...G3({mcpServers:{[t]:I9(o,e.pluginDir)}},`plugin`,a),source:`plugin`,origin:a})}}}return r}const R9=`mcpHeaderHelpers`;function z9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function BJe(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function VJe(e){if(!z9(e)||Object.keys(e).some(e=>e!==`command`&&e!==`args`))return;let t=e.command,n=e.args??[];if(!(typeof t!=`string`||!Pn(t)||!BJe(n)))return{command:t,args:[...n]}}function HJe(e){let t=[],n=[];for(let r of e){let e=Yp(r,`resolve MCP header helper allowlist`);if(e===void 0||e.trim()===``)continue;let i;try{i=JSON.parse(e)}catch{continue}if(!z9(i)||i.mcpHeaderHelpers===void 0)continue;if(r.kind!==`host`||r.scope!==`user`){n.push(`"${R9}" in ${r.displayName} was ignored: only user settings may allow a header helper.`);continue}let a=i[R9],o=Array.isArray(a)?a.map(VJe):void 0;if(o===void 0||o.some(e=>e===void 0)){n.push(`"${R9}" in ${r.displayName} was refused: it must be an array of {"command": "/absolute/path", "args": [...]} objects.`);continue}t.push(...o)}return{allowed:t,diagnostics:n}}function UJe(e,t,n,r){let i=X6(t),a={};for(let[t,n]of Object.entries(e))n===void 0||kHe(t)||i&&K3(t)||(a[t]=n);return a.PRODUCT_MCP_SERVER_NAME=n,a.PRODUCT_MCP_SERVER_URL=r,a}const B9=process.platform===`win32`;function V9(e,t=!1){if(typeof e.pid==`number`){if(B9){let n=[`/pid`,String(e.pid),`/T`,`/F`],r={stdio:`ignore`,windowsHide:!0};if(t){sn(`taskkill`,n,r);return}let i=on(`taskkill`,n,r);i.on(`error`,()=>void 0),i.unref();return}try{process.kill(-e.pid,`SIGKILL`)}catch{try{e.kill(`SIGKILL`)}catch{}}}}const H9=new Set;let U9=!1;function WJe(e){H9.add(e),!U9&&(U9=!0,process.once(`exit`,()=>{for(let e of H9)V9(e,!0);H9.clear()}))}function GJe(e){let t=e.timeoutMs??1e4,n=e.maxStdoutBytes??65536;return new Promise((r,i)=>{if(e.signal.aborted){i(new Y6(`cancelled`));return}let a;try{a=on(e.helper.command,[...e.helper.args],{cwd:e.cwd,env:e.env,shell:!1,stdio:[`ignore`,`pipe`,`ignore`],detached:!B9,windowsHide:!0})}catch{i(new Y6(`spawn-failed`));return}WJe(a);let o=[],s=0,c=!1,l=()=>{c=!0,H9.delete(a),clearTimeout(f),e.signal.removeEventListener(`abort`,d)},u=(e,t=!0)=>{c||(l(),t&&V9(a),a.stdout?.destroy(),i(new Y6(e)))},d=()=>u(`cancelled`),f=setTimeout(()=>u(`timeout`),t);e.signal.addEventListener(`abort`,d,{once:!0}),a.stdout?.on(`data`,e=>{if(s+=e.byteLength,s>n){u(`output-too-large`);return}o.push(e)}),a.stdout?.on(`error`,()=>u(`spawn-failed`)),a.on(`error`,()=>u(`spawn-failed`)),a.on(`close`,e=>{if(H9.delete(a),!c){if(e!==0){u(`exit-status`,!1);return}l();try{r(new TextDecoder(`utf-8`,{fatal:!0}).decode(Buffer.concat(o)))}catch{i(new Y6(`output-malformed`))}}})})}const KJe=[`autoBackgroundMs`,`callTimeoutMs`],qJe=[...f6].reverse();function W9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JJe(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0}function YJe(e){let t=Yp(e,`resolve MCP background-handoff settings`);if(t===void 0||t.trim()===``)return;let n=I5(e),r=e.displayName,i;try{i=JSON.parse(t)}catch(e){return{key:`*`,source:n,origin:r,reason:F5(e)}}if(!W9(i)||i.mcp===void 0)return;let a=i.mcp;return W9(a)?{source:n,origin:r,mcp:a}:{key:`*`,source:n,origin:r,reason:`"mcp" must be an object, got ${typeof a}`}}function XJe(e){let t=[],n=[];for(let r of e){let e=YJe(r);e!==void 0&&(`mcp`in e?n.push(e):t.push(e))}let r=e=>qJe.indexOf(e),i=[...n].sort((e,t)=>r(e.source)-r(t.source)),a=12e4,o=6e5;for(let e of i){let n={},r=!1;for(let i of KJe){let a=e.mcp[i];if(a!==void 0){if(!JJe(a)){r=!0,t.push({key:i,source:e.source,origin:e.origin,reason:`"${i}" must be a non-negative integer, got ${JSON.stringify(a)}`});continue}n[i]=a}}r||(n.autoBackgroundMs!==void 0&&(a=n.autoBackgroundMs),n.callTimeoutMs!==void 0&&(o=n.callTimeoutMs))}let s=[],c=a>0;return c&&a>=o&&(c=!1,s.push(`MCP tool-call handoff disabled: "mcp.autoBackgroundMs" (${a}) must be less than "mcp.callTimeoutMs" (${o}).`)),{autoBackgroundMs:a,callTimeoutMs:o,handoffEnabled:c,problems:t,diagnostics:s}}function G9(e){if(typeof e!=`object`||!e)return!1;let t=e;return[`scope`,`namespace`,`serverId`,`uri`].every(e=>typeof t[e]==`string`)&&typeof t.fingerprint==`string`&&/^[a-f0-9]{64}$/.test(t.fingerprint)}function ZJe(e){function t(t=!1){try{Qt(e);let t=JSON.parse(A(e,`utf8`));if(!t||t.version!==1||!Array.isArray(t.records)||!t.records.every(G9)||new Set(t.records.map(e=>e.namespace)).size!==t.records.length)throw Error(`Unrecognised store`);return t.records}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code===`ENOENT`)return[];if(t)throw Error(`Refusing to write unreadable or unrecognised MCP skill approval store.`);return[]}}function n(n){vn(Mn(e),{recursive:!0,mode:448});let r=`${e}.lock`,i;try{i=bn(r,`wx`,384)}catch{throw Error(`Refusing to write MCP skill approval store: another writer holds its lock.`)}try{Jt(e,`${JSON.stringify({version:1,records:n(t(!0))},null,2)}\n`)}finally{un(i),On(r)}}return{list:()=>t(),put:e=>{if(!G9(e))throw Error(`Invalid MCP skill approval.`);n(t=>[...t.filter(t=>t.namespace!==e.namespace),e])},remove:e=>n(t=>t.filter(t=>t.namespace!==e))}}function QJe(e){return ZJe(M(e.layout.userRoot,`mcp-skill-approvals.json`))}function K9(e){switch(e){case`trusted`:return`trusted`;case`untrusted`:return`untrusted`;case`revoked`:return`revoked`;case`stale/replaced`:return`stale/replaced`;case`identity-unavailable`:return`identity-unavailable`;case`store-unavailable`:return`store-unavailable`}}function $Je(e,t){return e.status===`trusted`?{repositoryKey:e.identity.repositoryKey,trustState:K9(t.state),generation:t.generation}:e.identity===void 0?{repositoryKey:`identity-unavailable`,trustState:K9(e.trustState),generation:t.generation}:{repositoryKey:e.identity.repositoryKey,trustState:K9(t.state),generation:t.generation}}async function q9(e,t){return sf(pq(t).workspaceTrust).inspect(e)}function eYe(e,...t){return UJe(Pq(e),...t)}async function tYe(e){let{entries:t,problems:n,sourceProblems:r}=L5(e.settingsSources,e.env,L9(e.productRuntime,e.cwd,e.projectAccess));for(let t of n)e.reportDiagnostic(t.name===``?`MCP source ${t.source} (${t.origin}) could not be read: ${t.reason}`:`MCP definition "${t.name}" from ${t.source} (${t.origin}) was refused: ${t.reason}`);for(let n of t)h6(n)&&e.reportDiagnostic(`MCP server "${n.name}" was not activated: the managed source could not be read, so a lower-trust definition cannot be trusted to be the real winner.`);let i=XJe(e.settingsSources);for(let t of i.problems)e.reportDiagnostic(`MCP setting "${t.key}" from ${t.source} (${t.origin}) was refused: ${t.reason}`);for(let t of i.diagnostics)e.reportDiagnostic(t);e.mode===`print`&&i.autoBackgroundMs>0&&e.reportDiagnostic(`MCP tool-call handoff ("mcp.autoBackgroundMs") is ignored in print mode; a long MCP tool call runs to completion in the foreground, bounded only by "mcp.callTimeoutMs".`);let a=e.projectAccess.identity,o=a===void 0?{state:`identity-unavailable`,generation:0}:await(e.inspectTrust??(()=>q9(a,e.productRuntime)))(e.cwd),s=$Je(e.projectAccess,o),c=new C6(t,{workspace:s}).list();async function l(t){if(T6(t.source)){if(!a)return!1;let t=await(e.inspectTrust??(()=>q9(a,e.productRuntime)))(e.cwd);if(t.state!==`trusted`||t.generation!==o.generation)return!1}let n=L5(e.settingsSources,e.env,L9(e.productRuntime,e.cwd,e.projectAccess)).entries,r=new C6(n,{workspace:s}).list().find(e=>e.serverId===t.name),i=c.find(e=>e.serverId===t.name);return!!r&&!!i&&r.securityIdentity===i.securityIdentity&&r.definitionFingerprint===i.definitionFingerprint}let u=HJe(e.settingsSources);for(let t of u.diagnostics)e.reportDiagnostic(t);let d={allowed:u.allowed,run:async({request:t,definition:n,helper:r},i)=>{let o=X6(t.source),s=n.url??``,c;if(o){if(a===void 0)throw new Y6(`spawn-failed`);c=a.worktreeRoot}else c=mq(e.productRuntime),vn(c,{recursive:!0});return GJe({helper:r,cwd:c,env:eYe(e.env,t.source,t.serverId,o?VVe(n,`url`,s):s),signal:i})}},f=RJe({skillApprovalStore:QJe(e.productRuntime),resolvedEntries:t,isDefinitionCurrent:l,resultReadToolName:`${e.productRuntime.config.identity.modelCommandToolPrefix}read_mcp_result`,sourceProblems:r,workspace:s,clientInfo:{name:e.productRuntime.config.identity.mcpClientName,version:`0.0.0`},...e.stdioAuthorities===void 0?{}:{stdioAuthorities:e.stdioAuthorities},...e.approvalStore===void 0?{}:{approvalStore:e.approvalStore},...e.httpTransportDeps===void 0?{}:{transport:e.httpTransportDeps},headersHelpers:d,oauth:tGe({productRuntime:e.productRuntime,network:{...e.httpTransportDeps?.policy===void 0?{}:{policy:e.httpTransportDeps.policy},...e.httpTransportDeps?.lookup===void 0?{}:{lookup:e.httpTransportDeps.lookup},...e.httpTransportDeps?.fetch===void 0?{}:{fetch:e.httpTransportDeps.fetch}},reportDiagnostic:e.reportDiagnostic}),timeouts:jJe(i.callTimeoutMs),createResultSpillStore:()=>Vfe({onCleanupFailure:t=>e.reportDiagnostic(`MCP tool-result retention cleanup failed (${t})`)}),...e.resultAdmissionLimits?{resultAdmissionLimits:e.resultAdmissionLimits}:{},reportDiagnostic:e.reportDiagnostic,userActionSurface:rYe(e.mode),elicitation:iYe(e.mode,e.askSurface),apps:aYe(e.mode,e.appSurface),cliName:e.productRuntime.vocabulary.cliName});function p(t){if(e.mode!==`interactive`&&e.mode!==`serve`||!i.handoffEnabled)return;let n=t??`default`,r=[],a={};for(let[e,t]of f.connectedToolProvenance)r.push(e),a[e]={serverId:t.serverId,sourceName:t.sourceName,securityIdentity:t.securityIdentity,permissionMode:n};return{thresholdMs:i.autoBackgroundMs,budgetMs:i.callTimeoutMs,toolNames:r,provenance:a}}let m=t.flatMap(e=>{let t=zJe(e);return t?[t]:[]});return{...f,buildToolCallHandoff:p,contributionDescriptors:m}}function nYe(e,t,n){return e===`interactive`?YU(t,n):void 0}function rYe(e){return e===`interactive`?`session`:`terminal`}function iYe(e,t){return e!==`print`&&t!==!1}function aYe(e,t){return e===`serve`&&t===!0}function oYe(e){return e.serve&&!e.mcpServe&&!e.acp}const sYe=new Set([`approved`,`rejected`,`revoked`]),J9=new Set([`managed`,`user`,`project`,`plugin`,`local`]);function Y9(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cYe(e){if(!Y9(e))return!1;let t=e.provenance;return typeof e.serverId==`string`&&typeof e.source==`string`&&J9.has(e.source)&&Y9(t)&&typeof t.kind==`string`&&typeof t.id==`string`&&typeof e.definitionFingerprint==`string`&&typeof e.securityIdentity==`string`&&typeof e.approvalAuthority==`string`&&J9.has(e.approvalAuthority)&&typeof e.decision==`string`&&sYe.has(e.decision)&&typeof e.decidedAt==`string`&&(e.repositoryKey===void 0||typeof e.repositoryKey==`string`)&&(e.workspaceGeneration===void 0||typeof e.workspaceGeneration==`number`)}function lYe(e){return Y9(e)&&typeof e.action==`string`&&typeof e.serverId==`string`&&typeof e.decision==`string`&&typeof e.at==`string`}function X9(e,t){return e.serverId===t.serverId&&e.approvalAuthority===t.approvalAuthority&&(e.repositoryKey??``)===(t.repositoryKey??``)}function uYe(e){function t(t=!1){try{Qt(e);let t=JSON.parse(A(e,`utf8`));if(!Y9(t)||t.version!==1||!Array.isArray(t.records)||!t.records.every(cYe)||!Array.isArray(t.audit)||!t.audit.every(lYe))throw Error(`Unrecognised approval store`);return{version:1,records:t.records,audit:t.audit}}catch(n){if(Y9(n)&&n.code===`ENOENT`)return{version:1,records:[],audit:[]};if(t)throw Error(`Refusing to write unreadable or unrecognised MCP approval store ${e}; repair or move it aside first.`);return{version:1,records:[],audit:[]}}}function n(n){vn(Mn(e),{recursive:!0,mode:448});let r=`${e}.lock`,i;try{i=bn(r,`wx`,384)}catch{throw Error(`Refusing to write MCP approval store ${e}: another writer holds ${r}. Retry after it finishes; remove a stale lock only after that process has stopped.`)}try{Jt(e,`${JSON.stringify(n(t(!0)),null,2)}\n`)}finally{un(i),On(r)}}return{list:()=>t().records,put(e){n(t=>({...t,records:[...t.records.filter(t=>!X9(t,e)),e]}))},putWithAudit(e,t){n(n=>({...n,records:[...n.records.filter(t=>!X9(t,e)),e],audit:[...n.audit,t].slice(-500)}))},listAudit:()=>t().audit,appendAudit(e){n(t=>({...t,audit:[...t.audit,e].slice(-500)}))}}}function dYe(e,t){return e??uYe(pq(t).mcpApprovals)}const Z9=`advisorConsentDestinations`;function Q9(e){let t=e.PRODUCT_DISABLE_ADVISOR?.trim().toLowerCase();return t===`1`||t===`true`}function fYe(e){let t=()=>{let t=Yg(e)[Z9];return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]};return{has:e=>t().includes(e),grant:n=>{let r=t();r.includes(n)||Xg(e,{...Yg(e),[Z9]:[...r,n]})}}}function pYe(e,t,n){return r=>{let i={providerOverride:r.profile,providerDefinitions:t,env:n},a=vy(e,i),o=r.model??a.model;return{provider:yy(e,o,i),model:o,destination:vu(a,t)}}}function mYe(e){let t=$pe(e.flag,e.safeMode?void 0:e.userSettings.advisorModel),n=e.orgPolicy?.allowedProviders;bu(e.mainProvider.provider,vu(e.mainProvider.config,e.providerDefinitions));let r=new sme({...t===void 0?{}:{spec:t},resolveTarget:pYe(e.settingsSources,e.providerDefinitions,e.env),...e.resolveProviderCredential===void 0?{}:{validateTarget:t=>{vy(e.settingsSources,{providerOverride:t.profile,providerDefinitions:e.providerDefinitions,env:e.env})},resolveTargetAsync:async t=>{let n=vy(e.settingsSources,{providerOverride:t.profile,providerDefinitions:e.providerDefinitions,env:e.env}),r=t.model??n.model;return{provider:Tt(await e.resolveProviderCredential({...n,model:r}),e.providerDefinitions),model:r,destination:vu(n,e.providerDefinitions)}}},consent:fYe(e.userSettingsPath),...n===void 0?{}:{allowedProfiles:n},killSwitch:Q9(e.env)});return r.isRegistered()?{controller:r,tool:zoe(r)}:t===void 0||Q9(e.env)?{controller:r}:{controller:r,notice:`Advisor "${$x(t)}" is not allowed by your organization policy; starting without it.`}}const hYe={maxTopics:5,maxTopicChars:2e3};function gYe(e){let t=e?.memory;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r={};return typeof n.enabled==`boolean`&&(r.enabled=n.enabled),typeof n.autoSave==`boolean`&&(r.autoSave=n.autoSave),r}function _Ye(e){let t=e.settings?.enabled??!1;e.flagEnabled!==void 0&&(t=e.flagEnabled);let n=e.env?.trim();n===`1`?t=!0:n===`0`&&(t=!1);let r=(e.settings?.autoSave??!1)||e.flagAutoSave===!0;return{enabled:t,autoSave:r}}function vYe(e,t){if(!e.enabled)return{};if(t===void 0)throw new U(`Project memory requires an explicit workspace-authority-backed memory store.`);return{memoryStore:t,recallMemory:{budget:hYe},automaticMemory:{policy:e.autoSave?`auto_save`:`approval_required`}}}function yYe(e){let t=_Ye({settings:gYe(e.settings),flagEnabled:e.args.memory,flagAutoSave:e.args.memoryAutoSave,env:e.productRuntime.environment.PRODUCT_MEMORY}),n=e.platform??process.platform;if(t.enabled&&e.memoryStore===void 0&&!Bd(n))return xYe(n,e.productRuntime,e.write),{};let r=vYe(t,e.memoryStore);return t.enabled&&bYe(e.cwd,e.productRuntime,e.write),r}function $9(e){process.stderr.write(e)}function bYe(e,t,n=$9){n(`Memory is ON (opt-in): capturing and recalling durable memory in ${M(e,t.layout.projectStateDirectories.memory)}. Inspect with /memory; disable with --no-memory or "memory": { "enabled": false } in settings.json.\n`)}function xYe(e,t,n=$9){n(`Memory is OFF: project memory is kept in ${t.layout.projectStateDirectories.memory}, and on this host (${e}) The agent cannot prove a write stays inside the project, so nothing is captured or recalled.\n`)}async function SYe(e,t,n){let r=aD(e);if(nC(r),gD(r.environment)!==void 0)return oye(e,r.environment,r.config.identity.cliName);let i={...e,productRuntime:r},a={...r.environment};delete a.PRODUCT_TELEMETRY_SERVICE_NAME;let o=bNe(a);Mq([...new Set([...Object.keys(r.environment),...Object.keys(process.env)])].filter(e=>e===`PRODUCT_TELEMETRY_SERVICE_NAME`||e===`${r.config.identity.envPrefix}TELEMETRY_SERVICE_NAME`?!1:e.startsWith(`PRODUCT_TELEMETRY_`)||e.startsWith(`${r.config.identity.envPrefix}TELEMETRY_`)));let s=await jGe(r);if(s.kind===`refused`)return;let c=s.kind===`launched`?s.initialInput:void 0,l=Jve(process.argv.slice(2))??Gve(process.argv.slice(2)),u=l===void 0?void 0:TJe();try{await CYe(i,t,n,c,u?.protocol,l,o)}finally{u?.restore()}}async function CYe(e,t,n,r,i,a,o={}){let s=aD(e),c=process.cwd(),l=xq(process.argv).includes(`--safe-mode`)||e.safeMode===!0,u=await Nwe(process.argv,c,{...e,safeMode:l}),d={...e,projectAccess:u,...l?{safeMode:!0}:{}};if(await dGe(d,process.argv,c,o,n?.renderSupervisedSessionView,n))return;let f;try{f=a??OD(),f={...f,safeMode:l}}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}let p=I1(s),{mcpServe:m,http:h,askClient:g}=RD(f,s.config.identity.cliName),{acp:_}=MD(f,s.config.identity.cliName),v=BGe(f,s.environment);if(Mq([`PRODUCT_HTTP_TOKEN`,`${s.config.identity.envPrefix}HTTP_TOKEN`]),f.help){process.stdout.write(Ave(s));return}if(f.version){process.stdout.write(`${s.config.identity.cliName} ${p}\n`);return}if(f.checkUpdate){let e=await _q({productRuntime:s,currentVersion:p,force:!0}),t=fwe(e);e.status===`error`&&(process.stderr.write(`${t}\n`),process.exit(1)),process.stdout.write(`${t}\n`);return}let y=l?{bare:!0,skipConfiguredHooks:!0}:{},b=e=>cC(e,s,c,u,!l),x=new ZD;if(f.reset){process.exitCode=await uPe(x,{productRuntime:s,yes:f.yes,isTTY:process.stdin.isTTY===!0});return}if((f.printMode||f.goal!==void 0||f.serve||m)&&!l&&!xq(process.argv).includes(`--restricted-workspace`)&&kD(u))if(f.serve&&f.open&&v4(u)){let e=await y4(u,c,{productRuntime:s});if(e.decision===`quit`){process.exitCode=1;return}u=e.access}else{process.stderr.write(`${AD(u,c,s.config.identity.cliName)}\n`),process.exitCode=1;return}if((f.printMode||f.goal!==void 0||f.serve||m)&&!l&&!xq(process.argv).includes(`--restricted-workspace`)&&kD(u))if(f.serve&&f.open&&v4(u)){let e=await y4(u,c,{productRuntime:s});if(e.decision===`quit`){process.exitCode=1;return}u=e.access}else{process.stderr.write(`${AD(u,c,s.config.identity.cliName)}\n`),process.exitCode=1;return}if((f.printMode||f.goal!==void 0||f.serve||m||_)&&u.status===`restricted`&&process.stderr.write(`${jD(s.layout.projectSettingsPaths)}\n`),DD(f)===`eval`){let t=Rq(c,d);process.exitCode=await P1(process.argv.slice(3),c,{settingsSources:t.settingsSources,projectAccess:t.projectAccess,environment:s.environment,resolveProviderCredential:(e.providerConnectionHost??gq(s)).resolveCredential});return}if(DD(f)===`session`&&f.positional[1]===`analyze`){await N1(process.argv.slice(4),c,void 0,gx(s.layout.userPaths.sessions));return}try{if(await QNe(f,c,x,s))return}catch(e){x.writeError(e instanceof Error?e.message:String(e)),process.exit(1)}if(f.serve&&f.open&&!process.stdout.isTTY)throw Error(`Opening the monitor requires an interactive terminal for its access code.`);u=await yze(u,c,{productRuntime:s,interactive:_ze(f)&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0,accessFixed:l||xq(process.argv).includes(`--restricted-workspace`)||e.projectAccess!==void 0}),zwe(d,u,c);let S=Oq(s),C=Sq({args:f,settings:S,productRuntime:s,safeMode:l,writeError:e=>x.writeError(e)}),w=C.options,T=C.presetId,E=k1(s.environment),ee=Cq({productRuntime:s,cwd:c,settingsSources:Rq(c,d).settingsSources}),te=Dq(ee);if(te!==void 0&&(process.stderr.write(`${te.message}\n`),te.fatal)){process.exitCode=1;return}let ne=ee.client,re=_?ZNe():void 0,{packContext:ie,packs:ae,packCommandModules:oe}=JNe(c,s,{shellExecutable:E,...ne===void 0?{}:{sandboxClient:ne,sandboxType:`os`},...re===void 0?{}:{editorFiles:re.current}}),se=n===void 0?void 0:P3(n,{enabled:!(f.printMode||f.goal!==void 0||f.serve||m||_),cwd:c,productRuntime:s,projectAccess:u,settings:S,reducedMotionFlag:f.reducedMotion,env:s.environment}),ce=se?.keybindingsSource,le=se?.theme,ue=f.printMode||f.goal?`print`:f.serve||m||_?`serve`:`interactive`,de=!(f.printMode||f.goal||m||_),fe=oYe({serve:f.serve,mcpServe:m,acp:_}),D=e.mcpActivationAdapter===void 0&&!l?await tYe({productRuntime:s,settingsSources:Rq(c,d).settingsSources,projectAccess:u,cwd:c,env:s.environment,mode:ue,askSurface:de,appSurface:fe,...e.mcpStdioAuthorities===void 0?{}:{stdioAuthorities:e.mcpStdioAuthorities},approvalStore:dYe(e.mcpApprovalStore,s),...e.mcpHttpTransportDeps===void 0?{}:{httpTransportDeps:e.mcpHttpTransportDeps},...e.mcpResultAdmissionLimits===void 0?{}:{resultAdmissionLimits:e.mcpResultAdmissionLimits},reportDiagnostic:e=>x.writeError(e)}):void 0;D!==void 0&&(d.mcpActivationAdapter=D.activationAdapter);let pe=Kje({productRuntime:s,report:e=>x.writeError(e)}),{commandHostAdapters:me,outputStyleRegistry:he,outputStyleLoadErrors:ge,providerDefinitions:_e,callerSuppliedProviderDefinitions:ve,baseCommandModules:ye,fixedCommandModules:be,startupUpdateNoticePromise:xe,remoteCommandPolicy:Se,workspaceComposition:O,orgPolicy:Ce,providerConnectionHost:we}=pze(c,f,d,p,oe,ce,le?.cataloguePort,ee,{status:()=>pe.status(),identityChanged:()=>void pe.identityChanged()});for(let{file:e,error:t}of ge)x.writeError(`Skipped output style "${e}": ${t}`);for(let{fileName:e,reason:t}of le?.skipped??[])x.writeError(`Skipped theme "${e}": ${t}`);let Te=Jwe(f,l?void 0:S.outputStyle),Ee;try{Ee=Ywe(he,Te)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}if(f.outputStyle!==void 0||!l&&S.outputStyle!==void 0){let e=`Output style: ${Ee.name} (${Ee.id}; input cost ${Ee.tokenCost})`;f.printMode?process.stderr.write(`${e}\n`):x.writeLine(e)}let De=f.serve&&!f.noSessionPersistence?Yqe():void 0,Oe=UDe({commandHostAdapters:me,settingsSources:O.settingsSources,settingsStores:O.settingsStores,providerDefinitions:_e,orgPolicy:Ce,environment:s.environment}),{registry:ke,wsTransport:Ae,bindTransports:je,usageReporters:Me}=iMe(s,O.sessionStore,O.projectAccess.status===`trusted`,f.open,De,f.daemon===!0,Oe),Ne,Pe=[];if((f.externalEventGrantFiles?.length??0)>0){try{Pe=rO(f.externalEventGrantFiles??[]),Ne=UA(Pe,e=>x.writeLine(e))}catch(e){process.stderr.write(`${e instanceof Error?e.message:`grant refused`}\n`),process.exit(1)}me.externalEvents=Ne.adapter}let Fe;if(Ne!==void 0){let e=Ne;try{Fe=ij({grants:Pe,receive:(t,n)=>e.receive(t,n),countRefusal:(t,n)=>e.countRefusal(t,n),port:f.externalEventPort??0,...f.externalEventTrustedProxies===void 0?{}:{trustedProxies:f.externalEventTrustedProxies},audit:HA(e=>x.writeLine(e))}),await Fe.start()}catch(e){process.stderr.write(`${e instanceof Error?e.message:`External event endpoint could not start.`}\n`),process.exit(1)}}let Ie=Ne,Le=async e=>{if(je(e),Ie!==void 0){if(!(e instanceof rx))throw Error(`External event grants require an InteractiveSession runtime`);await Ie.bind(e)}},{controller:Re,setChannel:ze}=xAe(ke,Me,s);me.costBudget=qj(c,s),me.sandbox=Owe(ee,{read:()=>Yg(rC(s)),write:e=>Xg(rC(s),e)});let Be=jKe(me,Re,x,s,void 0,{sessionStore:O.sessionStore,hasOwnProvider:()=>ZGe(Ue,_e),onHandedOff:()=>me.process?.requestExit(`other`)},pe);zDe(e=>x.writeError(e),ye,oe,w);let Ve=await LGe({cwd:c,args:f,startOptions:d,terminal:x,providerDefinitions:_e,workspace:O,providerConnectionHost:we,orgPolicy:Ce});if(Ve.handled){we.shutdown();return}let He=Ve.setupRequired!==void 0,Ue=He?{name:`setup-placeholder`,model:`setup-required`}:await we.resolveCredential(NCe(s,O.settingsSources,_e,f.provider)),We=w.model??Ue.model,Ge;try{Ge=Kwe(f,s.environment,gy(O.settingsSources),w)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exit(1)}if(me.effort=qwe(Ge),l&&(f.printMode?process.stderr.write(`Safe mode: project and user instruction files, skills, commands, agents, output styles, plugins, hooks and MCP servers are off. Provider, model, built-in tools and permissions work as usual.
2919
2919
  `):x.writeLine(`Safe mode: project and user instruction files, skills, commands, agents, output styles, plugins, hooks and MCP servers are off. Provider, model, built-in tools and permissions work as usual.`)),Ue.source===`env-default`&&Ue.sourceEnvVar!==void 0){let e=`Using ${Ue.name} (${We}) via ${Ue.sourceEnvVar} — run \`${s.config.identity.cliName} --configure\` to persist a profile.\n`;f.printMode?process.stderr.write(e):x.writeLine(e.trimEnd())}let Ke=t(E),qe=YNe({productRuntime:s,packContext:ie,providerConfig:{...Ue,model:We},providerDefinitions:_e,reproduction:{callerSuppliedDefinitions:ve,replayProvider:f.sessionLog!==void 0},notice:e=>process.stderr.write(`${e}\n`)}),Je=Wj(tTe({productRuntime:s,version:p,agentName:w.agentName??s.config.identity.displayName,providerDefinitions:_e,providerSettings:{...Ue,model:We},...f.sessionLog?{provider:PDe(f.sessionLog)}:{},...He?{provider:Zj()}:{},preset:C,baseCommandModules:ye,packs:ae,backgroundTaskRunners:Ke,subagentRunnerFactory:qe,transports:ke})),Ye=Je.provider===void 0||f.sessionLog!==void 0||He?Je.provider:Yj({provider:Je.provider,fallbackFlag:f.fallbackModel,settingsSources:O.settingsSources,primaryConfig:{...Ue,model:We},...f.provider!==void 0&&{providerOverride:f.provider},providerDefinitions:_e,environment:s.environment,resolveProviderCredential:we.resolveCredential,...Ce!==void 0&&{orgPolicy:Ce},announceMoves:f.printMode,notice:e=>f.printMode?process.stderr.write(`${e}\n`):x.writeLine(e)}),{backgroundTaskRunners:Xe,subagentRunnerFactory:Ze}=Xwe(Je,{backgroundTaskRunners:Ke,subagentRunnerFactory:qe}),Qe=[...Xe];Ye===void 0&&(process.stderr.write(`No provider could be constructed from the resolved settings.
2920
- `),process.exit(1));let{commandModules:$e,agentDefinitions:et,toolOptions:tt,permissionMode:nt,providerErrorGuidance:rt,promptFileReferenceTag:it,modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st}=BDe({product:Je,cwd:c,provider:Ye,selectedCommandModules:RDe(Je,be,w),...f.permissionMode===void 0?{}:{permissionMode:f.permissionMode},projectAccess:O.projectAccess});D!==void 0&&tt.additionalTools.push(...await D.connect());let ct=pYe({flag:f.advisor,userSettings:S,safeMode:l,env:s.environment,orgPolicy:Ce,settingsSources:[...O.settingsSources,...iC(s)],providerDefinitions:_e,userSettingsPath:rC(s),resolveProviderCredential:we.resolveCredential,mainProvider:{provider:Ye,config:Ue}});me.advisor=ct.controller,ct.tool!==void 0&&tt.additionalTools.push(ct.tool),ct.notice!==void 0&&x.writeError(ct.notice),ne!==void 0&&(tt.sandboxClient=ne),e.toolExecutionPolicy!==void 0&&(tt.toolExecutionPolicy=e.toolExecutionPolicy);let lt=D?.buildToolCallHandoff(nt);for(let{kind:e,id:t,reason:n}of Je.rejectedCapabilities)x.writeError(`Capability ${e} "${t}" was not composed: ${n}.`);let ut=Gwe(Uwe(s,w,T,nt,{cwd:c,args:f},Ee,Ge),D===void 0?void 0:tYe(ue,D.unavailableServers,s.vocabulary.cliName)),dt=O.sessionStore,ft,pt=!1;f.continueMode?ft=qfe(dt,c):f.resumeId===void 0?f.serve&&!f.noSessionPersistence&&(ft=yx(dt,c)):f.resumeId===``?pt=!0:(ft=Jfe(dt,f.resumeId),ft===void 0&&(process.stderr.write(`Session not found: ${f.resumeId}\n`),process.exit(1)));let mt=vYe({productRuntime:s,settings:S,args:f,memoryStore:O.memoryStore,cwd:c}),ht=x3(S,f.screenReader,s.environment),gt=vNe(o,()=>process.stderr.write(`${s.config.identity.displayName} telemetry export failed.\n`),void 0,{serviceVersion:p,telemetryServiceName:s.config.identity.telemetryServiceName,surface:xMe(f,m,_)},e=>process.stderr.write(`${e}\n`),ENe({cwd:c,projectAccess:O.projectAccess,settingsSources:[...O.settingsSources,...iC(s)],providerDefinitions:_e,env:s.environment,startupCredentials:[Ue.apiKey],resolvedCredentialSecrets:we.getResolvedSecrets}));if(f.printMode||f.goal){let e=IKe(s,c,f,Ye,dt,Qe,Ze,et,tt,$e,me,{resumeSessionId:ft,forkSession:f.forkSession},{model:We,...ut},mt,O.projectAccess,async()=>{await gt?.shutdown(),D!==void 0&&await D.shutdown()},Ce,rt,l?[]:s.layout.agentDefinitionRoots,aC(c,s),s.layout.projectSettingsPaths,iC(s),O.contributionSources,O.skillRoots,s.layout.taskContext,it,at,ot,st,E,gt,O.createEditCheckpointStore?.(),we.resolveCredential);try{await e}finally{we.shutdown(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}return}if(m||_){if(i===void 0)throw Error(`Protocol stdout was not reserved`);let e=a9({productRuntime:s,cwd:c,...gt?{livePromptTrace:gt}:{},args:f,provider:Ye,providerDefinitions:_e,resolveProviderCredential:we.resolveCredential,providerErrorGuidance:rt,promptFileReferenceTag:it,modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st,commandHookShell:E,sessionStore:dt,projectAccess:O.projectAccess,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},orgPolicy:Ce,backgroundTaskRunners:Qe,subagentRunnerFactory:Ze,agentDefinitions:et,agentDefinitionRoots:l?[]:s.layout.agentDefinitionRoots,...y,pluginDirectories:aC(c,s),projectSettingsPaths:s.layout.projectSettingsPaths,userSettingsSources:iC(s),contributionSources:O.contributionSources,skillRoots:O.skillRoots,taskContext:s.layout.taskContext,...tt,...lt===void 0?{}:{toolCallHandoff:lt},commandModules:$e,commandHostAdapters:me,transportRegistry:ke,...Se?{remoteCommandPolicy:Se}:{},resumeSessionId:ft,model:We,preset:ut,memorySessionOptions:mt});try{_?await CJe({productRuntime:s,sessionOptions:e,version:p,cwd:c,input:process.stdin,output:i,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},...re===void 0?{}:{editorFiles:re},admitWorkspace:()=>Kve({access:O.projectAccess,cwd:c,cliName:s.config.identity.cliName,restrictedByChoice:l||xq(process.argv).includes(`--restricted-workspace`)})}):await Fqe(s,e,p,i,h,g)}finally{we.shutdown(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}return}if(f.serve){let e=Gqe({productRuntime:s,cwd:c,...gt?{livePromptTrace:gt}:{},args:f,provider:Ye,providerDefinitions:_e,resolveProviderCredential:we.resolveCredential,providerErrorGuidance:rt,promptFileReferenceTag:it,modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st,commandHookShell:E,sessionStore:dt,projectAccess:O.projectAccess,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},orgPolicy:Ce,backgroundTaskRunners:Qe,subagentRunnerFactory:Ze,agentDefinitions:et,agentDefinitionRoots:l?[]:s.layout.agentDefinitionRoots,...y,pluginDirectories:aC(c,s),projectSettingsPaths:s.layout.projectSettingsPaths,userSettingsSources:iC(s),contributionSources:O.contributionSources,skillRoots:O.skillRoots,taskContext:s.layout.taskContext,...tt,...lt===void 0?{}:{toolCallHandoff:lt},commandModules:$e,commandHostAdapters:me,transportRegistry:ke,bindTransports:je,...De===void 0?{}:{sessionDirectory:De},...v===void 0?{}:{http:v},getMonitorWsUrl:()=>{if(Ae.boundPort===void 0)return;let e=`ws://127.0.0.1:${Ae.boundPort}`;return Ae.resolvedToken?`${e}?token=${encodeURIComponent(Ae.resolvedToken)}`:e},...Se?{remoteCommandPolicy:Se}:{},resumeSessionId:ft,model:We,preset:ut,memorySessionOptions:mt,...He?{setupRequired:!0}:{}});try{await e}finally{we.shutdown(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}return}if(!n||!le)throw Error(`Interactive presentation unavailable in headless runtime`);gPe(x,s.environment),n.installTuiProcessGuards(s.config.identity.cliName),me.process=MKe(),me.workspace=FKe({productRuntime:s,providerDefinitions:_e,userHome:s.userHome??s.layout.userRoot,argv:NKe(process.argv.slice(2),l),requestExit:()=>me.process?.requestExit(`other`),environment:o}),dPe(s.layout.userPaths.onboarded)&&(hPe(x,s,ht),fPe(s.layout.userPaths.onboarded)),Yje({productRuntime:s,onReissued:()=>void pe.identityChanged()}),pe.start({...Re.operatorApprover===void 0?{}:{operatorApprover:Re.operatorApprover}});let _t=n.renderApp({productDisplayName:`${s.config.identity.displayName}`,...gt?{livePromptTrace:gt}:{},modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st,commandHookShell:E,promptFileReferenceTag:it,providerDefinitions:_e,resolveProviderCredential:we.resolveCredential,...lt===void 0?{}:{toolCallHandoff:lt},...RGe(r,f.positional,f.literalPositionals===!0?()=>!1:bD),onChannelReady:VDe(n.setLiveChannel,ze,Be),cwd:c,provider:Ye,providerErrorGuidance:rt,projectAccess:O.projectAccess,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},orgPolicy:Ce,providerOverride:f.provider,providerType:Ue.name,modelId:We,outputStyle:ut.outputStyle,language:f.language,maxTurns:f.maxTurns,version:p,sessionStore:f.noSessionPersistence?void 0:dt,disableSessionLoops:d4(s.environment),resolveDefaultLoopPrompt:l4({productRuntime:s,projectAccess:O.projectAccess,userHome:s.userHome??s.layout.userRoot}),resumeSessionId:ft,showSessionPickerOnStart:pt,forkSession:f.forkSession,...f.movedFrom===void 0?{}:{workspaceMovedFrom:f.movedFrom},sessionName:f.sessionName,backgroundTaskRunners:Qe,subagentRunnerFactory:Ze,agentDefinitions:et,agentDefinitionRoots:l?[]:s.layout.agentDefinitionRoots,...y,pluginDirectories:aC(c,s),projectSettingsPaths:s.layout.projectSettingsPaths,baselinePermissionAllow:s.layout.baselinePermissionAllow,userSettingsSources:iC(s),environment:s.environment,contributionSources:O.contributionSources,skillRoots:O.skillRoots,taskContext:s.layout.taskContext,...tt,commandModules:$e,commandHostAdapters:me,remoteCommandPolicy:Se,shellExec:(e,t)=>kq(e,Pq(s.environment),t),startupUpdateNotice:vwe(xe),transportRegistry:ke,bindTransports:Le,...Ie===void 0?{}:{externalEventVerifierFactory:lA,externalEventGrantHistory:Nb(LA(s.layout.userRoot))},...mt,...F3({productRuntime:s,screenReader:ht,settings:S,env:s.environment,access:O.projectAccess,cwd:c}),cliAdapter:I3(n.createDefaultTuiCliAdapter,{productRuntime:s,providerDefinitions:_e,reloadPluginCommandSource:b}),reloadPluginCommandSource:b,keybindingsSource:ce,themeRegistry:le.registry,reducedMotion:le.reducedMotion,reducedMotionOverride:le.reducedMotionOverride,...Wwe(ut)});try{await _t}finally{we.shutdown(),pe.close(),await Fe?.stop(),Ie?.close(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}process.exit(0)}export{Aue as A,ro as B,DS as C,e_ as D,Nfe as E,uy as F,ea as H,_x as I,Soe as L,Yg as M,Cb as N,c_ as O,y_ as P,px as R,Hpe as S,Pfe as T,no as V,nC as _,b0 as a,dge as b,z1 as c,xq as d,OD as f,rC as g,sC as h,v0 as i,Fu as j,t_ as k,Q as l,aD as m,A0 as n,S0 as o,Ove as p,j0 as r,HPe as s,xYe as t,HNe as u,fge as v,Gme as w,Xme as x,Ghe as y,io as z};
2920
+ `),process.exit(1));let{commandModules:$e,agentDefinitions:et,toolOptions:tt,permissionMode:nt,providerErrorGuidance:rt,promptFileReferenceTag:it,modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st}=BDe({product:Je,cwd:c,provider:Ye,selectedCommandModules:RDe(Je,be,w),...f.permissionMode===void 0?{}:{permissionMode:f.permissionMode},projectAccess:O.projectAccess});D!==void 0&&tt.additionalTools.push(...await D.connect());let ct=mYe({flag:f.advisor,userSettings:S,safeMode:l,env:s.environment,orgPolicy:Ce,settingsSources:[...O.settingsSources,...iC(s)],providerDefinitions:_e,userSettingsPath:rC(s),resolveProviderCredential:we.resolveCredential,mainProvider:{provider:Ye,config:Ue}});me.advisor=ct.controller,ct.tool!==void 0&&tt.additionalTools.push(ct.tool),ct.notice!==void 0&&x.writeError(ct.notice),ne!==void 0&&(tt.sandboxClient=ne),e.toolExecutionPolicy!==void 0&&(tt.toolExecutionPolicy=e.toolExecutionPolicy);let lt=D?.buildToolCallHandoff(nt);for(let{kind:e,id:t,reason:n}of Je.rejectedCapabilities)x.writeError(`Capability ${e} "${t}" was not composed: ${n}.`);let ut=Gwe(Uwe(s,w,T,nt,{cwd:c,args:f},Ee,Ge),D===void 0?void 0:nYe(ue,D.unavailableServers,s.vocabulary.cliName)),dt=O.sessionStore,ft,pt=!1;f.continueMode?ft=qfe(dt,c):f.resumeId===void 0?f.serve&&!f.noSessionPersistence&&(ft=yx(dt,c)):f.resumeId===``?pt=!0:(ft=Jfe(dt,f.resumeId),ft===void 0&&(process.stderr.write(`Session not found: ${f.resumeId}\n`),process.exit(1)));let mt=yYe({productRuntime:s,settings:S,args:f,memoryStore:O.memoryStore,cwd:c}),ht=x3(S,f.screenReader,s.environment),gt=vNe(o,()=>process.stderr.write(`${s.config.identity.displayName} telemetry export failed.\n`),void 0,{serviceVersion:p,telemetryServiceName:s.config.identity.telemetryServiceName,surface:xMe(f,m,_)},e=>process.stderr.write(`${e}\n`),ENe({cwd:c,projectAccess:O.projectAccess,settingsSources:[...O.settingsSources,...iC(s)],providerDefinitions:_e,env:s.environment,startupCredentials:[Ue.apiKey],resolvedCredentialSecrets:we.getResolvedSecrets}));if(f.printMode||f.goal){let e=LKe(s,c,f,Ye,dt,Qe,Ze,et,tt,$e,me,{resumeSessionId:ft,forkSession:f.forkSession},{model:We,...ut},mt,O.projectAccess,async()=>{await gt?.shutdown(),D!==void 0&&await D.shutdown()},Ce,rt,l?[]:s.layout.agentDefinitionRoots,aC(c,s),s.layout.projectSettingsPaths,iC(s),O.contributionSources,O.skillRoots,s.layout.taskContext,it,at,ot,st,E,gt,O.createEditCheckpointStore?.(),we.resolveCredential);try{await e}finally{we.shutdown(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}return}if(m||_){if(i===void 0)throw Error(`Protocol stdout was not reserved`);let e=a9({productRuntime:s,cwd:c,...gt?{livePromptTrace:gt}:{},args:f,provider:Ye,providerDefinitions:_e,resolveProviderCredential:we.resolveCredential,providerErrorGuidance:rt,promptFileReferenceTag:it,modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st,commandHookShell:E,sessionStore:dt,projectAccess:O.projectAccess,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},orgPolicy:Ce,backgroundTaskRunners:Qe,subagentRunnerFactory:Ze,agentDefinitions:et,agentDefinitionRoots:l?[]:s.layout.agentDefinitionRoots,...y,pluginDirectories:aC(c,s),projectSettingsPaths:s.layout.projectSettingsPaths,userSettingsSources:iC(s),contributionSources:O.contributionSources,skillRoots:O.skillRoots,taskContext:s.layout.taskContext,...tt,...lt===void 0?{}:{toolCallHandoff:lt},commandModules:$e,commandHostAdapters:me,transportRegistry:ke,...Se?{remoteCommandPolicy:Se}:{},resumeSessionId:ft,model:We,preset:ut,memorySessionOptions:mt});try{_?await wJe({productRuntime:s,sessionOptions:e,version:p,cwd:c,input:process.stdin,output:i,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},...re===void 0?{}:{editorFiles:re},admitWorkspace:()=>Kve({access:O.projectAccess,cwd:c,cliName:s.config.identity.cliName,restrictedByChoice:l||xq(process.argv).includes(`--restricted-workspace`)})}):await Iqe(s,e,p,i,h,g)}finally{we.shutdown(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}return}if(f.serve){let e=Kqe({productRuntime:s,cwd:c,...gt?{livePromptTrace:gt}:{},args:f,provider:Ye,providerDefinitions:_e,resolveProviderCredential:we.resolveCredential,providerErrorGuidance:rt,promptFileReferenceTag:it,modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st,commandHookShell:E,sessionStore:dt,projectAccess:O.projectAccess,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},orgPolicy:Ce,backgroundTaskRunners:Qe,subagentRunnerFactory:Ze,agentDefinitions:et,agentDefinitionRoots:l?[]:s.layout.agentDefinitionRoots,...y,pluginDirectories:aC(c,s),projectSettingsPaths:s.layout.projectSettingsPaths,userSettingsSources:iC(s),contributionSources:O.contributionSources,skillRoots:O.skillRoots,taskContext:s.layout.taskContext,...tt,...lt===void 0?{}:{toolCallHandoff:lt},commandModules:$e,commandHostAdapters:me,transportRegistry:ke,bindTransports:je,...De===void 0?{}:{sessionDirectory:De},...v===void 0?{}:{http:v},getMonitorWsUrl:()=>{if(Ae.boundPort===void 0)return;let e=`ws://127.0.0.1:${Ae.boundPort}`;return Ae.resolvedToken?`${e}?token=${encodeURIComponent(Ae.resolvedToken)}`:e},...Se?{remoteCommandPolicy:Se}:{},resumeSessionId:ft,model:We,preset:ut,memorySessionOptions:mt,...He?{setupRequired:!0}:{}});try{await e}finally{we.shutdown(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}return}if(!n||!le)throw Error(`Interactive presentation unavailable in headless runtime`);gPe(x,s.environment),n.installTuiProcessGuards(s.config.identity.cliName),me.process=NKe(),me.workspace=IKe({productRuntime:s,providerDefinitions:_e,userHome:s.userHome??s.layout.userRoot,argv:PKe(process.argv.slice(2),l),requestExit:()=>me.process?.requestExit(`other`),environment:o}),dPe(s.layout.userPaths.onboarded)&&(hPe(x,s,ht),fPe(s.layout.userPaths.onboarded)),Yje({productRuntime:s,onReissued:()=>void pe.identityChanged()}),pe.start({...Re.operatorApprover===void 0?{}:{operatorApprover:Re.operatorApprover}});let _t=n.renderApp({productDisplayName:`${s.config.identity.displayName}`,...gt?{livePromptTrace:gt}:{},modelCommandToolPrefix:at,subagentHookEnvironmentNames:ot,observerFailureWarningCode:st,commandHookShell:E,promptFileReferenceTag:it,providerDefinitions:_e,resolveProviderCredential:we.resolveCredential,...lt===void 0?{}:{toolCallHandoff:lt},...zGe(r,f.positional,f.literalPositionals===!0?()=>!1:bD),onChannelReady:VDe(n.setLiveChannel,ze,Be),cwd:c,provider:Ye,providerErrorGuidance:rt,projectAccess:O.projectAccess,...O.createEditCheckpointStore===void 0?{}:{createEditCheckpointStore:O.createEditCheckpointStore},orgPolicy:Ce,providerOverride:f.provider,providerType:Ue.name,modelId:We,outputStyle:ut.outputStyle,language:f.language,maxTurns:f.maxTurns,version:p,sessionStore:f.noSessionPersistence?void 0:dt,disableSessionLoops:d4(s.environment),resolveDefaultLoopPrompt:l4({productRuntime:s,projectAccess:O.projectAccess,userHome:s.userHome??s.layout.userRoot}),resumeSessionId:ft,showSessionPickerOnStart:pt,forkSession:f.forkSession,...f.movedFrom===void 0?{}:{workspaceMovedFrom:f.movedFrom},sessionName:f.sessionName,backgroundTaskRunners:Qe,subagentRunnerFactory:Ze,agentDefinitions:et,agentDefinitionRoots:l?[]:s.layout.agentDefinitionRoots,...y,pluginDirectories:aC(c,s),projectSettingsPaths:s.layout.projectSettingsPaths,baselinePermissionAllow:s.layout.baselinePermissionAllow,userSettingsSources:iC(s),environment:s.environment,contributionSources:O.contributionSources,skillRoots:O.skillRoots,taskContext:s.layout.taskContext,...tt,commandModules:$e,commandHostAdapters:me,remoteCommandPolicy:Se,shellExec:(e,t)=>kq(e,Pq(s.environment),t),startupUpdateNotice:vwe(xe),transportRegistry:ke,bindTransports:Le,...Ie===void 0?{}:{externalEventVerifierFactory:lA,externalEventGrantHistory:Nb(LA(s.layout.userRoot))},...mt,...F3({productRuntime:s,screenReader:ht,settings:S,env:s.environment,access:O.projectAccess,cwd:c}),cliAdapter:I3(n.createDefaultTuiCliAdapter,{productRuntime:s,providerDefinitions:_e,reloadPluginCommandSource:b}),reloadPluginCommandSource:b,keybindingsSource:ce,themeRegistry:le.registry,reducedMotion:le.reducedMotion,reducedMotionOverride:le.reducedMotionOverride,...Wwe(ut)});try{await _t}finally{we.shutdown(),pe.close(),await Fe?.stop(),Ie?.close(),await gt?.shutdown(),D!==void 0&&await D.shutdown()}process.exit(0)}export{Aue as A,ro as B,DS as C,e_ as D,Nfe as E,uy as F,ea as H,_x as I,Soe as L,Yg as M,Cb as N,c_ as O,y_ as P,px as R,Hpe as S,Pfe as T,no as V,nC as _,b0 as a,dge as b,z1 as c,xq as d,OD as f,rC as g,sC as h,v0 as i,Fu as j,t_ as k,Q as l,aD as m,A0 as n,S0 as o,Ove as p,j0 as r,HPe as s,SYe as t,HNe as u,fge as v,Gme as w,Xme as x,Ghe as y,io as z};