@north-light/cli 0.3.679 → 0.3.680
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/api/client.js +3 -3
- package/dist/api/server-timing.d.ts +3 -0
- package/dist/api/server-timing.js +1 -0
- package/dist/clients/attach/viewer.js +447 -447
- package/dist/core/checkout-identities.js +3 -3
- package/dist/core/conversation-store/client.d.ts +9 -0
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +10 -2
- package/dist/core/conversation-store/index.js +1 -1
- package/dist/core/conversation-store/patch.js +1 -1
- package/dist/core/conversation-store/row-store.js +9 -9
- package/dist/core/runtime/broker.d.ts +3 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/front-door.js +4 -4
- package/dist/core/runtime/runner/blaxel/image-build.js +3 -3
- package/dist/core/runtime/runner/blaxel/release-image.js +2 -2
- package/dist/core/runtime/runner/machine/call.d.ts +5 -0
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/step-timings.d.ts +13 -0
- package/dist/core/step-timings.js +1 -0
- package/dist/core/timing.d.ts +2 -0
- package/dist/core/timing.js +2 -2
- package/dist/daemon/api/handlers/conversations.js +1 -1
- package/dist/daemon/api/handlers/nodes.d.ts +1 -0
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +4 -1
- package/packages/crouter-api/dist/api/server-timing.js +11 -0
- package/packages/crouter-api/dist/core/checkout-identities.js +4 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +8 -1
- package/packages/crouter-api/dist/core/conversation-store/index.js +1 -0
- package/packages/crouter-api/dist/core/conversation-store/patch.js +1 -2
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +2 -2
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +2 -2
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +1 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +7 -0
- package/packages/crouter-api/dist/core/runtime/spawn.js +30 -8
- package/packages/crouter-api/dist/core/step-timings.js +37 -0
- package/packages/crouter-api/dist/core/timing.js +14 -0
- 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/scripts/sandbox-bootstrap.sh +1 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var F=Object.defineProperty;var s=(o,n)=>F(o,"name",{value:n,configurable:!0});import{spawn as j}from"node:child_process";import{closeSync as K,existsSync as E,mkdirSync as C,openSync as X,statSync as J}from"node:fs";import{rm as V}from"node:fs/promises";import{basename as N,dirname as A,join as S}from"node:path";import{fileURLToPath as Y}from"node:url";import{emitEvent as W}from"../../../events/emit.js";import{contextDir as z,jobDir as Q,nodeRunDir as O,crtrHome as M,viewSocketPath as q}from"../../../canvas/paths.js";import{captureTeardownSnapshot as Z,isAnyPidAlive as g,killProcessTreePids as D,listProcessTableAsync as ee}from"../../../canvas/pid.js";import{scopesFilePath as L}from"../../../canvas/paths.js";import{writeFileBeneath as P}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as oe}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as te}from"../../broker-ownership.js";import{isShippedCanvasExtension as ne}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as re,mergeCanvasExtensions as ie}from"../../canvas-extensions.js";import{layoutRoot as ce,runtimeRoot as se}from"../../../layout.js";import{composeAppProcessEnv as ae,overlayBrokerEnv as de}from"../../spawn-env.js";const I=s(()=>S(A(Y(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),U=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),ue=s(o=>new Promise(n=>setTimeout(n,o)),"sleep");async function k(){const o=[],n=await ee();if(n===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:r,command:e}of n){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:r,execution:t[1],node:t[2],command:e})}return o}s(k,"findBrokers");const fe=new Set([502,503,504]),le=1e3,pe=3e4,me=3e4,$=9e4;async function he(o,n,r,e){const t=Date.now()+$;for(let c=le;;c=Math.min(c*2,pe)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(me,Math.max(1,t-Date.now())));let a,u;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${n}/start`,{headers:{authorization:`Bearer ${r}`},signal:e===void 0?i:AbortSignal.any([i,e])}),u=`the control plane answered ${a.status} for the start bundle of ${n}`}catch(f){e?.throwIfAborted(),u=`the control plane could not be reached for the start bundle of ${n}: ${f instanceof Error?f.message:String(f)}`}if(a?.ok)return await a.json();if(a!==void 0&&!fe.has(a.status))throw new Error(u);if(Date.now()+c>=t)throw new Error(`${u} (gave up after ${$/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(f=>{const w=setTimeout(l,c);function l(){clearTimeout(w),e?.removeEventListener("abort",l),f()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(he,"fetchBundle");const we=["CRTR_HOME","CRTR_RUNTIME_HOME"];function B(o,n){const r={...o};for(const e of we)delete r[e];return r.CRTR_CONTEXT_DIR!==void 0&&(r.CRTR_CONTEXT_DIR=z(n.id,r.CRTR_GRANTEE??n.app)),r.CRTR_SCOPES_FILE!==void 0&&(r.CRTR_SCOPES_FILE=L(n.id)),r}s(B,"localLaunchEnv");function _e(o){const n=s(i=>N(i).replace(/\.[jt]s$/,""),"stem"),r=new Set(re.map(n)),e=s(i=>ne(i)||N(A(i))==="pi-extensions"&&(r.has(n(i))||n(i).startsWith("canvas-")&&!E(i)),"shipped"),t=[],c=[];for(let i=0;i<o.length;i++)if(o[i]==="-e"&&o[i+1]!==void 0){const a=o[++i];if(e(a))continue;if(!E(a))throw new Error(`extension ${a} does not exist on this machine`);c.push(a)}else t.push(o[i]);return[...ie(c).flatMap(i=>["-e",i]),...t]}s(_e,"localExtensionArgv");function Ee(o,n,r){const e=JSON.parse(o);return JSON.stringify({...e,argv:_e(e.argv),env:B(e.env??{},n),...r===void 0?{}:{start:r}})}s(Ee,"machineLaunchRecipe");function Re(o,n,r){const e=o.launch,t=de({argv:[],env:B(e.env??{},o.node)},ae(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:ce(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??se(),CRTR_API_URL:n.apiUrl,CRTR_EXECUTION_ID:r,CRTR_ENVIRONMENT_ID:n.environmentId,CRTR_VIEW_WSS:"0",[oe]:"1"})}s(Re,"machineBrokerEnv");async function G(o,n,r){const{tree:e,identities:t}=Z(o,null,r);if(t===null)return{confirmed:!1,error:`the process tree of broker ${o} could not be read, so shutdown cannot be confirmed`};const c=s(async(i,a)=>{for(let u=0;g(i);u+=100){if(u>=a)return!1;await ue(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],n),D(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(D(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(G,"stopBroker");async function $e(o=1e4){const r=(await Promise.all((await k()).filter(e=>te(e.command,M())).map(e=>G(e.pid,o)))).filter(e=>!e.confirmed);if(r.length>0)throw new Error(r.map(e=>e.error??"a broker did not stop").join("; "))}s($e,"stopAllBrokers");function Be(o){const n=(o.stopGraceS??10)*1e3,r=s(async e=>(await k()).find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c={};let i=performance.now();const a=s(d=>{const p=performance.now();c[d]=Math.round((p-i)*10)/10,i=p},"stepDone"),u=await r(e.executionId);if(a("process_lookup"),u!==void 0)return{pid:u.pid,timings:c};if(t?.throwIfAborted(),!E(e.cwd)||!J(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!E(I()))throw new Error(`the broker entry ${I()} does not exist`);const f=e.bundle??await he(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const w=f.launch,l=O(e.nodeId);C(l,{recursive:!0}),P(l,S(l,"broker-launch.json"),Ee(e.launchJson,f.node,e.start),{atomic:!0,mode:384}),w.env?.CRTR_SCOPES_FILE!==void 0&&P(l,L(e.nodeId),JSON.stringify(w.scopes??[]),{atomic:!0});const x=Q(e.nodeId);C(x,{recursive:!0});const R=X(S(x,"broker.log"),"a"),v=Re(f,o,e.executionId);delete v.CRTR_NODE_TOKEN,a("file_writes");try{t?.throwIfAborted();const d=j(process.execPath,[I(),"--canvas-home",M(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",R,R,"pipe"],env:v});let p,b=!1;const y=s(()=>{p!==void 0&&o.onExit?.({execution:e.executionId,node:e.nodeId,...p})},"report");d.once("exit",(T,m)=>{p={code:T,signal:m},b&&y()});const h=d.stdio[3];if(h==null||!("end"in h))throw U(d.pid),new Error("broker token pipe did not open");const H=await new Promise((T,m)=>{d.once("error",m),d.once("spawn",()=>{d.off("error",m),h.once("error",_=>{U(d.pid),m(_)}),h.end(e.nodeToken,_=>{_?m(_):T(d.pid)})})});return b=!0,y(),d.unref(),a("spawn_and_token_pipe"),W({level:"info",event:"machine.start.timing",node_id:e.nodeId,fields:{execution:e.executionId,...c}}),{pid:H,timings:c}}finally{K(R)}},async wake({execution:e}){const t=await r(e.executionId);if(t===void 0)return"no_broker";try{return process.kill(t.pid,"SIGUSR1"),"signalled"}catch(c){if(c.code==="ESRCH")return"no_broker";throw c}},async stop({execution:e,options:t}){const c=await r(e.executionId);return c===void 0?{confirmed:!0}:await G(c.pid,n,t.excludePid)},async status({execution:e}){const t=await r(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async"status.all"(e){return{running:(await k()).map(t=>({execution:t.execution,pid:t.pid}))}},async delete({nodeId:e}){return await V(O(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:q(e.nodeId)}}}}s(Be,"createMachineExecutor");export{Be as createMachineExecutor,he as fetchBundle,k as findBrokers,_e as localExtensionArgv,Re as machineBrokerEnv,Ee as machineLaunchRecipe,$e as stopAllBrokers};
|
|
@@ -17,8 +17,10 @@ export type MachineStartArgs = RunnerStartInput & {
|
|
|
17
17
|
/** The start data written into `broker-launch.json` for the broker; absent, the broker asks `cycle-start` as before. */
|
|
18
18
|
start?: StartDataDTO;
|
|
19
19
|
};
|
|
20
|
+
/** `timings` are the Mac's own step durations in ms inside `executor.start` (absent from a Mac on an older release). */
|
|
20
21
|
export interface MachineStartResult {
|
|
21
22
|
pid: number | null;
|
|
23
|
+
timings?: Record<string, number>;
|
|
22
24
|
}
|
|
23
25
|
export interface MachineWakeArgs {
|
|
24
26
|
execution: RunnerExecution;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ye=Object.defineProperty;var l=(e,r)=>ye(e,"name",{value:r,configurable:!0});import{accessSync as be,constants as xe}from"node:fs";import{isAbsolute as Ce,resolve as Se,join as Ee}from"node:path";import{appSpace as Oe}from"../layout.js";import{ApiError as ie}from"../../api/errors.js";import{spawnNode as Ie,forkSourceNode as $e,currentNodeContext as Re,rootOfSpine as Me,newNodeId as ae,preflightNodeId as Fe}from"./nodes.js";import{resolveProfileOperand as De}from"../profiles/manifest.js";import{selectProfileForCwd as Ne,selectProfileForCwdReadOnly as Be}from"../profiles/select.js";import{buildLaunchSpecAsync as de,buildPiArgv as Pe}from"./launch.js";import{devEnvironmentCwd as Le,runsOnBlaxel as Te,sandboxWorktreeRequest as Ae}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as We,rollbackManagedWorktreeAsync as je}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as ze,rollbackManagedWorktreeOnMachine as He,worktreeMachineOf as Ke}from"../worktree-machine.js";import{usage as p,brokerLaunchFailed as H}from"../errors.js";import{writeGoal as Ue}from"./kickoff.js";import{appendSituationalContext as Xe,formatSituationalProse as Ge}from"./situational-context.js";import{ensureRoadmap as Ve}from"./roadmap.js";import{buildWakeBearings as qe}from"./bearings.js";import{encodeKickoffOrigin as Je,KICKOFF_ORIGIN_ENV as Ye}from"./stamp/protocol.js";import{carryInitialInput as Qe}from"../runs/initial-input.js";import{ExecutionCapReached as se,beginExecution as le,crtrHome as Ze,getNode as w,fullName as ce,jobDir as en,recordExecutionPid as nn,abortExecution as B,setFrozen as X}from"../canvas/index.js";import{contextDir as G,nodeAgentDir as V}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as rn}from"../spaces/open-beneath.js";import{conversationIdFromPath as K,conversationStore as $}from"../conversation-store/index.js";import{appMemoryTooSmall as on,boundFleet as ue,brokerThresholdsForDaemon as q}from"./fleet.js";import{admitBrokerMemory as tn}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as an}from"./blaxel-environment.js";import{openViewerWindow as dn,focusOf as sn,windowOfPane as ln}from"./placement.js";import{awaitBrokerViewSocket as cn}from"./view-socket.js";import{readLogSnapshot as un}from"../events/read.js";import{transition as C}from"./lifecycle.js";import{beginBootFaultAttempt as fn}from"../canvas/recovery.js";import{headlessBrokerHost as J,brokerLaunchJson as wn}from"./host.js";import{openDb as mn,withCanvasWrite as hn}from"../canvas/db.js";import{warmNodeRepos as pn}from"../graph/reader.js";import{mintNodeToken as _n}from"../canvas/node-tokens.js";import{personIdAsync as kn}from"../canvas/person.js";import{recordLaunch as vn}from"../canvas/canvas.js";import{setExecutionLaunchJson as gn}from"../canvas/executions.js";import{acceptedRelease as fe,remoteMachineEnvironmentOf as yn}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as bn,awaitMachineCall as xn}from"./runner/machine/call.js";import{MachineLostError as Cn,MachineOfflineError as Sn}from"./runner/machine/ops.js";import{isDrained as En}from"../../daemon/drain.js";import{ensureDaemon as On}from"../../daemon/manage.js";import{readConfig as In}from"../config.js";import{modelRequestFromConfig as $n,unregisteredConcreteModel as Rn,unroutableConcreteModel as Mn}from"../model-routes.js";import{openModelRegistry as Fn}from"./model-registry.js";import{MODEL_SPEC_NEXT as Dn}from"./model-selection.js";import{forkNodeLedger as Nn}from"./ledger.js";import{appRungForGrant as Bn}from"../llm/app-rungs.js";import{APP_FAMILY as Y}from"../model-routes.js";import{discoverLifecycleHookRegistry as Pn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Ln}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Tn}from"../async-array.js";import{checkStart as An}from"./start-check.js";function S(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(S,"launchFailureOutcome");async function Wn(e,r,a){try{return await J.launch(e,r,a)}catch(o){try{await C(e,"crash",{reason:"launch_failed",outcome:S(o)})}catch{}const t=o.message;throw H(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}l(Wn,"launchBrokerOrCrash");function jn(e){return un({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}l(jn,"lastStartupStep");function zn(e,r){const a=jn(e),o=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(r.reason==="exited"){const{code:t,signal:d}=r.status;return{text:`exited (code ${t??"null"}, signal ${d??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:t,signal:d,last_startup_step:a}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:a}}}l(zn,"notReadyDescription");async function Hn(e,r){try{await C(e,"crash",{reason:"launch_failed",outcome:S(r)})}catch{}try{J.teardown(e)}catch{}}l(Hn,"crashAndTearDown");async function Kn(e){const r=(await $().list()).map(({conversation_id:t,path:d})=>({id:t,path:d})),a=r.filter(t=>t.id===e),o=a.length>0?a:r.filter(t=>t.id.startsWith(e));if(o.length===0)throw p(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(o.length>1)throw p(`--fork-from '${e}': ambiguous \u2014 ${o.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return o[0].path}l(Kn,"resolveSessionUuid");async function we(e){const r=e.trim();if(r==="")throw p("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=K(Ce(r)?r:Se(process.cwd(),r));if(o===null)throw p(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await $().header(o)).path}const a=await w(r);if(a!==null){const o=a.pi_session_file;if(o==null||o==="")throw p(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=K(o);if(t===null)throw p(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await $().header(t)).path}return await Kn(r)}l(we,"resolveForkSource");async function Un(e,r,a,o={}){return e===null?null:e!==void 0&&e!==""?De(e).profileId:r!==null?(await w(r))?.profile_id??null:o.readOnlySelection===!0?Be(a):Ne(a)}l(Un,"resolveProfileId");function me(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return $n(e.model,r,e.modelExact===!0)}l(me,"requestFromLaunch");async function he(e,r,a){const o=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await Bn(r,o,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:d,...c}=e.env??{};return{...e,model:t.model,modelIntent:{family:Y,strength:t.strength},modelExact:void 0,env:{...c,CRTR_MODEL_INTENT:`${Y}/${t.strength}`}}}l(he,"appPaidLaunch");async function pe(e,r,a){if(e===void 0||e.kind==="logical"&&e.family!==Y)return;const o=await Rn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await Fn(),r);if(o!==void 0)throw p(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:Dn});const t=await Mn(e,r);if(t!==void 0)throw p(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(pe,"assertLaunchModelRegistered");function Xn(e,r,a){const o=e??r??null;if(!a&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}l(Xn,"resolveSpawner");async function Gn(e,r,a){const{buildStartBundle:o}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:t}=await import("../../daemon/api/handlers/broker-ops.js");if(await En())return"full";let d;try{d=await le(e.node_id,{daemonEpoch:ue().epoch(),cap:q().automaticReviveCap,runner:"machine",release:fe()})}catch(s){return s instanceof se?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),"failed")}let c;try{a.env={...a.env,CRTR_EXECUTION_ID:d};const s=await wn(e.node_id,a,e.cwd);await gn(d,s);const P=d;await pn(await mn(),e.node_id);const E=e.sub??await kn(),L=await o({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:E,launchJson:s,runner:"machine"});c=await hn(async _=>{const R=await t(e.node_id),M=await _n(_,P,e.node_id,new Date().toISOString());return await bn(r,"start",{executionId:P,nodeId:e.node_id,attempt:1,sandboxName:null,release:fe(),launchJson:s,cwd:e.cwd,resuming:!1,nodeToken:M,bundle:L,start:R})})}catch(s){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),await B(d,{reason:"launch_failed"}),"failed"}try{await xn(r,"start",c)}catch(s){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof Cn||s instanceof Sn&&s.sent?"uncertain":(await B(d,{reason:"launch_failed"}),"failed")}try{await vn(e.node_id,new Date().toISOString())}catch(s){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:s})}return"started"}l(Gn,"startOnMachine");async function _e(e,r,a){try{On()}catch{}const o=Re(),t=e.root===!0,d=Xn(e.parent,o.nodeId??null,t),c=e.mode??"base",s=e.rootLifecycle??(t?"resident":"terminal"),P=t&&s==="resident",E=d===null?null:await w(d),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Fe(e.nodeId);const _=e.forkFrom!==void 0?await we(e.forkFrom):void 0,R=_===void 0?null:await $e(_),M=await Tn([E,L,R],async f=>f?.isolated===!0||f?.run_id!=null&&(await w(f.run_id))?.isolated===!0);if(M&&e.isolated===!1)throw new ie(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const F=M||e.isolated===!0;if(F&&e.worktree===!0)throw new ie(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let m=F||e.worktree===!0?e.nodeId??await ae():e.nodeId,O=F?e.run!==void 0&&t&&!M?e.cwd:Ee(Oe(e.run?.grantee??E?.grantee??"app:terminal").nodes,m):e.cwd;const h=await Un(e.profile,d,O),T=F?null:await Le(h,e.worktreeCwd??O);T!==null&&(O=T,m??=await ae());const D=e.worktree===!0||T!==null,Q=e.run?.grant_id??E?.grant_id??null,N=e.run??L??E??R,Z=await he((await de(e.kind,c,{lifecycle:s,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:h,app:N?.grantee??"app:terminal"})).launch,Q,e.model);await pe(me(Z),{cwd:O,profileId:h}),await An({grantee:N?.grantee??"app:terminal",sub:N?.sub,grant_id:N?.grant_id});const ee=R?.node_id??null;let g,A=O;const W=D&&await Te(h)?await Ae(h,T??e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0,j=D&&W===void 0?await Ke(h):null;try{D&&W===void 0&&(g=j!==null?await ze(j,e.worktreeCwd??e.cwd,m,e.worktreeBase):await We(e.worktreeCwd??e.cwd,m,e.worktreeBase),A=g.path);const f=D?await he((await de(e.kind,c,{lifecycle:s,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:A,profileId:h,app:N?.grantee??"app:terminal"})).launch,Q,e.model):Z;W!==void 0&&(f.worktree=W),D&&await pe(me(f),{cwd:A,profileId:h});const n=await Ie({kind:e.kind,mode:c,lifecycle:s,cwd:A,name:e.name??e.kind,description:e.description,parent:t?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:ee,spawnedBy:t?d??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:F,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:_,modelOverride:e.model===void 0?void 0:f.model,...g!==void 0?{managedWorktree:g}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await Nn(n.node_id,ee??null)}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}if(await Ue(n.node_id,e.prompt),e.situationalContext!==void 0&&await Xe(n.node_id,Ge(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}const U=e.prompt!=="",ke=`${U&&e.wakeOrigin!==void 0?`${qe(e.wakeOrigin)}
|
|
1
|
+
var Ce=Object.defineProperty;var l=(e,r)=>Ce(e,"name",{value:r,configurable:!0});import{accessSync as Se,constants as Ee}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as $e}from"node:path";import{appSpace as Re}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Me,forkSourceNode as Fe,currentNodeContext as De,rootOfSpine as Ne,newNodeId as le,preflightNodeId as Be}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Pe,selectProfileForCwdReadOnly as Le}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as Ae}from"./launch.js";import{devEnvironmentCwd as We,runsOnBlaxel as je,sandboxWorktreeRequest as ze}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as He,rollbackManagedWorktreeAsync as Ke}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Ue,rollbackManagedWorktreeOnMachine as Xe,worktreeMachineOf as qe}from"../worktree-machine.js";import{usage as _,brokerLaunchFailed as K}from"../errors.js";import{writeGoal as Ge}from"./kickoff.js";import{appendSituationalContext as Ve,formatSituationalProse as Je}from"./situational-context.js";import{ensureRoadmap as Ye}from"./roadmap.js";import{buildWakeBearings as Qe}from"./bearings.js";import{encodeKickoffOrigin as Ze,KICKOFF_ORIGIN_ENV as en}from"./stamp/protocol.js";import{carryInitialInput as nn}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as rn,getNode as w,fullName as we,jobDir as tn,recordExecutionPid as on,abortExecution as T,setFrozen as G}from"../canvas/index.js";import{contextDir as V,nodeAgentDir as J}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as an}from"../spaces/open-beneath.js";import{conversationIdFromPath as U,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as dn,boundFleet as me,brokerThresholdsForDaemon as Y}from"./fleet.js";import{admitBrokerMemory as sn}from"./memory-admission.js";import{emitEvent as k}from"../events/emit.js";import{remoteEnvironmentOf as ln}from"./blaxel-environment.js";import{openViewerWindow as cn,focusOf as un,windowOfPane as fn}from"./placement.js";import{awaitBrokerViewSocket as wn}from"./view-socket.js";import{readLogSnapshot as mn}from"../events/read.js";import{transition as S}from"./lifecycle.js";import{beginBootFaultAttempt as hn}from"../canvas/recovery.js";import{headlessBrokerHost as Q,brokerLaunchJson as pn}from"./host.js";import{openDb as _n,withCanvasWrite as kn}from"../canvas/db.js";import{warmNodeRepos as vn}from"../graph/reader.js";import{mintNodeToken as gn}from"../canvas/node-tokens.js";import{personIdAsync as yn}from"../canvas/person.js";import{recordLaunch as bn}from"../canvas/canvas.js";import{setExecutionLaunchJson as xn}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as Cn}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as Sn,awaitMachineCall as En,callTimes as On}from"./runner/machine/call.js";import{addStepTiming as Z,timedStep as X}from"../step-timings.js";import{MachineLostError as In,MachineOfflineError as $n}from"./runner/machine/ops.js";import{isDrained as Rn}from"../../daemon/drain.js";import{ensureDaemon as Mn}from"../../daemon/manage.js";import{readConfig as Fn}from"../config.js";import{modelRequestFromConfig as Dn,unregisteredConcreteModel as Nn,unroutableConcreteModel as Bn}from"../model-routes.js";import{openModelRegistry as Tn}from"./model-registry.js";import{MODEL_SPEC_NEXT as Pn}from"./model-selection.js";import{forkNodeLedger as Ln}from"./ledger.js";import{appRungForGrant as An}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Wn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as jn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as zn}from"../async-array.js";import{checkStart as Hn}from"./start-check.js";function E(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(E,"launchFailureOutcome");async function Kn(e,r,o){try{return await Q.launch(e,r,o)}catch(t){try{await S(e,"crash",{reason:"launch_failed",outcome:E(t)})}catch{}const a=t.message;throw K(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}l(Kn,"launchBrokerOrCrash");function Un(e){return mn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}l(Un,"lastStartupStep");function Xn(e,r){const o=Un(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:d}=r.status;return{text:`exited (code ${a??"null"}, signal ${d??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:d,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}l(Xn,"notReadyDescription");async function qn(e,r){try{await S(e,"crash",{reason:"launch_failed",outcome:E(r)})}catch{}try{Q.teardown(e)}catch{}}l(qn,"crashAndTearDown");async function Gn(e){const r=(await R().list()).map(({conversation_id:a,path:d})=>({id:a,path:d})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw _(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw _(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}l(Gn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw _("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=U(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw _(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await R().header(t)).path}const o=await w(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw _(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=U(t);if(a===null)throw _(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await R().header(a)).path}return await Gn(r)}l(pe,"resolveForkSource");async function Vn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await w(r))?.profile_id??null:t.readOnlySelection===!0?Le(o):Pe(o)}l(Vn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Dn(e.model,r,e.modelExact===!0)}l(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await An(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:d,...c}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...c,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}l(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Nn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await Tn(),r);if(t!==void 0)throw _(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Pn});const a=await Bn(e,r);if(a!==void 0)throw _(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(ve,"assertLaunchModelRegistered");function Jn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}l(Jn,"resolveSpawner");async function Yn(e,r){const o=await On(e);o!==null&&Z("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))Z(`mac_${t}`,a)}l(Yn,"recordStartCallTimings");async function Qn(e,r,o){const{buildStartBundle:t}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:a}=await import("../../daemon/api/handlers/broker-ops.js");if(await Rn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Y().automaticReviveCap,runner:"machine",release:he()})}catch(s){return s instanceof ue?"full":(k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),"failed")}let c;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const s=await pn(e.node_id,o,e.cwd);await xn(d,s);const P=d;await X("warm_repos",async()=>await vn(await _n(),e.node_id));const O=e.sub??await yn(),L=await X("start_bundle",()=>t({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:O,launchJson:s,runner:"machine"}));c=await X("render_transaction",()=>kn(async v=>{const M=await a(e.node_id),F=await gn(v,P,e.node_id,new Date().toISOString());return await Sn(r,"start",{executionId:P,nodeId:e.node_id,attempt:1,sandboxName:null,release:he(),launchJson:s,cwd:e.cwd,resuming:!1,nodeToken:F,bundle:L,start:M})}))}catch(s){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),await T(d,{reason:"launch_failed"}),"failed"}let m;try{m=await En(r,"start",c)}catch(s){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof In||s instanceof $n&&s.sent?"uncertain":(await T(d,{reason:"launch_failed"}),"failed")}try{await Yn(c,m)}catch(s){k({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:s})}try{await X("record_launch",()=>bn(e.node_id,new Date().toISOString()))}catch(s){k({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:s})}return"started"}l(Qn,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Mn()}catch{}const a=De(),d=e.root===!0,c=Jn(e.parent,a.nodeId??null,d),m=e.mode??"base",s=e.rootLifecycle??(d?"resident":"terminal"),P=d&&s==="resident",O=c===null?null:await w(c),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Be(e.nodeId);const v=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,M=v===void 0?null:await Fe(v),F=await zn([O,L,M],async f=>f?.isolated===!0||f?.run_id!=null&&(await w(f.run_id))?.isolated===!0);if(F&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const D=F||e.isolated===!0;if(D&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let h=D||e.worktree===!0?e.nodeId??await le():e.nodeId,I=D?e.run!==void 0&&d&&!F?e.cwd:$e(Re(e.run?.grantee??O?.grantee??"app:terminal").nodes,h):e.cwd;const p=await Vn(e.profile,c,I),A=D?null:await We(p,e.worktreeCwd??I);A!==null&&(I=A,h??=await le());const N=e.worktree===!0||A!==null,ne=e.run?.grant_id??O?.grant_id??null,B=e.run??L??O??M,re=await ke((await ce(e.kind,m,{lifecycle:s,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:I,profileId:p,app:B?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:I,profileId:p}),await Hn({grantee:B?.grantee??"app:terminal",sub:B?.sub,grant_id:B?.grant_id});const te=M?.node_id??null;let y,W=I;const j=N&&await je(p)?await ze(p,A??e.worktreeCwd??e.cwd,h,e.worktreeBase):void 0,z=N&&j===void 0?await qe(p):null;try{N&&j===void 0&&(y=z!==null?await Ue(z,e.worktreeCwd??e.cwd,h,e.worktreeBase):await He(e.worktreeCwd??e.cwd,h,e.worktreeBase),W=y.path);const f=N?await ke((await ce(e.kind,m,{lifecycle:s,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:W,profileId:p,app:B?.grantee??"app:terminal"})).launch,ne,e.model):re;j!==void 0&&(f.worktree=j),N&&await ve(_e(f),{cwd:W,profileId:p});const n=await Me({kind:e.kind,mode:m,lifecycle:s,cwd:W,name:e.name??e.kind,description:e.description,parent:d?null:c,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:d?c??void 0:void 0,profile_id:p,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:D,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:v,modelOverride:e.model===void 0?void 0:f.model,...y!==void 0?{managedWorktree:y}:{},...h!==void 0?{nodeId:h}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(o?.(n.node_id),e.forkFrom!==void 0)try{await Ln(n.node_id,te??null)}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}if(await Ge(n.node_id,e.prompt),e.situationalContext!==void 0&&await Ve(n.node_id,Je(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}const q=e.prompt!=="",ye=`${q&&e.wakeOrigin!==void 0?`${Qe(e.wakeOrigin)}
|
|
2
2
|
|
|
3
|
-
`:""}${e.prompt}`;
|
|
3
|
+
`:""}${e.prompt}`;m==="orchestrator"&&await Ye(n.node_id,{goal:e.prompt.trim()}),await Zn(n);let oe;if(v!==void 0)try{const i=U(v);if(i===null)throw new Error(`invalid fork source ${v}`);const u=await R().fork(i,n.node_id);oe=(await R().header(u)).path}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}const g=Ae(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Ne(n.node_id)},q){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[en]=Ze(i),await nn(g,n)}const b=me();if(await ln(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await Cn(n.profile_id??null):null;if(u!==null){Z("birth",performance.now()-t);const C=await Qn(n,u,g);if(C==="started"||C==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await G(n.node_id,i),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}const ie=await b.reserveSlot(n.node_id),x=ie?await sn(n.node_id):null;if(x?.verdict==="too_small"){b.releaseReservation(n.node_id);const i=dn(x);throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}if(!ie||x?.verdict==="denied")return x?.verdict==="denied"&&b.releaseReservation(n.node_id),await G(n.node_id,new Date().toISOString()),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:x?.verdict==="denied"?{reason:"app_memory",free_bytes:x.free_bytes,needed_bytes:x.needed_bytes}:{reason:"broker_cap",live_count:await b.occupancy(),hard_cap:Y().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const be=await hn(n.node_id),{automaticReviveCap:xe}=Y();let $;try{$=await fe(n.node_id,{daemonEpoch:b.epoch(),cap:xe})}catch(i){if(!(i instanceof ue))throw i;return b.releaseReservation(n.node_id),await G(n.node_id,new Date().toISOString()),k({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}g.env={...g.env,CRTR_EXECUTION_ID:$};let H;try{H=await Kn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await T($,{reason:"launch_failed"}),i}finally{b.releaseReservation(n.node_id)}if(H.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await T($,{reason:"launch_failed"}),await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),K(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await on($,n.node_id,H.pid)==="shutdown")throw await T($,{reason:"superseded"}),Q.teardown(n.node_id),K(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(P&&e.readiness==="await"){const i=await wn(n.node_id,H.exited);if(!i.ready){const u=Xn(n.node_id,i);k({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const C=await be.explanation();throw await qn(n.node_id,new Error(C??u.text)),K(C!==null?`the root broker ${n.node_id} could not start \u2014 ${C}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,C!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ae=null,de=null;if(!d&&c!==null&&Fn("user").auto_open_child_viewers)try{const i=await un(c);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await cn(n.node_id,i.session??"",{name:we(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:q});u!==null&&u.pane!==null&&u.pane!==""&&(de=u.session,ae=fn(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:ae,session:de}}catch(f){throw y!==void 0&&h!==void 0&&await w(h)===null&&(z!==null?await Xe(z,y):await Ke(y)),f}}l(ge,"spawnChildPrepared");async function it(e){return ge(e)}l(it,"spawnChild");async function Zn(e){const r=Wn(e.cwd,e.profile_id).plans.get("node:start")??[];await jn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await J(e.node_id),contextDir:await V(e.node_id),jobDir:tn(e.node_id)},runtime:{isBirth:!0,canvasHome:rn(),profile:e.profile_id??null}})}l(Zn,"invokeBirthLifecycleHooks");const er=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function at(e,r,o){const t=await w(e);if(t===null)throw _(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await pe(e),d=await V(e);try{await R().header(U(a)),Se(d,Ee.R_OK)}catch(c){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${c.message}`)}return ge({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async c=>{const m=await V(c);an(await J(e),d,await J(c),m,er)})}l(at,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,at as forkNode,Zn as invokeBirthLifecycleHooks,pe as resolveForkSource,Vn as resolveProfileId,Jn as resolveSpawner,it as spawnChild,ge as spawnChildPrepared};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** Run `fn`, collecting the steps recorded beneath it. */
|
|
2
|
+
export declare function collectStepTimings<T>(fn: () => Promise<T>): Promise<{
|
|
3
|
+
value: T;
|
|
4
|
+
steps: Array<[string, number]>;
|
|
5
|
+
}>;
|
|
6
|
+
/** Record a step's duration in ms, when a request is collecting. */
|
|
7
|
+
export declare function addStepTiming(name: string, ms: number): void;
|
|
8
|
+
/** ms since the collection began (0 outside one). */
|
|
9
|
+
export declare function sinceCollectionStart(): number;
|
|
10
|
+
/** Run `fn` and record how long it took under `name`, whether it returns or throws. */
|
|
11
|
+
export declare function timedStep<T>(name: string, fn: () => Promise<T>): Promise<T>;
|
|
12
|
+
/** The `Server-Timing` header value for these steps: `name;dur=<ms>` joined by commas. */
|
|
13
|
+
export declare function serverTimingHeader(steps: ReadonlyArray<readonly [string, number]>): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var i=Object.defineProperty;var n=(t,e)=>i(t,"name",{value:e,configurable:!0});import{AsyncLocalStorage as a}from"node:async_hooks";const o=new a;async function u(t){const e=[];return{value:await o.run({steps:e,start:performance.now()},t),steps:e}}n(u,"collectStepTimings");function c(t,e){o.getStore()?.steps.push([t,e])}n(c,"addStepTiming");function f(){const t=o.getStore();return t===void 0?0:performance.now()-t.start}n(f,"sinceCollectionStart");async function m(t,e){const r=performance.now();try{return await e()}finally{c(t,performance.now()-r)}}n(m,"timedStep");function l(t){return t.map(([e,r])=>`${e};dur=${r.toFixed(1)}`).join(", ")}n(l,"serverTimingHeader");export{c as addStepTiming,u as collectStepTimings,l as serverTimingHeader,f as sinceCollectionStart,m as timedStep};
|
package/dist/core/timing.d.ts
CHANGED
|
@@ -9,3 +9,5 @@ export declare function timingProc(name: string): void;
|
|
|
9
9
|
* `up` ms since this process started (same sense as broker `duration_ms`)
|
|
10
10
|
*/
|
|
11
11
|
export declare function mark(phase: string, fields?: Record<string, unknown>): void;
|
|
12
|
+
/** Print each step of a response's `Server-Timing` header as a phase marker (`server.<name>`). */
|
|
13
|
+
export declare function markServerTiming(header: string): void;
|
package/dist/core/timing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`)}
|
|
1
|
+
var R=Object.defineProperty;var t=(e,n)=>R(e,"name",{value:n,configurable:!0});import{onServerTiming as T}from"../api/server-timing.js";const I="CRTR_TIMING",a="CRTR_TIMING_T0";function g(){return performance.timeOrigin+performance.now()}t(g,"nowMs");const i=(()=>{const e=process.env[I];return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"})(),$=(()=>{if(!i)return 0;const e=Number(process.env[a]);if(Number.isFinite(e)&&e>0)return e;const n=performance.timeOrigin;return process.env[a]=String(n),n})(),l=(()=>{const e=process.env.CRTR_TIMING_PROC;return e!==void 0&&e!==""?e:process.argv[2]==="surface"&&process.argv[3]==="attach"?"viewer":"cli"})();let f=0;function x(){return i}t(x,"timingEnabled");function G(e){i&&(process.env.CRTR_TIMING_PROC=e)}t(G,"timingProc");function _(e,n){if(!i)return;const r=g(),o=r-$,s=f===0?o:r-f;f=r;const c=performance.now(),m=n===void 0?"":" "+Object.entries(n).map(([u,v])=>`${u}=${String(v)}`).join(" "),d=process.env.CRTR_TIMING_PROC??l,p=t(u=>u.toFixed(1).padStart(8),"fmt");process.stderr.write(`[timing] +${p(o)}ms \u0394${p(s)}ms up=${p(c)}ms t=${r.toFixed(1)} ${d}/${process.pid} ${e}${m}
|
|
2
|
+
`)}t(_,"mark");function C(e){if(i)for(const n of e.split(",")){const[r,...o]=n.trim().split(";"),s=o.find(c=>c.startsWith("dur="))?.slice(4);r!==void 0&&r!==""&&s!==void 0&&_(`server.${r}`,{dur_ms:s})}}t(C,"markServerTiming"),T(C);export{_ as mark,C as markServerTiming,x as timingEnabled,G as timingProc};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
var _=Object.defineProperty;var r=(e,a)=>_(e,"name",{value:a,configurable:!0});import{conversationStore as b}from"../../../core/conversation-store/index.js";import{createRowStore as T}from"../../../core/conversation-store/row-store.js";import{conversationOwner as N}from"../../../core/canvas/sessions.js";import{mayOnNode as v}from"../router.js";import{ApiError as l}from"../../../api/errors.js";const m=128*1024*1024,s=r(()=>b(),"store"),o=r(e=>e.body,"input");function d(){throw new l(404,"not_found","conversation not found")}r(d,"notFound");async function p(e,a,n=!1){const t=await N(a);if(!t)return d();if(e.principal.class==="broker"){if(t!==e.principal.node)return d()}else if(n||e.principal.class!=="person"||!await v(e.principal,"read",t))return d();return t}r(p,"authorize");const O=r(async(e,a)=>{await p(e,a);const n=e.query.get("head"),t=e.query.get("tail");if(n!==null||t!==null){if(n===null||t===null||!/^\d+$/.test(n)||!/^\d+$/.test(t)||Number(n)>m||Number(t)>m)throw new l(400,"invalid_request","head and tail must be byte counts");const i=await s().read(a,{head:Number(n),tail:Number(t)});return e.res.writeHead(200,{"content-type":"application/x-ndjson","x-conversation-path":i.path,...i.tail?{"x-conversation-tail":String(i.entries.length+1)}:{}}),e.res.end([i.header,...i.entries,...i.tail??[]].map(f=>JSON.stringify(f)+`
|
|
2
2
|
`).join("")),{status:200}}const c=await s().readLines?.(a);if(!c)throw new Error("conversation store does not support streaming reads");e.res.writeHead(200,{"content-type":"application/x-ndjson","x-conversation-path":c.path});let u="";const w=r(()=>{const i=u;return u="",new Promise((f,y)=>e.res.write(i,h=>h?y(h):f()))},"flush");for await(const i of c.lines)u+=i+`
|
|
3
|
-
`,u.length>=256*1024&&await w();return u&&await w(),e.res.end(),{status:200}},"readResult"),k=[{method:"POST",pattern:"/v1/conversations",maxBodyBytes:m,handler:r(async e=>e.principal.class!=="broker"||o(e).node_id!==e.principal.node?d():{status:201,body:
|
|
3
|
+
`,u.length>=256*1024&&await w();return u&&await w(),e.res.end(),{status:200}},"readResult"),k=[{method:"POST",pattern:"/v1/conversations",maxBodyBytes:m,handler:r(async e=>e.principal.class!=="broker"||o(e).node_id!==e.principal.node?d():{status:201,body:await s().create(e.principal.node,o(e).header,o(e).entries)},"handler")},{method:"GET",pattern:"/v1/conversations",handler:r(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 s().list(e.principal.node)}}}if(e.principal.class!=="person")return d();const a=e.query.get("node_id");if(!a)throw new l(400,"invalid_request","node_id is required");return await v(e.principal,"read",a)?{status:200,body:{conversations:await s().list(a)}}:d()},"handler")},{method:"POST",pattern:"/v1/conversations/:id/entries",maxBodyBytes:m,handler:r(async e=>{await p(e,e.params.id,!0);const a=process.env.CRTR_FAULT_CONVERSATION??"";if(a.startsWith("append_refuse:")){const n=Number(a.slice(14));throw process.env.CRTR_FAULT_CONVERSATION=n>1?`append_refuse:${n-1}`:"",new l(503,"unavailable","conversation append refused (fault)")}return await s().append(e.params.id,o(e).entries),a==="append_drop_after_store"?(e.res.destroy(),{status:204}):{status:204}},"handler")},{method:"POST",pattern:"/v1/conversations/:id/commit",handler:r(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 T().commit(e.params.id)}}},"handler")},{method:"GET",pattern:"/v1/conversations/:id",handler:r(async e=>await O(e,e.params.id),"handler")},{method:"GET",pattern:"/v1/conversations/:id/header",handler:r(async e=>(await p(e,e.params.id),{status:200,body:await s().header(e.params.id)}),"handler")},{method:"PUT",pattern:"/v1/conversations/:id",maxBodyBytes:m,handler:r(async e=>(await p(e,e.params.id,!0),await s().replace(e.params.id,o(e).header,o(e).entries),{status:204}),"handler")},{method:"POST",pattern:"/v1/conversations/:id/fork",handler:r(async e=>{const a=await p(e,e.params.id,!0);return o(e).node_id!==a?d():{status:201,body:{conversation_id:await s().fork(e.params.id,a,o(e).leaf_id,o(e).cwd)}}},"handler")},{method:"DELETE",pattern:"/v1/conversations/:id",handler:r(async e=>(await p(e,e.params.id,!0),await s().delete(e.params.id),{status:204}),"handler")}];export{k as conversationRoutes};
|
|
@@ -8,6 +8,7 @@ interface CreatePreparation {
|
|
|
8
8
|
beforeBrokerLaunch?: (nodeId: string) => void;
|
|
9
9
|
}
|
|
10
10
|
export { resolveCreateKind } from '../../../core/runtime/launch-target.js';
|
|
11
|
+
/** Answers with a `Server-Timing` header naming how long each step of the create took, so the caller can read them without the control plane's logs. */
|
|
11
12
|
export declare function handleCreate(ctx: RequestContext, deps?: NodeHandlerDeps, preparation?: CreatePreparation): Promise<HandlerResult>;
|
|
12
13
|
export declare function handleList(ctx: RequestContext): Promise<HandlerResult>;
|
|
13
14
|
export declare function handleFork(ctx: RequestContext): Promise<HandlerResult>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var De=Object.defineProperty;var d=(e,n)=>De(e,"name",{value:n,configurable:!0});import{randomUUID as Le}from"node:crypto";import{envProfileId as Me}from"../../../shared/env.js";import{pausedCanvasProfiles as je}from"../../../core/profiles/manifest.js";import{existsSync as $,realpathSync as re,statSync as oe}from"node:fs";import{isAbsolute as V,resolve as L}from"node:path";import{appendSituationalContext as Ge,formatSituationalProse as Fe}from"../../../core/runtime/situational-context.js";import{closeNode as Be}from"../../../core/runtime/close.js";import{reviveNode as We}from"../../../core/runtime/revive.js";import{nowIso as x}from"../../../core/fs-utils.js";import{appPaidLaunch as Ve,assertLaunchModelRegistered as U,forkNode as xe,resolveForkSource as ae,spawnChildPrepared as Ue}from"../../../core/runtime/spawn.js";import{forkSourceNode as de,newNodeId as se}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as le,CREATE_LEASE_RENEW_MS as Ke,claimCreateLease as ce,createLeaseLive as ze,renewCreateLease as Je,childrenOf as Ye,completeCreateRequest as ue,findCreateRequest as fe,getNode as b,recordCreateRequestNode as He,reserveCreateRequest as pe,reserveCreateRequestNode as Qe,listNodes as Xe,recordRespawnAttempt as Ze,subscribersOf as qe,subscriptionsOf as me,updateNode as N}from"../../../core/canvas/canvas.js";import{armControllerWait as en,liveControllerWaits as nn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as tn}from"../../../core/canvas/recovery.js";import{nodeObject as rn}from"../../../core/graph/objects.js";import{recordActedOn as on}from"../../../core/graph/edges.js";import{publish as an}from"../../../core/graph/events.js";import{readerFor as dn}from"../reader.js";import{relocateSessionCwd as sn,unbindSession as ln}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as cn}from"../../../core/canvas/attention.js";import{isSafeNodeId as un}from"../../../core/canvas/paths.js";import{contextDir as we,nodeAgentDir as z}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as fn,cronRefusalError as pn}from"../../cron/authority.js";import{cronBirthPlacement as mn}from"../../cron/armed-context.js";import{existsBeneath as wn,isAbsentOrRefused as hn,isBeneathRefusal as yn,readdirBeneath as _n}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as gn,readNodeSession as bn,readNodeSnapshot as vn,transcriptMarkdown as kn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as Sn}from"../../../core/substrate/subject.js";import{reviveAll as Rn}from"../../../core/runtime/revive-all.js";import{promoteAsync as In,requestYieldAsync as On,reshapeNodeAsync as J}from"../../../core/runtime/promote.js";import{recycleNode as En}from"../../../core/runtime/recycle.js";import{relaunchRoot as An}from"../../../core/runtime/reset.js";import{assertReopenGate as Cn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as $n}from"./broker-recovery.js";import{readOutputRequest as Nn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Tn,readGoal as Pn,captureGoalIfAbsent as Dn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Ln,hasRoadmap as Mn}from"../../../core/runtime/roadmap.js";import{renameWindow as jn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Gn,explicitModelIntent as Fn,normalizeModel as Bn,readMergedLaunchConfigAsync as he}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Wn}from"../../../core/model-routes.js";import{persistDormantModel as Vn,setModelLive as xn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ye}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Un}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Kn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as zn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as _e}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Jn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Yn}from"../../../core/human-actions.js";import{parseDurationMs as Hn}from"../../../core/wake.js";import{claimWarmNode as Qn,refillWarmPool as ge,resumeWarmClaim as Xn,warmPoolEnabled as Zn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as qn,resolveLaunchTarget as et}from"../../../core/runtime/launch-target.js";import{fullName as nt}from"../../../core/canvas/labels.js";import{reportsForNode as be}from"./reports.js";import{requireUsableProfile as tt}from"./profiles.js";import{assertProfileActive as it,loadExactProfileManifest as rt}from"../../../core/profiles/manifest.js";import{getCron as H}from"../../../core/canvas/crons.js";import{cronWakeOrigin as ot}from"../../../core/runtime/bearings.js";import{boundDaemonControl as at}from"../../control.js";import{notFound as T,usage as h}from"../../../core/errors.js";import{assertScope as dt,validateScopes as ve}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as st,toNodeDetailDTO as Q,toNodeSummaryDTO as lt,toReviveResultDTO as ct}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{remoteEnvironmentOf as ke}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as ut}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as ft}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as pt,readableNodeIds as mt,resolvedScopes as wt}from"../router.js";import{forwardVerb as ht,queryWithoutMachine as yt,relayError as _t,unknownError as gt,withMachine as bt}from"../../peer/forward.js";import{fileRoot as vt}from"../../../core/spaces/file-root.js";import{activeGrant as kt,payerOfGrant as St}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Rt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as It}from"../../../core/grants/terminal.js";import{appRungForGrant as Ot}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Et}from"../../../core/model-routes.js";import{listProfileEnvNames as At}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Ct,NO_PROVIDER_CREDENTIAL_MESSAGE as Se}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as $t,mapAsync as Re}from"../../../core/async-array.js";async function w(e){const n=await b(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}d(w,"requireMeta");async function X(e){return{subscribesTo:await me(e),subscribers:await qe(e),children:await Ye(e)}}d(X,"edgesFor");async function v(e){const n=await w(e);return await Q(n,await X(e))}d(v,"detailOf");async function Nt(e){let n=(await be(e)).length;try{n+=_n(await z(e),await we(e)).length}catch(t){if(!hn(t))throw t}return n}d(Nt,"countFiles");function Tt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&ve(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new f(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Tt,"parseCreateBody");function Pt(e){if(e===void 0)return;const n=Hn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Pt,"parseDeadline");function Dt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Jn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>_e)throw new f(413,"payload_too_large",`serialized payload exceeds ${_e} bytes`)}return e}}d(Dt,"parseOutcomeDelivery");function Lt(e,n){const t=Yn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(Lt,"resolveOutcomeDelivery");function Mt(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(Mt,"buildRecipe");function jt(e,n,t){return!Zn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(jt,"warmRequestFor");import{resolveCreateKind as Jr}from"../../../core/runtime/launch-target.js";function Ie(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Wn(e.model,n,e.modelExact===!0)}d(Ie,"requestFromLaunch");function Gt(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!O(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(Gt,"withinCeiling");async function Oe(e,n,t){const r=(await Gn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await U(Ie(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Oe,"assertNodeModelChangeRegistered");async function Ft(e){if(!ft()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await H(e.cron))?.profile??null;return n!==null&&await ut(n)!==null}d(Ft,"callerRunsOnMachine");async function Ee(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await Ft(t))return;const r=vt({app:t.app,resolved:await wt(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(Ee,"assertCallerReaches");const Z=new Map;async function Bt(e,n={},t={}){const r=Gt(Tt(e.body),e.ceiling);if(e.principal.class==="broker"){const l=e.principal;if(r.prefer_warm===!0&&l.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==l.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await A(l,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==l.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await de(await ae(r.fork_from))}catch{}if(o?.grantee!==l.app||!await A(l,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=l.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const l=r.fork_from===void 0?null:await de(await ae(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,l?.node_id])if(o!=null&&await b(o)!==null&&!await pt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const l=e.principal;for(const s of["parent","creator","fork_from","node_id"])if(r[s]!=null)throw new f(403,"permission_error",`a cron cannot set ${s} on a node it starts`);r.prefer_warm=!1,r.node_id=await se(),l.isolated&&(r.isolated=!0,r.cwd=await z(r.node_id,l.app));const o=await fn({grantee:l.app,sub:l.sub,grant_id:l.grant,scopes:l.scopes,from_exec:l.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw pn(o);if(r.scopes!==void 0){const s=r.scopes.find(m=>!O(o.effectiveScopes,m)||!O(l.scopes,m));if(s!==void 0)throw new f(403,"scope_missing",`scope ${s} is not held by this cron`,void 0,void 0,{scope:s})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&dt(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&un(r.node_id)&&await b(r.node_id)!==null&&(await fe(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=Z.get(i);if(a!==void 0)return a;const c=Wt(e,r,i,n,t);Z.set(i,c);try{return await c}finally{Z.delete(i)}}d(Bt,"handleCreate");const Ae=`${process.pid}:${Le()}`,q="create_request_in_progress";async function Ce(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await ze(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await fe(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new f(409,q,"another create with this request_key is in progress; retry it")}d(Ce,"awaitForeignCreate");async function Wt(e,n,t,r,i){const a=await pe(t),c=Ae;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await ce(t,a.nodeId,c))try{return await Ce(e,t,a.nodeId)}catch(o){if(!(o instanceof f)||o.code!==q||!await ce(t,a.nodeId,c))throw o}const l=setInterval(()=>{Je(t,c).catch(()=>{})},Ke);try{return await Vt(e,n,t,r,i,a)}finally{clearInterval(l)}}d(Wt,"handleKeyedCreateRequest");async function Vt(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===q)throw c;const l=await pe(t);throw(l.nodeId===null||await b(l.nodeId)===null)&&await le(t,l.nodeId),c}}d(Vt,"keyedCreateOwned");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??Pt(n.deadline),c=Dt(n.outcome_delivery),l=e.principal.class==="cron"?await mn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await H(e.principal.cron))?.created_by??null},n.node_id):null;l!==null&&(n.root=l.root===!0);const o=l?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let s=null;if(n.output_schema!==void 0){try{s=JSON.parse(n.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(s===null||typeof s!="object"||Array.isArray(s))throw h("output_schema must be a JSON schema object");await zn(s)}const m=await et(n,{validateKind:Pe,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:p,kind:u,cwd:_,launch:R}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!$(_)&&await ke(p)===null)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Ee(e,_),n.worktree!==void 0&&await Ee(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:Lt(c,_),ne=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await U(Ie(await Ve(R,ne,n.model)),{cwd:_,profileId:p},t.modelRegistry),await St(ne)!=="app"&&!await Ct(p===null?[]:await At(p))&&!await Rt(m))throw new f(412,"no_provider_credential",Se,{error:"no_provider_credential",message:Se,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const te=i===void 0||i.nodeId===null||i.state==="warm_claimed"?jt(k,_,p):null,E=te!==null&&!(n.start===!0&&await ke(p)!==null)?te:null,W=s===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{s!==null&&await Kn(g,"terminal",s),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=E===null?null:await Xn(E,i.nodeId,W);if(g===null)throw await le(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ue(i.requestKey,g),{status:201,body:await v(g)}}if(E!==null){const g=await Qn(E,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},W);if(g!==null)return i!==void 0&&await ue(i.requestKey,g),ge(E),{status:201,body:await v(g)};B=E}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await se());if(i!==void 0&&i.nodeId===null){const g=await Qe(i.requestKey,D,Ae);if(g!==D)return await Ce(e,i.requestKey,g)}const I=Mt(D===void 0?k:{...k,node_id:D},o,_);l!==null&&(l.rootLifecycle!==void 0&&(I.rootLifecycle=l.rootLifecycle),l.scopes!==void 0&&k.scopes===void 0&&(I.scopes=l.scopes),l.run!==void 0&&(I.run=l.run),l.withinCreate!==void 0&&(I.withinCreate=l.withinCreate)),a!==void 0&&(I.deadlineAt=a),P!==void 0&&(I.outcomeDelivery=P),I.readiness=n.root===!0?"await":"launch";const ie=await Ue(I,W,()=>{B!==null&&ge(B)});return i!==void 0&&await He(i.requestKey,ie.node.node_id),{status:201,body:await v(ie.node.node_id)}}}d(G,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ee(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}d(ee,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}d(F,"oneOf");function xt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[R]of e.query)if(!n.has(R))throw h(`unknown nodes query parameter: ${R}`);const t=F(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=F(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),l=S(e,"profile_prefix"),o=S(e,"parent"),s=ee(S(e,"top_level"),"top_level"),m=S(e,"under"),p=ee(S(e,"under_inclusive"),"under_inclusive"),u=ee(S(e,"hanging"),"hanging"),_=F(S(e,"include"),"include",["activity"]);if(o!==void 0&&s===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...l!==void 0?{profile_prefix:l}:{},...o!==void 0?{parent:o}:{},...s!==void 0?{top_level:s}:{},...m!==void 0?{under:m}:{},...p!==void 0?{under_inclusive:p}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(xt,"parseListQuery");async function Ut(e){const n=xt(e);let t=await Xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await mt(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await cn(t.map(o=>o.node_id)):null,a=t.length>0?je():new Set,c=new Map((await nn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Re(t,async o=>{const s=await lt(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await be(o.node_id);s.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(p=>p.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return s})}}d(Ut,"handleList");async function Kt(e){const n=e.params.id,t=await ht(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:yt(e)});if(t.kind==="unknown")throw gt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw _t(t.status,t.body);return{status:t.status,body:bt(t.body,t.machine)}}return await w(n),{status:200,body:await v(n)}}d(Kt,"handleDetail");async function zt(e){const n=e.params.id;await w(n);const t=await vn(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:x()}}}d(zt,"handleSnapshot");async function Jt(e){const n=e.params.id,t=await Sn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(Jt,"handleSubject");function Yt(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(Yt,"parseMessagesQuery");async function Ht(e){const n=e.params.id,t=await gn(n,Yt(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:x()}}}d(Ht,"handleMessages");async function Qt(e){const n=e.params.id;await w(n);const t=await bn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:x()}}}d(Qt,"handleSession");async function Xt(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await kn(n)}}}d(Xt,"handleTranscript");async function Zt(e){const n=e.params.id;await w(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await we(i),self:a,files:await Nt(i)}),"root"),r=await $t([await t(n,!0),...await Re(await me(n),async i=>await t(i.node_id,!1))],async i=>await qt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(Zt,"handleContext");async function qt(e,n){try{return wn(await z(e),n)}catch(t){if(yn(t))return!1;throw t}}d(qt,"hasDir");async function ei(e){const n=await w(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await xe(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(ei,"handleFork");const ni=1e4;async function ti(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await Cn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await H(t.cron_id):null,c=await We(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await ot(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ze(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",o=(c.launch??M().get(n)?.handle)?.exited,s=c.outcome!=="frozen"&&await ye(n,o,ni);return{status:200,body:ct(n,c,l,s)}}d(ti,"handleRevive");async function ii(e){const n=e.params.id;return{status:200,body:{newNodeId:(await An(n))?.newNodeId??null}}}d(ii,"handleRelaunchRoot");async function ri(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=at(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Be(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:st(a)}}d(ri,"handleClose");async function oi(e){if(!j(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await tn(n),{status:204}}d(oi,"handleMarkRead");async function ai(e){const n=e.params.id;await w(n);const t=await En(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(ai,"handleRecycle");async function di(e){const n=e.params.id;return await w(n),await J(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(di,"handleDemote");async function si(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Oe(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await In(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await X(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(si,"handlePromote");async function li(e){const n=e.params.id;return await w(n),{status:200,body:{request:await Nn(n)}}}d(li,"handleBrokerStructuredRequest");async function ci(e){const n=e.params.id,t=e.body??{};if(await $n(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Dn(n,t.text)}}}d(ci,"handleBrokerGoal");async function ui(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Oe(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Tn(t,a);const c=await On(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await X(t))}}d(ui,"handleYield");async function fi(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await en(n,t.controller),{status:200,body:await v(n)}}d(fi,"handleWait");async function pi(e){const n=e.principal,t=await Rn(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(pi,"handleReviveAll");const mi=new Set(["interrupt","steer","after-turn","next-turn"]);function wi(e){if(e===null)return null;const n=d(r=>{throw new y({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!mi.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(wi,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await rn(i,n),c=await dn(i,e),l=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await on(i,l,a),await an(i,{event:"configured",object:a,actor:l,attrs:{changed:t.join(",")}})})}d(C,"recordConfigured");function $e(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d($e,"restartLiveBroker");function Ne(e,n){try{return re(e)===re(n)}catch{return!1}}d(Ne,"sameDirectory");async function hi(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(p=>p!=="profile"&&p!=="restart"&&i[p]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),s=await tt(e,i.profile);it(s.profileId);const m=rt(s.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${s.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==s.profileId&&(qn(o.kind)?(await Y(o.kind,o.cwd,s.profileId),await J(t,{profileId:s.profileId})):await N(t,{profile_id:s.profileId}),await C(e,t,["profile"])),i.restart===!0&&$e(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const s=await w(t),m=$(s.cwd);if(i.keep_session===!0||m&&V(o)&&$(o)&&Ne(s.cwd,o)){if(!V(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=oe(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!Ne(s.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${s.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const R=s.cwd;return R!==u&&(await K(async k=>{await N(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,R),await sn(t,R,u)}),await C(e,t,["cwd"])),i.restart===!0&&$e(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(s.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${s.cwd}`,received:o,field:"cwd",next:`Restore ${s.cwd}, then revive the fork normally.`});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if($(s.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${s.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!V(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const p=L(o);if(!$(p))throw new y({error:"cwd_missing",message:`cwd does not exist: ${p}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!oe(p).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${p}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${p}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await N(t,{cwd:p}),await ln(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await w(t);const c=i.listen===void 0?void 0:wi(i.listen);if(i.scopes!==void 0){const o=ve(i.scopes),s=a.grantee==="app:terminal"?await It(a):a.grant_id?await kt(a.grant_id):null;if(!o.every(m=>O(a.scopes,m)&&s!==null&&O(s.resolved,m)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!O(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await N(t,{scopes:o})}if(i.situational_context!==void 0&&await Ge(t,Fe(i.situational_context)),i.model!==void 0){const o=(await he(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,s=Fn(i.model,o),m=await Ot(a.grant_id,i.model,s===void 0),p=m?{family:Et,strength:m.strength}:s,u=m?m.model:Bn(i.model,o);await U({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let R=!1;if(await _.isClaimed(t)&&await ye(t,_.get(t)?.handle.exited)&&(R=await xn(t,u,p).then(()=>!0,k=>{if(k instanceof Un)return!1;throw k})),!R){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Vn(t,u,p)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Pe(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,s=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let p;s==="orchestrator"&&!await Mn(t)&&(p=d(async()=>{const u=await Pn(t);await Ln(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await J(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:s}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},p)}i.name!==void 0&&(a=await N(t,{name:i.name}),a.window&&jn(a.window,nt(a)));const l=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,l,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(hi,"handleConfig");async function Te(e="app:terminal"){return(await he(process.cwd(),Me()||null,e)).kinds}d(Te,"daemonKinds");async function Pe(e,n="app:terminal"){const t=Object.keys(await Te(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Pe,"assertKindServer");async function yi(){const e=await Te();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(yi,"handleListKinds");const Ur=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:Bt},{method:"GET",pattern:"/v1/nodes",handler:Ut},{method:"GET",pattern:"/v1/kinds",handler:d(()=>yi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:pi},{method:"GET",pattern:"/v1/nodes/:id",handler:Kt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:zt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Jt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Ht},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Qt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Xt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Zt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:ei},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:ti},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:ii},{method:"POST",pattern:"/v1/nodes/:id/close",handler:ri},{method:"POST",pattern:"/v1/nodes/:id/read",handler:oi},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:ai},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:di},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:si},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:li},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:ci},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:fi},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:hi}];export{hi as handleConfig,Bt as handleCreate,ei as handleFork,Ut as handleList,si as handlePromote,ui as handleYield,Ur as nodeRoutes,Jr as resolveCreateKind};
|
|
1
|
+
var De=Object.defineProperty;var d=(e,n)=>De(e,"name",{value:n,configurable:!0});import{randomUUID as Le}from"node:crypto";import{envProfileId as Me}from"../../../shared/env.js";import{pausedCanvasProfiles as je}from"../../../core/profiles/manifest.js";import{existsSync as T,realpathSync as re,statSync as oe}from"node:fs";import{isAbsolute as V,resolve as L}from"node:path";import{appendSituationalContext as Ge,formatSituationalProse as Fe}from"../../../core/runtime/situational-context.js";import{closeNode as Be}from"../../../core/runtime/close.js";import{reviveNode as We}from"../../../core/runtime/revive.js";import{nowIso as x}from"../../../core/fs-utils.js";import{appPaidLaunch as Ve,assertLaunchModelRegistered as U,forkNode as xe,resolveForkSource as ae,spawnChildPrepared as Ue}from"../../../core/runtime/spawn.js";import{forkSourceNode as de,newNodeId as se}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as le,CREATE_LEASE_RENEW_MS as Ke,claimCreateLease as ce,createLeaseLive as ze,renewCreateLease as Je,childrenOf as He,completeCreateRequest as ue,findCreateRequest as fe,getNode as b,recordCreateRequestNode as Ye,reserveCreateRequest as pe,reserveCreateRequestNode as Qe,listNodes as Xe,recordRespawnAttempt as Ze,subscribersOf as qe,subscriptionsOf as me,updateNode as $}from"../../../core/canvas/canvas.js";import{armControllerWait as en,liveControllerWaits as nn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as tn}from"../../../core/canvas/recovery.js";import{nodeObject as rn}from"../../../core/graph/objects.js";import{recordActedOn as on}from"../../../core/graph/edges.js";import{publish as an}from"../../../core/graph/events.js";import{readerFor as dn}from"../reader.js";import{relocateSessionCwd as sn,unbindSession as ln}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as cn}from"../../../core/canvas/attention.js";import{isSafeNodeId as un}from"../../../core/canvas/paths.js";import{contextDir as we,nodeAgentDir as z}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as fn,cronRefusalError as pn}from"../../cron/authority.js";import{cronBirthPlacement as mn}from"../../cron/armed-context.js";import{existsBeneath as wn,isAbsentOrRefused as hn,isBeneathRefusal as yn,readdirBeneath as _n}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as gn,readNodeSession as bn,readNodeSnapshot as vn,transcriptMarkdown as kn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as Sn}from"../../../core/substrate/subject.js";import{reviveAll as Rn}from"../../../core/runtime/revive-all.js";import{promoteAsync as In,requestYieldAsync as On,reshapeNodeAsync as J}from"../../../core/runtime/promote.js";import{recycleNode as En}from"../../../core/runtime/recycle.js";import{relaunchRoot as An}from"../../../core/runtime/reset.js";import{assertReopenGate as Cn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Tn}from"./broker-recovery.js";import{readOutputRequest as $n}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Nn,readGoal as Pn,captureGoalIfAbsent as Dn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Ln,hasRoadmap as Mn}from"../../../core/runtime/roadmap.js";import{renameWindow as jn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Gn,explicitModelIntent as Fn,normalizeModel as Bn,readMergedLaunchConfigAsync as he}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Wn}from"../../../core/model-routes.js";import{persistDormantModel as Vn,setModelLive as xn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ye}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Un}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Kn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as zn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as _e}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Jn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Hn}from"../../../core/human-actions.js";import{parseDurationMs as Yn}from"../../../core/wake.js";import{claimWarmNode as Qn,refillWarmPool as ge,resumeWarmClaim as Xn,warmPoolEnabled as Zn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as qn,resolveLaunchTarget as et}from"../../../core/runtime/launch-target.js";import{fullName as nt}from"../../../core/canvas/labels.js";import{reportsForNode as be}from"./reports.js";import{requireUsableProfile as tt}from"./profiles.js";import{assertProfileActive as it,loadExactProfileManifest as rt}from"../../../core/profiles/manifest.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as ot}from"../../../core/runtime/bearings.js";import{boundDaemonControl as at}from"../../control.js";import{notFound as N,usage as h}from"../../../core/errors.js";import{assertScope as dt,validateScopes as ve}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as st,toNodeDetailDTO as Q,toNodeSummaryDTO as lt,toReviveResultDTO as ct}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{remoteEnvironmentOf as ke}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as ut}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as ft}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as pt,readableNodeIds as mt,resolvedScopes as wt}from"../router.js";import{forwardVerb as ht,queryWithoutMachine as yt,relayError as _t,unknownError as gt,withMachine as bt}from"../../peer/forward.js";import{fileRoot as vt}from"../../../core/spaces/file-root.js";import{activeGrant as kt,payerOfGrant as St}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Rt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as It}from"../../../core/grants/terminal.js";import{appRungForGrant as Ot}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Et}from"../../../core/model-routes.js";import{listProfileEnvNames as At}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Ct,NO_PROVIDER_CREDENTIAL_MESSAGE as Se}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Tt,mapAsync as Re}from"../../../core/async-array.js";import{addStepTiming as $t,collectStepTimings as Nt,serverTimingHeader as Pt,sinceCollectionStart as Dt,timedStep as Lt}from"../../../core/step-timings.js";async function w(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(w,"requireMeta");async function X(e){return{subscribesTo:await me(e),subscribers:await qe(e),children:await He(e)}}d(X,"edgesFor");async function v(e){const n=await w(e);return await Q(n,await X(e))}d(v,"detailOf");async function Mt(e){let n=(await be(e)).length;try{n+=_n(await z(e),await we(e)).length}catch(t){if(!hn(t))throw t}return n}d(Mt,"countFiles");function jt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&ve(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new f(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return n}d(jt,"parseCreateBody");function Gt(e){if(e===void 0)return;const n=Yn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Gt,"parseDeadline");function Ft(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Jn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>_e)throw new f(413,"payload_too_large",`serialized payload exceeds ${_e} bytes`)}return e}}d(Ft,"parseOutcomeDelivery");function Bt(e,n){const t=Hn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(Bt,"resolveOutcomeDelivery");function Wt(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(Wt,"buildRecipe");function Vt(e,n,t){return!Zn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(Vt,"warmRequestFor");import{resolveCreateKind as eo}from"../../../core/runtime/launch-target.js";function Ie(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Wn(e.model,n,e.modelExact===!0)}d(Ie,"requestFromLaunch");function xt(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!O(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(xt,"withinCeiling");async function Oe(e,n,t){const r=(await Gn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await U(Ie(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Oe,"assertNodeModelChangeRegistered");async function Ut(e){if(!ft()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await ut(n)!==null}d(Ut,"callerRunsOnMachine");async function Ee(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await Ut(t))return;const r=vt({app:t.app,resolved:await wt(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(Ee,"assertCallerReaches");const Z=new Map;async function Kt(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Nt(()=>zt(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":Pt(a)}}}d(Kt,"handleCreate");async function zt(e,n,t){const r=xt(jt(e.body),e.ceiling);if(e.principal.class==="broker"){const l=e.principal;if(r.prefer_warm===!0&&l.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==l.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await A(l,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==l.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await de(await ae(r.fork_from))}catch{}if(o?.grantee!==l.app||!await A(l,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=l.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const l=r.fork_from===void 0?null:await de(await ae(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,l?.node_id])if(o!=null&&await b(o)!==null&&!await pt(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const l=e.principal;for(const s of["parent","creator","fork_from","node_id"])if(r[s]!=null)throw new f(403,"permission_error",`a cron cannot set ${s} on a node it starts`);r.prefer_warm=!1,r.node_id=await se(),l.isolated&&(r.isolated=!0,r.cwd=await z(r.node_id,l.app));const o=await fn({grantee:l.app,sub:l.sub,grant_id:l.grant,scopes:l.scopes,from_exec:l.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw pn(o);if(r.scopes!==void 0){const s=r.scopes.find(m=>!O(o.effectiveScopes,m)||!O(l.scopes,m));if(s!==void 0)throw new f(403,"scope_missing",`scope ${s} is not held by this cron`,void 0,void 0,{scope:s})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&dt(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&un(r.node_id)&&await b(r.node_id)!==null&&(await fe(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=Z.get(i);if(a!==void 0)return a;const c=Jt(e,r,i,n,t);Z.set(i,c);try{return await c}finally{Z.delete(i)}}d(zt,"createWithinTimings");const Ae=`${process.pid}:${Le()}`,q="create_request_in_progress";async function Ce(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await ze(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await fe(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new f(409,q,"another create with this request_key is in progress; retry it")}d(Ce,"awaitForeignCreate");async function Jt(e,n,t,r,i){const a=await pe(t),c=Ae;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await ce(t,a.nodeId,c))try{return await Ce(e,t,a.nodeId)}catch(o){if(!(o instanceof f)||o.code!==q||!await ce(t,a.nodeId,c))throw o}const l=setInterval(()=>{Je(t,c).catch(()=>{})},Ke);try{return await Ht(e,n,t,r,i,a)}finally{clearInterval(l)}}d(Jt,"handleKeyedCreateRequest");async function Ht(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===q)throw c;const l=await pe(t);throw(l.nodeId===null||await b(l.nodeId)===null)&&await le(t,l.nodeId),c}}d(Ht,"keyedCreateOwned");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??Gt(n.deadline),c=Ft(n.outcome_delivery),l=e.principal.class==="cron"?await mn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;l!==null&&(n.root=l.root===!0);const o=l?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let s=null;if(n.output_schema!==void 0){try{s=JSON.parse(n.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(s===null||typeof s!="object"||Array.isArray(s))throw h("output_schema must be a JSON schema object");await zn(s)}const m=await et(n,{validateKind:Pe,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:p,kind:u,cwd:_,launch:R}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!T(_)&&await ke(p)===null)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Ee(e,_),n.worktree!==void 0&&await Ee(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:Bt(c,_),ne=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await U(Ie(await Ve(R,ne,n.model)),{cwd:_,profileId:p},t.modelRegistry),await St(ne)!=="app"&&!await Ct(p===null?[]:await At(p))&&!await Rt(m))throw new f(412,"no_provider_credential",Se,{error:"no_provider_credential",message:Se,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const te=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Vt(k,_,p):null,E=te!==null&&!(n.start===!0&&await ke(p)!==null)?te:null,W=s===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{s!==null&&await Kn(g,"terminal",s),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=E===null?null:await Xn(E,i.nodeId,W);if(g===null)throw await le(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ue(i.requestKey,g),{status:201,body:await v(g)}}if(E!==null){const g=await Qn(E,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},W);if(g!==null)return i!==void 0&&await ue(i.requestKey,g),ge(E),{status:201,body:await v(g)};B=E}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await se());if(i!==void 0&&i.nodeId===null){const g=await Qe(i.requestKey,D,Ae);if(g!==D)return await Ce(e,i.requestKey,g)}const I=Wt(D===void 0?k:{...k,node_id:D},o,_);l!==null&&(l.rootLifecycle!==void 0&&(I.rootLifecycle=l.rootLifecycle),l.scopes!==void 0&&k.scopes===void 0&&(I.scopes=l.scopes),l.run!==void 0&&(I.run=l.run),l.withinCreate!==void 0&&(I.withinCreate=l.withinCreate)),a!==void 0&&(I.deadlineAt=a),P!==void 0&&(I.outcomeDelivery=P),I.readiness=n.root===!0?"await":"launch",$t("handler_checks",Dt());const ie=await Ue(I,W,()=>{B!==null&&ge(B)});return i!==void 0&&await Ye(i.requestKey,ie.node.node_id),{status:201,body:await Lt("response_detail",()=>v(ie.node.node_id))}}}d(G,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ee(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}d(ee,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}d(F,"oneOf");function Yt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[R]of e.query)if(!n.has(R))throw h(`unknown nodes query parameter: ${R}`);const t=F(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=F(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),l=S(e,"profile_prefix"),o=S(e,"parent"),s=ee(S(e,"top_level"),"top_level"),m=S(e,"under"),p=ee(S(e,"under_inclusive"),"under_inclusive"),u=ee(S(e,"hanging"),"hanging"),_=F(S(e,"include"),"include",["activity"]);if(o!==void 0&&s===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...l!==void 0?{profile_prefix:l}:{},...o!==void 0?{parent:o}:{},...s!==void 0?{top_level:s}:{},...m!==void 0?{under:m}:{},...p!==void 0?{under_inclusive:p}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(Yt,"parseListQuery");async function Qt(e){const n=Yt(e);let t=await Xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await mt(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await cn(t.map(o=>o.node_id)):null,a=t.length>0?je():new Set,c=new Map((await nn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Re(t,async o=>{const s=await lt(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await be(o.node_id);s.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(p=>p.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return s})}}d(Qt,"handleList");async function Xt(e){const n=e.params.id,t=await ht(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:yt(e)});if(t.kind==="unknown")throw gt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw _t(t.status,t.body);return{status:t.status,body:bt(t.body,t.machine)}}return await w(n),{status:200,body:await v(n)}}d(Xt,"handleDetail");async function Zt(e){const n=e.params.id;await w(n);const t=await vn(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:x()}}}d(Zt,"handleSnapshot");async function qt(e){const n=e.params.id,t=await Sn(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(qt,"handleSubject");function ei(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(ei,"parseMessagesQuery");async function ni(e){const n=e.params.id,t=await gn(n,ei(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:x()}}}d(ni,"handleMessages");async function ti(e){const n=e.params.id;await w(n);const t=await bn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:x()}}}d(ti,"handleSession");async function ii(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await kn(n)}}}d(ii,"handleTranscript");async function ri(e){const n=e.params.id;await w(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await we(i),self:a,files:await Mt(i)}),"root"),r=await Tt([await t(n,!0),...await Re(await me(n),async i=>await t(i.node_id,!1))],async i=>await oi(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(ri,"handleContext");async function oi(e,n){try{return wn(await z(e),n)}catch(t){if(yn(t))return!1;throw t}}d(oi,"hasDir");async function ai(e){const n=await w(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await xe(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(ai,"handleFork");const di=1e4;async function si(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await Cn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await Y(t.cron_id):null,c=await We(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await ot(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ze(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",o=(c.launch??M().get(n)?.handle)?.exited,s=c.outcome!=="frozen"&&await ye(n,o,di);return{status:200,body:ct(n,c,l,s)}}d(si,"handleRevive");async function li(e){const n=e.params.id;return{status:200,body:{newNodeId:(await An(n))?.newNodeId??null}}}d(li,"handleRelaunchRoot");async function ci(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=at(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Be(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:st(a)}}d(ci,"handleClose");async function ui(e){if(!j(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await tn(n),{status:204}}d(ui,"handleMarkRead");async function fi(e){const n=e.params.id;await w(n);const t=await En(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(fi,"handleRecycle");async function pi(e){const n=e.params.id;return await w(n),await J(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(pi,"handleDemote");async function mi(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Oe(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await In(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await X(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(mi,"handlePromote");async function wi(e){const n=e.params.id;return await w(n),{status:200,body:{request:await $n(n)}}}d(wi,"handleBrokerStructuredRequest");async function hi(e){const n=e.params.id,t=e.body??{};if(await Tn(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Dn(n,t.text)}}}d(hi,"handleBrokerGoal");async function yi(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Oe(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Nn(t,a);const c=await On(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await X(t))}}d(yi,"handleYield");async function _i(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await en(n,t.controller),{status:200,body:await v(n)}}d(_i,"handleWait");async function gi(e){const n=e.principal,t=await Rn(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(gi,"handleReviveAll");const bi=new Set(["interrupt","steer","after-turn","next-turn"]);function vi(e){if(e===null)return null;const n=d(r=>{throw new y({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!bi.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(vi,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await rn(i,n),c=await dn(i,e),l=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await on(i,l,a),await an(i,{event:"configured",object:a,actor:l,attrs:{changed:t.join(",")}})})}d(C,"recordConfigured");function Te(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Te,"restartLiveBroker");function $e(e,n){try{return re(e)===re(n)}catch{return!1}}d($e,"sameDirectory");async function ki(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(p=>p!=="profile"&&p!=="restart"&&i[p]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),s=await tt(e,i.profile);it(s.profileId);const m=rt(s.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${s.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==s.profileId&&(qn(o.kind)?(await H(o.kind,o.cwd,s.profileId),await J(t,{profileId:s.profileId})):await $(t,{profile_id:s.profileId}),await C(e,t,["profile"])),i.restart===!0&&Te(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const s=await w(t),m=T(s.cwd);if(i.keep_session===!0||m&&V(o)&&T(o)&&$e(s.cwd,o)){if(!V(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=oe(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!$e(s.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${s.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const R=s.cwd;return R!==u&&(await K(async k=>{await $(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,R),await sn(t,R,u)}),await C(e,t,["cwd"])),i.restart===!0&&Te(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(s.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${s.cwd}`,received:o,field:"cwd",next:`Restore ${s.cwd}, then revive the fork normally.`});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(T(s.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${s.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!V(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const p=L(o);if(!T(p))throw new y({error:"cwd_missing",message:`cwd does not exist: ${p}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!oe(p).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${p}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${p}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await $(t,{cwd:p}),await ln(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await w(t);const c=i.listen===void 0?void 0:vi(i.listen);if(i.scopes!==void 0){const o=ve(i.scopes),s=a.grantee==="app:terminal"?await It(a):a.grant_id?await kt(a.grant_id):null;if(!o.every(m=>O(a.scopes,m)&&s!==null&&O(s.resolved,m)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!O(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await $(t,{scopes:o})}if(i.situational_context!==void 0&&await Ge(t,Fe(i.situational_context)),i.model!==void 0){const o=(await he(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,s=Fn(i.model,o),m=await Ot(a.grant_id,i.model,s===void 0),p=m?{family:Et,strength:m.strength}:s,u=m?m.model:Bn(i.model,o);await U({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let R=!1;if(await _.isClaimed(t)&&await ye(t,_.get(t)?.handle.exited)&&(R=await xn(t,u,p).then(()=>!0,k=>{if(k instanceof Un)return!1;throw k})),!R){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Vn(t,u,p)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Pe(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,s=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let p;s==="orchestrator"&&!await Mn(t)&&(p=d(async()=>{const u=await Pn(t);await Ln(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await J(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:s}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},p)}i.name!==void 0&&(a=await $(t,{name:i.name}),a.window&&jn(a.window,nt(a)));const l=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,l,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(ki,"handleConfig");async function Ne(e="app:terminal"){return(await he(process.cwd(),Me()||null,e)).kinds}d(Ne,"daemonKinds");async function Pe(e,n="app:terminal"){const t=Object.keys(await Ne(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Pe,"assertKindServer");async function Si(){const e=await Ne();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(Si,"handleListKinds");const Xr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:Kt},{method:"GET",pattern:"/v1/nodes",handler:Qt},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Si(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:gi},{method:"GET",pattern:"/v1/nodes/:id",handler:Xt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Zt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:qt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:ni},{method:"GET",pattern:"/v1/nodes/:id/session",handler:ti},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:ii},{method:"GET",pattern:"/v1/nodes/:id/context",handler:ri},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:ai},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:si},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:li},{method:"POST",pattern:"/v1/nodes/:id/close",handler:ci},{method:"POST",pattern:"/v1/nodes/:id/read",handler:ui},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:fi},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:pi},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:mi},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:yi},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:wi},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:hi},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:_i},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ki}];export{ki as handleConfig,Kt as handleCreate,ai as handleFork,Qt as handleList,mi as handlePromote,yi as handleYield,Xr as nodeRoutes,eo as resolveCreateKind};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.680",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -156,8 +156,8 @@
|
|
|
156
156
|
},
|
|
157
157
|
"license": "UNLICENSED",
|
|
158
158
|
"dependencies": {
|
|
159
|
-
"@north-light/identity": "0.3.
|
|
160
|
-
"@north-light/plugin": "0.3.
|
|
159
|
+
"@north-light/identity": "0.3.680",
|
|
160
|
+
"@north-light/plugin": "0.3.680",
|
|
161
161
|
"@earendil-works/chord": "1.5.2",
|
|
162
162
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// local path resolution live exclusively in `api/node-transport.ts`.
|
|
5
5
|
import { ApiError, isErrorBody } from './errors.js';
|
|
6
6
|
import { routes } from './routes.js';
|
|
7
|
+
import { reportServerTiming } from './server-timing.js';
|
|
7
8
|
import { isSafeNodeId } from './dto/common.js';
|
|
8
9
|
import { isSafeBashJobId } from './dto/bash-jobs.js';
|
|
9
10
|
import { isSafeCronId, } from './dto/crons.js';
|
|
@@ -1093,7 +1094,9 @@ export class CrtrClient {
|
|
|
1093
1094
|
async sendOnce(method, path, body, callOpts = {}) {
|
|
1094
1095
|
const opts = this.resolveBudget(callOpts);
|
|
1095
1096
|
try {
|
|
1096
|
-
|
|
1097
|
+
const response = await this.transport(method, path, body, opts);
|
|
1098
|
+
reportServerTiming(response.headers.get('server-timing'));
|
|
1099
|
+
return await parse(response);
|
|
1097
1100
|
}
|
|
1098
1101
|
catch (error) {
|
|
1099
1102
|
throw toTransportApiError(error, opts.signal);
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// server-timing.ts — lets a caller see the `Server-Timing` header of the control plane's answers without this runtime-neutral client importing
|
|
2
|
+
// the runtime's timing module: the caller registers a listener, and the client hands it each header it receives.
|
|
3
|
+
let listener;
|
|
4
|
+
/** Register the function that receives each `Server-Timing` header value the client reads. */
|
|
5
|
+
export function onServerTiming(fn) {
|
|
6
|
+
listener = fn;
|
|
7
|
+
}
|
|
8
|
+
export function reportServerTiming(header) {
|
|
9
|
+
if (header !== null)
|
|
10
|
+
listener?.(header);
|
|
11
|
+
}
|
|
@@ -7,6 +7,7 @@ import { resolve } from 'node:path';
|
|
|
7
7
|
import { withCanvasWrite } from './canvas/db.js';
|
|
8
8
|
import { isCloudRole, PersonOutsideRequestError } from './canvas/person-state.js';
|
|
9
9
|
import { emitEvent } from './events/emit.js';
|
|
10
|
+
import { timedStep } from './step-timings.js';
|
|
10
11
|
import { realpathOrSelf } from './fs-utils.js';
|
|
11
12
|
import { checkoutChain } from './graph/repo-sync/identity.js';
|
|
12
13
|
import { callMachine } from './runtime/runner/machine/call.js';
|
|
@@ -17,10 +18,12 @@ import { MachineCallFailedError, MachineLostError, MachineOfflineError } from '.
|
|
|
17
18
|
export const machineCheckoutHandlers = {
|
|
18
19
|
'repo.identify': async ({ dirs }) => {
|
|
19
20
|
// A directory whose lookup failed (anywhere in its chain) is left out of the answer, so the cloud keeps what it stored; `[]` means not a repo.
|
|
21
|
+
const startedAt = performance.now();
|
|
20
22
|
const answers = await Promise.all(dirs.map(async (dir) => {
|
|
21
23
|
const chain = await checkoutChain(realpathOrSelf(resolve(dir)));
|
|
22
24
|
return chain.every((id) => id.ok) ? [dir, chain] : null;
|
|
23
25
|
}));
|
|
26
|
+
emitEvent({ level: 'info', event: 'machine.repo_identify.timing', fields: { dirs: dirs.length, duration_ms: Math.round(performance.now() - startedAt) } });
|
|
24
27
|
return Object.fromEntries(answers.filter((a) => a !== null));
|
|
25
28
|
},
|
|
26
29
|
};
|
|
@@ -32,7 +35,7 @@ export async function warmMachineCheckouts(environment, dirs) {
|
|
|
32
35
|
return true;
|
|
33
36
|
let answer;
|
|
34
37
|
try {
|
|
35
|
-
answer = await callMachine(environment, 'repo.identify', { dirs: wanted });
|
|
38
|
+
answer = await timedStep('repo_identify_call', () => callMachine(environment, 'repo.identify', { dirs: wanted }));
|
|
36
39
|
}
|
|
37
40
|
catch (error) {
|
|
38
41
|
if (!(error instanceof MachineOfflineError || error instanceof MachineLostError || error instanceof MachineCallFailedError))
|