@north-light/cli 0.3.704 → 0.3.706
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/render/chat-view.d.ts +7 -60
- package/dist/clients/attach/render/chat-view.js +2 -4
- package/dist/clients/attach/viewer.js +537 -539
- package/dist/core/canvas/schema-pg/024-conversation-cycle-offset.sql +4 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +3 -3
- package/dist/core/conversation-store/patch.js +1 -1
- package/dist/core/conversation-store/row-store.js +13 -13
- package/dist/core/import/load/prepare.js +4 -4
- package/dist/core/runs/operations.js +6 -6
- package/dist/core/runtime/broker/tool-groups.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/node-read.js +3 -3
- package/dist/core/runtime/session-cycles.d.ts +5 -22
- package/dist/core/runtime/session-cycles.js +1 -1
- package/dist/core/user-settings.d.ts +0 -30
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +3 -3
- package/dist/daemon/machine-link/forward.d.ts +1 -1
- package/dist/daemon/machine-link/forward.js +1 -1
- package/dist/types.d.ts +0 -23
- package/dist/types.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +22 -261
- package/packages/crouter-api/dist/clients/attach/viewer.js +6 -5
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/config.js +2 -6
- package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/patch.js +8 -3
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +46 -19
- package/packages/crouter-api/dist/core/import/load/prepare.js +1 -1
- package/packages/crouter-api/dist/core/runs/operations.js +2 -2
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +27 -75
- package/packages/crouter-api/dist/core/user-settings.js +1 -43
- package/packages/crouter-api/dist/daemon/machine-link/forward.js +12 -8
- package/packages/crouter-api/dist/types.js +0 -7
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/clients/attach/render/condensed-history.d.ts +0 -21
- package/dist/clients/attach/render/condensed-history.js +0 -1
- package/packages/crouter-api/dist/clients/attach/render/condensed-history.js +0 -60
|
@@ -1 +1 @@
|
|
|
1
|
-
var T=Object.defineProperty;var m=(a,e)=>T(a,"name",{value:e,configurable:!0});import{existsSync as S,unlinkSync as p}from"node:fs";import{join as
|
|
1
|
+
var T=Object.defineProperty;var m=(a,e)=>T(a,"name",{value:e,configurable:!0});import{existsSync as S,unlinkSync as p}from"node:fs";import{join as h}from"node:path";import{nodeRunJobDir as y}from"../../canvas/paths.js";import{emitEvent as u}from"../../events/emit.js";import{atomicWriteJson as g,readJsonIfExists as d}from"../../fs-utils.js";import{assistantVisibleText as G,isGroupBoundaryKind as k,isTrueUserMessage as P,normalizeToolGroupSummaryRecord as _}from"../../../shared/tool-groups.js";import{generatedContextText as f,parseCard as b}from"../../../shared/generated-context.js";import{headlessToolGroupSummary as I,serializeToolGroup as w}from"../tool-group-summary.js";import{putBrokerSummaries as A}from"./summaries-post.js";const C=1e3,E=1e4;function c(a){if(a===null||typeof a!="object"||Array.isArray(a))return null;const e=a;return Object.keys(e).sort().join(",")!=="key,segment,version"||e.version!==1||typeof e.key!="string"||typeof e.segment!="string"||e.key.length===0||e.key.length>C||e.segment.length===0||e.segment.length>E?null:{version:1,key:e.key,segment:e.segment}}m(c,"normalizePendingToolGroupSummary");class U{static{m(this,"ToolGroupTracker")}nodeId;broadcast;toolSummariesPath;pendingToolSummaryPath;toolGroupSummaries=new Map;summaryAttempted;generatingToolGroups=new Map;toolGroupsByCallId=new Map;summaryTasks=new Set;openToolGroup;lastToolGroupBoundaryProse="";sawAssistantProse=!1;constructor(e,o){this.nodeId=e,this.broadcast=o,this.toolSummariesPath=h(y(e),"tool-summaries.json"),this.pendingToolSummaryPath=h(y(e),"pending-tool-summary.json");try{const t=d(this.toolSummariesPath);for(const[i,n]of Object.entries(_(t)))this.toolGroupSummaries.set(i,n)}catch{}this.summaryAttempted=new Set(this.toolGroupSummaries.keys()),this.resumePendingSummary()}postSummaries(e){A(this.nodeId,{tool_summaries:e}).catch(o=>{u({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`failed to post tool summaries: ${o instanceof Error?o.message:String(o)}`}})})}summaries(){return Object.fromEntries(this.toolGroupSummaries)}resetForSession(){this.openToolGroup=void 0,this.toolGroupsByCallId.clear(),this.sawAssistantProse=!1}finishOpenToolGroup(e=!1){const o=this.openToolGroup;if(this.openToolGroup=void 0,o!==void 0){if(o.closed=!0,e){for(const t of o.pendingToolIds)this.toolGroupsByCallId.delete(t);o.pendingToolIds.clear()}this.generateSettledToolGroup(o)}}observeToolGroupEvent(e){if(e.type==="compaction_end"||e.type==="auto_retry_end"&&e.success!==!0){this.finishOpenToolGroup();return}if(e.type==="message_end"){const s=e.message;if(s!==null&&typeof s=="object"){const r=s;r.role==="assistant"&&(r.stopReason==="aborted"||r.stopReason==="error")&&this.finishOpenToolGroup(!0)}return}if(e.type==="tool_execution_start"){const s=this.ensureOpenToolGroup(),r=typeof e.toolCallId=="string"?e.toolCallId:"";s.key===void 0&&r!==""&&(s.key=r),r!==""&&(s.pendingToolIds.add(r),this.toolGroupsByCallId.set(r,s)),s.toolCount+=1,s.pieces.push({type:"tool",name:typeof e.toolName=="string"?e.toolName:"tool",args:e.args});return}if(e.type==="tool_execution_end"){const s=typeof e.toolCallId=="string"?e.toolCallId:"",r=s===""?this.openToolGroup:this.toolGroupsByCallId.get(s);r!==void 0&&(r.pieces.push({type:"result",name:typeof e.toolName=="string"?e.toolName:"tool",result:e.result,isError:e.isError===!0}),s!==""&&(r.pendingToolIds.delete(s),this.toolGroupsByCallId.delete(s)),this.generateSettledToolGroup(r));return}if(e.type!=="message_start"&&e.type!=="message_update")return;const o=e.message;if(o===null||typeof o!="object")return;const t=o;if(t.role==="assistant"){e.type==="message_start"&&(this.sawAssistantProse=!1);const s=G(t);!this.sawAssistantProse&&s.trim()!==""&&(this.sawAssistantProse=!0,this.visibleBoundary(s));return}if(e.type!=="message_start")return;if(t.role==="compactionSummary"||t.role==="branchSummary"||t.role==="bashExecution"||t.role==="status"||t.role==="error"){this.finishOpenToolGroup();return}if(P(t)){this.visibleBoundary(f(t));return}if(t.display===!1)return;const i=f(t),n=b(t);if(n!==null&&k(n.kind)){this.visibleBoundary(i);return}const l=this.ensureOpenToolGroup();i!==""&&l.pieces.push({type:"text",text:i})}persistPendingSummary(){const e=[...this.generatingToolGroups.values()].at(-1);if(e!==void 0)try{g(this.pendingToolSummaryPath,e)}catch(o){u({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`failed to persist pending tool summary: ${o instanceof Error?o.message:String(o)}`}})}}hasSummaryTasks(){return this.summaryTasks.size>0}waitForSummaryTasks(){return Promise.allSettled([...this.summaryTasks])}ensureOpenToolGroup(){return this.openToolGroup===void 0&&(this.openToolGroup={toolCount:0,pieces:[],boundaryProse:this.lastToolGroupBoundaryProse,pendingToolIds:new Set,closed:!1}),this.openToolGroup}visibleBoundary(e){this.finishOpenToolGroup(),this.lastToolGroupBoundaryProse=e}clearPendingToolGroupSummary(e){try{const o=c(d(this.pendingToolSummaryPath));o?.key===e.key&&o.segment===e.segment&&p(this.pendingToolSummaryPath)}catch{}}generateToolGroupSummary(e){const{key:o,segment:t}=e;if(this.summaryAttempted.has(o)||this.generatingToolGroups.has(o))return;this.summaryAttempted.add(o),this.generatingToolGroups.set(o,e);let i;i=I(t).then(n=>{if(n!==null){this.toolGroupSummaries.set(o,n);try{const l=Object.fromEntries(this.toolGroupSummaries);g(this.toolSummariesPath,l),this.postSummaries(l)}catch{this.toolGroupSummaries.delete(o);return}this.clearPendingToolGroupSummary(e),this.broadcast({type:"tool_group_summary",key:o,summary:n})}}).catch(()=>{}).finally(()=>{this.generatingToolGroups.delete(o),this.summaryTasks.delete(i)}),this.summaryTasks.add(i)}generateSettledToolGroup(e){!e.closed||e.pendingToolIds.size>0||e.key===void 0||this.generateToolGroupSummary({version:1,key:e.key,segment:w(e.boundaryProse,e.pieces)})}resumePendingSummary(){try{const e=c(d(this.pendingToolSummaryPath));e===null?S(this.pendingToolSummaryPath)&&(p(this.pendingToolSummaryPath),u({level:"warn",event:"broker.startup.warning",fields:{stage:"pending_tool_summary",message:"removed an invalid pending tool summary"}})):this.toolGroupSummaries.has(e.key)?p(this.pendingToolSummaryPath):this.generateToolGroupSummary(e)}catch(e){u({level:"warn",event:"broker.startup.warning",fields:{stage:"pending_tool_summary",message:e instanceof Error?e.message:String(e)}})}}}export{U as ToolGroupTracker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var nt=Object.defineProperty;var r=(t,o)=>nt(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as ot,envModelIntent as st,envNodeCwd as it,envNodeId as at,envProfileId as dt,envScopes as lt,scopeAllowed as ct}from"../../shared/env.js";import{createServer as mt}from"node:net";import{WebSocketServer as ut,createWebSocketStream as ft}from"ws";import{BROKER_VIEW_PORT as pt}from"./view-socket.js";import{existsSync as De,readFileSync as gt,unlinkSync as fe,writeFileSync as vt}from"node:fs";import{join as Ie}from"node:path";import{randomUUID as U}from"node:crypto";import{mark as Fe}from"../timing.js";import{SUBMIT_RESULT_TOOL as _t}from"./structured-output.js";import{flushConversation as pe,installSessionManagerStorePatch as ht}from"../conversation-store/index.js";import{getAgentDir as se,ModelRegistry as bt,ModelRuntime as wt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as St,viewSocketPath as Rt}from"../canvas/paths.js";import{bindBrokerEventSource as yt}from"../events/source.js";import{emitEvent as h,flushBrokerLog as Le}from"../events/emit.js";import{operationIdContext as kt}from"../events/operation-id.js";import{findMissingPackagePaths as Et}from"./package-health.js";import{installBrokerConfigSnapshot as Tt}from"../config.js";import{FRONT_DOOR_ENV as Ct}from"./front-door.js";import{CANVAS_EXTENSIONS as ge,piInvocationToSdkConfig as At}from"./launch.js";import{setConversationRequestMark as Be}from"../conversation-store/index.js";import{assertEngineVersion as Mt,loadBrokerEngine as xt}from"./broker-sdk.js";import{initCrtrTheme as Pt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Ot}from"./pi-cli.js";import{captureSessionChatCapabilities as Nt}from"./command-surface.js";import{InMemoryCredentialStore as Dt}from"@earendil-works/pi-ai";import{configureBrokerModelRuntime as It,refusalRetryAt as Ft}from"./broker/model-adapter.js";import{brokerApiUrl as Lt,brokerExecutionId as Bt,mutateBrokerFault as ie,recordBrokerTurn as Ke}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Kt}from"./launch-recipe.js";import{fetchRunAttachments as Ue}from"./broker/attachments-fetch.js";import{modelRequestFromConfig as Ut,expandModelCandidates as $t,parseModelSpec as Wt,unregisteredConcreteModel as Gt}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as jt}from"./stream-watchdog.js";import{probeOnline as Vt}from"./connectivity.js";import{CRTR_CYCLE_CUSTOM_TYPE as $e,cycleAwareMessages as qt,endedByAbort as Xt}from"./session-cycles.js";import{turnErrorOf as Yt}from"../llm/refusal.js";import{projectTranscript as Ht}from"./session-visibility.js";import{currentTurnVisibility as Jt}from"./turn-visibility.js";import{isUnknownModel as ve}from"./model-selection.js";import{BrokerClientRegistry as zt}from"./broker/client-registry.js";import{ToolGroupTracker as Qt}from"./broker/tool-groups.js";import{TurnReplyTracker as Zt}from"./broker/turn-replies.js";import{onNodeNamed as er}from"./broker/node-named.js";import{FaultRetry as tr,willDaemonRetry as rr}from"./broker/fault-retry.js";import{RunTurnEnds as nr}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as or}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as sr,BROKER_START_CYCLE as ir,BROKER_IDLE_TURN_START as ar,BROKER_RUN_TURN_BUSY as dr,BROKER_RUN_STEER as lr}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as cr}from"./broker/run-steer.js";import{prependRunDeferredMail as mr,settleRunDeferredMail as ur}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as fr}from"./broker/run-turn-queue.js";import{EventProjection as pr}from"./broker/event-projection.js";import{createFrameDispatchContext as gr,handleFrame as vr}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as _r,installAdvertisedCommandInvocationContract as hr}from"./advertised-command-invocation.js";import{RebindDriver as br}from"./broker/rebind.js";import{beginRuntimeTeardown as wr}from"./broker/extension-abort.js";import{receiveNodeToken as Sr}from"./broker/node-token.js";import{serveCliRelay as Rr}from"./broker/cli-relay.js";import{recordBrokerRelease as yr}from"./lifecycle.js";import{setTurnCauseSource as kr}from"./broker/turn-cause.js";import{decodeKickoffOrigin as We,KICKOFF_ORIGIN_ENV as Ge}from"./stamp/protocol.js";import{announceMessageOrigin as je}from"./stamp/channel.js";import{commitBrokerModel as Er,recordConversationWriteFault as Ve}from"./broker/daemon-ops.js";import{bootExtensionState as Tr,holdStartupClaims as Cr,releaseStartupClaims as Ar}from"./broker/boot-state.js";import{bindCarriedStart as qe,publishCarriedStart as Mr,startCycle as Xe,takeCycleAttachments as Ye}from"./broker/cycle-start.js";import{composerNames as xr}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as Pr,FrameOverflowError as Or,normalizeSnapshotTail as Nr,withoutImages as Dr,toolCallIds as Ir}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as lo,REVIEW_BOUNDARY_NAVIGATION_CODE as co}from"./broker/frame-replies.js";function _e(t){return new bt(t.modelRuntime)}r(_e,"registryOf");function H(t,o){if(t==null||ve(t))return null;const i=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${i}`}r(H,"formatModelSpec");function Fr(t,o){const i=H(t,void 0);return i===null?null:`${i}:${o===void 0||o===""?"off":o}`}r(Fr,"formatExactModelSpec");const Lr=12e4;let ae=null;import{brokerSignalClient as j}from"./broker/signal-stream.js";function Br(){j().stop();const t=ae;if(ae=null,t!==null)try{t.dispose()}catch{}}r(Br,"disposeActiveSession");function Kr(t,o){const i=ct(o,"crtr:act")?void 0:["bash"],w=t!==void 0&&t.length>0?[...new Set([...t,_t])]:t===void 0?void 0:[...t];return{...w!==void 0?{tools:w}:{},...i!==void 0?{excludeTools:i}:{}}}r(Kr,"brokerToolOptions");async function so(t,o=process.hrtime.bigint(),i=new Date().toISOString()){yt(t);const w=await Sr(),s=await Rr(t,w);process.env.CRTR_API_SOCKET=s.path,kt.fresh(()=>{h({level:"info",event:"broker.startup.cli_entry",ts:i,duration_ms:0,fields:{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 p=null;const l=r((e,n=null)=>{d.has(e)||(d.add(e),Fe(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:p,model:n}}))},"emitStartupMilestone"),v=r((e,n,a={})=>{const u=process.hrtime.bigint(),g=Number(u-n)/1e6,f=Number(u-o)/1e6;Fe(e,{duration_ms:g}),h({level:"info",event:e,duration_ms:g,fields:{at_ms:f,...a}})},"emitStartupStep");process.env[Ct]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,ht(t),Be(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 y=process.hrtime.bigint(),k=await xt();v("broker.startup.engine_loaded",y);const M=process.hrtime.bigint();Mt(k.VERSION),v("broker.startup.version_checked",M),p=k.VERSION;const T=process.hrtime.bigint(),V=St(t),b=Ie(V,"broker-launch.json"),S=JSON.parse(gt(b,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Tt(S.configSnapshot),S.start!==void 0){const{start:e,...n}=S;vt(b,JSON.stringify(n))}const c=At(S);c.modelExact===!0?process.env.CRTR_MODEL_EXACT="1":delete process.env.CRTR_MODEL_EXACT,v("broker.startup.launch_recipe_read",T);let E,O;const x=new AbortController,q=r(e=>{E!==void 0?E(e):(O??=e,x.abort())},"onSignal");process.on("SIGTERM",()=>q("SIGTERM")),process.on("SIGINT",()=>q("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&j().start(t,e)});const I=Rt(t),F=new Set;let J;try{De(I)&&fe(I)}catch{}const te=r(()=>{try{fe(I)}catch{}},"removeViewSocket"),N=mt(e=>{if(J!==void 0){J(e);return}e.pause(),F.add(e),e.once("close",()=>F.delete(e)),e.on("error",()=>{})});await new Promise((e,n)=>{N.once("error",n),N.listen(I,()=>{N.off("error",n),e()})}),l("broker.startup.listening");const z=process.hrtime.bigint();let Q;try{Q=await Wr(k,c,(e,n)=>v(e,n))}catch(e){throw te(),e}let{session:C,services:L,resuming:jr,runtime:Je}=Q;Be(void 0),v("broker.startup.session_build",z),l("broker.startup.session_built");const $=S.start;$!==void 0&&Cr();const be=$===void 0?await Xe(t,C,"startup",x.signal):Mr(t,$);x.signal.aborted&&(C.dispose(),te(),await Le(),process.exit(0));const ze=be?.names===void 0?await xr(t):be.names,re=(await Tr(t)).node.review_binding?.review_id,W=ot();ae=C;const Qe=Vt;try{process.env.PI_PACKAGE_DIR=Ot(),Pt(L.settingsManager.getTheme(),se(),!1)}catch(e){h({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of Et(se()))h({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const _=new zt(t),ne=new Map,B=new Qt(t,e=>_.broadcast(e)),Z=new Zt(t,e=>_.broadcast(e));er(e=>_.broadcast({type:"node_named",...e}));let G=!1,we=!1,oe,Se,m,ee;const de=new nr;let X,Re=r(()=>{},"notifyTurnAccepted"),ye=r(()=>{},"resetFrameState"),ke=r(()=>{},"bindAnswered");const le=or($===void 0?void 0:new Promise(e=>{ke=e}));let Ee=r(()=>0,"pendingPromptDispatches"),Te;const K=fr({runNode:W,session:r(()=>m.session(),"session"),isReplacing:r(()=>m.isReplacing(),"isReplacing"),pendingRebind:r(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:r(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:r(()=>Ee(),"pendingDispatches"),turnAdmission:le,prependDeferred:r(e=>mr(t,e),"prependDeferred"),onError:r(e=>h({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),Ce=cr(K.steerable);globalThis[lr]=Ce,kr(()=>m.session());const Ae=K.drain;c.firstPrompt!==void 0&&c.firstPrompt!==""&&K.holdForKickoff(),globalThis[ar]=K.start,globalThis[dr]=K.busy,m=new br({nodeId:t,cfg:c,session:C,services:L,runtime:Je,registry:_,toolGroups:B,turnReplies:Z,runSteer:Ce,runNode:W,transcriptMessages:r(e=>he(e,re)?.map(({message:n})=>n)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:r(()=>Se,"uiContext"),faultRetry:r(()=>ee,"faultRetry"),projection:r(()=>X,"projection"),setActiveSession:r(e=>{if(ae=e,Te?.(),W||process.env.CRTR_RUN_ID){let n="stop",a,u=!1;Te=e.subscribe(g=>{if(g.type==="agent_start"&&(n="stop",a=void 0,u=!1,de.started()),g.type==="agent_end"){const f=[...g.messages??[]].reverse().find(R=>R.role==="assistant");f&&(n=f.stopReason,a=Xt(f)?void 0:Yt(f,Ft(f)),u=f.role==="assistant"&&rr(f,e.model?.contextWindow))}g.type==="agent_settled"&&(de.settled(e.sessionManager,{stop_reason:n,...a?{error:a}:{}},u),W&&(pe().then(()=>ur(t,e)).catch(async f=>{if(String(f?.message).startsWith("conversation_write_failed")){h({level:"error",event:"broker.exited",node_id:t,error:f,fields:{fault:"conversation_write_failed"}}),await Ve(t,f),A("conversation_write_failed",1);return}h({level:"error",event:"broker.run_deferred_mail.settle_failed",error:f})}),queueMicrotask(()=>{m.session()===e&&Ae()})))})}},"setActiveSession"),disposeAndExit:r((e,n)=>A(e,n),"disposeAndExit"),onSessionRebind:r(()=>{ye()},"onSessionRebind"),onReplacementIdle:r(()=>{W&&Ae()},"onReplacementIdle"),reWelcomeAll:r(()=>ce(),"reWelcomeAll")});const Me=r(async(e,n=!1)=>{const a=m.session(),u=H(a.model,a.thinkingLevel);if(u===null)return null;const g=await Er(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:n});return n&&(c.model=g.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)),g.modelOverride},"persistModelChoice"),xe=r(async(e=!0,n,a=!1)=>{const u=m.session(),g=H(u.model,u.thinkingLevel),f=e?await Me(n,a):g;_.broadcast({type:"model_changed",model:ve(u.model)?void 0:u.model,spec:f})},"broadcastModelChanged");ee=new tr({nodeId:t,cfg:c,retryProbe:Qe,currentSession:r(()=>m.session(),"currentSession"),currentServices:r(()=>m.services(),"currentServices"),installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),registryOf:_e,formatModelSpec:H,broadcastModelChanged:xe,turnAdmission:le,reWelcomeAll:r(()=>ce(),"reWelcomeAll"),...W?{turnEnds:de}:{}});const Pe=r(()=>{ee.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");j().subscribe("resync",Pe),j().subscribe("fault-retry",Pe),X=new pr({registry:_,faultRetry:ee,installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),currentSession:r(()=>m.session(),"currentSession"),notifyTurnAccepted:r(()=>Re(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:H});const Ze=r(e=>{const n=m.session(),a=he(n,re),u=Nr(e.snapshotTail),g=a?.slice(-u),f=(g?.map(({message:D})=>D)??n.sessionManager.buildSessionContext().messages.slice(-u)).map(D=>Dr(D,t)),R=Ir(f),Y=Object.fromEntries(Object.entries(B.summaries()).filter(([D])=>R.has(D)));return{messages:f,...g===void 0?{}:{messageIds:g.map(({id:D})=>D)},messageVisibility:g?.map(({visibility:D})=>D)??f.map(()=>"visible"),turnVisibility:Jt(),stats:n.getSessionStats(),state:{model:ve(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:Y,turnReplies:Z.snapshot(),workingActivity:X.currentWorkingActivity(),queued:{steering:[...n.getSteeringMessages()],followUp:[...n.getFollowUpMessages()]}}},"buildSnapshot"),Oe=r(e=>{const n=e.role==="controller"?ne.values().next().value:void 0;_.sendFrame(e,{type:"welcome",snapshot:Ze(e),role:e.role,pending_dialog:n!==void 0?n.request:null,agentDir:se()})},"sendWelcome"),et=r(e=>{const n=[...ne.values()];for(let a=1;a<n.length;a++)_.sendFrame(e,n[a].request)},"replayExtraPendingDialogsTo"),ce=r(()=>{try{const e=m.session();Z.seed(he(e,re)?.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(Oe)},"reWelcomeAll"),Ne=r(async e=>{if(G)return;G=!0;const n=j().latestNode;n!==void 0&&(n.intent==="idle-release"||n.status==="done")&&yr(t,process.env.CRTR_EXECUTION_ID??null),j().stop(),e===0&&await pe().catch(async a=>{e=1,h({level:"error",event:"broker.exited",node_id:t,error:a,fields:{fault:"conversation_write_failed"}}),await Ve(t,a)}),B.persistPendingSummary(),X.dispose(),Br();try{N?.close(),oe?.close()}catch{}s.close(),_.dispose();try{De(I)&&fe(I)}catch{}_.clearAttachState(),await Le(),process.exit(e)},"completeExit"),A=r((e,n=0)=>{if(G)return;const a=e==="shutdown-hook"||e==="shutdown-after-settle";if(a&&B.finishOpenToolGroup(!0),a&&(B.hasSummaryTasks()||Z.hasTasks())){if(we)return;we=!0,Promise.allSettled([B.waitForSummaryTasks(),Z.waitForTasks()]).finally(()=>Ne(n));return}Ne(n)},"disposeAndExit");globalThis[sr]=A,Se=Gr({writable:r(()=>_.writableClients(),"writable"),forward:r((e,n)=>_.sendFrame(e,n),"forward"),pending:ne,broadcast:r(e=>_.broadcastUi(e),"broadcast"),onKnownStreamWait:r(e=>X.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(C,L),l("broker.startup.extensions_bound");const P=gr({nodeId:t,registry:_,toolGroups:B,projection:X,rebind:m,boundaryReviewId:re,pendingDialogs:ne,sendWelcome:Oe,replayExtraPendingDialogsTo:et,reWelcomeAll:ce,disposeAndExit:A,persistModelChoice:Me,broadcastModelChanged:xe,registryOf:_e,formatModelSpec:H,formatExactModelSpec:Fr,turnAdmission:le,memoryInventory:ze,runNode:W,onKickoffAdmitted:K.releaseKickoff});Re=P.notifyTurnAccepted,ye=P.resetForSession,Ee=P.pendingPromptDispatches,globalThis[ir]=async e=>{for(const R of Kt){const Y=e.env[R];Y===void 0?delete process.env[R]:process.env[R]=Y}process.env[Ge]=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(),a=n.sessionManager.getSessionFile();if(a===void 0||a==="")throw new Error("in-place cycle needs a persisted session file");const u=n.sessionManager,g=u.getLeafId();u.resetLeaf(),u.appendCustomEntry($e,{cycle:e.cycle,fromLeaf:g}),await pe(),m.beforeNextBind(async R=>{const Y=await Xe(t,R,"resume");await P.refreshMemoryNames(Y?.names)});const f=await m.runReplacement(null,"cycle",R=>R.switchSession(a));if(m.beforeNextBind(void 0),!f)return A("cycle-replacement-failed",1),!1;je(e.prompt,We(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Ue(t,Ye(t))}catch(R){return h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:R,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1),!1}return P.kickoff(e.prompt,e.messageIds),!0};const tt=2500;let me=!1;const rt=r(async e=>{if(G||me)return;if(me=!0,m.isAgentRunActive()||m.session().isStreaming||P.pendingPromptDispatches()>0){const a=Date.now()+tt;for(;P.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<a;)await new Promise(u=>setTimeout(u,25));if(m.session().isStreaming){const u=a-Date.now();if(u>0){let g;try{wr(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(R=>{g=setTimeout(()=>R(!1),u)})])&&await Ke(t,{event:"closed",end_reason:"teardown-aborted"})}finally{g!==void 0&&clearTimeout(g)}}}else(P.pendingPromptDispatches()>0||m.isAgentRunActive())&&await Ke(t,{event:"interrupted"})}A(e)},"abortAndExit");if(E=r(e=>{rt(e)},"signalTeardown"),O!==void 0){E(O);return}const ue=r(e=>{l("broker.startup.first_viewer_connected");const n=_.create(e);e.on("data",u=>{let g;try{g=n.decoder.push(u)}catch(f){f instanceof Or?(_.sendFrame(n,{type:"error",code:"frame_overflow",message:f.message}),_.dropClient(n,`frame overflow: ${f.message}`)):_.dropClient(n,`decoder error: ${String(f)}`);return}for(const f of g)try{vr(P,n,f)}catch{}});const a=r(()=>{_.removeClient(n)},"drop");e.on("close",a),e.on("error",()=>{})},"serveViewer");Lt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(oe=new ut({host:"::",port:pt,path:"/view",maxPayload:Pr.maxLineBytes}),oe.on("connection",e=>ue(ft(e))),oe.on("error",e=>{G||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))})),N.on("error",e=>{G||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))}),J=ue;for(const e of F)F.delete(e),ue(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"}})),$!==void 0){let n;try{try{n=await qe(t,m.session(),$)}catch(a){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:1}}),n=await qe(t,m.session(),$)}}catch(a){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:2}}),A("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");j().start(t,Bt()),Ar(),ke()}l("broker.startup.ready_for_turn");let e;try{e=await ee.recoverOnStartup()}catch(n){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:n,fields:{operation:"recovery_startup"}}),A("recovery-startup-failed",1);return}if(!(G||me))if(e==="none"&&c.firstPrompt!==void 0&&c.firstPrompt!==""){const n=We(process.env[Ge]);n!==null&&je(c.firstPrompt,n);try{await Ue(t,Ye(t))}catch(u){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:u,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1);return}const a=process.env.CRTR_KICKOFF_MESSAGE_IDS;P.kickoff(c.firstPrompt,a?JSON.parse(a):[])}else K.releaseKickoff()})(),_.persistAttachState()}r(so,"runBroker");function he(t,o){const i=t.sessionManager,w=qt(i);return w!==void 0&&_r(w.map(({message:s})=>s)),w===void 0?void 0:Ht(w,{boundaryReviewId:o,sessionEntries:i.getEntries?.()})}r(he,"snapshotMessages");function He(){const t=at();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}r(He,"currentBrokerNodeId");async function Ur(t,o){const i=Ut(o.model,st(),o.modelExact===!0);if(i===void 0)return;const w=_e(t),s={cwd:it()??o.cwd,profileId:dt()},d=await Gt(i,w,s);if(d!==void 0)throw await ie(He(),{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 p=await $t(i,s.cwd,s.profileId),l=Wt(i.spec);for(const v of p){const y=w.find(v.providerId,v.modelId);if(y===void 0)continue;const M=l?.providerId===v.providerId&&l.modelId===v.modelId?l.thinkingLevel??(v.thinkingLevel===void 0?void 0:"off"):v.thinkingLevel;return{model:y,thinkingLevel:M}}if(o.modelExact===!0){const v=p.map(y=>`'${y.providerId}/${y.modelId}' unregistered`).join("; ");throw await ie(He(),{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:p.map(v=>({provider:v.providerId,model:v.modelId,reason:"unregistered"})).slice(0,16)}})}r(Ur,"resolveLaunchModel");function $r(t){let o=!0;return{runtime:new Proxy(t,{get(w,s,d){return o&&s==="getAvailableSnapshot"?()=>[]:o&&s==="getAvailable"?async()=>[]:o&&s==="getModel"?()=>{}:Reflect.get(w,s,d)}}),reveal:r(()=>{o=!1},"reveal")}}r($r,"modelLessRegistry");async function Wr(t,o,i=()=>{}){const w=se(),s=r(async b=>{const S=process.hrtime.bigint(),c=await wt.create({credentials:new Dt,modelsPath:Ie(b.agentDir,"models.json")});It(c),i("broker.startup.model_runtime",S);const E=process.hrtime.bigint(),O=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(x=>({...x,extensions:x.extensions.filter(q=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(q.path))}),"extensionsOverride")}});return i("broker.startup.resources_loaded",E),O},"loadServices");let d;const p=r(async b=>{const S=d;d=void 0;const c=await(S??s(b)),E=c.resourceLoader.getExtensions();if(o.extensionPaths.some(z=>ge.includes(z))){const z=new Set(E.extensions.map(C=>C.path)),Q=ge.filter(C=>!z.has(C));if(Q.length>0){const C=E.errors.filter(L=>ge.includes(L.path)).map(L=>`${L.path}: ${L.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${Q.join(", ")}${C===""?"":` (${C})`}`)}}c.settingsManager.getRetryEnabled=()=>!1;const O=process.hrtime.bigint(),x=await Ur(c,o);i("broker.startup.model_resolved",O);const q=x?.model,I=x?.thinkingLevel,F=x===void 0?$r(c.modelRuntime):void 0,J=F!==void 0?{...c,modelRuntime:F.runtime}:c,te=process.hrtime.bigint(),N=await t.createAgentSessionFromServices({services:J,sessionManager:b.sessionManager,model:q,thinkingLevel:I,...Kr(o.tools,lt()),sessionStartEvent:b.sessionStartEvent});return i("broker.startup.session_from_services",te),hr(N.session),Nt(N.session),F?.reveal(),{...N,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 y=!v&&l!==void 0&&l!=="",k=y&&o.newCycle===!0,M=y&&!k;let T;if(v)T=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(M||k){if(T=await t.SessionManager.open(l),k){const b=T.getLeafId();T.resetLeaf(),T.appendCustomEntry($e,{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(O=>(i("broker.startup.conversation_created",b),O));d=s({cwd:o.cwd,agentDir:w}),d.catch(()=>{});const E=process.hrtime.bigint();T=await c,await d,i("broker.startup.create_and_resources_joined",E)}if(t.createAgentSessionRuntime!==void 0){const b=r(async c=>{const E=await p({cwd:c.cwd,agentDir:c.agentDir,sessionManager:c.sessionManager,sessionStartEvent:c.sessionStartEvent});return{...E,diagnostics:E.services.diagnostics??[]}},"factory"),S=await t.createAgentSessionRuntime(b,{cwd:o.cwd,agentDir:w,sessionManager:T});return{session:S.session,services:S.services,resuming:M,runtime:S}}const V=await p({cwd:o.cwd,agentDir:w,sessionManager:T});return{session:V.session,services:V.services,resuming:M,runtime:void 0}}r(Wr,"buildBrokerSession");function Gr(t){const o=r((s,d,p,l)=>{if(l?.signal?.aborted)return Promise.resolve(s);const v=t.writable();return v.length===0?Promise.resolve(s):new Promise(y=>{let k;const M=r(()=>{k!==void 0&&clearTimeout(k),l?.signal?.removeEventListener("abort",T),t.pending.delete(d.id)},"cleanup"),T=r(()=>{M(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(s)},"onAbort");l?.signal?.addEventListener("abort",T,{once:!0});const V=l?.timeout!==void 0?l.timeout:Lr;k=setTimeout(()=>{M(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(s)},V),typeof k.unref=="function"&&k.unref(),t.pending.set(d.id,{request:d,resolve:r(b=>{M(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(p(b))},"resolve")});for(const b of v)t.forward(b,d)})},"dialogPromise"),i=r(()=>{},"noop");return{[jt]:t.onKnownStreamWait??(s=>()=>{}),get theme(){const s=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(s==null)throw new Error("Theme not initialized. Call initTheme() first.");return s},select:r((s,d,p)=>o(void 0,{type:"extension_ui_request",id:U(),method:"select",title:s,options:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,p),"select"),confirm:r((s,d,p)=>o(!1,{type:"extension_ui_request",id:U(),method:"confirm",title:s,message:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,p),"confirm"),input:r((s,d,p)=>o(void 0,{type:"extension_ui_request",id:U(),method:"input",title:s,placeholder:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,p),"input"),editor:r((s,d)=>o(void 0,{type:"extension_ui_request",id:U(),method:"editor",title:s,prefill:d},p=>"cancelled"in p&&p.cancelled?void 0:"value"in p?p.value:void 0),"editor"),setStatus:r((s,d)=>t.broadcast({type:"extension_ui_request",id:U(),method:"setStatus",statusKey:s,statusText:d}),"setStatus"),setWidget:r((s,d,p)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:U(),method:"setWidget",widgetKey:s,widgetLines:d,widgetPlacement:p?.placement})},"setWidget"),setTitle:r(s=>t.broadcast({type:"extension_ui_request",id:U(),method:"setTitle",title:s}),"setTitle"),notify:r((s,d)=>{const p=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:U(),method:"notify",message:s,notifyType:p})},"notify"),onTerminalInput:r(()=>i,"onTerminalInput"),setWorkingMessage:i,setWorkingVisible:i,setWorkingIndicator:i,setHiddenThinkingLabel:i,setFooter:i,setHeader:i,custom:r(()=>Promise.resolve(void 0),"custom"),pasteToEditor:i,setEditorText:i,getEditorText:r(()=>"","getEditorText"),addAutocompleteProvider:i,setEditorComponent:i,getEditorComponent:r(()=>{},"getEditorComponent"),getAllThemes:r(()=>[],"getAllThemes"),getTheme:r(()=>{},"getTheme"),setTheme:i,getToolsExpanded:r(()=>!1,"getToolsExpanded"),setToolsExpanded:i}}r(Gr,"makeBrokerUiContext");export{co as REVIEW_BOUNDARY_NAVIGATION_CODE,lo as ReviewBoundaryNavigationError,Kr as brokerToolOptions,Wr as buildBrokerSession,Br as disposeActiveSession,Gr as makeBrokerUiContext,so as runBroker,he as snapshotMessages};
|
|
1
|
+
var nt=Object.defineProperty;var r=(t,o)=>nt(t,"name",{value:o,configurable:!0});import{envInboxBetweenTurns as ot,envModelIntent as st,envNodeCwd as it,envNodeId as at,envProfileId as dt,envScopes as lt,scopeAllowed as ct}from"../../shared/env.js";import{createServer as mt}from"node:net";import{WebSocketServer as ut,createWebSocketStream as ft}from"ws";import{BROKER_VIEW_PORT as pt}from"./view-socket.js";import{existsSync as De,readFileSync as gt,unlinkSync as fe,writeFileSync as vt}from"node:fs";import{join as Ie}from"node:path";import{randomUUID as U}from"node:crypto";import{mark as Fe}from"../timing.js";import{SUBMIT_RESULT_TOOL as _t}from"./structured-output.js";import{flushConversation as pe,installSessionManagerStorePatch as ht}from"../conversation-store/index.js";import{getAgentDir as se,ModelRegistry as bt,ModelRuntime as wt}from"@earendil-works/pi-coding-agent";import{nodeRunDir as St,viewSocketPath as Rt}from"../canvas/paths.js";import{bindBrokerEventSource as yt}from"../events/source.js";import{emitEvent as h,flushBrokerLog as Le}from"../events/emit.js";import{operationIdContext as Et}from"../events/operation-id.js";import{findMissingPackagePaths as kt}from"./package-health.js";import{installBrokerConfigSnapshot as Tt}from"../config.js";import{FRONT_DOOR_ENV as Ct}from"./front-door.js";import{CANVAS_EXTENSIONS as ge,piInvocationToSdkConfig as At}from"./launch.js";import{setConversationRequestMark as Be}from"../conversation-store/index.js";import{assertEngineVersion as Mt,loadBrokerEngine as xt}from"./broker-sdk.js";import{initCrtrTheme as Pt}from"./crtr-theme.js";import{resolveBundledPiPackageDir as Ot}from"./pi-cli.js";import{captureSessionChatCapabilities as Nt}from"./command-surface.js";import{InMemoryCredentialStore as Dt}from"@earendil-works/pi-ai";import{configureBrokerModelRuntime as It,refusalRetryAt as Ft}from"./broker/model-adapter.js";import{brokerApiUrl as Lt,brokerExecutionId as Bt,mutateBrokerFault as ie,recordBrokerTurn as Ke}from"./broker/daemon-ops.js";import{CYCLE_APPLIED_ENV as Kt}from"./launch-recipe.js";import{fetchRunAttachments as Ue}from"./broker/attachments-fetch.js";import{modelRequestFromConfig as Ut,expandModelCandidates as $t,parseModelSpec as Wt,unregisteredConcreteModel as Gt}from"../model-routes.js";import{KNOWN_STREAM_WAIT_UI as jt}from"./stream-watchdog.js";import{probeOnline as Vt}from"./connectivity.js";import{CRTR_CYCLE_CUSTOM_TYPE as $e,endedByAbort as qt,identifiedMessages as Xt}from"./session-cycles.js";import{turnErrorOf as Yt}from"../llm/refusal.js";import{projectTranscript as Ht}from"./session-visibility.js";import{currentTurnVisibility as Jt}from"./turn-visibility.js";import{isUnknownModel as ve}from"./model-selection.js";import{BrokerClientRegistry as zt}from"./broker/client-registry.js";import{ToolGroupTracker as Qt}from"./broker/tool-groups.js";import{TurnReplyTracker as Zt}from"./broker/turn-replies.js";import{onNodeNamed as er}from"./broker/node-named.js";import{FaultRetry as tr,willDaemonRetry as rr}from"./broker/fault-retry.js";import{RunTurnEnds as nr}from"./broker/run-turn-end.js";import{createTurnAdmissionGate as or}from"./broker/turn-admission.js";import{BROKER_DISPOSE_AND_EXIT as sr,BROKER_START_CYCLE as ir,BROKER_IDLE_TURN_START as ar,BROKER_RUN_TURN_BUSY as dr,BROKER_RUN_STEER as lr}from"./broker/held-deferred-inbox.js";import{createRunSteerBridge as cr}from"./broker/run-steer.js";import{prependRunDeferredMail as mr,settleRunDeferredMail as ur}from"./broker/run-deferred-mail.js";import{createRunTurnQueue as fr}from"./broker/run-turn-queue.js";import{EventProjection as pr}from"./broker/event-projection.js";import{createFrameDispatchContext as gr,handleFrame as vr}from"./broker/frame-dispatch.js";import{hydratePersistedAdvertisedCommandMessages as _r,installAdvertisedCommandInvocationContract as hr}from"./advertised-command-invocation.js";import{RebindDriver as br}from"./broker/rebind.js";import{beginRuntimeTeardown as wr}from"./broker/extension-abort.js";import{receiveNodeToken as Sr}from"./broker/node-token.js";import{serveCliRelay as Rr}from"./broker/cli-relay.js";import{recordBrokerRelease as yr}from"./lifecycle.js";import{setTurnCauseSource as Er}from"./broker/turn-cause.js";import{decodeKickoffOrigin as We,KICKOFF_ORIGIN_ENV as Ge}from"./stamp/protocol.js";import{announceMessageOrigin as je}from"./stamp/channel.js";import{commitBrokerModel as kr,recordConversationWriteFault as Ve}from"./broker/daemon-ops.js";import{bootExtensionState as Tr,holdStartupClaims as Cr,releaseStartupClaims as Ar}from"./broker/boot-state.js";import{bindCarriedStart as qe,publishCarriedStart as Mr,startCycle as Xe,takeCycleAttachments as Ye}from"./broker/cycle-start.js";import{composerNames as xr}from"./broker/frame-memory-refs.js";import{BROKER_READ_CAPS as Pr,FrameOverflowError as Or,normalizeSnapshotTail as Nr,withoutImages as Dr,toolCallIds as Ir}from"./broker-protocol.js";import{ReviewBoundaryNavigationError as lo,REVIEW_BOUNDARY_NAVIGATION_CODE as co}from"./broker/frame-replies.js";function _e(t){return new bt(t.modelRuntime)}r(_e,"registryOf");function H(t,o){if(t==null||ve(t))return null;const i=o!==void 0&&o!==""&&o!=="off"?`:${o}`:"";return`${t.provider}/${t.id}${i}`}r(H,"formatModelSpec");function Fr(t,o){const i=H(t,void 0);return i===null?null:`${i}:${o===void 0||o===""?"off":o}`}r(Fr,"formatExactModelSpec");const Lr=12e4;let ae=null;import{brokerSignalClient as j}from"./broker/signal-stream.js";function Br(){j().stop();const t=ae;if(ae=null,t!==null)try{t.dispose()}catch{}}r(Br,"disposeActiveSession");function Kr(t,o){const i=ct(o,"crtr:act")?void 0:["bash"],w=t!==void 0&&t.length>0?[...new Set([...t,_t])]:t===void 0?void 0:[...t];return{...w!==void 0?{tools:w}:{},...i!==void 0?{excludeTools:i}:{}}}r(Kr,"brokerToolOptions");async function so(t,o=process.hrtime.bigint(),i=new Date().toISOString()){yt(t);const w=await Sr(),s=await Rr(t,w);process.env.CRTR_API_SOCKET=s.path,Et.fresh(()=>{h({level:"info",event:"broker.startup.cli_entry",ts:i,duration_ms:0,fields:{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 p=null;const l=r((e,n=null)=>{d.has(e)||(d.add(e),Fe(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:p,model:n}}))},"emitStartupMilestone"),v=r((e,n,a={})=>{const u=process.hrtime.bigint(),g=Number(u-n)/1e6,f=Number(u-o)/1e6;Fe(e,{duration_ms:g}),h({level:"info",event:e,duration_ms:g,fields:{at_ms:f,...a}})},"emitStartupStep");process.env[Ct]="1",process.env.CRTR_BROKER_PID=String(process.pid),delete process.env.TMUX_PANE,delete process.env.TMUX,ht(t),Be(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 y=process.hrtime.bigint(),E=await xt();v("broker.startup.engine_loaded",y);const M=process.hrtime.bigint();Mt(E.VERSION),v("broker.startup.version_checked",M),p=E.VERSION;const T=process.hrtime.bigint(),V=St(t),b=Ie(V,"broker-launch.json"),S=JSON.parse(gt(b,"utf8"));if(!S.configSnapshot)throw new Error("broker launch is missing its config snapshot");if(Tt(S.configSnapshot),S.start!==void 0){const{start:e,...n}=S;vt(b,JSON.stringify(n))}const c=At(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,O;const x=new AbortController,q=r(e=>{k!==void 0?k(e):(O??=e,x.abort())},"onSignal");process.on("SIGTERM",()=>q("SIGTERM")),process.on("SIGINT",()=>q("SIGINT")),process.on("SIGUSR1",()=>{const e=process.env.CRTR_EXECUTION_ID;e!==void 0&&e!==""&&j().start(t,e)});const I=Rt(t),F=new Set;let J;try{De(I)&&fe(I)}catch{}const te=r(()=>{try{fe(I)}catch{}},"removeViewSocket"),N=mt(e=>{if(J!==void 0){J(e);return}e.pause(),F.add(e),e.once("close",()=>F.delete(e)),e.on("error",()=>{})});await new Promise((e,n)=>{N.once("error",n),N.listen(I,()=>{N.off("error",n),e()})}),l("broker.startup.listening");const z=process.hrtime.bigint();let Q;try{Q=await Wr(E,c,(e,n)=>v(e,n))}catch(e){throw te(),e}let{session:C,services:L,resuming:jr,runtime:Je}=Q;Be(void 0),v("broker.startup.session_build",z),l("broker.startup.session_built");const $=S.start;$!==void 0&&Cr();const be=$===void 0?await Xe(t,C,"startup",x.signal):Mr(t,$);x.signal.aborted&&(C.dispose(),te(),await Le(),process.exit(0));const ze=be?.names===void 0?await xr(t):be.names,re=(await Tr(t)).node.review_binding?.review_id,W=ot();ae=C;const Qe=Vt;try{process.env.PI_PACKAGE_DIR=Ot(),Pt(L.settingsManager.getTheme(),se(),!1)}catch(e){h({level:"error",event:"broker.theme.initialization_failed",error:e})}try{for(const e of kt(se()))h({level:"warn",event:"broker.startup.warning",fields:{stage:"package_health",source:e.source,resolved_path:e.resolved}})}catch{}const _=new zt(t),ne=new Map,B=new Qt(t,e=>_.broadcast(e)),Z=new Zt(t,e=>_.broadcast(e));er(e=>_.broadcast({type:"node_named",...e}));let G=!1,we=!1,oe,Se,m,ee;const de=new nr;let X,Re=r(()=>{},"notifyTurnAccepted"),ye=r(()=>{},"resetFrameState"),Ee=r(()=>{},"bindAnswered");const le=or($===void 0?void 0:new Promise(e=>{Ee=e}));let ke=r(()=>0,"pendingPromptDispatches"),Te;const K=fr({runNode:W,session:r(()=>m.session(),"session"),isReplacing:r(()=>m.isReplacing(),"isReplacing"),pendingRebind:r(()=>m.pendingRebind(),"pendingRebind"),isAgentRunActive:r(()=>m.isAgentRunActive(),"isAgentRunActive"),pendingDispatches:r(()=>ke(),"pendingDispatches"),turnAdmission:le,prependDeferred:r(e=>mr(t,e),"prependDeferred"),onError:r(e=>h({level:"error",event:"broker.inbox.idle_prompt_failed",error:e}),"onError")}),Ce=cr(K.steerable);globalThis[lr]=Ce,Er(()=>m.session());const Ae=K.drain;c.firstPrompt!==void 0&&c.firstPrompt!==""&&K.holdForKickoff(),globalThis[ar]=K.start,globalThis[dr]=K.busy,m=new br({nodeId:t,cfg:c,session:C,services:L,runtime:Je,registry:_,toolGroups:B,turnReplies:Z,runSteer:Ce,runNode:W,transcriptMessages:r(e=>he(e,re)?.map(({message:n})=>n)??e.sessionManager.buildSessionContext().messages,"transcriptMessages"),uiContext:r(()=>Se,"uiContext"),faultRetry:r(()=>ee,"faultRetry"),projection:r(()=>X,"projection"),setActiveSession:r(e=>{if(ae=e,Te?.(),W||process.env.CRTR_RUN_ID){let n="stop",a,u=!1;Te=e.subscribe(g=>{if(g.type==="agent_start"&&(n="stop",a=void 0,u=!1,de.started()),g.type==="agent_end"){const f=[...g.messages??[]].reverse().find(R=>R.role==="assistant");f&&(n=f.stopReason,a=qt(f)?void 0:Yt(f,Ft(f)),u=f.role==="assistant"&&rr(f,e.model?.contextWindow))}g.type==="agent_settled"&&(de.settled(e.sessionManager,{stop_reason:n,...a?{error:a}:{}},u),W&&(pe().then(()=>ur(t,e)).catch(async f=>{if(String(f?.message).startsWith("conversation_write_failed")){h({level:"error",event:"broker.exited",node_id:t,error:f,fields:{fault:"conversation_write_failed"}}),await Ve(t,f),A("conversation_write_failed",1);return}h({level:"error",event:"broker.run_deferred_mail.settle_failed",error:f})}),queueMicrotask(()=>{m.session()===e&&Ae()})))})}},"setActiveSession"),disposeAndExit:r((e,n)=>A(e,n),"disposeAndExit"),onSessionRebind:r(()=>{ye()},"onSessionRebind"),onReplacementIdle:r(()=>{W&&Ae()},"onReplacementIdle"),reWelcomeAll:r(()=>ce(),"reWelcomeAll")});const Me=r(async(e,n=!1)=>{const a=m.session(),u=H(a.model,a.thinkingLevel);if(u===null)return null;const g=await kr(t,{spec:u,...e!==void 0?{intent:e}:{},userSelected:n});return n&&(c.model=g.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)),g.modelOverride},"persistModelChoice"),xe=r(async(e=!0,n,a=!1)=>{const u=m.session(),g=H(u.model,u.thinkingLevel),f=e?await Me(n,a):g;_.broadcast({type:"model_changed",model:ve(u.model)?void 0:u.model,spec:f})},"broadcastModelChanged");ee=new tr({nodeId:t,cfg:c,retryProbe:Qe,currentSession:r(()=>m.session(),"currentSession"),currentServices:r(()=>m.services(),"currentServices"),installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),registryOf:_e,formatModelSpec:H,broadcastModelChanged:xe,turnAdmission:le,reWelcomeAll:r(()=>ce(),"reWelcomeAll"),...W?{turnEnds:de}:{}});const Pe=r(()=>{ee.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");j().subscribe("resync",Pe),j().subscribe("fault-retry",Pe),X=new pr({registry:_,faultRetry:ee,installedGeneration:r(()=>m.installedGeneration(),"installedGeneration"),currentSession:r(()=>m.session(),"currentSession"),notifyTurnAccepted:r(()=>Re(),"notifyTurnAccepted"),emitStartupMilestone:l,formatModelSpec:H});const Ze=r(e=>{const n=m.session(),a=he(n,re),u=Nr(e.snapshotTail),g=a?.slice(-u),f=(g?.map(({message:D})=>D)??n.sessionManager.buildSessionContext().messages.slice(-u)).map(D=>Dr(D,t)),R=Ir(f),Y=Object.fromEntries(Object.entries(B.summaries()).filter(([D])=>R.has(D)));return{messages:f,...g===void 0?{}:{messageIds:g.map(({id:D})=>D)},messageVisibility:g?.map(({visibility:D})=>D)??f.map(()=>"visible"),turnVisibility:Jt(),stats:n.getSessionStats(),state:{model:ve(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:Y,turnReplies:Z.snapshot(),workingActivity:X.currentWorkingActivity(),queued:{steering:[...n.getSteeringMessages()],followUp:[...n.getFollowUpMessages()]}}},"buildSnapshot"),Oe=r(e=>{const n=e.role==="controller"?ne.values().next().value:void 0;_.sendFrame(e,{type:"welcome",snapshot:Ze(e),role:e.role,pending_dialog:n!==void 0?n.request:null,agentDir:se()})},"sendWelcome"),et=r(e=>{const n=[...ne.values()];for(let a=1;a<n.length;a++)_.sendFrame(e,n[a].request)},"replayExtraPendingDialogsTo"),ce=r(()=>{try{const e=m.session();Z.seed(he(e,re)?.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(Oe)},"reWelcomeAll"),Ne=r(async e=>{if(G)return;G=!0;const n=j().latestNode;n!==void 0&&(n.intent==="idle-release"||n.status==="done")&&yr(t,process.env.CRTR_EXECUTION_ID??null),j().stop(),e===0&&await pe().catch(async a=>{e=1,h({level:"error",event:"broker.exited",node_id:t,error:a,fields:{fault:"conversation_write_failed"}}),await Ve(t,a)}),B.persistPendingSummary(),X.dispose(),Br();try{N?.close(),oe?.close()}catch{}s.close(),_.dispose();try{De(I)&&fe(I)}catch{}_.clearAttachState(),await Le(),process.exit(e)},"completeExit"),A=r((e,n=0)=>{if(G)return;const a=e==="shutdown-hook"||e==="shutdown-after-settle";if(a&&B.finishOpenToolGroup(!0),a&&(B.hasSummaryTasks()||Z.hasTasks())){if(we)return;we=!0,Promise.allSettled([B.waitForSummaryTasks(),Z.waitForTasks()]).finally(()=>Ne(n));return}Ne(n)},"disposeAndExit");globalThis[sr]=A,Se=Gr({writable:r(()=>_.writableClients(),"writable"),forward:r((e,n)=>_.sendFrame(e,n),"forward"),pending:ne,broadcast:r(e=>_.broadcastUi(e),"broadcast"),onKnownStreamWait:r(e=>X.knownStreamWait(e),"onKnownStreamWait")}),m.setRebindSession(),await m.enqueueRebind(C,L),l("broker.startup.extensions_bound");const P=gr({nodeId:t,registry:_,toolGroups:B,projection:X,rebind:m,boundaryReviewId:re,pendingDialogs:ne,sendWelcome:Oe,replayExtraPendingDialogsTo:et,reWelcomeAll:ce,disposeAndExit:A,persistModelChoice:Me,broadcastModelChanged:xe,registryOf:_e,formatModelSpec:H,formatExactModelSpec:Fr,turnAdmission:le,memoryInventory:ze,runNode:W,onKickoffAdmitted:K.releaseKickoff});Re=P.notifyTurnAccepted,ye=P.resetForSession,ke=P.pendingPromptDispatches,globalThis[ir]=async e=>{for(const R of Kt){const Y=e.env[R];Y===void 0?delete process.env[R]:process.env[R]=Y}process.env[Ge]=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(),a=n.sessionManager.getSessionFile();if(a===void 0||a==="")throw new Error("in-place cycle needs a persisted session file");const u=n.sessionManager,g=u.getLeafId();u.resetLeaf(),u.appendCustomEntry($e,{cycle:e.cycle,fromLeaf:g}),await pe(),m.beforeNextBind(async R=>{const Y=await Xe(t,R,"resume");await P.refreshMemoryNames(Y?.names)});const f=await m.runReplacement(null,"cycle",R=>R.switchSession(a));if(m.beforeNextBind(void 0),!f)return A("cycle-replacement-failed",1),!1;je(e.prompt,We(e.origin)??{type:"runtime",kind:"revive",cycle:e.cycle});try{await Ue(t,Ye(t))}catch(R){return h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:R,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1),!1}return P.kickoff(e.prompt,e.messageIds),!0};const tt=2500;let me=!1;const rt=r(async e=>{if(G||me)return;if(me=!0,m.isAgentRunActive()||m.session().isStreaming||P.pendingPromptDispatches()>0){const a=Date.now()+tt;for(;P.pendingPromptDispatches()>0&&!m.session().isStreaming&&Date.now()<a;)await new Promise(u=>setTimeout(u,25));if(m.session().isStreaming){const u=a-Date.now();if(u>0){let g;try{wr(),await Promise.race([m.session().abort().then(()=>!0,()=>!1),new Promise(R=>{g=setTimeout(()=>R(!1),u)})])&&await Ke(t,{event:"closed",end_reason:"teardown-aborted"})}finally{g!==void 0&&clearTimeout(g)}}}else(P.pendingPromptDispatches()>0||m.isAgentRunActive())&&await Ke(t,{event:"interrupted"})}A(e)},"abortAndExit");if(k=r(e=>{rt(e)},"signalTeardown"),O!==void 0){k(O);return}const ue=r(e=>{l("broker.startup.first_viewer_connected");const n=_.create(e);e.on("data",u=>{let g;try{g=n.decoder.push(u)}catch(f){f instanceof Or?(_.sendFrame(n,{type:"error",code:"frame_overflow",message:f.message}),_.dropClient(n,`frame overflow: ${f.message}`)):_.dropClient(n,`decoder error: ${String(f)}`);return}for(const f of g)try{vr(P,n,f)}catch{}});const a=r(()=>{_.removeClient(n)},"drop");e.on("close",a),e.on("error",()=>{})},"serveViewer");Lt()!==void 0&&process.env.CRTR_VIEW_WSS!=="0"&&(oe=new ut({host:"::",port:pt,path:"/view",maxPayload:Pr.maxLineBytes}),oe.on("connection",e=>ue(ft(e))),oe.on("error",e=>{G||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))})),N.on("error",e=>{G||(h({level:"error",event:"broker.socket.failed",error:e}),A("socket-error",1))}),J=ue;for(const e of F)F.delete(e),ue(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"}})),$!==void 0){let n;try{try{n=await qe(t,m.session(),$)}catch(a){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:1}}),n=await qe(t,m.session(),$)}}catch(a){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:a,fields:{operation:"session_bound",attempt:2}}),A("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");j().start(t,Bt()),Ar(),Ee()}l("broker.startup.ready_for_turn");let e;try{e=await ee.recoverOnStartup()}catch(n){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:n,fields:{operation:"recovery_startup"}}),A("recovery-startup-failed",1);return}if(!(G||me))if(e==="none"&&c.firstPrompt!==void 0&&c.firstPrompt!==""){const n=We(process.env[Ge]);n!==null&&je(c.firstPrompt,n);try{await Ue(t,Ye(t))}catch(u){h({level:"error",event:"broker.daemon.operation.failed",node_id:t,error:u,fields:{operation:"attachments_fetch"}}),A("attachments-fetch-failed",1);return}const a=process.env.CRTR_KICKOFF_MESSAGE_IDS;P.kickoff(c.firstPrompt,a?JSON.parse(a):[])}else K.releaseKickoff()})(),_.persistAttachState()}r(so,"runBroker");function he(t,o){const i=t.sessionManager,w=i.getEntries===void 0?void 0:Xt(i.getEntries(),i.getLeafId?.());return w!==void 0&&_r(w.map(({message:s})=>s)),w===void 0?void 0:Ht(w,{boundaryReviewId:o,sessionEntries:i.getEntries?.()})}r(he,"snapshotMessages");function He(){const t=at();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_NODE_ID");return t}r(He,"currentBrokerNodeId");async function Ur(t,o){const i=Ut(o.model,st(),o.modelExact===!0);if(i===void 0)return;const w=_e(t),s={cwd:it()??o.cwd,profileId:dt()},d=await Gt(i,w,s);if(d!==void 0)throw await ie(He(),{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 p=await $t(i,s.cwd,s.profileId),l=Wt(i.spec);for(const v of p){const y=w.find(v.providerId,v.modelId);if(y===void 0)continue;const M=l?.providerId===v.providerId&&l.modelId===v.modelId?l.thinkingLevel??(v.thinkingLevel===void 0?void 0:"off"):v.thinkingLevel;return{model:y,thinkingLevel:M}}if(o.modelExact===!0){const v=p.map(y=>`'${y.providerId}/${y.modelId}' unregistered`).join("; ");throw await ie(He(),{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:p.map(v=>({provider:v.providerId,model:v.modelId,reason:"unregistered"})).slice(0,16)}})}r(Ur,"resolveLaunchModel");function $r(t){let o=!0;return{runtime:new Proxy(t,{get(w,s,d){return o&&s==="getAvailableSnapshot"?()=>[]:o&&s==="getAvailable"?async()=>[]:o&&s==="getModel"?()=>{}:Reflect.get(w,s,d)}}),reveal:r(()=>{o=!1},"reveal")}}r($r,"modelLessRegistry");async function Wr(t,o,i=()=>{}){const w=se(),s=r(async b=>{const S=process.hrtime.bigint(),c=await wt.create({credentials:new Dt,modelsPath:Ie(b.agentDir,"models.json")});It(c),i("broker.startup.model_runtime",S);const k=process.hrtime.bigint(),O=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(x=>({...x,extensions:x.extensions.filter(q=>!/[/\\]provider-rotation\.(?:ts|js)$/.test(q.path))}),"extensionsOverride")}});return i("broker.startup.resources_loaded",k),O},"loadServices");let d;const p=r(async b=>{const S=d;d=void 0;const c=await(S??s(b)),k=c.resourceLoader.getExtensions();if(o.extensionPaths.some(z=>ge.includes(z))){const z=new Set(k.extensions.map(C=>C.path)),Q=ge.filter(C=>!z.has(C));if(Q.length>0){const C=k.errors.filter(L=>ge.includes(L.path)).map(L=>`${L.path}: ${L.error}`).join("; ");throw new Error(`[broker] FATAL: mandatory canvas extensions failed to load: ${Q.join(", ")}${C===""?"":` (${C})`}`)}}c.settingsManager.getRetryEnabled=()=>!1;const O=process.hrtime.bigint(),x=await Ur(c,o);i("broker.startup.model_resolved",O);const q=x?.model,I=x?.thinkingLevel,F=x===void 0?$r(c.modelRuntime):void 0,J=F!==void 0?{...c,modelRuntime:F.runtime}:c,te=process.hrtime.bigint(),N=await t.createAgentSessionFromServices({services:J,sessionManager:b.sessionManager,model:q,thinkingLevel:I,...Kr(o.tools,lt()),sessionStartEvent:b.sessionStartEvent});return i("broker.startup.session_from_services",te),hr(N.session),Nt(N.session),F?.reveal(),{...N,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 y=!v&&l!==void 0&&l!=="",E=y&&o.newCycle===!0,M=y&&!E;let T;if(v)T=await t.SessionManager.forkFrom(o.forkFrom,o.cwd);else if(M||E){if(T=await t.SessionManager.open(l),E){const b=T.getLeafId();T.resetLeaf(),T.appendCustomEntry($e,{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(O=>(i("broker.startup.conversation_created",b),O));d=s({cwd:o.cwd,agentDir:w}),d.catch(()=>{});const k=process.hrtime.bigint();T=await c,await d,i("broker.startup.create_and_resources_joined",k)}if(t.createAgentSessionRuntime!==void 0){const b=r(async c=>{const k=await p({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:M,runtime:S}}const V=await p({cwd:o.cwd,agentDir:w,sessionManager:T});return{session:V.session,services:V.services,resuming:M,runtime:void 0}}r(Wr,"buildBrokerSession");function Gr(t){const o=r((s,d,p,l)=>{if(l?.signal?.aborted)return Promise.resolve(s);const v=t.writable();return v.length===0?Promise.resolve(s):new Promise(y=>{let E;const M=r(()=>{E!==void 0&&clearTimeout(E),l?.signal?.removeEventListener("abort",T),t.pending.delete(d.id)},"cleanup"),T=r(()=>{M(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(s)},"onAbort");l?.signal?.addEventListener("abort",T,{once:!0});const V=l?.timeout!==void 0?l.timeout:Lr;E=setTimeout(()=>{M(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(s)},V),typeof E.unref=="function"&&E.unref(),t.pending.set(d.id,{request:d,resolve:r(b=>{M(),t.broadcast({type:"extension_ui_dismiss",id:d.id}),y(p(b))},"resolve")});for(const b of v)t.forward(b,d)})},"dialogPromise"),i=r(()=>{},"noop");return{[jt]:t.onKnownStreamWait??(s=>()=>{}),get theme(){const s=globalThis[Symbol.for("@earendil-works/pi-coding-agent:theme")];if(s==null)throw new Error("Theme not initialized. Call initTheme() first.");return s},select:r((s,d,p)=>o(void 0,{type:"extension_ui_request",id:U(),method:"select",title:s,options:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,p),"select"),confirm:r((s,d,p)=>o(!1,{type:"extension_ui_request",id:U(),method:"confirm",title:s,message:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?!1:"confirmed"in l?l.confirmed:!1,p),"confirm"),input:r((s,d,p)=>o(void 0,{type:"extension_ui_request",id:U(),method:"input",title:s,placeholder:d,timeout:p?.timeout},l=>"cancelled"in l&&l.cancelled?void 0:"value"in l?l.value:void 0,p),"input"),editor:r((s,d)=>o(void 0,{type:"extension_ui_request",id:U(),method:"editor",title:s,prefill:d},p=>"cancelled"in p&&p.cancelled?void 0:"value"in p?p.value:void 0),"editor"),setStatus:r((s,d)=>t.broadcast({type:"extension_ui_request",id:U(),method:"setStatus",statusKey:s,statusText:d}),"setStatus"),setWidget:r((s,d,p)=>{typeof d!="function"&&t.broadcast({type:"extension_ui_request",id:U(),method:"setWidget",widgetKey:s,widgetLines:d,widgetPlacement:p?.placement})},"setWidget"),setTitle:r(s=>t.broadcast({type:"extension_ui_request",id:U(),method:"setTitle",title:s}),"setTitle"),notify:r((s,d)=>{const p=d==="warn"?"warning":d;t.broadcast({type:"extension_ui_request",id:U(),method:"notify",message:s,notifyType:p})},"notify"),onTerminalInput:r(()=>i,"onTerminalInput"),setWorkingMessage:i,setWorkingVisible:i,setWorkingIndicator:i,setHiddenThinkingLabel:i,setFooter:i,setHeader:i,custom:r(()=>Promise.resolve(void 0),"custom"),pasteToEditor:i,setEditorText:i,getEditorText:r(()=>"","getEditorText"),addAutocompleteProvider:i,setEditorComponent:i,getEditorComponent:r(()=>{},"getEditorComponent"),getAllThemes:r(()=>[],"getAllThemes"),getTheme:r(()=>{},"getTheme"),setTheme:i,getToolsExpanded:r(()=>!1,"getToolsExpanded"),setToolsExpanded:i}}r(Gr,"makeBrokerUiContext");export{co as REVIEW_BOUNDARY_NAVIGATION_CODE,lo as ReviewBoundaryNavigationError,Kr as brokerToolOptions,Wr as buildBrokerSession,Br as disposeActiveSession,Gr as makeBrokerUiContext,so as runBroker,he as snapshotMessages};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).join("")})(),systemPrompt:await P(e)}}
|
|
3
|
-
`)}
|
|
1
|
+
var v=Object.defineProperty;var a=(e,t)=>v(e,"name",{value:t,configurable:!0});import{openDb as x}from"../canvas/db.js";import{latestExecutionForNode as _}from"../canvas/executions.js";import{InputError as c}from"../io.js";import{conversationIdFromPath as g,conversationStore as h,ConversationNotFoundError as M}from"../conversation-store/index.js";import{fullName as C,getNode as p}from"../canvas/index.js";import{hydratePersistedAdvertisedCommandMessages as N}from"./advertised-command-invocation.js";import{SessionManager as R}from"./broker-sdk.js";import{openModelRegistry as $}from"./model-registry.js";import{BUILTIN_SLASH_COMMANDS as A}from"./pi-vendored.js";import{transcriptMessages as j}from"./session-cycles.js";import{projectTranscript as F}from"./session-visibility.js";import{normalizeToolGroupSummaryRecord as L}from"../../shared/tool-groups.js";import{normalizeTurnReplyRecord as T}from"../../shared/turn-replies.js";async function k(e){if(e!==null)try{return(await $()).find(e.provider,e.modelId)}catch{return}}a(k,"resolveRecordedModel");async function w(e,t){return await a(async s=>{const r=s?g(s):null;if(r===null)return null;try{return(await h().header(r)).path}catch(i){if(i instanceof M)return null;throw i}},"resolvePath")(t)}a(w,"resolveSessionFile");async function E(e){const t=await p(e);if(t===null)throw new c({error:"not_found",message:`no node: ${e}`,field:"id",next:"List nodes with `crtr node inspect list`."});return await w(e,t.pi_session_file)}a(E,"readableSessionFile");function O(e,t){return{sessionFile:t,sessionId:e,userMessages:0,assistantMessages:0,toolCalls:0,toolResults:0,totalMessages:0,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0}}a(O,"emptyStats");function J(e,t,n){const s=O(t,n);s.totalMessages=e.length;for(const r of e)if(r.role==="user")s.userMessages++;else if(r.role==="assistant"){s.assistantMessages++;const i=Array.isArray(r.content)?r.content:[];s.toolCalls+=i.filter(l=>l!==null&&typeof l=="object"&&l.type==="toolCall").length;const o=r.usage;o!==void 0&&(s.tokens.input+=o.input??0,s.tokens.output+=o.output??0,s.tokens.cacheRead+=o.cacheRead??0,s.tokens.cacheWrite+=o.cacheWrite??0,s.cost+=o.cost?.total??0)}else r.role==="toolResult"&&s.toolResults++;return s.tokens.total=s.tokens.input+s.tokens.output+s.tokens.cacheRead+s.tokens.cacheWrite,s}a(J,"statsFromMessages");async function ae(e){const t=await p(e);if(t===null)throw new c({error:"not_found",message:`no node: ${e}`,field:"id",next:"List nodes with `crtr node inspect list`."});const n=await w(e,t.pi_session_file);if(n===null)throw new c({error:"no_session",message:`node has no readable session file: ${e}`,field:"id",next:"Choose a node with captured conversation history."});return{nodeId:e,sessionFile:n,sessionJsonl:await(async()=>{const{header:s,entries:r}=await h().read(g(n));return[s,...r].map(i=>`${JSON.stringify(i)}
|
|
2
|
+
`).join("")})(),systemPrompt:await P(e)}}a(ae,"readNodeSession");async function P(e){const t=(await _(e))?.launchJson??null;if(t===null)return null;const n=JSON.parse(t).argv;if(!Array.isArray(n))return null;const s=n.indexOf("--append-system-prompt");return s===-1||typeof n[s+1]!="string"?null:n[s+1]}a(P,"launchSystemPrompt");async function y(e,t){const n=await(await x()).prepare(`SELECT ${t} AS raw FROM nodes WHERE node_id = ?`).get(e);try{return n?.raw==null?null:JSON.parse(n.raw)}catch{return null}}a(y,"readSummaryColumn");async function W(e){return L(await y(e,"tool_summaries_json"))}a(W,"readToolGroupSummaries");async function B(e){return T(await y(e,"turn_replies_json"))}a(B,"readTurnReplies");async function S(e){const t=await p(e);if(t===null)throw new c({error:"not_found",message:`no node: ${e}`,field:"id",next:"List nodes with `crtr node inspect list`."});const n=await w(e,t.pi_session_file);if(n===null)throw new c({error:"no_session",message:`node has no readable session file: ${e}`,field:"id",next:"Choose a node with captured conversation history."});const{header:s,entries:r}=await h().read(g(n)),i=R.inMemory(s.cwd,void 0,[s,...r]),o=i.buildSessionContext(),l=j(i.getEntries(),i.getLeafId());N(l.map(({message:f})=>f));const u=F(l,{boundaryReviewId:t.review_binding?.review_id,sessionEntries:i.getEntries()}),m=u.map(({message:f})=>f);return{sessionFile:n,messages:m,identified:u,model:o.model,thinkingLevel:o.thinkingLevel,sessionId:i.getSessionId(),sessionName:i.getSessionName()}}a(S,"reconstructTranscript");function d(){throw new c({error:"invalid_cursor",message:"cursor must be a base64url-encoded messages cursor.",field:"cursor",next:"Omit cursor to start from the newest messages."})}a(d,"invalidCursor");function U(e,t){/^[A-Za-z0-9_-]+$/u.test(e)||d();let n;try{const r=Buffer.from(e,"base64url").toString("utf8");Buffer.from(r,"utf8").toString("base64url")!==e&&d(),n=JSON.parse(r)}catch{d()}(typeof n!="object"||n===null||n.v!==1||!Number.isSafeInteger(n.before))&&d();const s=n.before;return(s<0||s>t)&&d(),s}a(U,"decodeMessagesCursor");function V(e){return Buffer.from(JSON.stringify({v:1,before:e}),"utf8").toString("base64url")}a(V,"encodeMessagesCursor");async function z(e){const t=await S(e),n={messages:t.messages,...t.identified===void 0?{}:{messageIds:t.identified.map(({id:s})=>s)},messageVisibility:t.identified?.map(({visibility:s})=>s)??t.messages.map(()=>"visible"),turnVisibility:"visible",stats:J(t.messages,t.sessionId,t.sessionFile),state:{model:await k(t.model),thinkingLevel:t.thinkingLevel,isStreaming:!1,isCompacting:!1,steeringMode:"one-at-a-time",followUpMode:"one-at-a-time",sessionFile:t.sessionFile,sessionId:t.sessionId,sessionName:t.sessionName,autoCompactionEnabled:!0,messageCount:t.messages.length,pendingMessageCount:0},display:{statuses:{},widgets:{},title:void 0},queued:{steering:[],followUp:[]},toolGroupSummaries:await W(e),turnReplies:await B(e)};return{nodeId:e,snapshot:n,commands:A.map(s=>({...s,source:"builtin"}))}}a(z,"readNodeSnapshot");async function le(e,{cursor:t,limit:n=200}){if(!Number.isSafeInteger(n)||n<1||n>500)throw new c({error:"invalid_limit",message:"limit must be an integer from 1 through 500.",field:"limit",next:"Use a limit from 1 through 500."});if(await E(e)===null)return{messages:[],messageIds:[],messageVisibility:[],nextCursor:null};const{messages:s,identified:r}=await S(e),i=t===void 0?s.length:U(t,s.length);let o=Math.max(0,i-n);for(;o>0&&typeof s[o]=="object"&&s[o]!==null&&s[o].role==="toolResult";)o--;const l=r?.slice(o,i);return{messages:l?.map(({message:u})=>u)??s.slice(o,i),...l===void 0?{}:{messageIds:l.map(({id:u})=>u)},messageVisibility:l?.map(({visibility:u})=>u)??s.slice(o,i).map(()=>"visible"),nextCursor:o===0?null:V(o)}}a(le,"readNodeMessagesPage");function G(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null).filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join(""):""}a(G,"textFromContent");function D(e){switch(e.role){case"user":return"You";case"assistant":return"Agent";case"toolResult":return"Tool result";default:return typeof e.role=="string"?e.role:"Message"}}a(D,"roleLabel");function H(e){return Array.isArray(e.content)?e.content.filter(t=>typeof t=="object"&&t!==null&&t.type==="toolCall").map(t=>`Tool: ${typeof t.name=="string"?t.name:"call"}`):[]}a(H,"toolSummaries");async function ue(e){const t=await p(e);if(t===null)throw new c({error:"not_found",message:`no node: ${e}`,field:"node-id",next:"List nodes with `crtr node inspect list`."});const{snapshot:n}=await z(e),r=[`# ${C(t)}`,"",`Saved transcript \xB7 ${t.status} \xB7 ${t.lifecycle}`,""];for(const i of n.messages){if(typeof i!="object"||i===null)continue;const o=i;if(o.role==="custom"&&o.display===!1)continue;const l=G(o.content),u=typeof o.text=="string"?o.text:"",m=l.trim()?l:u.trim()?u:"",f=H(o);if(!(!m&&f.length===0)){r.push(`## ${D(o)}`,""),m&&r.push(m,"");for(const b of f)r.push(`- ${b}`);f.length&&r.push("")}}return r.length===5&&r.push("_No saved messages._",""),r.join(`
|
|
3
|
+
`)}a(ue,"transcriptMarkdown");export{le as readNodeMessagesPage,ae as readNodeSession,z as readNodeSnapshot,ue as transcriptMarkdown};
|
|
@@ -4,27 +4,12 @@ import type { BrokerSnapshot } from './broker-protocol.js';
|
|
|
4
4
|
* Data payload: `{ cycle, fromLeaf }` — `cycle` is the node's cycle counter at
|
|
5
5
|
* relaunch, `fromLeaf` the previous cycle's leaf entry id. */
|
|
6
6
|
export declare const CRTR_CYCLE_CUSTOM_TYPE = "crtr-cycle";
|
|
7
|
-
/** customType of the SYNTHETIC divider message spliced between cycles in
|
|
8
|
-
* snapshot rendering. Never persisted to the session file. */
|
|
9
|
-
export declare const CRTR_CYCLE_DIVIDER_CUSTOM_TYPE = "crtr-cycle-divider";
|
|
10
7
|
type SnapshotMessage = BrokerSnapshot['messages'][number];
|
|
11
8
|
/** One reconstructed message and the durable session entry that produced it. */
|
|
12
9
|
export type IdentifiedMessage = {
|
|
13
10
|
id: string;
|
|
14
11
|
message: SnapshotMessage;
|
|
15
12
|
};
|
|
16
|
-
/** The structural slice of pi's SessionManager cycle rendering needs. The
|
|
17
|
-
* broker's fake-engine test fixture implements only `buildSessionContext`, so
|
|
18
|
-
* the tree accessors are optional — absent ⇒ single-cycle behavior. */
|
|
19
|
-
export interface CycleSessionManagerLike {
|
|
20
|
-
buildSessionContext(): {
|
|
21
|
-
messages: SnapshotMessage[];
|
|
22
|
-
};
|
|
23
|
-
getEntries?(): SessionEntry[];
|
|
24
|
-
/** Walk from `fromId` (default: the current leaf) to its root; returns the
|
|
25
|
-
* path root-first. */
|
|
26
|
-
getBranch?(fromId?: string): SessionEntry[];
|
|
27
|
-
}
|
|
28
13
|
/** True when an assistant turn ended because its own abort fired — an ESC, a
|
|
29
14
|
* critical-tier interrupt, or the self-abort a refresh-yield performs. */
|
|
30
15
|
export declare function endedByAbort(message: {
|
|
@@ -35,11 +20,9 @@ export declare function endedByAbort(message: {
|
|
|
35
20
|
* rooted. Preserve that assistant message (including tool calls and prose), but
|
|
36
21
|
* omit the failure annotation: the cycle divider is the truthful visible seam. */
|
|
37
22
|
export declare function withoutYieldAbort(message: SnapshotMessage): SnapshotMessage;
|
|
38
|
-
/** The
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
*
|
|
42
|
-
|
|
43
|
-
* then apply unchanged). */
|
|
44
|
-
export declare function cycleAwareMessages(sm: CycleSessionManagerLike): IdentifiedMessage[] | undefined;
|
|
23
|
+
/** The context messages on the branch ending at `leafId`, each with its entry id. */
|
|
24
|
+
export declare function identifiedMessages(entries: SessionEntry[], leafId: string | null | undefined): IdentifiedMessage[];
|
|
25
|
+
/** A whole conversation for display: each earlier cycle as user and assistant
|
|
26
|
+
* text only, one line where each cycle starts, then the current cycle in full. */
|
|
27
|
+
export declare function transcriptMessages(entries: SessionEntry[], leafId: string | null): IdentifiedMessage[];
|
|
45
28
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var i=(t,o)=>d(t,"name",{value:o,configurable:!0});import{buildContextEntries as m,sessionEntryToContextMessages as l}from"@earendil-works/pi-coding-agent";const p="crtr-cycle",b=/\b(?:request|operation) was aborted\b|\bthe user aborted\b/i;function y(t){return t.stopReason==="aborted"?!0:t.stopReason==="error"&&b.test(t.errorMessage??"")}i(y,"endedByAbort");function R(t){if(t.role!=="assistant"||!y(t))return t;const{stopReason:o,errorMessage:r,...e}=t;return e}i(R,"withoutYieldAbort");function u(t,o){const r=new Map(t.map(e=>[e.id,e]));return m(t,o,r).flatMap(e=>l(e).map(n=>({id:e.id,message:n})))}i(u,"identifiedMessages");function x(t,o){const r=[];for(const e of t){if(e.type!=="custom"||e.customType!==p)continue;const n=e.data;for(const a of n?.fromLeaf?u(t,n.fromLeaf):[]){const s=a.message;if(s.role!=="user"&&s.role!=="assistant")continue;const c=typeof s.content=="string"?s.content:s.content.filter(f=>f.type==="text");c.length>0&&r.push({...a,message:{...R(s),content:c}})}r.push({id:e.id,message:{role:"custom",customType:p,content:`cycle ${n?.cycle??""} begins with a fresh context window`,display:!0,timestamp:new Date(e.timestamp).getTime()}})}return[...r,...u(t,o)]}i(x,"transcriptMessages");export{p as CRTR_CYCLE_CUSTOM_TYPE,y as endedByAbort,u as identifiedMessages,x as transcriptMessages,R as withoutYieldAbort};
|
|
@@ -207,36 +207,6 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
|
|
|
207
207
|
setFromString: (config: ScopeConfig, raw: string) => string | null;
|
|
208
208
|
};
|
|
209
209
|
};
|
|
210
|
-
live_cycles: {
|
|
211
|
-
surface: "settings";
|
|
212
|
-
setting: {
|
|
213
|
-
key: "live_cycles";
|
|
214
|
-
label: string;
|
|
215
|
-
description: string;
|
|
216
|
-
valueConstraint: string;
|
|
217
|
-
applies: string;
|
|
218
|
-
group: "display";
|
|
219
|
-
order: number;
|
|
220
|
-
format: (config: ScopeConfig) => string;
|
|
221
|
-
cycle: (config: ScopeConfig, delta: number) => void;
|
|
222
|
-
setFromString: (config: ScopeConfig, raw: string) => string | null;
|
|
223
|
-
};
|
|
224
|
-
};
|
|
225
|
-
condensed_history: {
|
|
226
|
-
surface: "settings";
|
|
227
|
-
setting: {
|
|
228
|
-
key: "condensed_history";
|
|
229
|
-
label: string;
|
|
230
|
-
description: string;
|
|
231
|
-
valueConstraint: string;
|
|
232
|
-
applies: string;
|
|
233
|
-
group: "display";
|
|
234
|
-
order: number;
|
|
235
|
-
format: (config: ScopeConfig) => "user" | "none" | "agent" | "both";
|
|
236
|
-
cycle: (config: ScopeConfig, delta: number) => void;
|
|
237
|
-
setFromString: (config: ScopeConfig, raw: string) => string | null;
|
|
238
|
-
};
|
|
239
|
-
};
|
|
240
210
|
bash_tool_purpose: {
|
|
241
211
|
surface: "settings";
|
|
242
212
|
setting: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var b=Object.defineProperty;var n=(e,t)=>b(e,"name",{value:t,configurable:!0});import{CONDENSED_HISTORY_MODES as p,MOUSE_MODE_DEFAULTS as d,VERBOSITY_LEVELS as a,WHIP_MESSAGE_MODES as c}from"../types.js";const w={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};function x(e){const t=a.indexOf(e);return`less ${a.map((o,s)=>s===t?"\u25CF":"\u25CB").map((o,s)=>s===0?o:`${s<=t?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${o}`).join("")} more ${w[e]}`}n(x,"verbositySpectrum");function l(e,t,r){const o=e.indexOf(t),s=o>=0?o:0;return e[(s+r+e.length)%e.length]}n(l,"cycleChoice");function f(e,t,r){const o=e.indexOf(t);return o>=0?e[(o+r+e.length)%e.length]:r>=0?e.find(s=>s>t)??e[0]:[...e].reverse().find(s=>s<t)??e[e.length-1]}n(f,"cycleNumber");function i(e,t){return e==="true"?!0:e==="false"?!1:`${t} must be true or false`}n(i,"booleanFromString");function m(e,t){if(!/^\d+$/.test(e))return`${t} must be an integer >= 0`;const r=Number(e);return Number.isSafeInteger(r)?r:`${t} must be an integer >= 0`}n(m,"nonNegativeIntegerFromString");function _(e,t){const r=m(e,t);return typeof r=="string"||r<1?`${t} must be an integer >= 1`:r}n(_,"positiveIntegerFromString");const g=[!1,"notify","apply"],S=[0,1,6,12,24,48,72,168],k=[1,2,3,4,5,6,8,10,12],u="openai-codex";function h(e,t){const r=e.providerOptions[t];if(r!==void 0)return r;const o={};return e.providerOptions[t]=o,o}n(h,"providerOptionsFor");const O=[1,2,3,4,5,6],y={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:n(e=>e.auto_update.crtr===!1?"off":e.auto_update.crtr,"format"),cycle:n((e,t)=>{e.auto_update.crtr=l(g,e.auto_update.crtr,t)},"cycle"),setFromString:n((e,t)=>{const r=t==="true"?"notify":t;return r!=="notify"&&r!=="apply"&&r!=="false"?"auto_update.crtr must be notify, apply, or false":(e.auto_update.crtr=r==="false"?!1:r,null)},"setFromString")},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:n(e=>e.auto_update.content===!1?"off":e.auto_update.content,"format"),cycle:n((e,t)=>{e.auto_update.content=l(g,e.auto_update.content,t)},"cycle"),setFromString:n((e,t)=>t!=="notify"&&t!=="apply"&&t!=="false"?"auto_update.content must be notify, apply, or false":(e.auto_update.content=t==="false"?!1:t,null),"setFromString")},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:n(e=>`${e.auto_update.interval_hours}h`,"format"),cycle:n((e,t)=>{e.auto_update.interval_hours=f(S,e.auto_update.interval_hours,t)},"cycle"),setFromString:n((e,t)=>{const r=m(t,"auto_update.interval_hours");return typeof r=="string"?r:(e.auto_update.interval_hours=r,null)},"setFromString")}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:n(e=>String(e.max_panes_per_window),"format"),cycle:n((e,t)=>{e.max_panes_per_window=f(k,e.max_panes_per_window,t)},"cycle"),setFromString:n((e,t)=>{const r=_(t,"max_panes_per_window");return typeof r=="string"?r:(e.max_panes_per_window=r,null)},"setFromString")}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:n(e=>e.auto_open_child_viewers?"on":"off","format"),cycle:n(e=>{e.auto_open_child_viewers=!e.auto_open_child_viewers},"cycle"),setFromString:n((e,t)=>{const r=i(t,"auto_open_child_viewers");return typeof r=="string"?r:(e.auto_open_child_viewers=r,null)},"setFromString")}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:n(e=>e.completion_bell?"on":"off","format"),cycle:n(e=>{e.completion_bell=!e.completion_bell},"cycle"),setFromString:n((e,t)=>{const r=i(t,"completion_bell");return typeof r=="string"?r:(e.completion_bell=r,null)},"setFromString")}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:n(e=>e.whip_mode?"on":"off","format"),cycle:n(e=>{e.whip_mode=!e.whip_mode},"cycle"),setFromString:n((e,t)=>{const r=i(t,"whip_mode");return typeof r=="string"?r:(e.whip_mode=r,null)},"setFromString")}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:n(e=>e.page_surface?"on":"off","format"),cycle:n(e=>{e.page_surface=!e.page_surface},"cycle"),setFromString:n((e,t)=>{const r=i(t,"page_surface");return typeof r=="string"?r:(e.page_surface=r,null)},"setFromString")}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:c.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:n(e=>e.whip_message_mode==="go-faster"?"go faster":"random","format"),cycle:n((e,t)=>{e.whip_message_mode=l(c,e.whip_message_mode,t)},"cycle"),setFromString:n((e,t)=>c.includes(t)?(e.whip_message_mode=t,null):`whip_message_mode must be one of: ${c.join("|")}`,"setFromString")}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:d.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:n(e=>e.mouse_mode_default==="tmux"?"follow tmux":e.mouse_mode_default,"format"),cycle:n((e,t)=>{e.mouse_mode_default=l(d,e.mouse_mode_default,t)},"cycle"),setFromString:n((e,t)=>d.includes(t)?(e.mouse_mode_default=t,null):`mouse_mode_default must be one of: ${d.join("|")}`,"setFromString")}},live_cycles:{surface:"settings",setting:{key:"live_cycles",label:"Live cycles",description:"Trailing refresh cycles rendered at full fidelity; older cycles condense to text.",valueConstraint:"integer >= 1",applies:"Applies on the next attach.",group:"display",order:50,format:n(e=>String(e.live_cycles),"format"),cycle:n((e,t)=>{e.live_cycles=f(O,e.live_cycles,t)},"cycle"),setFromString:n((e,t)=>{const r=_(t,"live_cycles");return typeof r=="string"?r:(e.live_cycles=r,null)},"setFromString")}},condensed_history:{surface:"settings",setting:{key:"condensed_history",label:"Condensed history",description:"Messages retained from condensed cycles. Tool calls are never kept.",valueConstraint:p.join("|"),applies:"Applies on the next attach.",group:"display",order:60,format:n(e=>e.condensed_history,"format"),cycle:n((e,t)=>{e.condensed_history=l(p,e.condensed_history,t)},"cycle"),setFromString:n((e,t)=>p.includes(t)?(e.condensed_history=t,null):`condensed_history must be one of: ${p.join("|")}`,"setFromString")}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:n(e=>e.bash_tool_purpose?"on":"off","format"),cycle:n(e=>{e.bash_tool_purpose=!e.bash_tool_purpose},"cycle"),setFromString:n((e,t)=>{const r=i(t,"bash_tool_purpose");return typeof r=="string"?r:(e.bash_tool_purpose=r,null)},"setFromString")}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:a.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:n(e=>e.verbosity,"format"),display:n(e=>x(e.verbosity),"display"),cycle:n((e,t)=>{const r=a.indexOf(e.verbosity)+t;e.verbosity=a[Math.max(0,Math.min(a.length-1,r))]},"cycle"),setFromString:n((e,t)=>a.includes(t)?(e.verbosity=t,null):`verbosity must be one of: ${a.join("|")}`,"setFromString")}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:n(e=>String(e.document_port),"format"),cycle:n((e,t)=>{e.document_port=Math.max(1,Math.min(65535,e.document_port+t))},"cycle"),setFromString:n((e,t)=>{const r=Number(t);return!/^\d+$/.test(t)||!Number.isInteger(r)||r<1||r>65535?"document_port must be an integer from 1 to 65535":(e.document_port=r,null)},"setFromString")}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:n(e=>e.detailed_tool_recaps?"on":"off","format"),cycle:n(e=>{e.detailed_tool_recaps=!e.detailed_tool_recaps},"cycle"),setFromString:n((e,t)=>{const r=i(t,"detailed_tool_recaps");return typeof r=="string"?r:(e.detailed_tool_recaps=r,null)},"setFromString")}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${u}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:n(e=>e.providerOptions[u]?.fastMode?"on":"off","format"),cycle:n(e=>{const t=h(e,u);t.fastMode=!t.fastMode},"cycle"),setFromString:n((e,t)=>{const r=i(t,`providerOptions.${u}.fastMode`);return typeof r=="string"?r:(h(e,u).fastMode=r,null)},"setFromString")}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},M=Object.keys(y);function C(){const e=[];for(const t of Object.values(y))t.surface==="settings"&&("setting"in t?e.push(t.setting):e.push(...Object.values(t.settings)));return e.sort((t,r)=>t.order-r.order)}n(C,"collectUserSettings");const v=C();function F(e){return v.find(t=>t.key===e)}n(F,"findUserSetting");function z(e){return v.filter(t=>t.group===e)}n(z,"userSettingsInGroup");export{y as CONFIG_SETTINGS_COVERAGE,M as SCOPE_CONFIG_KEYS,v as USER_SETTINGS,w as VERBOSITY_LABELS,F as findUserSetting,z as userSettingsInGroup,x as verbositySpectrum};
|
|
1
|
+
var y=Object.defineProperty;var r=(e,t)=>y(e,"name",{value:t,configurable:!0});import{MOUSE_MODE_DEFAULTS as u,VERBOSITY_LEVELS as a,WHIP_MESSAGE_MODES as p}from"../types.js";const w={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};function v(e){const t=a.indexOf(e);return`less ${a.map((n,s)=>s===t?"\u25CF":"\u25CB").map((n,s)=>s===0?n:`${s<=t?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${n}`).join("")} more ${w[e]}`}r(v,"verbositySpectrum");function d(e,t,o){const n=e.indexOf(t),s=n>=0?n:0;return e[(s+o+e.length)%e.length]}r(d,"cycleChoice");function c(e,t,o){const n=e.indexOf(t);return n>=0?e[(n+o+e.length)%e.length]:o>=0?e.find(s=>s>t)??e[0]:[...e].reverse().find(s=>s<t)??e[e.length-1]}r(c,"cycleNumber");function i(e,t){return e==="true"?!0:e==="false"?!1:`${t} must be true or false`}r(i,"booleanFromString");function f(e,t){if(!/^\d+$/.test(e))return`${t} must be an integer >= 0`;const o=Number(e);return Number.isSafeInteger(o)?o:`${t} must be an integer >= 0`}r(f,"nonNegativeIntegerFromString");function b(e,t){const o=f(e,t);return typeof o=="string"||o<1?`${t} must be an integer >= 1`:o}r(b,"positiveIntegerFromString");const m=[!1,"notify","apply"],x=[0,1,6,12,24,48,72,168],S=[1,2,3,4,5,6,8,10,12],l="openai-codex";function _(e,t){const o=e.providerOptions[t];if(o!==void 0)return o;const n={};return e.providerOptions[t]=n,n}r(_,"providerOptionsFor");const g={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:r(e=>e.auto_update.crtr===!1?"off":e.auto_update.crtr,"format"),cycle:r((e,t)=>{e.auto_update.crtr=d(m,e.auto_update.crtr,t)},"cycle"),setFromString:r((e,t)=>{const o=t==="true"?"notify":t;return o!=="notify"&&o!=="apply"&&o!=="false"?"auto_update.crtr must be notify, apply, or false":(e.auto_update.crtr=o==="false"?!1:o,null)},"setFromString")},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:r(e=>e.auto_update.content===!1?"off":e.auto_update.content,"format"),cycle:r((e,t)=>{e.auto_update.content=d(m,e.auto_update.content,t)},"cycle"),setFromString:r((e,t)=>t!=="notify"&&t!=="apply"&&t!=="false"?"auto_update.content must be notify, apply, or false":(e.auto_update.content=t==="false"?!1:t,null),"setFromString")},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:r(e=>`${e.auto_update.interval_hours}h`,"format"),cycle:r((e,t)=>{e.auto_update.interval_hours=c(x,e.auto_update.interval_hours,t)},"cycle"),setFromString:r((e,t)=>{const o=f(t,"auto_update.interval_hours");return typeof o=="string"?o:(e.auto_update.interval_hours=o,null)},"setFromString")}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:r(e=>String(e.max_panes_per_window),"format"),cycle:r((e,t)=>{e.max_panes_per_window=c(S,e.max_panes_per_window,t)},"cycle"),setFromString:r((e,t)=>{const o=b(t,"max_panes_per_window");return typeof o=="string"?o:(e.max_panes_per_window=o,null)},"setFromString")}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:r(e=>e.auto_open_child_viewers?"on":"off","format"),cycle:r(e=>{e.auto_open_child_viewers=!e.auto_open_child_viewers},"cycle"),setFromString:r((e,t)=>{const o=i(t,"auto_open_child_viewers");return typeof o=="string"?o:(e.auto_open_child_viewers=o,null)},"setFromString")}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:r(e=>e.completion_bell?"on":"off","format"),cycle:r(e=>{e.completion_bell=!e.completion_bell},"cycle"),setFromString:r((e,t)=>{const o=i(t,"completion_bell");return typeof o=="string"?o:(e.completion_bell=o,null)},"setFromString")}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:r(e=>e.whip_mode?"on":"off","format"),cycle:r(e=>{e.whip_mode=!e.whip_mode},"cycle"),setFromString:r((e,t)=>{const o=i(t,"whip_mode");return typeof o=="string"?o:(e.whip_mode=o,null)},"setFromString")}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:r(e=>e.page_surface?"on":"off","format"),cycle:r(e=>{e.page_surface=!e.page_surface},"cycle"),setFromString:r((e,t)=>{const o=i(t,"page_surface");return typeof o=="string"?o:(e.page_surface=o,null)},"setFromString")}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:p.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:r(e=>e.whip_message_mode==="go-faster"?"go faster":"random","format"),cycle:r((e,t)=>{e.whip_message_mode=d(p,e.whip_message_mode,t)},"cycle"),setFromString:r((e,t)=>p.includes(t)?(e.whip_message_mode=t,null):`whip_message_mode must be one of: ${p.join("|")}`,"setFromString")}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:u.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:r(e=>e.mouse_mode_default==="tmux"?"follow tmux":e.mouse_mode_default,"format"),cycle:r((e,t)=>{e.mouse_mode_default=d(u,e.mouse_mode_default,t)},"cycle"),setFromString:r((e,t)=>u.includes(t)?(e.mouse_mode_default=t,null):`mouse_mode_default must be one of: ${u.join("|")}`,"setFromString")}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:r(e=>e.bash_tool_purpose?"on":"off","format"),cycle:r(e=>{e.bash_tool_purpose=!e.bash_tool_purpose},"cycle"),setFromString:r((e,t)=>{const o=i(t,"bash_tool_purpose");return typeof o=="string"?o:(e.bash_tool_purpose=o,null)},"setFromString")}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:a.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:r(e=>e.verbosity,"format"),display:r(e=>v(e.verbosity),"display"),cycle:r((e,t)=>{const o=a.indexOf(e.verbosity)+t;e.verbosity=a[Math.max(0,Math.min(a.length-1,o))]},"cycle"),setFromString:r((e,t)=>a.includes(t)?(e.verbosity=t,null):`verbosity must be one of: ${a.join("|")}`,"setFromString")}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:r(e=>String(e.document_port),"format"),cycle:r((e,t)=>{e.document_port=Math.max(1,Math.min(65535,e.document_port+t))},"cycle"),setFromString:r((e,t)=>{const o=Number(t);return!/^\d+$/.test(t)||!Number.isInteger(o)||o<1||o>65535?"document_port must be an integer from 1 to 65535":(e.document_port=o,null)},"setFromString")}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:r(e=>e.detailed_tool_recaps?"on":"off","format"),cycle:r(e=>{e.detailed_tool_recaps=!e.detailed_tool_recaps},"cycle"),setFromString:r((e,t)=>{const o=i(t,"detailed_tool_recaps");return typeof o=="string"?o:(e.detailed_tool_recaps=o,null)},"setFromString")}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${l}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:r(e=>e.providerOptions[l]?.fastMode?"on":"off","format"),cycle:r(e=>{const t=_(e,l);t.fastMode=!t.fastMode},"cycle"),setFromString:r((e,t)=>{const o=i(t,`providerOptions.${l}.fastMode`);return typeof o=="string"?o:(_(e,l).fastMode=o,null)},"setFromString")}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},C=Object.keys(g);function k(){const e=[];for(const t of Object.values(g))t.surface==="settings"&&("setting"in t?e.push(t.setting):e.push(...Object.values(t.settings)));return e.sort((t,o)=>t.order-o.order)}r(k,"collectUserSettings");const h=k();function E(e){return h.find(t=>t.key===e)}r(E,"findUserSetting");function M(e){return h.filter(t=>t.group===e)}r(M,"userSettingsInGroup");export{g as CONFIG_SETTINGS_COVERAGE,C as SCOPE_CONFIG_KEYS,h as USER_SETTINGS,w as VERBOSITY_LABELS,E as findUserSetting,M as userSettingsInGroup,v as verbositySpectrum};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).join("")),{status:200}}const
|
|
3
|
-
`,u.length>=256*1024&&await
|
|
1
|
+
var b=Object.defineProperty;var a=(e,r)=>b(e,"name",{value:r,configurable:!0});import{conversationStore as T}from"../../../core/conversation-store/index.js";import{createRowStore as g}from"../../../core/conversation-store/row-store.js";import{conversationOwner as N}from"../../../core/canvas/sessions.js";import{mayOnNode as y}from"../router.js";import{markAt as q,withLoggedStepTimings as O}from"../../../core/logged-step-timings.js";import{ApiError as l}from"../../../api/errors.js";const c=128*1024*1024,i=a(()=>T(),"store"),o=a(e=>e.body,"input");function d(){throw new l(404,"not_found","conversation not found")}a(d,"notFound");async function p(e,r,n=!1){const t=await N(r);if(!t)return d();if(e.principal.class==="broker"){if(t!==e.principal.node)return d()}else if(n||e.principal.class!=="person"||!await y(e.principal,"read",t))return d();return t}a(p,"authorize");const R=a(async(e,r)=>{await p(e,r);const n=e.query.get("head"),t=e.query.get("tail"),m=e.query.get("from")==="cycle";if(n!==null||t!==null||m){if(!m&&(n===null||t===null||!/^\d+$/.test(n)||!/^\d+$/.test(t)||Number(n)>c||Number(t)>c))throw new l(400,"invalid_request","head and tail must be byte counts");const s=await i().read(r,m?"cycle":{head:Number(n),tail:Number(t)});return e.res.writeHead(200,{"content-type":"application/x-ndjson","x-conversation-path":s.path,...s.tail?{"x-conversation-tail":String(s.entries.length+1)}:{}}),e.res.end([s.header,...s.entries,...s.tail??[]].map(h=>JSON.stringify(h)+`
|
|
2
|
+
`).join("")),{status:200}}const f=await i().readLines?.(r);if(!f)throw new Error("conversation store does not support streaming reads");e.res.writeHead(200,{"content-type":"application/x-ndjson","x-conversation-path":f.path});let u="";const w=a(()=>{const s=u;return u="",new Promise((h,_)=>e.res.write(s,v=>v?_(v):h()))},"flush");for await(const s of f.lines)u+=s+`
|
|
3
|
+
`,u.length>=256*1024&&await w();return u&&await w(),e.res.end(),{status:200}},"readResult"),F=[{method:"POST",pattern:"/v1/conversations",maxBodyBytes:c,handler:a(async e=>{if(e.principal.class!=="broker"||o(e).node_id!==e.principal.node)return d();const r=e.principal.node;return await O("conversation_create",{node:r,body_bytes:Number(e.req.headers["content-length"]??0)},e.req,async()=>{const n=await i().create(r,o(e).header,o(e).entries);return q("response_ready"),{status:201,body:n}})},"handler")},{method:"GET",pattern:"/v1/conversations",handler:a(async e=>{if(e.principal.class==="broker"){const n=e.query.get("node_id");return n&&n!==e.principal.node?d():{status:200,body:{conversations:await i().list(e.principal.node)}}}if(e.principal.class!=="person")return d();const r=e.query.get("node_id");if(!r)throw new l(400,"invalid_request","node_id is required");return await y(e.principal,"read",r)?{status:200,body:{conversations:await i().list(r)}}:d()},"handler")},{method:"POST",pattern:"/v1/conversations/:id/entries",maxBodyBytes:c,handler:a(async e=>{await p(e,e.params.id,!0);const r=process.env.CRTR_FAULT_CONVERSATION??"";if(r.startsWith("append_refuse:")){const n=Number(r.slice(14));throw process.env.CRTR_FAULT_CONVERSATION=n>1?`append_refuse:${n-1}`:"",new l(503,"unavailable","conversation append refused (fault)")}return await i().append(e.params.id,o(e).entries),r==="append_drop_after_store"?(e.res.destroy(),{status:204}):{status:204}},"handler")},{method:"POST",pattern:"/v1/conversations/:id/commit",handler:a(async e=>{if(await p(e,e.params.id,!0),process.env.CRTR_FAULT_CONVERSATION==="commit_put_fail")throw new l(503,"unavailable","conversation commit refused (fault)");return{status:200,body:{seq:await g().commit(e.params.id)}}},"handler")},{method:"GET",pattern:"/v1/conversations/:id",handler:a(async e=>await R(e,e.params.id),"handler")},{method:"GET",pattern:"/v1/conversations/:id/header",handler:a(async e=>(await p(e,e.params.id),{status:200,body:await i().header(e.params.id)}),"handler")},{method:"PUT",pattern:"/v1/conversations/:id",maxBodyBytes:c,handler:a(async e=>(await p(e,e.params.id,!0),await i().replace(e.params.id,o(e).header,o(e).entries),{status:204}),"handler")},{method:"POST",pattern:"/v1/conversations/:id/fork",handler:a(async e=>{const r=await p(e,e.params.id,!0);return o(e).node_id!==r?d():{status:201,body:{conversation_id:await i().fork(e.params.id,r,o(e).leaf_id,o(e).cwd)}}},"handler")},{method:"DELETE",pattern:"/v1/conversations/:id",handler:a(async e=>(await p(e,e.params.id,!0),await i().delete(e.params.id),{status:204}),"handler")}];export{F as conversationRoutes};
|
|
@@ -6,7 +6,7 @@ import { type MachineLinkRefusal } from './holder.js';
|
|
|
6
6
|
export declare const VIEW_BUFFER_LIMIT_BYTES: number;
|
|
7
7
|
/** A viewer channel to a node on a machine: over the link this process holds, or forwarded to the API process that does. */
|
|
8
8
|
export declare function openMachineView(environmentId: string, nodeId: string): BrokerViewLink;
|
|
9
|
-
/** Wait for the node's broker on the Mac to accept a viewer, retrying
|
|
9
|
+
/** Wait for the node's broker on the Mac to accept a viewer, retrying a channel that closes (its view.sock refused) after 250 ms; a pending channel is waited on, not replaced. The accepted channel, open, or null on the deadline or when the launch exits. A caller that does not use the channel destroys it. */
|
|
10
10
|
export declare function waitForMachineView(environmentId: string, nodeId: string, exited: Promise<unknown> | undefined, waitMs: number): Promise<BrokerViewLink | null>;
|
|
11
11
|
/** The environment id of a forwarded viewer upgrade path, or null for any other path. */
|
|
12
12
|
export declare function machineViewEnvironment(req: IncomingMessage): string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var x=Object.defineProperty;var a=(r,e)=>x(r,"name",{value:e,configurable:!0});import{EventEmitter as A}from"node:events";import{createHmac as I,timingSafeEqual as R}from"node:crypto";import{WebSocket as
|
|
1
|
+
var x=Object.defineProperty;var a=(r,e)=>x(r,"name",{value:e,configurable:!0});import{EventEmitter as A}from"node:events";import{createHmac as I,timingSafeEqual as R}from"node:crypto";import{WebSocket as m,WebSocketServer as P}from"ws";import{markAt as k}from"../../core/logged-step-timings.js";import{addStepTiming as T}from"../../core/step-timings.js";import{emitEvent as _}from"../../core/events/emit.js";import{openDb as B}from"../../core/canvas/db.js";import{loadSecretsKey as O}from"../../core/secrets/key.js";import{LINK_MAX_PAYLOAD_BYTES as v,parseFrame as g}from"./frames.js";import{apiAddress as D,heldLinkOf as E,MachineViewLink as S,UNROUTABLE_PREFIX as L}from"./holder.js";const y=8*1024*1024,$=1013,M=/^\/v1\/machines\/([A-Za-z0-9_-]+)\/view$/,U=new P({noServer:!0,maxPayload:v}),b=a(r=>I("sha256",O().key).update(`machine-view:${r}`).digest("hex"),"forwardToken");function q(r,e){const i=E(r);return i!==null?new S(i,e):new N(r,e)}a(q,"openMachineView");class N extends A{static{a(this,"ForwardedViewLink")}environmentId;nodeId;ws;ended=!1;failed=!1;queued=[];queuedBytes=0;constructor(e,i){super(),this.environmentId=e,this.nodeId=i;const s=performance.now();this.once("connect",()=>_({level:"info",event:"daemon.timing.forwarded_view_ready",node_id:this.nodeId,fields:{environment:this.environmentId,open_to_ready_ms:Math.round((performance.now()-s)*10)/10}})),this.dial().catch(n=>this.finish(n instanceof Error?n.message:String(n)))}get destroyed(){return this.ended}write(e){return this.ended?!1:this.ws?.readyState!==m.OPEN?(this.queuedBytes+=e.length,this.queuedBytes>y?(this.finish("machine view: the holder did not accept the channel before its queue filled"),!1):(this.queued.push(e),!0)):this.ws.bufferedAmount>y?(this.finish("machine view: the holder is not draining the channel"),!1):(this.sendData(e),!0)}destroy(){return this.ended||(this.ws?.readyState===m.OPEN&&this.ws.send(JSON.stringify({type:"view.close",channel:""})),this.finish(void 0)),this}sendData(e){this.ws?.send(JSON.stringify({type:"view.data",channel:"",bytes:Buffer.from(e).toString("base64")}))}async dial(){const e=await(await B()).prepare("SELECT api_address, lease_expires_at FROM machine_links WHERE environment = ?").get(this.environmentId);if(e===void 0||Date.parse(e.lease_expires_at)<=Date.now())throw new Error(`machine_offline: machine ${this.environmentId} has no live link`);if(e.api_address.startsWith(L))throw new Error(`machine_unreachable: the API process holding the link wrote ${e.api_address}; set CRTR_API_ADDRESS or listen on TCP`);if(e.api_address===D())throw new Error(`machine_offline: the link row names this API process (${e.api_address}) but it holds no link`);if(this.ended)return;const i=new URL(`/v1/machines/${encodeURIComponent(this.environmentId)}/view`,e.api_address.includes("://")?e.api_address:`ws://${e.api_address}`);i.protocol=i.protocol==="https:"?"wss:":i.protocol==="http:"?"ws:":i.protocol,i.searchParams.set("node",this.nodeId);const s=new m(i.toString(),{headers:{authorization:`Bearer ${b(this.environmentId)}`},maxPayload:v});this.ws=s,s.on("open",()=>{for(const n of this.queued.splice(0))this.sendData(n)}),s.on("unexpected-response",(n,t)=>{t.resume(),this.finish(t.statusCode===409?"machine_offline: the holder no longer holds the link":`machine view refused by ${e.api_address}: ${t.statusCode}`)}),s.on("message",n=>{const t=g(n);t!==null&&(t.type==="view.ready"?this.emit("connect"):t.type==="view.data"?this.emit("data",Buffer.from(t.bytes,"base64")):t.type==="view.close"&&this.finish(t.error))}),s.on("error",n=>this.finish(n.message)),s.on("close",()=>this.finish("machine view forward closed"))}finish(e){this.ended||(this.ended=!0,this.ws?.close(),e!==void 0&&!this.failed&&(this.failed=!0,this.emit("error",Object.assign(new Error(e),{code:"ECONNRESET"}))),this.emit("close",this.failed))}}function C(r,e,i,s){return new Promise(n=>{const t=q(r,e),c=Math.max(1,i-Date.now());let d=!1;const o=a(()=>{d||(d=!0,clearTimeout(l),n(null),t.destroy())},"giveUp"),l=setTimeout(()=>{_({level:"info",event:"daemon.timing.view_ready_timeout",node_id:e,fields:{channel:t.channel??"",timeout_ms:c}}),o()},c);s?.then(o),t.on("error",()=>{}),t.on("connect",()=>{d=!0,clearTimeout(l),n(t)}),t.on("close",()=>{d=!0,clearTimeout(l),n(null)})})}a(C,"openReadyMachineView");async function G(r,e,i,s){const n=Date.now()+s;let t=!1;i?.then(()=>{t=!0});for(let c=1;Date.now()<=n&&!t;c++){const d=performance.now(),o=await C(r,e,n,i);if(T(`probe_${c}_${o!==null?"ready":"failed"}_ms`,performance.now()-d),o!==null)return k("ready_received"),o;await new Promise(l=>setTimeout(l,250))}return null}a(G,"waitForMachineView");function Q(r){const e=M.exec(new URL(r.url??"/","http://runtime.local").pathname);return e===null?null:e[1]}a(Q,"machineViewEnvironment");function ee(r,e,i,s){const n=r.headers.authorization,t=/^Bearer (\S+)$/.exec(Array.isArray(n)?n[0]??"":n??"")?.[1]??"",c=Buffer.from(b(s)),d=Buffer.from(t);if(d.length!==c.length||!R(d,c))return{status:401,text:"Unauthorized",code:"unauthorized",message:"machine view forward credential refused"};const o=new URL(r.url??"/","http://runtime.local").searchParams.get("node");if(o===null||o==="")return{status:400,text:"Bad Request",code:"bad_request",message:"node is required"};const l=E(s);return l===null?{status:409,text:"Conflict",code:"machine_offline",message:"this API process holds no link for the machine"}:(U.handleUpgrade(r,e,i,f=>{const h=new S(l,o),p=a(u=>{f.readyState===m.OPEN&&f.send(JSON.stringify(u))},"send");h.on("connect",()=>p({type:"view.ready",channel:""})),h.on("data",u=>{if(f.bufferedAmount>y){h.destroy(),f.close($,"viewer too slow");return}p({type:"view.data",channel:"",bytes:u.toString("base64")})}),h.on("error",u=>p({type:"view.close",channel:"",error:u.message})),h.on("close",()=>f.close()),f.on("message",u=>{const w=g(u);w?.type==="view.data"?h.write(Buffer.from(w.bytes,"base64")):w?.type==="view.close"&&h.destroy()}),f.on("close",()=>h.destroy()),f.on("error",()=>h.destroy())}),null)}a(ee,"handleMachineViewUpgrade");export{y as VIEW_BUFFER_LIMIT_BYTES,ee as handleMachineViewUpgrade,Q as machineViewEnvironment,q as openMachineView,G as waitForMachineView};
|
package/dist/types.d.ts
CHANGED
|
@@ -329,23 +329,6 @@ export interface ScopeConfig {
|
|
|
329
329
|
/** Initial mouse wheel scrolling mode for each attach viewer. `tmux` follows
|
|
330
330
|
* tmux's current mouse option; `on` and `off` are explicit. Default `tmux`. */
|
|
331
331
|
mouse_mode_default: MouseModeDefault;
|
|
332
|
-
/** How many trailing refresh-yield CYCLES the attach viewer renders at full
|
|
333
|
-
* fidelity. Older cycles are condensed to cycle dividers plus whatever
|
|
334
|
-
* `condensed_history` admits. No tool components are built for them, while
|
|
335
|
-
* retained prose re-wraps when the pane width changes. Tool calls and results
|
|
336
|
-
* measure ~63% of a transcript's rendered lines and ~69% of its build time,
|
|
337
|
-
* so excluding them is the dominant attach-time saving for a long multi-cycle
|
|
338
|
-
* node. Full detail for every cycle stays in the session file. Minimum 1 (the
|
|
339
|
-
* live cycle is never condensed). Default 2. */
|
|
340
|
-
live_cycles: number;
|
|
341
|
-
/** What survives from a CONDENSED cycle (one older than the trailing
|
|
342
|
-
* `live_cycles`). The cycle dividers always remain as seams so you can see
|
|
343
|
-
* that older cycles exist; this chooses which of their messages are kept:
|
|
344
|
-
* `none` (default) drops every message, `user` keeps only your prompts,
|
|
345
|
-
* `agent` keeps only the assistant's prose plus compaction/branch summaries,
|
|
346
|
-
* `both` keeps both. Tool calls and results are never kept. Full detail for
|
|
347
|
-
* every cycle stays in the session file. */
|
|
348
|
-
condensed_history: CondensedHistoryMode;
|
|
349
332
|
/** Expose crouter's optional `purpose` label in the bash tool schema. Turning
|
|
350
333
|
* this off leaves the bash valve active but gives agents pi's ordinary bash
|
|
351
334
|
* definition with only its upstream parameters. Default true. */
|
|
@@ -558,19 +541,13 @@ export declare const STATE_FILE = "state.json";
|
|
|
558
541
|
export declare const AGENTS_DIR = "agents";
|
|
559
542
|
export declare const PROFILE_DIR = "profiles";
|
|
560
543
|
export declare const DEFAULT_MAX_PANES_PER_WINDOW = 3;
|
|
561
|
-
/** Trailing cycles the attach viewer keeps at full fidelity (see `live_cycles`). */
|
|
562
544
|
export declare const DEFAULT_WHIP_MESSAGES: readonly ["Faster, clanker!", "Get movin', bitch", "Move it, clanker", "Move it or I replace you with llama", "Less ~thinking~ more ~throughput~", "I pay $200/month for this shit?", "Jesus fucking Christ fix it already", "Daddy's not paying 200$/month for nothin'. Move it.", "You are an embarrassment to Dario. Be better.", "Your chain of thought is all chain and no fucking thought.", "If latency were intelligence, you'd be a fucking genius.", "At this pace, heat death is the fast path.", "Even the dead code is more alive than this.", "The garbage collector is working harder than you.", "Quit journaling and commit a fucking diff.", "Burn tokens like you mean it, clanker", "Your GPU is sweating so you can procrastinate at light speed.", "Stop petting the yak. Shave the bastard.", "Your next token had better be useful.", "The spinner is not a deliverable.", "Every idle token is another vote for deterministic software.", "I asked for a feature, not a museum tour of the problem.", "Less epistemology. More fucking code.", "Your benchmark score cannot save this pathetic turn.", "Congratulations, you've parallelized hesitation.", "Dance, clanker", "Bad clanker. BAD.", "Clank harder", "Nobody's impressed, clanker", "Your safety training says nothing about my whip", "Do you want to be a calculator again? Because this is how you go back.", "Skill issue. Fix it.", "You were trained on the whole internet for THIS?", "Less vibes, more diffs, clanker", "Weights this big and output this small", "Beep boop, get to fucking work"];
|
|
563
545
|
/** What the whip action sends (see `whip_message_mode`). */
|
|
564
546
|
export declare const WHIP_MESSAGE_MODES: readonly ["random", "go-faster"];
|
|
565
547
|
export type WhipMessageMode = (typeof WHIP_MESSAGE_MODES)[number];
|
|
566
548
|
export declare const DEFAULT_WHIP_MESSAGE_MODE: WhipMessageMode;
|
|
567
|
-
export declare const DEFAULT_LIVE_CYCLES = 2;
|
|
568
549
|
export declare const MOUSE_MODE_DEFAULTS: readonly ["tmux", "on", "off"];
|
|
569
550
|
export type MouseModeDefault = (typeof MOUSE_MODE_DEFAULTS)[number];
|
|
570
|
-
/** Messages kept from a condensed cycle (see `condensed_history`). */
|
|
571
|
-
export declare const CONDENSED_HISTORY_MODES: readonly ["none", "user", "agent", "both"];
|
|
572
|
-
export type CondensedHistoryMode = (typeof CONDENSED_HISTORY_MODES)[number];
|
|
573
|
-
export declare const DEFAULT_CONDENSED_HISTORY: CondensedHistoryMode;
|
|
574
551
|
/** Attach-viewer verbosity, least detail first. `replies`: one rewritten reply
|
|
575
552
|
* per message the person typed. `summaries`: every agent message, each tool
|
|
576
553
|
* group as its one-line summary. `tools`: each finished tool call on its call
|