@north-light/cli 0.3.724 → 0.3.725

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.
@@ -1 +1 @@
1
- var mt=Object.defineProperty;var r=(t,o)=>mt(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as ut,envModelExact as ft,envModelIntent as Be,envNodeCwd as pt,envNodeId as gt,envProfileId as vt,envScopes as _t,scopeAllowed as ht}from"../../shared/env.js";import{createServer as wt}from"node:net";import{WebSocketServer as bt,createWebSocketStream as St}from"ws";import{BROKER_VIEW_PORT as yt}from"./view-socket.js";import{existsSync as Ke,readFileSync as Et,unlinkSync as ge,writeFileSync as Rt}from"node:fs";import{join as $e}from"node:path";import{randomUUID as U}from"node:crypto";import{mark as Ue}from"../timing.js";import{SUBMIT_RESULT_TOOL as kt}from"./structured-output.js";import{conversationIdFromPath as Tt,flushConversation as ve,installSessionManagerStorePatch as Ct,readConversationAsync as At}from"../conversation-store/index.js";import{getAgentDir as se,ModelRegistry as Mt,ModelRuntime as xt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as Pt,viewSocketPath as Ot}from"../canvas/paths.js";import{bindBrokerEventSource as Nt}from"../events/source.js";import{emitEvent as h,flushBrokerLog as We}from"../events/emit.js";import{operationIdContext as Dt}from"../events/operation-id.js";import{findMissingPackagePaths as It}from"./package-health.js";import{installBrokerConfigSnapshot as Lt}from"../config.js";import{FRONT_DOOR_ENV as Ft}from"./front-door.js";import{CANVAS_EXTENSIONS as _e,piInvocationToSdkConfig as Bt}from"./launch.js";import{setConversationRequestMark as Ge}from"../conversation-store/index.js";import{assertEngineVersion as Kt,loadBrokerEngine as $t}from"./broker-sdk.js";import{initCrtrTheme as Ut}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Wt}from"./pi-cli.js";import{captureSessionChatCapabilities as Gt}from"./command-surface.js";import{InMemoryCredentialStore as jt}from"@earendil-works/pi-ai";import{askGateway as Vt,configureBrokerModelRuntime as qt,refusalRetryAt as Xt}from"./broker/model-adapter.js";import{brokerApiUrl as Yt,brokerExecutionId as Ht,mutateBrokerFault as ie,recordBrokerTurn as je}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Jt}from"./launch-recipe.js";import{fetchRunAttachments as Ve}from"./broker/attachments-fetch.js";import{llmModelFor as zt,modelRequestFromConfig as Qt,expandModelCandidates as Zt,parseModelSpec as er,unregisteredConcreteModel as tr}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as rr}from"./stream-watchdog.js";import{CRTR_CYCLE_CUSTOM_TYPE as he,earlierCycleMessages as nr,endedByAbort as or,identifiedMessages as sr,welcomeWindow as ir,WELCOME_EARLIER_BYTES as ar,WELCOME_EARLIER_CYCLES as dr}from"./session-cycles.js";import{turnErrorOf as lr}from"../llm/refusal.js";import{projectTranscript as cr}from"./session-visibility.js";import{currentTurnVisibility as mr}from"./turn-visibility.js";import{isUnknownModel as we}from"./model-selection.js";import{BrokerClientRegistry as ur}from"./broker/client-registry.js";import{ToolGroupTracker as fr}from"./broker/tool-groups.js";import{TurnReplyTracker as pr}from"./broker/turn-replies.js";import{onNodeNamed as gr}from"./broker/node-named.js";import{FaultRetry as vr,willDaemonRetry as _r}from"./broker/fault-retry.js";import{RunTurnEnds as hr}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as wr}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as br,BROKER_START_CYCLE as Sr,BROKER_IDLE_TURN_START as yr,BROKER_RUN_TURN_BUSY as Er,BROKER_RUN_STEER as Rr}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as kr}from"./broker/run-steer.js";import{prependRunDeferredMail as Tr,settleRunDeferredMail as Cr}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as Ar}from"./broker/run-turn-queue.js";import{EventProjection as Mr}from"./broker/event-projection.js";import{createFrameDispatchContext as xr,handleFrame as Pr}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as Or,installAdvertisedCommandInvocationContract as Nr}from"./advertised-command-invocation.js";import{RebindDriver as Dr}from"./broker/rebind.js";import{beginRuntimeTeardown as Ir}from"./broker/extension-abort.js";import{receiveNodeToken as Lr}from"./broker/node-token.js";import{serveCliRelay as Fr}from"./broker/cli-relay.js";import{recordBrokerRelease as Br}from"./lifecycle.js";import{setTurnCauseSource as Kr}from"./broker/turn-cause.js";import{decodeKickoffOrigin as qe,KICKOFF_ORIGIN_ENV as Xe}from"./stamp/protocol.js";import{announceMessageOrigin as Ye}from"./stamp/channel.js";import{commitBrokerModel as $r,recordConversationWriteFault as He}from"./broker/daemon-ops.js";import{bootExtensionState as Ur,holdStartupClaims as Wr,releaseStartupClaims as Gr}from"./broker/boot-state.js";import{bindCarriedStart as Je,publishCarriedStart as jr,startCycle as ze,takeCycleAttachments as Qe}from"./broker/cycle-start.js";import{composerNames as Vr}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as qr,FrameOverflowError as Xr,withoutImages as Ze,toolCallIds as Yr}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as So,REVIEW_BOUNDARY_NAVIGATION_CODE as yo}from"./broker/frame-replies.js";function be(t){return new Mt(t.modelRuntime)}r(be,"registryOf");function H(t,o){if(t==null||we(t))return null;const a=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${a}`}r(H,"formatModelSpec");function Hr(t,o){const a=H(t,void 0);return a===null?null:`${a}:${o===void 0||o===""?"off":o}`}r(Hr,"formatExactModelSpec");const Jr=12e4;let ae=null;import{brokerSignalClient as V}from"./broker/signal-stream.js";function zr(){V().stop();const t=ae;if(ae=null,t!==null)try{t.dispose()}catch{}}r(zr,"disposeActiveSession");function Qr(t,o){const a=ht(o,"crtr:act")?void 0:["bash"],b=t!==void 0&&t.length>0?[...new Set([...t,kt])]:t===void 0?void 0:[...t];return{...b!==void 0?{tools:b}:{},...a!==void 0?{excludeTools:a}:{}}}r(Qr,"brokerToolOptions");async function ho(t,o=process.hrtime.bigint(),a=new Date().toISOString()){Nt(t);const b=await Lr(),i=await Fr(t,b);process.env.CRTR_API_SOCKET=i.path,Dt.fresh(()=>{h({level:"info",event:"broker.startup.cli_entry",ts:a,duration_ms:0,fields:{pid:process.pid,runtime_version:process.version,engine_version:null,model:null}}),h({level:"info",event:"broker.startup.module_loaded",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:null,model:null}})});const d=new Set;let f=null;const l=r((e,n=null)=>{d.has(e)||(d.add(e),Ue(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),h({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:f,model:n}}))},"emitStartupMilestone"),v=r((e,n,s={})=>{const u=process.hrtime.bigint(),p=Number(u-n)/1e6,g=Number(u-o)/1e6;Ue(e,{duration_ms:p}),h({level:"info",event:e,duration_ms:p,fields:{at_ms:g,...s}})},"emitStartupStep");process.env[Ft]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,Ct(t),Ge(e=>v("broker.startup.conversation_request",process.hrtime.bigint()-BigInt(Math.round(e.durationMs*1e6)),{method:e.method,route:e.route,first_request:e.firstRequest,worker_age_ms:e.workerAgeMs}));const E=process.hrtime.bigint(),R=await $t();v("broker.startup.engine_loaded",E);const x=process.hrtime.bigint();Kt(R.VERSION),v("broker.startup.version_checked",x),f=R.VERSION;const T=process.hrtime.bigint(),q=Pt(t),w=$e(q,"broker-launch.json"),S=JSON.parse(Et(w,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Lt(S.configSnapshot),S.start!==void 0){const{start:e,...n}=S;Rt(w,JSON.stringify(n))}const c=Bt(S);c.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT,v("broker.startup.launch_recipe_read",T);let k,N;const P=new AbortController,X=r(e=>{k!==void 0?k(e):(N??=e,P.abort())},"onSignal");process.on("SIGTERM",()=>X("SIGTERM")),process.on("SIGINT",()=>X("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&V().start(t,e)});const I=Ot(t),L=new Set;let J;try{Ke(I)&&ge(I)}catch{}const re=r(()=>{try{ge(I)}catch{}},"removeViewSocket"),D=wt(e=>{if(J!==void 0){J(e);return}e.pause(),L.add(e),e.once("close",()=>L.delete(e)),e.on("error",()=>{})});await new Promise((e,n)=>{D.once("error",n),D.listen(I,()=>{D.off("error",n),e()})}),l("broker.startup.listening");const z=process.hrtime.bigint();let Q;try{Q=await tn(R,c,(e,n)=>v(e,n))}catch(e){throw re(),e}let{session:C,services:F,resuming:nn,runtime:tt}=Q;Ge(void 0),v("broker.startup.session_build",z),l("broker.startup.session_built");const W=S.start;W!==void 0&&Wr();const ye=W===void 0?await ze(t,C,"startup",P.signal):jr(t,W);P.signal.aborted&&(C.dispose(),re(),await We(),process.exit(0));const rt=ye?.names===void 0?await Vr(t):ye.names,Z=(await Ur(t)).node.review_binding?.review_id,G=ut();ae=C;const nt=r(async()=>{const e=m.session().model;return e===void 0?{ok:!0}:await Vt(zt(`${e.provider}/${e.id}`,Be(),ft()))},"retryProbe");try{process.env.PI_PACKAGE_DIR=Wt(),Ut(F.settingsManager.getTheme(),se(),!1)}catch(e){h({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of It(se()))h({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const _=new ur(t),ne=new Map,B=new fr(t,e=>_.broadcast(e)),ee=new pr(t,e=>_.broadcast(e));gr(e=>_.broadcast({type:"node_named",...e}));let j=!1,Ee=!1,oe,Re,m,te;const de=new hr;let Y,ke=r(()=>{},"notifyTurnAccepted"),Te=r(()=>{},"resetFrameState"),Ce=r(()=>{},"bindAnswered");const le=wr(W===void 0?void 0:new Promise(e=>{Ce=e}));let Ae=r(()=>0,"pendingPromptDispatches"),Me;const K=Ar({runNode:G,session:r(()=>m.session(),"session"),isReplacing:r(()=>m.isReplacing(),"isReplacing"),pendingRebind:r(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:r(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:r(()=>Ae(),"pendingDispatches"),turnAdmission:le,prependDeferred:r(e=>Tr(t,e),"prependDeferred"),onError:r(e=>h({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),xe=kr(K.steerable);globalThis[Rr]=xe,Kr(()=>m.session());const Pe=K.drain;c.firstPrompt!==void 0&&c.firstPrompt!==""&&K.holdForKickoff(),globalThis[yr]=K.start,globalThis[Er]=K.busy,m=new Dr({nodeId:t,cfg:c,session:C,services:F,runtime:tt,registry:_,toolGroups:B,turnReplies:ee,runSteer:xe,runNode:G,transcriptMessages:r(e=>Se(e,Z)?.map(({message:n})=>n)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:r(()=>Re,"uiContext"),faultRetry:r(()=>te,"faultRetry"),projection:r(()=>Y,"projection"),setActiveSession:r(e=>{if(ae=e,Me?.(),G||process.env.CRTR_RUN_ID){let n="stop",s,u=!1;Me=e.subscribe(p=>{if(p.type==="agent_start"&&(n="stop",s=void 0,u=!1,de.started()),p.type==="agent_end"){const g=[...p.messages??[]].reverse().find(y=>y.role==="assistant");g&&(n=g.stopReason,s=or(g)?void 0:lr(g,Xt(g)),u=g.role==="assistant"&&_r(g,e.model?.contextWindow))}p.type==="agent_settled"&&(de.settled(e.sessionManager,{stop_reason:n,...s?{error:s}:{}},u),G&&(ve().then(()=>Cr(t,e)).catch(async g=>{if(String(g?.message).startsWith("conversation_write_failed")){h({level:"error",event:"broker.exited",node_id:t,error:g,fields:{fault:"conversation_write_failed"}}),await He(t,g),M("conversation_write_failed",1);return}h({level:"error",event:"broker.run_deferred_mail.settle_failed",error:g})}),queueMicrotask(()=>{m.session()===e&&Pe()})))})}},"setActiveSession"),disposeAndExit:r((e,n)=>M(e,n),"disposeAndExit"),onSessionRebind:r(()=>{Te()},"onSessionRebind"),onReplacementIdle:r(()=>{G&&Pe()},"onReplacementIdle"),reWelcomeAll:r(()=>me(),"reWelcomeAll")});const Oe=r(async(e,n=!1)=>{const s=m.session(),u=H(s.model,s.thinkingLevel);if(u===null)return null;const p=await $r(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:n});return n&&(c.model=p.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,c.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",c.modelExact=!0)),p.modelOverride},"persistModelChoice"),Ne=r(async(e=!0,n,s=!1)=>{const u=m.session(),p=H(u.model,u.thinkingLevel),g=e?await Oe(n,s):p;_.broadcast({type:"model_changed",model:we(u.model)?void 0:u.model,spec:g})},"broadcastModelChanged");te=new vr({nodeId:t,cfg:c,retryProbe:nt,currentSession:r(()=>m.session(),"currentSession"),currentServices:r(()=>m.services(),"currentServices"),installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),registryOf:be,formatModelSpec:H,broadcastModelChanged:Ne,turnAdmission:le,reWelcomeAll:r(()=>me(),"reWelcomeAll"),...G?{turnEnds:de}:{}});const De=r(()=>{te.rearmIfStranded().catch(e=>{h({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");V().subscribe("resync",De),V().subscribe("fault-retry",De),Y=new Mr({registry:_,faultRetry:te,installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),currentSession:r(()=>m.session(),"currentSession"),notifyTurnAccepted:r(()=>ke(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:H});let ce=[];const Ie=r(async e=>{ce=[];const n=e.sessionManager.getEntries()[0],s=e.sessionManager.getSessionFile(),u=s===void 0?null:Tt(s);if(!(Z!==void 0||n?.type!=="custom"||n.customType!==he||u===null))try{const{entries:p}=await At(u,{beforeCycle:ar});ce=nr(p,n,dr)}catch(p){h({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`earlier cycles read failed: ${String(p)}`}})}},"loadEarlierCycles"),ot=Ie(C),st=r(e=>{const n=m.session(),s=Se(n,Z),u=s===void 0?void 0:[...ce.map(A=>({...A,visibility:"visible"})),...s],p=u?.map(({message:A})=>A)??n.sessionManager.buildSessionContext().messages,{start:g}=ir(p,A=>JSON.stringify(Ze(A,t)).length),y=e.snapshotTail===void 0?g:Math.max(g,p.length-e.snapshotTail),$=u?.slice(y),pe=p.slice(y).map(A=>Ze(A,t)),lt=Yr(pe),ct=Object.fromEntries(Object.entries(B.summaries()).filter(([A])=>lt.has(A)));return{messages:pe,...$===void 0?{}:{messageIds:$.map(({id:A})=>A)},messageVisibility:$?.map(({visibility:A})=>A)??pe.map(()=>"visible"),turnVisibility:mr(),stats:n.getSessionStats(),state:{model:we(n.model)?void 0:n.model,thinkingLevel:n.thinkingLevel,isStreaming:n.isStreaming,isCompacting:n.isCompacting,steeringMode:n.steeringMode,followUpMode:n.followUpMode,sessionFile:n.sessionFile,sessionId:n.sessionId,sessionName:n.sessionName,autoCompactionEnabled:n.autoCompactionEnabled,messageCount:n.messages.length,pendingMessageCount:n.pendingMessageCount},display:{..._.displaySnapshot()},toolGroupSummaries:ct,turnReplies:ee.snapshot(),workingActivity:Y.currentWorkingActivity(),queued:{steering:[...n.getSteeringMessages()],followUp:[...n.getFollowUpMessages()]}}},"buildSnapshot"),Le=r(e=>{const n=e.role==="controller"?ne.values().next().value:void 0;_.sendFrame(e,{type:"welcome",snapshot:st(e),role:e.role,pending_dialog:n!==void 0?n.request:null,agentDir:se()})},"sendWelcome"),it=r(e=>{const n=[...ne.values()];for(let s=1;s<n.length;s++)_.sendFrame(e,n[s].request)},"replayExtraPendingDialogsTo"),me=r(()=>{try{const e=m.session();ee.seed(Se(e,Z)?.map(({message:n})=>n)??e.sessionManager.buildSessionContext().messages)}catch(e){h({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}_.forEachHelloed(Le)},"reWelcomeAll"),Fe=r(async e=>{if(j)return;j=!0;const n=V().latestNode;n!==void 0&&(n.intent==="idle-release"||n.status==="done")&&Br(t,process.env.CRTR_EXECUTION_ID??null),V().stop(),e===0&&await ve().catch(async s=>{e=1,h({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"conversation_write_failed"}}),await He(t,s)}),B.persistPendingSummary(),Y.dispose(),zr();try{D?.close(),oe?.close()}catch{}i.close(),_.dispose();try{Ke(I)&&ge(I)}catch{}_.clearAttachState(),await We(),process.exit(e)},"completeExit"),M=r((e,n=0)=>{if(j)return;const s=e==="shutdown-hook"||e==="shutdown-after-settle";if(s&&B.finishOpenToolGroup(!0),s&&(B.hasSummaryTasks()||ee.hasTasks())){if(Ee)return;Ee=!0,Promise.allSettled([B.waitForSummaryTasks(),ee.waitForTasks()]).finally(()=>Fe(n));return}Fe(n)},"disposeAndExit");globalThis[br]=M,Re=rn({writable:r(()=>_.writableClients(),"writable"),forward:r((e,n)=>_.sendFrame(e,n),"forward"),pending:ne,broadcast:r(e=>_.broadcastUi(e),"broadcast"),onKnownStreamWait:r(e=>Y.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(C,F),l("broker.startup.extensions_bound");const O=xr({nodeId:t,registry:_,toolGroups:B,projection:Y,rebind:m,boundaryReviewId:Z,pendingDialogs:ne,sendWelcome:Le,replayExtraPendingDialogsTo:it,reWelcomeAll:me,disposeAndExit:M,persistModelChoice:Oe,broadcastModelChanged:Ne,registryOf:be,formatModelSpec:H,formatExactModelSpec:Hr,turnAdmission:le,memoryInventory:rt,runNode:G,onKickoffAdmitted:K.releaseKickoff});ke=O.notifyTurnAccepted,Te=O.resetForSession,Ae=O.pendingPromptDispatches,globalThis[Sr]=async e=>{for(const y of Jt){const $=e.env[y];$===void 0?delete process.env[y]:process.env[y]=$}process.env[Xe]=e.origin,e.messageIds.length>0?process.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(e.messageIds):delete process.env.CRTR_KICKOFF_MESSAGE_IDS,e.model!==void 0?c.model=e.model:delete c.model,e.modelExact?(c.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete c.modelExact,delete process.env.CRTR_MODEL_EXACT),c.editorName=e.editorLabel,K.holdForKickoff(),B.finishOpenToolGroup(!0);const n=m.session(),s=n.sessionManager.getSessionFile();if(s===void 0||s==="")throw new Error("in-place cycle needs a persisted session file");const u=n.sessionManager,p=u.getLeafId();u.resetLeaf(),u.appendCustomEntry(he,{cycle:e.cycle,fromLeaf:p}),await ve(),m.beforeNextBind(async y=>{const[$]=await Promise.all([ze(t,y,"resume"),Ie(y)]);await O.refreshMemoryNames($?.names)});const g=await m.runReplacement(null,"cycle",y=>y.switchSession(s));if(m.beforeNextBind(void 0),!g)return M("cycle-replacement-failed",1),!1;Ye(e.prompt,qe(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Ve(t,Qe(t))}catch(y){return h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:y,fields:{operation:"attachments_fetch"}}),M("attachments-fetch-failed",1),!1}return O.kickoff(e.prompt,e.messageIds),!0};const at=2500;let ue=!1;const dt=r(async e=>{if(j||ue)return;if(ue=!0,m.isAgentRunActive()||m.session().isStreaming||O.pendingPromptDispatches()>0){const s=Date.now()+at;for(;O.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<s;)await new Promise(u=>setTimeout(u,25));if(m.session().isStreaming){const u=s-Date.now();if(u>0){let p;try{Ir(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(y=>{p=setTimeout(()=>y(!1),u)})])&&await je(t,{event:"closed",end_reason:"teardown-aborted"})}finally{p!==void 0&&clearTimeout(p)}}}else(O.pendingPromptDispatches()>0||m.isAgentRunActive())&&await je(t,{event:"interrupted"})}M(e)},"abortAndExit");if(k=r(e=>{dt(e)},"signalTeardown"),N!==void 0){k(N);return}const fe=r(e=>{l("broker.startup.first_viewer_connected");const n=_.create(e);e.on("data",u=>{let p;try{p=n.decoder.push(u)}catch(g){g instanceof Xr?(_.sendFrame(n,{type:"error",code:"frame_overflow",message:g.message}),_.dropClient(n,`frame overflow: ${g.message}`)):_.dropClient(n,`decoder error: ${String(g)}`);return}for(const g of p)try{Pr(O,n,g)}catch{}});const s=r(()=>{_.removeClient(n)},"drop");e.on("close",s),e.on("error",()=>{})},"serveViewer");Yt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(oe=new bt({host:"::",port:yt,path:"/view",maxPayload:qr.maxLineBytes}),oe.on("connection",e=>fe(St(e))),oe.on("error",e=>{j||(h({level:"error",event:"broker.socket.failed",error:e}),M("socket-error",1))})),D.on("error",e=>{j||(h({level:"error",event:"broker.socket.failed",error:e}),M("socket-error",1))}),await ot,J=fe;for(const e of L)L.delete(e),fe(e),e.resume();(async()=>{if(Promise.all([ie(t,{op:"clear",link:"viewer\u2194broker"}),ie(t,{op:"clear",link:"relay\u2194broker"})]).catch(n=>h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:n,fields:{operation:"broker_socket_bound_fault_clear"}})),W!==void 0){let n;try{try{n=await Je(t,m.session(),W)}catch(s){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:s,fields:{operation:"session_bound",attempt:1}}),n=await Je(t,m.session(),W)}}catch(s){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:s,fields:{operation:"session_bound",attempt:2}}),M("session-bound-failed",1);return}if(n?.action==="shutdown"){m.requestShutdown();return}if(n?.action==="relaunch_root")throw new Error("a startup bind never relaunches a root");V().start(t,Ht()),Gr(),Ce()}l("broker.startup.ready_for_turn");let e;try{e=await te.recoverOnStartup()}catch(n){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:n,fields:{operation:"recovery_startup"}}),M("recovery-startup-failed",1);return}if(!(j||ue))if(e==="none"&&c.firstPrompt!==void 0&&c.firstPrompt!==""){const n=qe(process.env[Xe]);n!==null&&Ye(c.firstPrompt,n);try{await Ve(t,Qe(t))}catch(u){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:u,fields:{operation:"attachments_fetch"}}),M("attachments-fetch-failed",1);return}const s=process.env.CRTR_KICKOFF_MESSAGE_IDS;O.kickoff(c.firstPrompt,s?JSON.parse(s):[])}else K.releaseKickoff()})(),_.persistAttachState()}r(ho,"runBroker");function Se(t,o){const a=t.sessionManager,b=a.getEntries===void 0?void 0:sr(a.getEntries(),a.getLeafId?.());return b!==void 0&&Or(b.map(({message:i})=>i)),b===void 0?void 0:cr(b,{boundaryReviewId:o,sessionEntries:a.getEntries?.()})}r(Se,"snapshotMessages");function et(){const t=gt();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}r(et,"currentBrokerNodeId");async function Zr(t,o){const a=Qt(o.model,Be(),o.modelExact===!0);if(a===void 0)return;const b=be(t),i={cwd:pt()??o.cwd,profileId:vt()},d=await tr(a,b,i);if(d!==void 0)throw await ie(et(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${d.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${d.request.spec}' is not registered in the serving model registry`);const f=await Zt(a,i.cwd,i.profileId),l=er(a.spec);for(const v of f){const E=b.find(v.providerId,v.modelId);if(E===void 0)continue;const x=l?.providerId===v.providerId&&l.modelId===v.modelId?l.thinkingLevel??(v.thinkingLevel===void 0?void 0:"off"):v.thinkingLevel;return{model:E,thinkingLevel:x}}if(o.modelExact===!0){const v=f.map(E=>`'${E.providerId}/${E.modelId}' unregistered`).join("; ");throw await ie(et(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`exact-consult model '${o.model}' is unavailable \u2014 refusing to substitute (${v})`}}),new Error(`[broker] FATAL: exact-consult model '${o.model}' is unavailable`)}h({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:f.map(v=>({provider:v.providerId,model:v.modelId,reason:"unregistered"})).slice(0,16)}})}r(Zr,"resolveLaunchModel");function en(t){let o=!0;return{runtime:new Proxy(t,{get(b,i,d){return o&&i==="getAvailableSnapshot"?()=>[]:o&&i==="getAvailable"?async()=>[]:o&&i==="getModel"?()=>{}:Reflect.get(b,i,d)}}),reveal:r(()=>{o=!1},"reveal")}}r(en,"modelLessRegistry");async function tn(t,o,a=()=>{}){const b=se(),i=r(async w=>{const S=process.hrtime.bigint(),c=await xt.create({credentials:new jt,modelsPath:$e(w.agentDir,"models.json")});qt(c),a("broker.startup.model_runtime",S);const k=process.hrtime.bigint(),N=await t.createAgentSessionServices({cwd:w.cwd,agentDir:w.agentDir,modelRuntime:c,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:r(P=>({...P,extensions:P.extensions.filter(X=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(X.path))}),"extensionsOverride")}});return a("broker.startup.resources_loaded",k),N},"loadServices");let d;const f=r(async w=>{const S=d;d=void 0;const c=await(S??i(w)),k=c.resourceLoader.getExtensions();if(o.extensionPaths.some(z=>_e.includes(z))){const z=new Set(k.extensions.map(C=>C.path)),Q=_e.filter(C=>!z.has(C));if(Q.length>0){const C=k.errors.filter(F=>_e.includes(F.path)).map(F=>`${F.path}: ${F.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${Q.join(", ")}${C===""?"":` (${C})`}`)}}c.settingsManager.getRetryEnabled=()=>!1;const N=process.hrtime.bigint(),P=await Zr(c,o);a("broker.startup.model_resolved",N);const X=P?.model,I=P?.thinkingLevel,L=P===void 0?en(c.modelRuntime):void 0,J=L!==void 0?{...c,modelRuntime:L.runtime}:c,re=process.hrtime.bigint(),D=await t.createAgentSessionFromServices({services:J,sessionManager:w.sessionManager,model:X,thinkingLevel:I,...Qr(o.tools,_t()),sessionStartEvent:w.sessionStartEvent});return a("broker.startup.session_from_services",re),Nr(D.session),Gt(D.session),L?.reveal(),{...D,services:c}},"buildForManager"),l=o.resumeSessionPath,v=o.forkFrom!==void 0&&o.forkFrom!=="";if(!v&&(l===void 0||l==="")&&o.resumeSessionId!==void 0&&o.resumeSessionId!=="")throw new Error(`[broker] resume requires a session .jsonl PATH; got only a bare id '${o.resumeSessionId}' (pi_session_file was never captured for this node)`);const E=!v&&l!==void 0&&l!=="",R=E&&o.newCycle===!0,x=E&&!R;let T;if(v)T=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(x||R){if(T=await t.SessionManager.open(l),R){const w=T.getLeafId();T.resetLeaf(),T.appendCustomEntry(he,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:w})}}else{const w=process.hrtime.bigint(),S=t.SessionManager.createAsync,c=(S!==void 0?S.call(t.SessionManager,o.cwd):Promise.resolve(t.SessionManager.create(o.cwd))).then(N=>(a("broker.startup.conversation_created",w),N));d=i({cwd:o.cwd,agentDir:b}),d.catch(()=>{});const k=process.hrtime.bigint();T=await c,await d,a("broker.startup.create_and_resources_joined",k)}if(t.createAgentSessionRuntime!==void 0){const w=r(async c=>{const k=await f({cwd:c.cwd,agentDir:c.agentDir,sessionManager:c.sessionManager,sessionStartEvent:c.sessionStartEvent});return{...k,diagnostics:k.services.diagnostics??[]}},"factory"),S=await t.createAgentSessionRuntime(w,{cwd:o.cwd,agentDir:b,sessionManager:T});return{session:S.session,services:S.services,resuming:x,runtime:S}}const q=await f({cwd:o.cwd,agentDir:b,sessionManager:T});return{session:q.session,services:q.services,resuming:x,runtime:void 0}}r(tn,"buildBrokerSession");function rn(t){const o=r((i,d,f,l)=>{if(l?.signal?.aborted)return Promise.resolve(i);const v=t.writable();return v.length===0?Promise.resolve(i):new Promise(E=>{let R;const x=r(()=>{R!==void 0&&clearTimeout(R),l?.signal?.removeEventListener("abort",T),t.pending.delete(d.id)},"cleanup"),T=r(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),E(i)},"onAbort");l?.signal?.addEventListener("abort",T,{once:!0});const q=l?.timeout!==void 0?l.timeout:Jr;R=setTimeout(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),E(i)},q),typeof R.unref=="function"&&R.unref(),t.pending.set(d.id,{request:d,resolve:r(w=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),E(f(w))},"resolve")});for(const w of v)t.forward(w,d)})},"dialogPromise"),a=r(()=>{},"noop");return{[rr]:t.onKnownStreamWait??(i=>()=>{}),get theme(){const i=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(i==null)throw new Error("Theme not initialized. Call initTheme() first.");return i},select:r((i,d,f)=>o(void 0,{type:"extension_ui_request",id:U(),method:"select",title:i,options:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,f),"select"),confirm:r((i,d,f)=>o(!1,{type:"extension_ui_request",id:U(),method:"confirm",title:i,message:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,f),"confirm"),input:r((i,d,f)=>o(void 0,{type:"extension_ui_request",id:U(),method:"input",title:i,placeholder:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,f),"input"),editor:r((i,d)=>o(void 0,{type:"extension_ui_request",id:U(),method:"editor",title:i,prefill:d},f=>"cancelled"in f&&f.cancelled?void 0:"value"in f?f.value:void 0),"editor"),setStatus:r((i,d)=>t.broadcast({type:"extension_ui_request",id:U(),method:"setStatus",statusKey:i,statusText:d}),"setStatus"),setWidget:r((i,d,f)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:U(),method:"setWidget",widgetKey:i,widgetLines:d,widgetPlacement:f?.placement})},"setWidget"),setTitle:r(i=>t.broadcast({type:"extension_ui_request",id:U(),method:"setTitle",title:i}),"setTitle"),notify:r((i,d)=>{const f=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:U(),method:"notify",message:i,notifyType:f})},"notify"),onTerminalInput:r(()=>a,"onTerminalInput"),setWorkingMessage:a,setWorkingVisible:a,setWorkingIndicator:a,setHiddenThinkingLabel:a,setFooter:a,setHeader:a,custom:r(()=>Promise.resolve(void 0),"custom"),pasteToEditor:a,setEditorText:a,getEditorText:r(()=>"","getEditorText"),addAutocompleteProvider:a,setEditorComponent:a,getEditorComponent:r(()=>{},"getEditorComponent"),getAllThemes:r(()=>[],"getAllThemes"),getTheme:r(()=>{},"getTheme"),setTheme:a,getToolsExpanded:r(()=>!1,"getToolsExpanded"),setToolsExpanded:a}}r(rn,"makeBrokerUiContext");export{yo as REVIEW_BOUNDARY_NAVIGATION_CODE,So as ReviewBoundaryNavigationError,Qr as brokerToolOptions,tn as buildBrokerSession,zr as disposeActiveSession,rn as makeBrokerUiContext,ho as runBroker,Se as snapshotMessages};
1
+ var ut=Object.defineProperty;var r=(t,o)=>ut(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as ft,envModelExact as pt,envModelIntent as Be,envNodeCwd as gt,envNodeId as vt,envProfileId as _t,envScopes as ht,scopeAllowed as bt}from"../../shared/env.js";import{createServer as wt}from"node:net";import{WebSocketServer as St,createWebSocketStream as yt}from"ws";import{BROKER_VIEW_PORT as Et}from"./view-socket.js";import{existsSync as $e,readFileSync as Rt,unlinkSync as ve,writeFileSync as kt}from"node:fs";import{join as Ke}from"node:path";import{randomUUID as U}from"node:crypto";import{mark as Ue}from"../timing.js";import{SUBMIT_RESULT_TOOL as Tt}from"./structured-output.js";import{conversationIdFromPath as Ct,flushConversation as _e,installSessionManagerStorePatch as At,readConversationAsync as Mt}from"../conversation-store/index.js";import{getAgentDir as ie,ModelRegistry as xt,ModelRuntime as Pt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as Ot,viewSocketPath as Nt}from"../canvas/paths.js";import{bindBrokerEventSource as Dt}from"../events/source.js";import{emitEvent as _,flushBrokerLog as We}from"../events/emit.js";import{operationIdContext as It}from"../events/operation-id.js";import{findMissingPackagePaths as Lt}from"./package-health.js";import{installBrokerConfigSnapshot as Ft}from"../config.js";import{FRONT_DOOR_ENV as Bt}from"./front-door.js";import{CANVAS_EXTENSIONS as he,piInvocationToSdkConfig as $t}from"./launch.js";import{setConversationRequestMark as Ge}from"../conversation-store/index.js";import{assertEngineVersion as Kt,loadBrokerEngine as Ut}from"./broker-sdk.js";import{initCrtrTheme as Wt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Gt}from"./pi-cli.js";import{captureSessionChatCapabilities as jt}from"./command-surface.js";import{InMemoryCredentialStore as Vt}from"@earendil-works/pi-ai";import{askGateway as qt,configureBrokerModelRuntime as Xt,refusalRetryAt as Yt}from"./broker/model-adapter.js";import{brokerApiUrl as Ht,brokerExecutionId as Jt,mutateBrokerFault as ae,recordBrokerTurn as je}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as zt}from"./launch-recipe.js";import{fetchRunAttachments as Ve}from"./broker/attachments-fetch.js";import{llmModelFor as Qt,modelRequestFromConfig as Zt,expandModelCandidates as er,parseModelSpec as tr,unregisteredConcreteModel as rr}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as nr}from"./stream-watchdog.js";import{CRTR_CYCLE_CUSTOM_TYPE as be,earlierCycleMessages as or,endedByAbort as sr,identifiedMessages as ir,welcomeWindow as ar,WELCOME_EARLIER_BYTES as dr,WELCOME_EARLIER_CYCLES as lr}from"./session-cycles.js";import{turnErrorOf as cr}from"../llm/refusal.js";import{projectTranscript as mr}from"./session-visibility.js";import{currentTurnVisibility as ur}from"./turn-visibility.js";import{isUnknownModel as we}from"./model-selection.js";import{BrokerClientRegistry as fr}from"./broker/client-registry.js";import{ToolGroupTracker as pr}from"./broker/tool-groups.js";import{TurnReplyTracker as gr}from"./broker/turn-replies.js";import{onNodeNamed as vr}from"./broker/node-named.js";import{FaultRetry as _r,willDaemonRetry as hr}from"./broker/fault-retry.js";import{RunTurnEnds as br}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as wr}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as Sr,BROKER_START_CYCLE as yr,BROKER_IDLE_TURN_START as Er,BROKER_RUN_TURN_BUSY as Rr,BROKER_RUN_STEER as kr}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as Tr}from"./broker/run-steer.js";import{prependRunDeferredMail as Cr,settleRunDeferredMail as Ar}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as Mr}from"./broker/run-turn-queue.js";import{EventProjection as xr}from"./broker/event-projection.js";import{createFrameDispatchContext as Pr,handleFrame as Or}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as Nr,installAdvertisedCommandInvocationContract as Dr}from"./advertised-command-invocation.js";import{RebindDriver as Ir}from"./broker/rebind.js";import{beginRuntimeTeardown as Lr}from"./broker/extension-abort.js";import{receiveNodeToken as Fr}from"./broker/node-token.js";import{serveCliRelay as Br}from"./broker/cli-relay.js";import{recordBrokerRelease as $r}from"./lifecycle.js";import{setTurnCauseSource as Kr}from"./broker/turn-cause.js";import{decodeKickoffOrigin as qe,KICKOFF_ORIGIN_ENV as Xe}from"./stamp/protocol.js";import{announceMessageOrigin as Ye}from"./stamp/channel.js";import{commitBrokerModel as Ur,recordConversationWriteFault as He}from"./broker/daemon-ops.js";import{bootExtensionState as Wr,holdStartupClaims as Gr,releaseStartupClaims as jr}from"./broker/boot-state.js";import{bindCarriedStart as Je,publishCarriedStart as Vr,startCycle as ze,takeCycleAttachments as Qe}from"./broker/cycle-start.js";import{composerNames as qr}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as Xr,FrameOverflowError as Yr,withoutImages as Ze,toolCallIds as Hr}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as yo,REVIEW_BOUNDARY_NAVIGATION_CODE as Eo}from"./broker/frame-replies.js";function Se(t){return new xt(t.modelRuntime)}r(Se,"registryOf");function J(t,o){if(t==null||we(t))return null;const a=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${a}`}r(J,"formatModelSpec");function Jr(t,o){const a=J(t,void 0);return a===null?null:`${a}:${o===void 0||o===""?"off":o}`}r(Jr,"formatExactModelSpec");const zr=12e4;let de=null;import{brokerSignalClient as V}from"./broker/signal-stream.js";function Qr(){V().stop();const t=de;if(de=null,t!==null)try{t.dispose()}catch{}}r(Qr,"disposeActiveSession");function Zr(t,o){const a=bt(o,"crtr:act")?void 0:["bash"],w=t!==void 0&&t.length>0?[...new Set([...t,Tt])]:t===void 0?void 0:[...t];return{...w!==void 0?{tools:w}:{},...a!==void 0?{excludeTools:a}:{}}}r(Zr,"brokerToolOptions");async function bo(t,o=process.hrtime.bigint(),a=new Date().toISOString()){Dt(t);const w=await Fr(),i=await Br(t,w);process.env.CRTR_API_SOCKET=i.path,It.fresh(()=>{_({level:"info",event:"broker.startup.cli_entry",ts:a,duration_ms:0,fields:{pid:process.pid,runtime_version:process.version,engine_version:null,model:null}}),_({level:"info",event:"broker.startup.module_loaded",duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:null,model:null}})});const d=new Set;let f=null;const l=r((e,n=null)=>{d.has(e)||(d.add(e),Ue(e,{duration_ms:Number(process.hrtime.bigint()-o)/1e6}),_({level:"info",event:e,duration_ms:Number(process.hrtime.bigint()-o)/1e6,fields:{runtime_version:process.version,engine_version:f,model:n}}))},"emitStartupMilestone"),v=r((e,n,s={})=>{const u=process.hrtime.bigint(),p=Number(u-n)/1e6,g=Number(u-o)/1e6;Ue(e,{duration_ms:p}),_({level:"info",event:e,duration_ms:p,fields:{at_ms:g,...s}})},"emitStartupStep");process.env[Bt]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,At(t),Ge(e=>v("broker.startup.conversation_request",process.hrtime.bigint()-BigInt(Math.round(e.durationMs*1e6)),{method:e.method,route:e.route,first_request:e.firstRequest,worker_age_ms:e.workerAgeMs}));const E=process.hrtime.bigint(),R=await Ut();v("broker.startup.engine_loaded",E);const x=process.hrtime.bigint();Kt(R.VERSION),v("broker.startup.version_checked",x),f=R.VERSION;const T=process.hrtime.bigint(),q=Ot(t),b=Ke(q,"broker-launch.json"),S=JSON.parse(Rt(b,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Ft(S.configSnapshot),S.start!==void 0){const{start:e,...n}=S;kt(b,JSON.stringify(n))}const c=$t(S);c.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT,v("broker.startup.launch_recipe_read",T);let k,N;const P=new AbortController,X=r(e=>{k!==void 0?k(e):(N??=e,P.abort())},"onSignal");process.on("SIGTERM",()=>X("SIGTERM")),process.on("SIGINT",()=>X("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&V().start(t,e)});const I=Nt(t),L=new Set;let z;try{$e(I)&&ve(I)}catch{}const te=r(()=>{try{ve(I)}catch{}},"removeViewSocket"),D=wt(e=>{if(z!==void 0){z(e);return}e.pause(),L.add(e),e.once("close",()=>L.delete(e)),e.on("error",()=>{})});await new Promise((e,n)=>{D.once("error",n),D.listen(I,()=>{D.off("error",n),e()})}),l("broker.startup.listening");const Q=process.hrtime.bigint();let Z;try{Z=await rn(R,c,(e,n)=>v(e,n))}catch(e){throw te(),e}let{session:C,services:F,resuming:on,runtime:rt}=Z;Ge(void 0),v("broker.startup.session_build",Q),l("broker.startup.session_built");const W=S.start;W!==void 0&&Gr();const ye=W===void 0?await ze(t,C,"startup",P.signal):Vr(t,W);P.signal.aborted&&(C.dispose(),te(),await We(),process.exit(0));const nt=ye?.names===void 0?await qr(t):ye.names,re=(await Wr(t)).node.review_binding?.review_id,G=ft();de=C;const ot=r(async()=>{const e=m.session().model;return e===void 0?{ok:!0}:await qt(Qt(`${e.provider}/${e.id}`,Be(),pt()))},"retryProbe");try{process.env.PI_PACKAGE_DIR=Gt(),Wt(F.settingsManager.getTheme(),ie(),!1)}catch(e){_({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of Lt(ie()))_({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const h=new fr(t),ne=new Map,B=new pr(t,e=>h.broadcast(e)),Y=new gr(t,e=>h.broadcast(e));vr(e=>h.broadcast({type:"node_named",...e}));let j=!1,Ee=!1,oe,Re,m,ee;const le=new br;let H,ke=r(()=>{},"notifyTurnAccepted"),Te=r(()=>{},"resetFrameState"),Ce=r(()=>{},"bindAnswered");const ce=wr(W===void 0?void 0:new Promise(e=>{Ce=e}));let Ae=r(()=>0,"pendingPromptDispatches"),Me;const $=Mr({runNode:G,session:r(()=>m.session(),"session"),isReplacing:r(()=>m.isReplacing(),"isReplacing"),pendingRebind:r(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:r(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:r(()=>Ae(),"pendingDispatches"),turnAdmission:ce,prependDeferred:r(e=>Cr(t,e),"prependDeferred"),onError:r(e=>_({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),xe=Tr($.steerable);globalThis[kr]=xe,Kr(()=>m.session());const Pe=$.drain;c.firstPrompt!==void 0&&c.firstPrompt!==""&&$.holdForKickoff(),globalThis[Er]=$.start,globalThis[Rr]=$.busy,m=new Ir({nodeId:t,cfg:c,session:C,services:F,runtime:rt,registry:h,toolGroups:B,turnReplies:Y,runSteer:xe,runNode:G,transcriptMessages:r(e=>me(e),"transcriptMessages"),uiContext:r(()=>Re,"uiContext"),faultRetry:r(()=>ee,"faultRetry"),projection:r(()=>H,"projection"),setActiveSession:r(e=>{if(de=e,Me?.(),G||process.env.CRTR_RUN_ID){let n="stop",s,u=!1;Me=e.subscribe(p=>{if(p.type==="agent_start"&&(n="stop",s=void 0,u=!1,le.started()),p.type==="agent_end"){const g=[...p.messages??[]].reverse().find(y=>y.role==="assistant");g&&(n=g.stopReason,s=sr(g)?void 0:cr(g,Yt(g)),u=g.role==="assistant"&&hr(g,e.model?.contextWindow))}p.type==="agent_settled"&&(le.settled(e.sessionManager,{stop_reason:n,...s?{error:s}:{}},u),G&&(_e().then(()=>Ar(t,e)).catch(async g=>{if(String(g?.message).startsWith("conversation_write_failed")){_({level:"error",event:"broker.exited",node_id:t,error:g,fields:{fault:"conversation_write_failed"}}),await He(t,g),M("conversation_write_failed",1);return}_({level:"error",event:"broker.run_deferred_mail.settle_failed",error:g})}),queueMicrotask(()=>{m.session()===e&&Pe()})))})}},"setActiveSession"),disposeAndExit:r((e,n)=>M(e,n),"disposeAndExit"),onSessionRebind:r(()=>{Te()},"onSessionRebind"),onReplacementIdle:r(()=>{G&&Pe()},"onReplacementIdle"),reWelcomeAll:r(()=>ue(),"reWelcomeAll")});const Oe=r(async(e,n=!1)=>{const s=m.session(),u=J(s.model,s.thinkingLevel);if(u===null)return null;const p=await Ur(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:n});return n&&(c.model=p.modelOverride,e!==void 0?(process.env.CRTR_MODEL_INTENT=`${e.family}/${e.strength}`,delete process.env.CRTR_MODEL_EXACT,c.modelExact=void 0):(delete process.env.CRTR_MODEL_INTENT,process.env.CRTR_MODEL_EXACT="1",c.modelExact=!0)),p.modelOverride},"persistModelChoice"),Ne=r(async(e=!0,n,s=!1)=>{const u=m.session(),p=J(u.model,u.thinkingLevel),g=e?await Oe(n,s):p;h.broadcast({type:"model_changed",model:we(u.model)?void 0:u.model,spec:g})},"broadcastModelChanged");ee=new _r({nodeId:t,cfg:c,retryProbe:ot,currentSession:r(()=>m.session(),"currentSession"),currentServices:r(()=>m.services(),"currentServices"),installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),registryOf:Se,formatModelSpec:J,broadcastModelChanged:Ne,turnAdmission:ce,reWelcomeAll:r(()=>ue(),"reWelcomeAll"),...G?{turnEnds:le}:{}});const De=r(()=>{ee.rearmIfStranded().catch(e=>{_({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry re-arm failed: ${e instanceof Error?e.message:String(e)}`}})})},"rearmStrandedRetry");V().subscribe("resync",De),V().subscribe("fault-retry",De),H=new xr({registry:h,faultRetry:ee,installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),currentSession:r(()=>m.session(),"currentSession"),notifyTurnAccepted:r(()=>ke(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:J});let se=[];const Ie=r(async e=>{se=[];const n=e.sessionManager.getEntries()[0],s=e.sessionManager.getSessionFile(),u=s===void 0?null:Ct(s);if(!(re!==void 0||n?.type!=="custom"||n.customType!==be||u===null))try{const{entries:p}=await Mt(u,{beforeCycle:dr});se=or(p,n,lr)}catch(p){_({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`earlier cycles read failed: ${String(p)}`}})}},"loadEarlierCycles"),st=Ie(C);function me(e){const n=et(e,re)?.map(({message:s})=>s)??e.sessionManager.buildSessionContext().messages;return[...se.map(({message:s})=>s),...n]}r(me,"turnSeedMessages");const it=r(e=>{const n=m.session(),s=et(n,re),u=s===void 0?void 0:[...se.map(A=>({...A,visibility:"visible"})),...s],p=u?.map(({message:A})=>A)??n.sessionManager.buildSessionContext().messages,{start:g}=ar(p,A=>JSON.stringify(Ze(A,t)).length),y=e.snapshotTail===void 0?g:Math.max(g,p.length-e.snapshotTail),K=u?.slice(y),ge=p.slice(y).map(A=>Ze(A,t)),ct=Hr(ge),mt=Object.fromEntries(Object.entries(B.summaries()).filter(([A])=>ct.has(A)));return{messages:ge,...K===void 0?{}:{messageIds:K.map(({id:A})=>A)},messageVisibility:K?.map(({visibility:A})=>A)??ge.map(()=>"visible"),turnVisibility:ur(),stats:n.getSessionStats(),state:{model:we(n.model)?void 0:n.model,thinkingLevel:n.thinkingLevel,isStreaming:n.isStreaming,isCompacting:n.isCompacting,steeringMode:n.steeringMode,followUpMode:n.followUpMode,sessionFile:n.sessionFile,sessionId:n.sessionId,sessionName:n.sessionName,autoCompactionEnabled:n.autoCompactionEnabled,messageCount:n.messages.length,pendingMessageCount:n.pendingMessageCount},display:{...h.displaySnapshot()},toolGroupSummaries:mt,turnReplies:Y.snapshot(),workingActivity:H.currentWorkingActivity(),queued:{steering:[...n.getSteeringMessages()],followUp:[...n.getFollowUpMessages()]}}},"buildSnapshot"),Le=r(e=>{const n=e.role==="controller"?ne.values().next().value:void 0;h.sendFrame(e,{type:"welcome",snapshot:it(e),role:e.role,pending_dialog:n!==void 0?n.request:null,agentDir:ie()})},"sendWelcome"),at=r(e=>{const n=[...ne.values()];for(let s=1;s<n.length;s++)h.sendFrame(e,n[s].request)},"replayExtraPendingDialogsTo"),ue=r(()=>{try{const e=m.session();Y.seed(me(e))}catch(e){_({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply reseed failed: ${String(e)}`}})}h.forEachHelloed(Le)},"reWelcomeAll"),Fe=r(async e=>{if(j)return;j=!0;const n=V().latestNode;n!==void 0&&(n.intent==="idle-release"||n.status==="done")&&$r(t,process.env.CRTR_EXECUTION_ID??null),V().stop(),e===0&&await _e().catch(async s=>{e=1,_({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"conversation_write_failed"}}),await He(t,s)}),B.persistPendingSummary(),H.dispose(),Qr();try{D?.close(),oe?.close()}catch{}i.close(),h.dispose();try{$e(I)&&ve(I)}catch{}h.clearAttachState(),await We(),process.exit(e)},"completeExit"),M=r((e,n=0)=>{if(j)return;const s=e==="shutdown-hook"||e==="shutdown-after-settle";if(s&&B.finishOpenToolGroup(!0),s&&(B.hasSummaryTasks()||Y.hasTasks())){if(Ee)return;Ee=!0,Promise.allSettled([B.waitForSummaryTasks(),Y.waitForTasks()]).finally(()=>Fe(n));return}Fe(n)},"disposeAndExit");globalThis[Sr]=M,Re=nn({writable:r(()=>h.writableClients(),"writable"),forward:r((e,n)=>h.sendFrame(e,n),"forward"),pending:ne,broadcast:r(e=>h.broadcastUi(e),"broadcast"),onKnownStreamWait:r(e=>H.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(C,F),l("broker.startup.extensions_bound");const O=Pr({nodeId:t,registry:h,toolGroups:B,projection:H,rebind:m,boundaryReviewId:re,pendingDialogs:ne,sendWelcome:Le,replayExtraPendingDialogsTo:at,reWelcomeAll:ue,disposeAndExit:M,persistModelChoice:Oe,broadcastModelChanged:Ne,registryOf:Se,formatModelSpec:J,formatExactModelSpec:Jr,turnAdmission:ce,memoryInventory:nt,runNode:G,onKickoffAdmitted:$.releaseKickoff});ke=O.notifyTurnAccepted,Te=O.resetForSession,Ae=O.pendingPromptDispatches,globalThis[yr]=async e=>{for(const y of zt){const K=e.env[y];K===void 0?delete process.env[y]:process.env[y]=K}process.env[Xe]=e.origin,e.messageIds.length>0?process.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(e.messageIds):delete process.env.CRTR_KICKOFF_MESSAGE_IDS,e.model!==void 0?c.model=e.model:delete c.model,e.modelExact?(c.modelExact=!0,process.env.CRTR_MODEL_EXACT="1"):(delete c.modelExact,delete process.env.CRTR_MODEL_EXACT),c.editorName=e.editorLabel,$.holdForKickoff(),B.finishOpenToolGroup(!0);const n=m.session(),s=n.sessionManager.getSessionFile();if(s===void 0||s==="")throw new Error("in-place cycle needs a persisted session file");const u=n.sessionManager,p=u.getLeafId();u.resetLeaf(),u.appendCustomEntry(be,{cycle:e.cycle,fromLeaf:p}),await _e(),m.beforeNextBind(async y=>{const[K]=await Promise.all([ze(t,y,"resume"),Ie(y)]);await O.refreshMemoryNames(K?.names)});const g=await m.runReplacement(null,"cycle",y=>y.switchSession(s));if(m.beforeNextBind(void 0),!g)return M("cycle-replacement-failed",1),!1;Ye(e.prompt,qe(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Ve(t,Qe(t))}catch(y){return _({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:y,fields:{operation:"attachments_fetch"}}),M("attachments-fetch-failed",1),!1}return O.kickoff(e.prompt,e.messageIds),!0};const dt=2500;let fe=!1;const lt=r(async e=>{if(j||fe)return;if(fe=!0,m.isAgentRunActive()||m.session().isStreaming||O.pendingPromptDispatches()>0){const s=Date.now()+dt;for(;O.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<s;)await new Promise(u=>setTimeout(u,25));if(m.session().isStreaming){const u=s-Date.now();if(u>0){let p;try{Lr(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(y=>{p=setTimeout(()=>y(!1),u)})])&&await je(t,{event:"closed",end_reason:"teardown-aborted"})}finally{p!==void 0&&clearTimeout(p)}}}else(O.pendingPromptDispatches()>0||m.isAgentRunActive())&&await je(t,{event:"interrupted"})}M(e)},"abortAndExit");if(k=r(e=>{lt(e)},"signalTeardown"),N!==void 0){k(N);return}const pe=r(e=>{l("broker.startup.first_viewer_connected");const n=h.create(e);e.on("data",u=>{let p;try{p=n.decoder.push(u)}catch(g){g instanceof Yr?(h.sendFrame(n,{type:"error",code:"frame_overflow",message:g.message}),h.dropClient(n,`frame overflow: ${g.message}`)):h.dropClient(n,`decoder error: ${String(g)}`);return}for(const g of p)try{Or(O,n,g)}catch{}});const s=r(()=>{h.removeClient(n)},"drop");e.on("close",s),e.on("error",()=>{})},"serveViewer");Ht()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(oe=new St({host:"::",port:Et,path:"/view",maxPayload:Xr.maxLineBytes}),oe.on("connection",e=>pe(yt(e))),oe.on("error",e=>{j||(_({level:"error",event:"broker.socket.failed",error:e}),M("socket-error",1))})),D.on("error",e=>{j||(_({level:"error",event:"broker.socket.failed",error:e}),M("socket-error",1))}),await st;try{Y.seed(me(m.session()))}catch(e){_({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`turn reply seed failed: ${String(e)}`}})}z=pe;for(const e of L)L.delete(e),pe(e),e.resume();(async()=>{if(Promise.all([ae(t,{op:"clear",link:"viewer\u2194broker"}),ae(t,{op:"clear",link:"relay\u2194broker"})]).catch(n=>_({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:n,fields:{operation:"broker_socket_bound_fault_clear"}})),W!==void 0){let n;try{try{n=await Je(t,m.session(),W)}catch(s){_({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:s,fields:{operation:"session_bound",attempt:1}}),n=await Je(t,m.session(),W)}}catch(s){_({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:s,fields:{operation:"session_bound",attempt:2}}),M("session-bound-failed",1);return}if(n?.action==="shutdown"){m.requestShutdown();return}if(n?.action==="relaunch_root")throw new Error("a startup bind never relaunches a root");V().start(t,Jt()),jr(),Ce()}l("broker.startup.ready_for_turn");let e;try{e=await ee.recoverOnStartup()}catch(n){_({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:n,fields:{operation:"recovery_startup"}}),M("recovery-startup-failed",1);return}if(!(j||fe))if(e==="none"&&c.firstPrompt!==void 0&&c.firstPrompt!==""){const n=qe(process.env[Xe]);n!==null&&Ye(c.firstPrompt,n);try{await Ve(t,Qe(t))}catch(u){_({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:u,fields:{operation:"attachments_fetch"}}),M("attachments-fetch-failed",1);return}const s=process.env.CRTR_KICKOFF_MESSAGE_IDS;O.kickoff(c.firstPrompt,s?JSON.parse(s):[])}else $.releaseKickoff()})(),h.persistAttachState()}r(bo,"runBroker");function et(t,o){const a=t.sessionManager,w=a.getEntries===void 0?void 0:ir(a.getEntries(),a.getLeafId?.());return w!==void 0&&Nr(w.map(({message:i})=>i)),w===void 0?void 0:mr(w,{boundaryReviewId:o,sessionEntries:a.getEntries?.()})}r(et,"snapshotMessages");function tt(){const t=vt();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}r(tt,"currentBrokerNodeId");async function en(t,o){const a=Zt(o.model,Be(),o.modelExact===!0);if(a===void 0)return;const w=Se(t),i={cwd:gt()??o.cwd,profileId:_t()},d=await rr(a,w,i);if(d!==void 0)throw await ae(tt(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`model '${d.request.spec}' is not registered in the serving model registry`}}),new Error(`[broker] FATAL: model '${d.request.spec}' is not registered in the serving model registry`);const f=await er(a,i.cwd,i.profileId),l=tr(a.spec);for(const v of f){const E=w.find(v.providerId,v.modelId);if(E===void 0)continue;const x=l?.providerId===v.providerId&&l.modelId===v.modelId?l.thinkingLevel??(v.thinkingLevel===void 0?void 0:"off"):v.thinkingLevel;return{model:E,thinkingLevel:x}}if(o.modelExact===!0){const v=f.map(E=>`'${E.providerId}/${E.modelId}' unregistered`).join("; ");throw await ae(tt(),{op:"record",input:{link:"crtr\u2192pi",op:"model resolution at launch",kind:"model-not-found",retry:{disposition:"fatal"},message:`exact-consult model '${o.model}' is unavailable \u2014 refusing to substitute (${v})`}}),new Error(`[broker] FATAL: exact-consult model '${o.model}' is unavailable`)}_({level:"warn",event:"broker.model.none_viable",fields:{rejected_candidates:f.map(v=>({provider:v.providerId,model:v.modelId,reason:"unregistered"})).slice(0,16)}})}r(en,"resolveLaunchModel");function tn(t){let o=!0;return{runtime:new Proxy(t,{get(w,i,d){return o&&i==="getAvailableSnapshot"?()=>[]:o&&i==="getAvailable"?async()=>[]:o&&i==="getModel"?()=>{}:Reflect.get(w,i,d)}}),reveal:r(()=>{o=!1},"reveal")}}r(tn,"modelLessRegistry");async function rn(t,o,a=()=>{}){const w=ie(),i=r(async b=>{const S=process.hrtime.bigint(),c=await Pt.create({credentials:new Vt,modelsPath:Ke(b.agentDir,"models.json")});Xt(c),a("broker.startup.model_runtime",S);const k=process.hrtime.bigint(),N=await t.createAgentSessionServices({cwd:b.cwd,agentDir:b.agentDir,modelRuntime:c,resourceLoaderOptions:{additionalExtensionPaths:o.extensionPaths,appendSystemPrompt:o.appendSystemPromptPath!==void 0?[o.appendSystemPromptPath]:void 0,noContextFiles:!0,extensionsOverride:r(P=>({...P,extensions:P.extensions.filter(X=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(X.path))}),"extensionsOverride")}});return a("broker.startup.resources_loaded",k),N},"loadServices");let d;const f=r(async b=>{const S=d;d=void 0;const c=await(S??i(b)),k=c.resourceLoader.getExtensions();if(o.extensionPaths.some(Q=>he.includes(Q))){const Q=new Set(k.extensions.map(C=>C.path)),Z=he.filter(C=>!Q.has(C));if(Z.length>0){const C=k.errors.filter(F=>he.includes(F.path)).map(F=>`${F.path}: ${F.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${Z.join(", ")}${C===""?"":` (${C})`}`)}}c.settingsManager.getRetryEnabled=()=>!1;const N=process.hrtime.bigint(),P=await en(c,o);a("broker.startup.model_resolved",N);const X=P?.model,I=P?.thinkingLevel,L=P===void 0?tn(c.modelRuntime):void 0,z=L!==void 0?{...c,modelRuntime:L.runtime}:c,te=process.hrtime.bigint(),D=await t.createAgentSessionFromServices({services:z,sessionManager:b.sessionManager,model:X,thinkingLevel:I,...Zr(o.tools,ht()),sessionStartEvent:b.sessionStartEvent});return a("broker.startup.session_from_services",te),Dr(D.session),jt(D.session),L?.reveal(),{...D,services:c}},"buildForManager"),l=o.resumeSessionPath,v=o.forkFrom!==void 0&&o.forkFrom!=="";if(!v&&(l===void 0||l==="")&&o.resumeSessionId!==void 0&&o.resumeSessionId!=="")throw new Error(`[broker] resume requires a session .jsonl PATH; got only a bare id '${o.resumeSessionId}' (pi_session_file was never captured for this node)`);const E=!v&&l!==void 0&&l!=="",R=E&&o.newCycle===!0,x=E&&!R;let T;if(v)T=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(x||R){if(T=await t.SessionManager.open(l),R){const b=T.getLeafId();T.resetLeaf(),T.appendCustomEntry(be,{cycle:Number(process.env.CRTR_CYCLES),fromLeaf:b})}}else{const b=process.hrtime.bigint(),S=t.SessionManager.createAsync,c=(S!==void 0?S.call(t.SessionManager,o.cwd):Promise.resolve(t.SessionManager.create(o.cwd))).then(N=>(a("broker.startup.conversation_created",b),N));d=i({cwd:o.cwd,agentDir:w}),d.catch(()=>{});const k=process.hrtime.bigint();T=await c,await d,a("broker.startup.create_and_resources_joined",k)}if(t.createAgentSessionRuntime!==void 0){const b=r(async c=>{const k=await f({cwd:c.cwd,agentDir:c.agentDir,sessionManager:c.sessionManager,sessionStartEvent:c.sessionStartEvent});return{...k,diagnostics:k.services.diagnostics??[]}},"factory"),S=await t.createAgentSessionRuntime(b,{cwd:o.cwd,agentDir:w,sessionManager:T});return{session:S.session,services:S.services,resuming:x,runtime:S}}const q=await f({cwd:o.cwd,agentDir:w,sessionManager:T});return{session:q.session,services:q.services,resuming:x,runtime:void 0}}r(rn,"buildBrokerSession");function nn(t){const o=r((i,d,f,l)=>{if(l?.signal?.aborted)return Promise.resolve(i);const v=t.writable();return v.length===0?Promise.resolve(i):new Promise(E=>{let R;const x=r(()=>{R!==void 0&&clearTimeout(R),l?.signal?.removeEventListener("abort",T),t.pending.delete(d.id)},"cleanup"),T=r(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),E(i)},"onAbort");l?.signal?.addEventListener("abort",T,{once:!0});const q=l?.timeout!==void 0?l.timeout:zr;R=setTimeout(()=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),E(i)},q),typeof R.unref=="function"&&R.unref(),t.pending.set(d.id,{request:d,resolve:r(b=>{x(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),E(f(b))},"resolve")});for(const b of v)t.forward(b,d)})},"dialogPromise"),a=r(()=>{},"noop");return{[nr]:t.onKnownStreamWait??(i=>()=>{}),get theme(){const i=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(i==null)throw new Error("Theme not initialized. Call initTheme() first.");return i},select:r((i,d,f)=>o(void 0,{type:"extension_ui_request",id:U(),method:"select",title:i,options:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,f),"select"),confirm:r((i,d,f)=>o(!1,{type:"extension_ui_request",id:U(),method:"confirm",title:i,message:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,f),"confirm"),input:r((i,d,f)=>o(void 0,{type:"extension_ui_request",id:U(),method:"input",title:i,placeholder:d,timeout:f?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,f),"input"),editor:r((i,d)=>o(void 0,{type:"extension_ui_request",id:U(),method:"editor",title:i,prefill:d},f=>"cancelled"in f&&f.cancelled?void 0:"value"in f?f.value:void 0),"editor"),setStatus:r((i,d)=>t.broadcast({type:"extension_ui_request",id:U(),method:"setStatus",statusKey:i,statusText:d}),"setStatus"),setWidget:r((i,d,f)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:U(),method:"setWidget",widgetKey:i,widgetLines:d,widgetPlacement:f?.placement})},"setWidget"),setTitle:r(i=>t.broadcast({type:"extension_ui_request",id:U(),method:"setTitle",title:i}),"setTitle"),notify:r((i,d)=>{const f=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:U(),method:"notify",message:i,notifyType:f})},"notify"),onTerminalInput:r(()=>a,"onTerminalInput"),setWorkingMessage:a,setWorkingVisible:a,setWorkingIndicator:a,setHiddenThinkingLabel:a,setFooter:a,setHeader:a,custom:r(()=>Promise.resolve(void 0),"custom"),pasteToEditor:a,setEditorText:a,getEditorText:r(()=>"","getEditorText"),addAutocompleteProvider:a,setEditorComponent:a,getEditorComponent:r(()=>{},"getEditorComponent"),getAllThemes:r(()=>[],"getAllThemes"),getTheme:r(()=>{},"getTheme"),setTheme:a,getToolsExpanded:r(()=>!1,"getToolsExpanded"),setToolsExpanded:a}}r(nn,"makeBrokerUiContext");export{Eo as REVIEW_BOUNDARY_NAVIGATION_CODE,yo as ReviewBoundaryNavigationError,Zr as brokerToolOptions,rn as buildBrokerSession,Qr as disposeActiveSession,nn as makeBrokerUiContext,bo as runBroker,et as snapshotMessages};
@@ -1,3 +1,3 @@
1
- var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as F,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as A,endLiveExecution as me,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as O}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as x,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function dr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}s(dr,"sessionHasConversation");async function mr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||H(i)}s(mr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await mr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await O(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const m=!k&&await n.reserveSlot(e);let o=null;if(m){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!m||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await me(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function pi(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"||r.cwd!==i.path))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(pi,"assertCheckoutNotRemoved");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await F(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(m&&(typeof o!="string"||!fe(o)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=m&&typeof o=="string";if(w&&!await re(o))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await F(e,{cycles:r.cycles});const S=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,S,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),$=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await dr(p.resumeSessionPath)?(await x(e))?.trim():void 0,T=$!==void 0&&$!=="",se=w||D||T,M=r.cycle_pending===!0||B;await F(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const ce=(await d().header(await d().fork(N,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)l=y(r,{...p,prompt:$}),h=C(),await V(l,r);else if(v)l=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await x(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await O(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,l,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await O(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
1
+ var le=Object.defineProperty;var s=(e,r)=>le(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as ue}from"./unsandboxed.js";import{existsSync as H}from"node:fs";import{conversationIdFromPath as _,conversationStore as d,ConversationNotFoundError as G}from"../conversation-store/index.js";import{isAbsolute as fe}from"node:path";import{findNodeBySessionFile as we,getNode as R,updateNode as F,beginExecution as he,ExecutionAlreadyLive as pe,recordExecutionPid as de,abortExecution as A,endLiveExecution as me,unbindSession as U,recordLaunch as ve,setFrozen as _e,clearFrozen as K,fullName as ye}from"../canvas/index.js";import{emitEvent as W}from"../events/emit.js";import{consumeDeadlineOnWake as ke}from"../feed/messages.js";import{isParked as J,transition as O}from"./lifecycle.js";import{publishNotice as ge}from"./close.js";import{InputError as E}from"../io.js";import{buildPiArgv as y}from"./launch.js";import{buildReviveKickoff as be,drainBearings as Re,hasRetainedReports as Ee,readGoal as x,readYieldMessage as xe,RUNTIME_RESTART_CONTINUATION as Se}from"./kickoff.js";import{readRoadmap as j}from"./roadmap.js";import{encodeKickoffOrigin as $e,KICKOFF_ORIGIN_ENV as Ce}from"./stamp/protocol.js";import{carryInitialInput as V}from"../runs/initial-input.js";import{headlessBrokerHost as Ne,brokerLaunchJson as Fe}from"./host.js";import{isCloudRole as Ae}from"../canvas/person.js";import{asNodePerson as Oe}from"../../daemon/reconcilers/node-lifecycle/node-person.js";import{processRunner as Pe}from"./runner/process.js";import{runnerForEnvironment as X}from"./runner/index.js";import{MachineOfflineError as Y}from"./runner/machine/ops.js";import{blaxelEnvironmentOf as q}from"./blaxel-environment.js";import{recordLaunchFailure as Be}from"../../daemon/reconcilers/node-lifecycle/launch-failure.js";import{acceptedRelease as Q,remoteMachineEnvironmentOf as De,checkBilledWake as Te,EnvironmentImagePending as Me,imageForWake as Le}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{ExecutionCapReached as ze,liveExecutionForNode as He,setExecutionLaunchJson as Ge}from"../canvas/executions.js";import{isDrained as Ue}from"../../daemon/drain.js";import{appMemoryFull as Ke,appMemoryTooSmall as We,boundFleet as Z,brokerCapReached as I,brokerThresholdsForDaemon as P}from"./fleet.js";import{admitBrokerMemory as Je}from"./memory-admission.js";import{beginBootFaultAttempt as je,clearFault as Ve,hasAdmittedTurn as Xe,readFault as Ye}from"../canvas/recovery.js";import{clearNodeLedger as ee,forkNodeLedger as qe,noticeChangedWhileDone as Qe}from"./ledger.js";import{forkSourceNode as Ze,rootOfSpine as Ie}from"./nodes.js";import{ApiError as er}from"../../api/errors.js";import{grantSnapshotMissing as rr}from"../../daemon/readiness.js";import{checkGrantActive as ir,checkStart as tr}from"./start-check.js";import{isReviewCompanionBound as nr}from"../review/companion.js";import{assertProfileActive as ar}from"../profiles/manifest.js";import{isPidAlive as or}from"../canvas/pid.js";import{crtrHome as sr,jobDir as cr}from"../canvas/paths.js";import{contextDir as lr,ensureNodeDirs as ur,nodeAgentDir as fr}from"../canvas/node-agent-paths.js";import{discoverLifecycleHookRegistry as wr}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as hr}from"../command-hooks/transport/exec-lifecycle.js";async function pr(e,r){const i=e.pi_session_file,t=i?_(i):null;if(t===null)return{};try{const n=await d().header(t);return r?{resumeSessionPath:n.path}:{resumeSessionPath:n.path,newCycle:!0}}catch(n){if(n instanceof G)return{};throw n}}s(pr,"resumeArgs");async function re(e){const r=_(e);if(r===null)return!1;try{return await d().header(r),!0}catch(i){if(i instanceof G)return!1;throw i}}s(re,"conversationExists");async function dr(e){const r=_(e);return r===null?!0:(await d().read(r)).entries.some(i=>i.type==="message")}s(dr,"sessionHasConversation");async function mr(e){const r=_(e);if(r===null)return!0;const i=(await d().header(r)).header.cwd;return typeof i!="string"||H(i)}s(mr,"sessionCwdExists");async function vr(e,r,i,t){const n=r.pi_session_file;if(!n||!await re(n))return{};const u=await we(n);return u!==null&&u.node_id!==e&&or(u.pi_pid)?{}:t&&!await mr(n)?{}:await pr(r,i)}s(vr,"resumableSessionArgs");async function _r(e){return await j(e)===null&&await xe(e)===null&&!await Ee(e)}s(_r,"isUnstartedBirth");async function fi(e){const r=await x(e);if(r!==null&&r.trim()!=="")return!0;const i=await j(e);return i!==null&&i.trim()!==""}s(fi,"hasFreshGroundState");async function wi(e,r){const i=await ie(e,r,!0);if(i.parked)throw new Error(`reviveNode: internal parked decision for activating revive ${e}`);return i.result}s(wi,"reviveNode");async function hi(e,r,i){return ie(e,{...r,viewerAttach:!0},i)}s(hi,"decideAttachRevive");async function ie(e,r,i){const t=Ae()?await R(e):null;return t===null?await te(e,r,i):await Oe({node_id:e,sub:t.sub??null,profile_id:t.profile_id??null},()=>te(e,r,i))}s(ie,"decideRevive");async function te(e,r,i){let t=await R(e);if(t===null)throw new Error(`reviveNode: unknown node ${e}`);if(t=await R(e)??t,t.run_id&&(await R(t.run_id))?.deleting_at)throw new Error("run is deleting");if(t.final_report!==null)throw new Error(`reviveNode: refusing to revive ${e} \u2014 its finalization latch is set (final_report=${t.final_report}). A final landed between the caller's reopen-gate check and this revive; re-run with --reopen if this retask is still wanted.`);ar(t.profile_id),ue(t.grantee);const n=Z(),u=t.grantee==="app:terminal"&&await rr();if(!await n.has(e)&&!await n.isClaimed(e)&&r.wakeReason!=="runtime-restart-abort"&&r.viewerAttach!==!0&&!(!i&&t.lifecycle==="resident"&&J(t))&&(await ir(t),await tr(t),await q(t.profile_id??null)!==null&&await Te(t)),await n.isClaimed(e))return await n.has(e)&&await O(e,t.intent==="refresh"?"refresh-launch":"revive"),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"already-live"}};if(!i&&t.lifecycle==="resident"&&J(t))return{parked:!0};if(u){if(r.capacity==="refuse")throw new er(503,"runtime_starting","the first grant snapshot from the directory has not committed");return await ne(e,t,{reason:"grant_snapshot"}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}const k=await Ue();if(k&&r.capacity==="refuse")throw new Error(`the daemon is drained for an import; ${e} cannot start until it ends`);const m=!k&&await n.reserveSlot(e);let o=null;if(m){try{o=await Je(e)}catch(w){throw n.releaseReservation(e),w}o.verdict!=="admitted"&&n.releaseReservation(e)}if(o?.verdict==="too_small")throw We(o);if(!m||o?.verdict==="denied"){if(r.capacity==="refuse")throw o?.verdict==="denied"?Ke(o):I(P().automaticReviveCap,await n.occupancy());return await ne(e,t,k?{reason:"drain"}:o?.verdict==="denied"?{reason:"app_memory",free_bytes:o.free_bytes,needed_bytes:o.needed_bytes}:{reason:"broker_cap",live_count:await n.occupancy(),hard_cap:P().automaticReviveCap}),{parked:!1,result:{window:null,session:t.tmux_session??null,resumed:!1,outcome:"frozen"}}}try{return{parked:!1,result:await gr(e,t,r)}}finally{n.releaseReservation(e)}}s(te,"decideReviveAsCaller");async function ne(e,r,i){r.frozen_at==null&&(await _e(e,new Date().toISOString()),await me(e,{reason:"frozen"}),W({level:"info",event:"broker.frozen",node_id:e,fields:i}))}s(ne,"freezeForWait");async function yr(e,r){const i=await q(r.profile_id??null),t=await De(r.profile_id??null)!==null;if(!(i!==null||t)&&!H(r.cwd)){const u=r.fork_from!=null?`Restore ${r.cwd}, then revive the fork normally with \`crtr node lifecycle revive ${e}\`.`:r.managed_worktree?.state==="open"?"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon recovery.":`Recreate ${r.cwd}, or repair it with \`crtr node config --cwd <path> --node ${e}\`; durable node work resumes in a fresh conversation. Then retry \`crtr node lifecycle revive ${e}\`.`;throw new E({error:"cwd_missing",message:`${e} cannot be revived \u2014 its recorded cwd no longer exists: ${r.cwd}`,next:u})}return{blaxelEnvironment:i,remoteMachine:t}}s(yr,"assertRecordedCwdExists");function pi(e,r){const i=r.managed_worktree;if(!(i?.state!=="closed"||i.cleanup!=="complete"))throw new E({error:"checkout_removed",message:`${e} cannot be revived \u2014 cleanup removed its checkout ${i.path} and branch ${i.branch}`,next:`Start a new node in ${i.repo_root}.`})}s(pi,"assertCheckoutNotRemoved");async function kr(e,r,i){const t=wr(r.cwd,r.profile_id).plans.get("node:start")??[];await hr(t,{node:{id:e,name:r.name,kind:r.kind,mode:r.mode,lifecycle:r.lifecycle,cwd:r.cwd,nodeDir:await fr(e),contextDir:await lr(e),jobDir:cr(e)},runtime:{isBirth:i,canvasHome:sr(),profile:r.profile_id??null}})}s(kr,"runNodeStartHooks");async function gr(e,r,i){const{blaxelEnvironment:t,remoteMachine:n}=await yr(e,r),u=t!==null||n;r.host_kind!=="broker"&&(await F(e,{host_kind:"broker"}),r.host_kind="broker"),r.review_binding!=null&&!await nr(e)&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);const m=r.fork_from!=null&&r.pi_session_id==null,o=r.fork_source_file;if(m&&(typeof o!="string"||!fe(o)))throw new E({error:"fork_source_invalid",message:`${e} cannot be revived \u2014 its resolved fork source file is missing or invalid.`,next:`Restore the node's fork source metadata, then retry \`crtr node lifecycle revive ${e}\`.`});const w=m&&typeof o=="string";if(w&&!await re(o))throw new E({error:"fork_from_missing",message:`${e} cannot be revived \u2014 its fork source no longer exists: ${o}`,next:`Restore ${o}, or update the node's fork source, then retry \`crtr node lifecycle revive ${e}\`.`});const{automaticReviveCap:ae}=P();if(t!==null){const c=await Le(t);if(c.state==="pending")throw new Me(t,c.error)}const oe=t!==null?X("blaxel"):n?X("machine"):Pe;let f;try{f=await he(e,{daemonEpoch:Z().epoch(),cap:ae,...t!==null?{runner:"blaxel",release:Q()}:n?{runner:"machine",release:Q()}:{}})}catch(c){if(c instanceof ze)throw I(c.cap,c.live);if(c instanceof pe)return{window:null,session:r.tmux_session??null,resumed:!1,outcome:"already-live"};throw c}try{r.cycles=(r.cycles??0)+1,await F(e,{cycles:r.cycles});const S=r.intent==="refresh"||r.cycle_pending===!0?!1:i.resume,p=w?{}:await vr(e,r,S,!u),g=p.resumeSessionPath!==void 0,B=g&&p.newCycle===!0,v=g&&!B,D=!g&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&await _r(e),$=v&&(i.wakeReason===void 0||i.wakeReason==="runtime-restart-abort")&&!await Xe(e)&&!await dr(p.resumeSessionPath)?(await x(e))?.trim():void 0,T=$!==void 0&&$!=="",se=w||D||T,M=r.cycle_pending===!0||B;await F(e,{cycle_pending:M}),r.cycle_pending=M,!w&&!g&&(r.pi_session_id!=null||r.pi_session_file!=null)&&(await U(e),r.pi_session_id=null,r.pi_session_file=null);let l,h=null;const C=s(()=>({type:"runtime",kind:"kickoff",...r.spawned_by!=null&&r.spawned_by!==""?{spawnedBy:r.spawned_by}:{}}),"birthOrigin");if(w){const a=await x(e),N=_(o);if(N===null)throw new Error(`invalid fork source ${o}`);const ce=(await d().header(await d().fork(N,e))).path;l=y(r,{resumeSessionPath:ce,...a!=null&&a!==""?{prompt:a}:{}}),a!=null&&a!==""&&(h=C()),await qe(e,(await Ze(o))?.node_id??null)}else if(T)l=y(r,{...p,prompt:$}),h=C(),await V(l,r);else if(v)l=y(r,{...p,...i.wakeReason==="runtime-restart-abort"?{prompt:Se}:{}}),i.wakeReason==="runtime-restart-abort"&&(h={type:"runtime",kind:"restart-continuation"});else if(D){const a=(await x(e))?.trim();l=y(r,a!==void 0&&a!==""?{prompt:a}:{}),a!==void 0&&a!==""&&(h=C(),await V(l,r)),await ee(e)}else{const a=await Re(r,f);l=y(r,{...p,prompt:await be(r,a,i.wakeReason==="runtime-restart-abort"?void 0:i.wakeReason)}),r.run_id&&a.unreadMessageIds?.length&&(l.env.CRTR_KICKOFF_MESSAGE_IDS=JSON.stringify(a.unreadMessageIds)),h=i.wakeReason!==void 0&&i.wakeReason!=="runtime-restart-abort"?{type:"runtime",kind:"wake",wake:i.wakeReason}:{type:"runtime",kind:"revive",cycle:r.cycles??0},await ee(e)}l.env={...l.env,CRTR_SUBTREE:await Ie(e)},h!==null&&(l.env[Ce]=$e(h)),r.status==="done"&&r.last_settled_at!=null&&await Qe(e,r.last_settled_at),await O(e,r.intent==="refresh"?"refresh-launch":"revive"),(await Ye(e))?.op!=="conversation_write_failed"&&await Ve(e,{preserveEpisode:!0});const L=await je(e);i.recovery!==!0&&i.viewerAttach!==!0&&await ke(e),await ur(e,r.grantee),await kr(e,r,se),l.env={...l.env,CRTR_EXECUTION_ID:f};const z=await Fe(e,l,r.cwd);await Ge(f,z);let b;try{const a=await He(e);if(b=await oe.start({executionId:f,nodeId:e,attempt:a?.attempt??1,release:a?.release??"",launchJson:z,cwd:r.cwd,resuming:v}),!u&&b.pid===null)throw new Error(`broker host returned no pid for ${e}`)}catch(a){if(a instanceof Y)throw a;try{await O(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:a instanceof Error?a.message:String(a)}}}),await ge(e,"notice.crash",`Child crashed \u2014 ${ye(r)} (${e}) failed to relaunch and is now dead: ${a.message}
2
2
 
3
3
  It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e})}catch{}throw await A(f,{reason:"launch_failed"}),new Error(`[broker] refusing to revive ${e}: ${a.message}`)}if(await ve(e,new Date().toISOString()),u)return await K(e),{window:null,session:r.tmux_session??null,resumed:v,faultExplanation:L.explanation,outcome:"launched"};if(await de(f,e,b.pid)==="shutdown")throw await A(f,{reason:"superseded"}),Ne.teardown(e),new Error(`[broker] refusing to revive ${e}: execution was superseded during launch`);return await K(e),{window:null,session:r.tmux_session??null,resumed:v,launch:b,faultExplanation:L.explanation,outcome:"launched"}}catch(c){throw c instanceof Y&&c.sent||(await A(f,{reason:"launch_failed"}),await Be(f,c).catch(S=>{W({level:"warn",event:"broker.launch_failure.unrecorded",node_id:e,error:S})})),c}}s(gr,"launchRevive");export{pi as assertCheckoutNotRemoved,yr as assertRecordedCwdExists,hi as decideAttachRevive,fi as hasFreshGroundState,pr as resumeArgs,wi as reviveNode,kr as runNodeStartHooks};
@@ -1,8 +1,8 @@
1
- var j=Object.defineProperty;var c=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as D,lstatSync as z,mkdirSync as W,readFileSync as J,readdirSync as X,readlinkSync as V,rmSync as Z,writeFileSync as b}from"node:fs";import{join as g,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",p="crtr",B="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
1
+ var j=Object.defineProperty;var l=(t,r)=>j(t,"name",{value:r,configurable:!0});import{spawn as q}from"node:child_process";import{constants as D,lstatSync as z,mkdirSync as W,readFileSync as J,readdirSync as X,readlinkSync as V,rmSync as Z,writeFileSync as b}from"node:fs";import{join as g,relative as Q}from"node:path";import{crc32 as tt,deflateRawSync as et}from"node:zlib";import{BlaxelApiError as rt}from"./client.js";const nt="public.ecr.aws/docker/library/node:24-alpine",ot="ghcr.io/blaxel-ai/sandbox:latest",c="crtr",B="/var/lib/crtr/recipe-pi-agent",st="blaxel.toml",it=`[build]
2
2
  slim = false
3
- `,at="1.1.0",_="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${p}/.local/share/pnpm/store`],G=c(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${p}/.npmrc`,"writeRunUserNpmrc"),R="repos",U="/work/.crtr/setup.log",M="/work/.crtr/setup-failed",C="/usr/local/bin/gh",lt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],N=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),pt=c(t=>(t??"").split(`
4
- `).map(r=>r.trim()).filter(r=>r!==""),"lines"),E=c((t,r)=>`RUN { ${r}; } >> ${U} 2>&1 || echo ${N(t)} "exited $?" >> ${M}`,"guarded");function ut(t,r,i=!1){const s=pt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${lt.map(N).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${p} -s /bin/sh ${p} && mkdir -p /work/.crtr ${B} && chown -R ${p} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${M} ${U}`,E("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${p} ${R}/ /work/`),s.length>0&&e.push(E("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work"),e.push(`RUN ${G()}`);for(const o of t.repositories)e.push(`RUN if [ -f /work/${o.name}/pnpm-lock.yaml ]; then cd /work/${o.name} && HOME=/home/${p} pnpm fetch >> ${U} 2>&1 || echo 'pnpm fetch ${o.name} failed' >> ${U}; fi`);for(const o of s)e.push(E(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${B} pi install ${N(o)}`));a&&e.push(E("setup script",`bash /tmp/${_}`)),e.push(E("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${p} /work /home/${p} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${p}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${p}:${p} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${G()} && chown ${p}:${p} /home/${p}/.npmrc`),e.push(`USER ${p}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
- `)}c(ut,"recipeDockerfile");const dt=c((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function _t(t){const r=t.git??dt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(g(t.dir,R),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),g(R,n.name)],a,t.dir)}b(g(t.dir,st),it),b(g(t.dir,"Dockerfile"),ut(t.recipe,t.revision,i!==null)),i!==null&&b(g(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
3
+ `,at="1.1.0",_="recipe-setup.sh",ct=["@northlight-systems:registry=https://npm.pkg.github.com","//npm.pkg.github.com/:_authToken=${NODE_AUTH_TOKEN}",`store-dir=/home/${c}/.local/share/pnpm/store`],G=l(()=>`printf '%s\\n' ${ct.map(t=>`'${t}'`).join(" ")} > /home/${c}/.npmrc`,"writeRunUserNpmrc"),R="repos",U="/work/.crtr/setup.log",M="/work/.crtr/setup-failed",C="/usr/local/bin/gh",lt=["#!/bin/sh",'token=$(printf "protocol=https\\nhost=github.com\\n\\n" | git credential fill 2>/dev/null | sed -n "s/^password=//p")','[ -n "$token" ] && export GH_TOKEN="$token"','exec /usr/bin/gh "$@"'],N=l(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),pt=l(t=>(t??"").split(`
4
+ `).map(r=>r.trim()).filter(r=>r!==""),"lines"),E=l((t,r)=>`RUN { ${r}; } >> ${U} 2>&1 || echo ${N(t)} "exited $?" >> ${M}`,"guarded");function ut(t,r,i=!1){const s=pt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${nt}`,"RUN apk add --no-cache bash git curl ripgrep github-cli",`RUN printf '%s\\n' ${lt.map(N).join(" ")} > ${C} && chmod 755 ${C}`,`COPY --from=${ot} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${c} -s /bin/sh ${c} && mkdir -p /work/.crtr ${B} && chown -R ${c} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${M} ${U}`,E("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${c} ${R}/ /work/`),s.length>0&&e.push(E("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${at}`)),a&&e.push(`COPY ${_} /tmp/${_}`),e.push("WORKDIR /work"),e.push(`RUN ${G()}`);for(const o of t.repositories)e.push(`RUN if [ -f /work/${o.name}/pnpm-lock.yaml ]; then cd /work/${o.name} && HOME=/home/${c} pnpm fetch >> ${U} 2>&1 || echo 'pnpm fetch ${o.name} failed' >> ${U}; chown -R ${c}:${c} /work/${o.name} /home/${c}; fi`);for(const o of s)e.push(E(`pi install ${o}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${B} pi install ${N(o)}`));a&&e.push(E("setup script",`bash /tmp/${_}`)),e.push(E("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${c} /work /home/${c} /var/lib/crtr`)),e.push("",...n);for(const o of["/work",`/home/${c}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${c}:${c} ${o} ${o}`);for(const o of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${o} ${o}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push("RUN rm -f /work/.npmrc",`RUN ${G()} && chown ${c}:${c} /home/${c}/.npmrc`),e.push(`USER ${c}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
5
+ `)}l(ut,"recipeDockerfile");const dt=l((t,r,i)=>new Promise((s,a)=>{const n=q("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",o=>{e+=o.toString()}),n.on("error",a),n.on("close",o=>{o===0?s():a(new Error(`git ${t[0]} failed (${o}): ${e.slice(0,300)}`))})}),"runGit");async function _t(t){const r=t.git??dt,i=t.packagesToken??null,s=t.cloneUrl??(n=>`https://github.com/${n}.git`);W(g(t.dir,R),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,s(n.github_full_name),g(R,n.name)],a,t.dir)}b(g(t.dir,st),it),b(g(t.dir,"Dockerfile"),ut(t.recipe,t.revision,i!==null)),i!==null&&b(g(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
6
6
  `,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&b(g(t.dir,_),t.recipe.setup_script.endsWith(`
7
7
  `)?t.recipe.setup_script:`${t.recipe.setup_script}
8
- `)}c(_t,"prepareBuildDir");function F(t,r,i){for(const s of X(r).sort()){const a=g(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(V(a)),mode:D.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:J(a),mode:D.S_IFREG|n.mode&511})}}c(F,"walk");function ht(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),$=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE($.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,$);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE($.length,20),l.writeUInt32LE(o.data.length,24),l.writeUInt16LE(d.length,28),l.writeUInt32LE(o.mode<<16>>>0,38),l.writeUInt32LE(a,42),s.push(l,d),a+=u.length+d.length+$.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(ht,"zipDirectory");async function k(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}c(k,"api");async function H(t,r){const{status:i,json:s}=await k(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}c(H,"getImage");async function Ut(t,r){await k(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(Ut,"deleteImage");const ft=60*6e4;async function xt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),$=c(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...$(o)),l=(await k(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ht(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=s.timeoutMs??ft,K=e+T;let O=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,y=$(f).filter(m=>m>I).sort((m,L)=>m-L);if(h==="BUILT"&&y.length>=2){O??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),L=y[0],S=c(w=>Date.parse(w??"")>=L,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),P=(A.length>0?A:v?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}c(xt,"buildImage");const Lt=c(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}c(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,ft as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,B as RECIPE_PI_AGENT_DIR,R as REPOS_DIR,p as RUN_USER,ct as RUN_USER_NPMRC,ot as SANDBOX_API_IMAGE,M as SETUP_FAILED_FILE,U as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,xt as buildImage,Ut as deleteImage,Lt as environmentImageName,H as getImage,_t as prepareBuildDir,ut as recipeDockerfile,Rt as removeBuildDir,ht as zipDirectory};
8
+ `)}l(_t,"prepareBuildDir");function F(t,r,i){for(const s of X(r).sort()){const a=g(r,s),n=z(a),e=Q(t,a).split("\\").join("/");n.isDirectory()?F(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(V(a)),mode:D.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:J(a),mode:D.S_IFREG|n.mode&511})}}l(F,"walk");function ht(t){const r=[];F(t,t,r);const i=[],s=[];let a=0;for(const o of r){const d=Buffer.from(o.name),$=et(o.data),I=tt(o.data),u=Buffer.alloc(30);u.writeUInt32LE(67324752,0),u.writeUInt16LE(20,4),u.writeUInt16LE(2048,6),u.writeUInt16LE(8,8),u.writeUInt32LE(33,12),u.writeUInt32LE(I,14),u.writeUInt32LE($.length,18),u.writeUInt32LE(o.data.length,22),u.writeUInt16LE(d.length,26),i.push(u,d,$);const p=Buffer.alloc(46);p.writeUInt32LE(33639248,0),p.writeUInt16LE(788,4),p.writeUInt16LE(20,6),p.writeUInt16LE(2048,8),p.writeUInt16LE(8,10),p.writeUInt32LE(33,14),p.writeUInt32LE(I,16),p.writeUInt32LE($.length,20),p.writeUInt32LE(o.data.length,24),p.writeUInt16LE(d.length,28),p.writeUInt32LE(o.mode<<16>>>0,38),p.writeUInt32LE(a,42),s.push(p,d),a+=u.length+d.length+$.length}const n=Buffer.concat(s),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}l(ht,"zipDirectory");async function k(t,r,i,s,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...s===void 0?{}:{body:JSON.stringify(s)}}),o=await e.text();let d=null;if(o!=="")try{d=JSON.parse(o)}catch{d={raw:o}}if(!e.ok&&!a.includes(e.status))throw new rt(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${o.slice(0,300)}`);return{status:e.status,headers:e.headers,json:d}}l(k,"api");async function H(t,r){const{status:i,json:s}=await k(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:s}l(H,"getImage");async function Ut(t,r){await k(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}l(Ut,"deleteImage");const ft=60*6e4;async function xt(t,r,i,s={}){const a=s.sleep??(f=>new Promise(h=>setTimeout(h,f))),n=s.now??Date.now,e=n(),o=await H(t,r),d=new Set((o?.spec?.tags??[]).map(f=>f.name)),$=l(f=>(f?.metadata?.events??[]).map(h=>Date.parse(h.time??"")).filter(h=>!Number.isNaN(h)),"eventTimes"),I=Math.max(-1/0,...$(o)),p=(await k(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const x=await(t.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(ht(i))});if(!x.ok)throw new Error(`uploading the build context of image ${r} failed (${x.status}): ${(await x.text()).slice(0,300)}`);const T=s.timeoutMs??ft,K=e+T;let O=null;for(;;){const f=await H(t,r),h=f?.metadata?.status,y=$(f).filter(m=>m>I).sort((m,L)=>m-L);if(h==="BUILT"&&y.length>=2){O??=n();const m=(f?.spec?.tags??[]).filter(w=>w.name!==void 0),L=y[0],S=l(w=>Date.parse(w??"")>=L,"touchedSince"),A=m.filter(w=>!d.has(w.name)||S(w.createdAt)||S(w.updatedAt)),v=n()-O>=(s.tagGraceMs??6e4),P=(A.length>0?A:v?m:[]).sort((w,Y)=>(Y.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(P!==void 0)return{ref:`sandbox/${r}:${P}`,buildMs:n()-e};if(v)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(h==="FAILED"||h==="TERMINATED"){const m=f?.metadata?.events??[];throw new Error(`building image ${r} ${h.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>K)throw new Error(`building image ${r} did not finish within ${T} ms (last status ${h??"none"})`);await a(s.pollMs??3e3)}}l(xt,"buildImage");const Lt=l(t=>`env-${t}`,"environmentImageName");function Rt(t){Z(t,{recursive:!0,force:!0})}l(Rt,"removeBuildDir");export{it as BLAXEL_TOML,st as BLAXEL_TOML_FILE,ft as BUILD_TIMEOUT_MS,C as GH_WRAPPER_PATH,nt as NODE_BASE_IMAGE,B as RECIPE_PI_AGENT_DIR,R as REPOS_DIR,c as RUN_USER,ct as RUN_USER_NPMRC,ot as SANDBOX_API_IMAGE,M as SETUP_FAILED_FILE,U as SETUP_LOG_FILE,_ as SETUP_SCRIPT_FILE,xt as buildImage,Ut as deleteImage,Lt as environmentImageName,H as getImage,_t as prepareBuildDir,ut as recipeDockerfile,Rt as removeBuildDir,ht as zipDirectory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.724",
3
+ "version": "0.3.725",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.724",
162
- "@north-light/plugin": "0.3.724",
161
+ "@north-light/identity": "0.3.725",
162
+ "@north-light/plugin": "0.3.725",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -371,7 +371,7 @@ export async function assertRecordedCwdExists(nodeId, meta) {
371
371
  /** Cleanup deleted this node's managed checkout and its branch, and nothing rebuilds them: refuse on any host, before a caller changes state. */
372
372
  export function assertCheckoutNotRemoved(nodeId, meta) {
373
373
  const worktree = meta.managed_worktree;
374
- if (worktree?.state !== 'closed' || worktree.cleanup !== 'complete' || meta.cwd !== worktree.path)
374
+ if (worktree?.state !== 'closed' || worktree.cleanup !== 'complete')
375
375
  return;
376
376
  throw new InputError({
377
377
  error: 'checkout_removed',
@@ -73,9 +73,10 @@ export function recipeDockerfile(recipe, revision, packagesToken = false) {
73
73
  out.push('WORKDIR /work');
74
74
  out.push(`RUN ${writeRunUserNpmrc()}`);
75
75
  // Warm the image's pnpm store from each repository's lockfile, so `pnpm install` in the sandbox links instead of downloading. A failed fetch only costs that
76
- // warmth, so it is logged and never refuses the sandbox start.
76
+ // warmth, so it is logged and never refuses the sandbox start. The fetch runs as root, so the repository and the store go back to the run user after it:
77
+ // a setup script's `su crtr -c 'pnpm install'` cannot replace a root-owned `node_modules/.modules.yaml`.
77
78
  for (const repo of recipe.repositories) {
78
- out.push(`RUN if [ -f /work/${repo.name}/pnpm-lock.yaml ]; then cd /work/${repo.name} && HOME=/home/${RUN_USER} pnpm fetch >> ${SETUP_LOG_FILE} 2>&1 || echo 'pnpm fetch ${repo.name} failed' >> ${SETUP_LOG_FILE}; fi`);
79
+ out.push(`RUN if [ -f /work/${repo.name}/pnpm-lock.yaml ]; then cd /work/${repo.name} && HOME=/home/${RUN_USER} pnpm fetch >> ${SETUP_LOG_FILE} 2>&1 || echo 'pnpm fetch ${repo.name} failed' >> ${SETUP_LOG_FILE}; chown -R ${RUN_USER}:${RUN_USER} /work/${repo.name} /home/${RUN_USER}; fi`);
79
80
  }
80
81
  for (const source of packages)
81
82
  out.push(guarded(`pi install ${source}`, `HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${RECIPE_PI_AGENT_DIR} pi install ${shellQuote(source)}`));
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.724",
3
+ "version": "0.3.725",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.724",
3
+ "version": "0.3.725",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.724",
3
+ "version": "0.3.725",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.724",
31
- "@north-light/identity": "0.3.724"
30
+ "@north-light/api": "0.3.725",
31
+ "@north-light/identity": "0.3.725"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.724",
3
+ "version": "0.3.725",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.724",
9
+ "version": "0.3.725",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.724",
32
- "@north-light/plugin": "0.3.724",
31
+ "@north-light/identity": "0.3.725",
32
+ "@north-light/plugin": "0.3.725",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.724",
11905
+ "version": "0.3.725",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.724",
11910
+ "version": "0.3.725",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.724",
11915
+ "version": "0.3.725",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.724",
11923
+ "version": "0.3.725",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.724",
11927
- "@north-light/identity": "0.3.724"
11926
+ "@north-light/api": "0.3.725",
11927
+ "@north-light/identity": "0.3.725"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.724",
11932
+ "version": "0.3.725",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.724",
11936
- "@north-light/identity": "0.3.724",
11937
- "@north-light/plugin": "0.3.724",
11935
+ "@north-light/api": "0.3.725",
11936
+ "@north-light/identity": "0.3.725",
11937
+ "@north-light/plugin": "0.3.725",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {