@north-light/cli 0.3.679 → 0.3.681
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/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/profiles.d.ts +1 -1
- package/dist/api/server-timing.d.ts +3 -0
- package/dist/api/server-timing.js +1 -0
- package/dist/clients/attach/viewer.js +489 -489
- 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/profiles/manifest.js +1 -1
- 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/host.js +3 -3
- 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/core/user-settings.d.ts +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/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/crtrd.js +15 -15
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +5 -1
- package/packages/crouter-api/dist/api/contract.js +1 -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/profiles/manifest.js +7 -1
- package/packages/crouter-api/dist/core/runtime/host.js +9 -0
- 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 +43 -10
- 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,3 +1,3 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var c=(e,r)=>Ne(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as De}from"./unsandboxed.js";import{spawn as Ce}from"node:child_process";import{mkdirSync as
|
|
2
|
-
`,credentialed:JSON.stringify(
|
|
3
|
-
`,{atomic:!0,mode:432}),b
|
|
1
|
+
var Ne=Object.defineProperty;var c=(e,r)=>Ne(e,"name",{value:r,configurable:!0});import{assertGranteeRunsHere as De}from"./unsandboxed.js";import{spawn as Ce}from"node:child_process";import{mkdirSync as de,existsSync as j,unlinkSync as me,openSync as G,closeSync as L,writeSync as Le,chmodSync as $e,lstatSync as Ae}from"node:fs";import{ensureAppSpace as Be}from"../spaces/space.js";import{sandboxCacheEnv as je}from"../spaces/cache-env.js";import{compileLaunch as Ge,launchStillGranted as Fe}from"../spaces/mounts.js";import{grantsGeneration as he}from"../grants/mirror.js";import{LAUNCHER_SOCKET as z}from"../../launcher/spec.js";import{launcherRequest as F}from"../../launcher/client.js";import{piAgentDir as pe}from"./package-health.js";import{existsBeneath as V,readFileBeneath as Me,readTextBeneathIfExists as Ke,setModeBeneath as S,withDirBeneath as Q,writeFileBeneath as M}from"../spaces/open-beneath.js";import{dirname as Y,join as m,resolve as Je,isAbsolute as Ue}from"node:path";import{fileURLToPath as we}from"node:url";import{connectViewSocket as He}from"./view-socket.js";import{appSpace as K}from"../layout.js";import{readConfig as We,readMergedLaunchConfig as qe}from"../config.js";import{loadRotationConfig as Xe}from"../subscription-state.js";import{getNode as _}from"../canvas/index.js";import{withCanvasWrite as ze}from"../canvas/db.js";import{requestExecutionStop as Ve,setExecutionLaunchJson as Qe}from"../canvas/executions.js";import{scopesFilePath as Z,crtrHome as ge,nodeRunDir as I,nodeRunJobDir as Ye,jobDir as Ze,viewSocketPath as Ie,nodeAgentDir as er,contextDir as rr,nodeHome as nr}from"../canvas/paths.js";import{encodeFrame as Ee}from"./broker-protocol.js";import{buildBrokerEnv as tr}from"./spawn-env-rows.js";import{hostExecPathFresh as or}from"./branded-host.js";import{isPidAlive as ee,killProcessTreePids as _e,isAnyPidAlive as ir,captureTeardownSnapshot as sr}from"../canvas/pid.js";import{assertMandatoryCanvasExtensions as ar}from"./canvas-extensions.js";import{appMemoryFull as cr,appMemoryTooSmall as lr,boundFleet as ur,brokerCapReached as fr,brokerThresholdsForDaemon as dr}from"./fleet.js";import{admitBrokerMemory as mr}from"./memory-admission.js";import{emitEvent as w}from"../events/emit.js";import{bindBrokerEventSource as hr,eventSource as pr}from"../events/source.js";import{envBrokerEngine as wr}from"../../shared/env.js";import{conversationIdFromPath as gr,conversationStore as Er,ConversationNotFoundError as ke}from"../conversation-store/index.js";import{mintNodeToken as _r}from"../canvas/node-tokens.js";import{personId as kr}from"../canvas/person.js";function J(){const e=Y(we(import.meta.url));return m(e,"broker-cli.js")}c(J,"resolveBrokerEntry");const vr="@earendil-works/pi-coding-agent";function ve(){const e=m(pe(),"models.json"),r=Ke(Y(e),e);if(r===null)return null;const t=JSON.parse(r),o=c(n=>Array.isArray(n)?n.map(o):n===null||typeof n!="object"?n:Object.fromEntries(Object.entries(n).filter(([s])=>!/^(apiKey|authorization|headers|token|secret)$/i.test(s)).map(([s,a])=>[s,o(a)])),"scrub");return{text:r,clean:`${JSON.stringify(o(t),null,2)}
|
|
2
|
+
`,credentialed:JSON.stringify(t)!==JSON.stringify(o(t))}}c(ve,"scrubbedBrokerModels");function yr(e,r){const t=m(pe(),"models.json"),o=m(r,"models.json"),n=ve();if(n!==null){if(t===o&&n.text!==n.clean){if(n.credentialed)throw new Error("terminal models.json contains credentials; move them into daemon secrets");S(e,o,432);return}M(e,o,n.clean,{atomic:!0,mode:432}),S(e,o,432)}}c(yr,"writeBrokerModels");function ye(e){return e.env.CRTR_BROKER_ENGINE??wr()}c(ye,"resolveEngineSpec");function be(e){return e.includes("/")||e.endsWith(".jsonl")}c(be,"isPlainLaunchSessionPath");function br(e,r){return Ue(e)?e:Je(r,e)}c(br,"resolvePlainLaunchPath");async function Sr(e,r,t,o){if(t==="--session"&&!be(o))throw new Error(`[broker] refusing to launch ${e}: launch recipe passes bare --session id '${o}' \u2014 the broker fatally rejects bare ids; pass the .jsonl path instead.`);if(!be(o))return;const n=br(o,r),s=gr(n);try{if(s===null)throw new ke(n);await Er().header(s)}catch(a){if(!(a instanceof ke))throw a;const u=t==="--session"?"session file":"fork source";throw new Error(`[broker] refusing to launch ${e}: launch recipe references missing ${u} '${o}' (${n})`)}}c(Sr,"preflightLaunchSessionArg");async function Se(e,r,t){const o=ve();return JSON.stringify({...r,configSnapshot:{user:We("user"),launch:qe(t,r.env.CRTR_PROFILE_ID||null),rotation:await Xe()},scopes:(await _(e))?.scopes??null,models:o===null?null:JSON.parse(o.clean)})}c(Se,"brokerLaunchJson");async function Rr(e,r,t,o){const n=I(e);de(n,{recursive:!0}),process.platform==="linux"&&j(z)&&Ae(n).uid===process.getuid()&&$e(n,504);const s=m(n,"broker-launch.json");M(n,s,o??await Se(e,r,t),{atomic:!0}),r.env.CRTR_SCOPES_FILE!==void 0&&M(n,Z(e),JSON.stringify((await _(e))?.scopes??[]),{atomic:!0});const a=Me(n,s).toString("utf8"),u=JSON.parse(a);if(!Array.isArray(u.argv))throw new Error(`[broker] refusing to launch ${e}: broker-launch.json is missing the argv array`);const g=ye(r);try{const l=import.meta.resolve(g);if(l.startsWith("file:")&&!j(we(l)))throw new Error(`resolved to missing file ${l}`)}catch(l){throw new Error(`[broker] refusing to launch ${e}: cannot resolve broker engine '${g}' from ${J()} \u2014 ${l.message}`)}const h=u.argv,N=[];for(let l=0;l<h.length;l++){const T=h[l];if(T==="-e"){const D=h[++l];D!==void 0&&N.push(D);continue}if(T!=="--session"&&T!=="--fork")continue;const R=h[++l];R!==void 0&&await Sr(e,t,T,R)}try{ar(N)}catch(l){throw new Error(`[broker] refusing to launch ${e}: ${l.message}`)}}c(Rr,"preflightBrokerLaunch");const Pr=2e3,xr=2e3,Tr=150;async function U(e,r){const t=Date.now()+r;for(;ir(e);){const o=t-Date.now();if(o<=0)return!1;await new Promise(n=>setTimeout(n,Math.min(Tr,o)))}return!0}c(U,"waitForTreeExit");async function Or(e,r,t){return e.length===0?{confirmed:!0}:t&&await U(e,Pr)?{confirmed:!0}:(_e(e,"SIGTERM",r),await U(e,xr)?{confirmed:!0}:(_e(e,"SIGKILL",r),await U(e,5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`broker process tree for ${e.join(", ")} remained alive after SIGKILL`)}))}c(Or,"terminateBrokerTree");async function Re(e,r){const t=await _(e),o=t?.pi_pid,n=o!=null?sr(o,t?.pi_pid_identity??null,r.excludePid):null;return n?.reused===!0&&w({level:"warn",event:"broker.teardown.pid_reuse_refused",node_id:e,fields:{recorded_pid:o,expected_identity:t?.pi_pid_identity??null}}),{tree:n?.tree??[],identities:n?.identities??null,nodeId:e,launcherPid:j(z)&&n?.tree.includes(o)?o:null}}c(Re,"prepareBrokerTeardown");async function Pe(e){if(e.launcherPid!==null){try{await F({operation:"stop",pid:e.launcherPid})}catch(r){return ee(e.launcherPid)?{confirmed:!1,error:r instanceof Error?r:new Error(String(r))}:{confirmed:!0}}return await U([e.launcherPid],5e3)?{confirmed:!0}:{confirmed:!1,error:new Error(`launcher pid ${e.launcherPid} remained alive`)}}return new Promise(r=>{let t=!1,o=!1;const n=c(g=>{o||(o=!0,r(g))},"settle"),s=c(()=>{try{me(Ie(e.nodeId))}catch{}},"cleanupSocket"),a=c(g=>{Or(e.tree,e.identities,g).then(n,h=>n({confirmed:!1,error:h instanceof Error?h:new Error(String(h))}))},"finish"),u=He(e.nodeId);u.once("error",()=>{t||(s(),a(!1))}),u.once("connect",()=>{t=!0;try{u.write(Ee({type:"hello",role:"controller",client_id:`daemon-shutdown-${process.pid}`})),u.write(Ee({type:"shutdown"}))}catch{}u.end(),s(),a(!0)})})}c(Pe,"runPreparedBrokerTeardown");async function dn(e,r={},t){let o;try{await Ve(e,{afterTurn:r.startAfter!==void 0,reason:r.reason??"teardown"}),o=await Re(e,r)}catch(n){const s={confirmed:!1,error:n instanceof Error?n:new Error(String(n))};return w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:s.error}),s}return await new Promise(n=>{const s=c(()=>{Pe(o).then(async a=>{if(a.confirmed){if(t!==void 0)try{await t()}catch(u){w({level:"error",event:"broker.teardown.after_failed",node_id:e,error:u})}}else w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:a.error});n(a)},a=>{const u={confirmed:!1,error:a instanceof Error?a:new Error(String(a))};w({level:"error",event:"broker.teardown.unconfirmed",node_id:e,error:u.error}),n(u)})},"run");r.startAfter===void 0?setImmediate(s):r.startAfter.then(s,s)})}c(dn,"requestBrokerTeardown");function xe(){return process.platform==="linux"&&j(z)}c(xe,"isolatedBrokerLauncherAvailable");const mn={async launch(e,r,t){if(De((await _(e))?.grantee),(await _(e))?.isolated===!0&&!xe())throw new Error("isolated broker requires the Linux root launcher");const o=t.launchJson??await Se(e,r,t.cwd);await Rr(e,r,t.cwd,o);const n=r.env.CRTR_EXECUTION_ID;t.launchJson===void 0&&n!==void 0&&await Qe(n,o);const s=ur();if(!await s.reserveSlot(e))throw fr(dr().automaticReviveCap,await s.occupancy());let a=null,u,g=!1;try{const h=Ze(e);de(h,{recursive:!0}),a=G(m(h,"broker.log"),"a");const N=ye(r),l={...await tr(r),CRTR_BROKER_ENGINE:N};if(N!==vr){const i=r.env.NODE_OPTIONS??process.env.NODE_OPTIONS;i!==void 0&&(l.NODE_OPTIONS=i);const f=r.env.CRTR_TEST_PG_URL??process.env.CRTR_TEST_PG_URL;f!==void 0&&(l.CRTR_TEST_PG_URL=f)}pr()===void 0&&hr(e);const T=(await _(e))?.run_id;if(T){const i=await _(T);if(!i||i.deleting_at)throw new Error("run is deleting")}const R=r.env.CRTR_EXECUTION_ID;if(!R)throw new Error("broker launch has no execution id");const D=await ze(i=>_r(i,R,e,new Date().toISOString())),H=xe();if((await _(e))?.isolated===!0&&!H)throw new Error("isolated broker requires the Linux root launcher");if(process.platform==="linux"&&process.env.CRTR_LAUNCHER_SOCKET&&!H)throw new Error("root launcher socket is unavailable; refusing an unsandboxed broker");if(H){const i=await _(e);if(!i)throw new Error(`missing node ${e}`);const f=i.grantee??"app:terminal",O=await mr(e,{useMemo:!1});if(O.verdict==="denied")throw cr(O);if(O.verdict==="too_small")throw lr(O);const v=await Be(f);Object.assign(l,je(f));const y={uid:process.getuid(),gid:v.gid},E=I(e);for(const[d,k]of[[K(f).nodes,er(e,f)],[K(f).nodes,rr(e,f)],[E,Ye(e)]])Q(d,k,()=>{},!0),S(d,k,1528,y);S(E,m(E,"broker-launch.json"),416,y),V(E,Z(e))&&S(E,Z(e),416,y);const te=m(E,"system-prompt.md");V(E,te)&&S(E,te,432,y);for(const d of["output-schema.json","situational-context.md"]){const k=m(E,d);V(E,k)&&S(E,k,432,y)}const oe=i.isolated===!0,b=nr(e,f,oe);oe&&(Q(K(f).nodes,b,()=>{},!0),S(K(f).nodes,b,1528,y),l.HOME=b,l.PI_CODING_AGENT_DIR=m(b,".pi","agent"));const X=m(b,".pi","agent");Q(b,X,()=>{},!0),yr(b,X);const ie=m(X,"settings.json"),Te=m(Y(J()),"../../builtin-pi-packages/pi-crtr-extensions");M(b,ie,`${JSON.stringify({packages:[Te]})}
|
|
3
|
+
`,{atomic:!0,mode:432}),S(b,ie,432);const se=m(I(e),`token-${R}`),A=G(se,"wx+",384);me(se),Le(A,D);const ae=[G(`/proc/self/fd/${A}`,"r"),G(`/proc/self/fd/${A}`,"r")];L(A);const ce={nodeId:e,app:f,sub:i.sub??kr(),grantId:i.grant_id??null,scopes:i.scopes??null,isolated:i.isolated===!0,...i.isolated===!0?{cwd:i.cwd}:{},command:[process.execPath,J(),"--canvas-home",ge(),"--epoch",s.epoch(),e],env:Object.fromEntries(Object.entries({...l,...i.isolated===!0?{PWD:i.cwd}:{}}).filter(d=>d[1]!==void 0)),auditMissing:c(d=>w({level:"warn",event:"broker.mount.missing",node_id:e,fields:{source:d}}),"auditMissing")};try{let d;for(const C of ae){const B=await he(),p=await Ge(ce);p.broker=!0;const x=await F({operation:"launch",spec:p},[C]);if(!("pid"in x))throw new Error("launcher did not return a pid");if(await he()===B||await Fe(ce,p)){d=x.pid;break}w({level:"info",event:"broker.launch.regranted",node_id:e,fields:{pid:x.pid}}),await F({operation:"stop",pid:x.pid,signal:"SIGKILL"}).catch(()=>{})}if(d===void 0)throw new Error("grant changed during every launch attempt");const k=d,Oe=Date.now(),le=new Promise(C=>{const B=setInterval(()=>{ee(k)||(clearInterval(B),F({operation:"exit.status",pid:k}).then(p=>"oomKilled"in p?{oomKilled:p.oomKilled,code:p.code??null,signal:p.signal??null}:{oomKilled:!1,code:null,signal:null},()=>({oomKilled:!1,code:null,signal:null})).then(({oomKilled:p,code:x,signal:fe})=>{w({level:p||x!==0?"warn":"info",event:"broker.exited",node_id:e,fields:{pid:k,code:x,signal:fe,uptime_ms:Date.now()-Oe,oom_killed:p}}),C({code:x,signal:fe,...p?{oomKilled:!0}:{}})}))},250);B.unref()});L(a),a=null;const ue={pid:k,exited:le};return s.register(e,ue),g=!0,le.then(async C=>await s.onChildExit(e,C,R)),ue}finally{for(const d of ae)L(d)}}const W=await or(),P=Ce(W,[J(),"--canvas-home",ge(),"--epoch",s.epoch(),e],{cwd:t.cwd,detached:!0,stdio:["ignore",a,a,"pipe"],env:l});u=P;try{await new Promise((i,f)=>{P.once("spawn",i),P.once("error",f)})}catch(i){throw w({level:"error",event:"broker.launch.failed",node_id:e,error:i,fields:{cwd:t.cwd,executable:W}}),new Error(`could not spawn the broker (executable ${W}, cwd ${t.cwd}): ${i.message}`,{cause:i})}const $=P.stdio[3];if(!$||!("end"in $))throw new Error("broker token pipe did not open");$.on("error",i=>w({event:"broker.token_pipe.failed",level:"error",node_id:e,error:i})),$.end(D),L(a),a=null;const re=Date.now(),ne=new Promise(i=>{let f=!1;const O=c(v=>{f||(f=!0,i(v))},"finish");P.once("exit",(v,y)=>{w({level:v===0?"info":"warn",event:"broker.exited",node_id:e,fields:{code:v,signal:y,uptime_ms:Date.now()-re}}),O({code:v,signal:y})}),P.once("error",v=>{w({level:"error",event:"broker.launch.failed",node_id:e,error:v,fields:{uptime_ms:Date.now()-re}}),O({code:null,signal:null})})});P.unref();const q={pid:P.pid??null,exited:ne};return q.pid!==null&&(s.register(e,q),g=!0,ne.then(async i=>await s.onChildExit(e,i,R))),q}catch(h){if(!g&&u?.pid!=null)try{u.kill("SIGTERM")}catch{}throw h}finally{g||s.releaseReservation(e),a!==null&&L(a)}},async isAlive(e){return ee((typeof e=="string"?await _(e):e)?.pi_pid)},async teardown(e,r={}){try{return Pe(await Re(e,r))}catch(t){return Promise.resolve({confirmed:!1,error:t instanceof Error?t:new Error(String(t))})}},async signal(e,r){const t=(await _(e))?.pi_pid;if(t!=null)try{process.kill(t,r)}catch{}}};export{Se as brokerLaunchJson,mn as headlessBrokerHost,xe as isolatedBrokerLauncherAvailable,Rr as preflightBrokerLaunch,dn as requestBrokerTeardown};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as K}from"node:child_process";import{constants as
|
|
2
|
-
`).map(r=>r.trim()).filter(r=>r!==""),"lines")
|
|
1
|
+
var Y=Object.defineProperty;var c=(t,r)=>Y(t,"name",{value:r,configurable:!0});import{spawn as K}from"node:child_process";import{constants as v,lstatSync as j,mkdirSync as q,readFileSync as z,readdirSync as H,readlinkSync as J,rmSync as W,writeFileSync as _}from"node:fs";import{join as E,relative as V}from"node:path";import{crc32 as Z,deflateRawSync as Q}from"node:zlib";import{BlaxelApiError as X}from"./client.js";const tt="public.ecr.aws/docker/library/node:24-alpine",et="ghcr.io/blaxel-ai/sandbox:latest",f="crtr",A="/var/lib/crtr/recipe-pi-agent",rt="1.1.0",b="recipe-setup.sh",L="repos",D="/work/.crtr/setup.log",P="/work/.crtr/setup-failed",B=c(t=>`'${t.replace(/'/g,"'\\''")}'`,"shellQuote"),nt=c(t=>(t??"").split(`
|
|
2
|
+
`).map(r=>r.trim()).filter(r=>r!==""),"lines"),$=c((t,r)=>`RUN { ${r}; } >> ${D} 2>&1 || echo ${B(t)} "exited $?" >> ${P}`,"guarded");function st(t,r,i=!1){const o=nt(t.pi_packages),a=t.setup_script!==null&&t.setup_script.trim()!=="",n=[`FROM ${tt}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${et} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${f} -s /bin/sh ${f} && mkdir -p /work/.crtr ${A} && chown -R ${f} /work /var/lib/crtr`],e=[`${n[0]} AS build`,...i?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${P} ${D}`,$("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];t.repositories.length>0&&e.push(`COPY --chown=${f} ${L}/ /work/`),o.length>0&&e.push($("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${rt}`)),a&&e.push(`COPY ${b} /tmp/${b}`),e.push("WORKDIR /work");for(const s of o)e.push($(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${A} pi install ${B(s)}`));a&&e.push($("setup script",`bash /tmp/${b}`)),e.push($("finalize",`echo ${Math.trunc(r)} > /work/.crtr/recipe-revision && chown -R ${f} /work /home/${f} /var/lib/crtr`)),e.push("",...n);for(const s of["/work",`/home/${f}`,"/var/lib/crtr"])e.push(`COPY --from=build --chown=${f}:${f} ${s} ${s}`);for(const s of["/usr/local","/usr","/etc","/lib"])e.push(`COPY --from=build ${s} ${s}`);return e.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),e.push("RUN if getent passwd postgres >/dev/null; then chown -R postgres:postgres /var/lib/postgresql; fi"),i&&e.push(`RUN rm -f /work/.npmrc /home/${f}/.npmrc`),e.push(`USER ${f}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),e.join(`
|
|
3
3
|
`)}c(st,"recipeDockerfile");const ot=c((t,r,i)=>new Promise((o,a)=>{const n=K("git",t,{cwd:i,env:{...process.env,...r,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let e="";n.stderr.on("data",s=>{e+=s.toString()}),n.on("error",a),n.on("close",s=>{s===0?o():a(new Error(`git ${t[0]} failed (${s}): ${e.slice(0,300)}`))})}),"runGit");async function ht(t){const r=t.git??ot,i=t.packagesToken??null,o=t.cloneUrl??(n=>`https://github.com/${n}.git`);q(E(t.dir,L),{recursive:!0});const a=t.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${t.token}`).toString("base64")}`};for(const n of t.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await r(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),E(L,n.name)],a,t.dir)}_(E(t.dir,"Dockerfile"),st(t.recipe,t.revision,i!==null)),i!==null&&_(E(t.dir,".env.build"),`NODE_AUTH_TOKEN=${i}
|
|
4
4
|
`,{mode:384}),t.recipe.setup_script!==null&&t.recipe.setup_script.trim()!==""&&_(E(t.dir,b),t.recipe.setup_script.endsWith(`
|
|
5
5
|
`)?t.recipe.setup_script:`${t.recipe.setup_script}
|
|
6
|
-
`)}c(ht,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=V(t,a).split("\\").join("/");n.isDirectory()?C(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(J(a)),mode:
|
|
6
|
+
`)}c(ht,"prepareBuildDir");function C(t,r,i){for(const o of H(r).sort()){const a=E(r,o),n=j(a),e=V(t,a).split("\\").join("/");n.isDirectory()?C(t,a,i):n.isSymbolicLink()?i.push({name:e,data:Buffer.from(J(a)),mode:v.S_IFLNK|511}):n.isFile()&&i.push({name:e,data:z(a),mode:v.S_IFREG|n.mode&511})}}c(C,"walk");function it(t){const r=[];C(t,t,r);const i=[],o=[];let a=0;for(const s of r){const u=Buffer.from(s.name),g=Q(s.data),I=Z(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(I,14),p.writeUInt32LE(g.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),i.push(p,u,g);const l=Buffer.alloc(46);l.writeUInt32LE(33639248,0),l.writeUInt16LE(788,4),l.writeUInt16LE(20,6),l.writeUInt16LE(2048,8),l.writeUInt16LE(8,10),l.writeUInt32LE(33,14),l.writeUInt32LE(I,16),l.writeUInt32LE(g.length,20),l.writeUInt32LE(s.data.length,24),l.writeUInt16LE(u.length,28),l.writeUInt32LE(s.mode<<16>>>0,38),l.writeUInt32LE(a,42),o.push(l,u),a+=p.length+u.length+g.length}const n=Buffer.concat(o),e=Buffer.alloc(22);return e.writeUInt32LE(101010256,0),e.writeUInt16LE(r.length,8),e.writeUInt16LE(r.length,10),e.writeUInt32LE(n.length,12),e.writeUInt32LE(a,16),Buffer.concat([...i,n,e])}c(it,"zipDirectory");async function R(t,r,i,o,a=[]){const n=`${t.controlUrl??"https://api.blaxel.ai/v0"}${i}`,e=await(t.fetch??fetch)(n,{method:r,headers:{authorization:`Bearer ${t.apiKey}`,"x-blaxel-workspace":t.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await e.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!e.ok&&!a.includes(e.status))throw new X(e.status,null,`Blaxel ${r} ${n} failed (${e.status}): ${s.slice(0,300)}`);return{status:e.status,headers:e.headers,json:u}}c(R,"api");async function G(t,r){const{status:i,json:o}=await R(t,"GET",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404]);return i===404?null:o}c(G,"getImage");async function mt(t,r){await R(t,"DELETE",`/images/sandbox/${encodeURIComponent(r)}`,void 0,[404])}c(mt,"deleteImage");async function wt(t,r,i,o={}){const a=o.sleep??(h=>new Promise(d=>setTimeout(d,h))),n=o.now??Date.now,e=n(),s=await G(t,r),u=new Set((s?.spec?.tags??[]).map(h=>h.name)),g=c(h=>(h?.metadata?.events??[]).map(d=>Date.parse(d.time??"")).filter(d=>!Number.isNaN(d)),"eventTimes"),I=Math.max(-1/0,...g(s)),l=(await R(t,"POST","/images",{resourceType:"sandbox",name:r})).headers.get("x-blaxel-upload-url");if(l===null)throw new Error(`Blaxel gave no upload URL for image ${r}`);const U=await(t.fetch??fetch)(l,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(it(i))});if(!U.ok)throw new Error(`uploading the build context of image ${r} failed (${U.status}): ${(await U.text()).slice(0,300)}`);const F=e+(o.timeoutMs??20*6e4);let N=null;for(;;){const h=await G(t,r),d=h?.metadata?.status,k=g(h).filter(m=>m>I).sort((m,x)=>m-x);if(d==="BUILT"&&k.length>=2){N??=n();const m=(h?.spec?.tags??[]).filter(w=>w.name!==void 0),x=k[0],O=c(w=>Date.parse(w??"")>=x,"touchedSince"),T=m.filter(w=>!u.has(w.name)||O(w.createdAt)||O(w.updatedAt)),y=n()-N>=(o.tagGraceMs??6e4),S=(T.length>0?T:y?m:[]).sort((w,M)=>(M.updatedAt??"").localeCompare(w.updatedAt??""))[0]?.name;if(S!==void 0)return{ref:`sandbox/${r}:${S}`,buildMs:n()-e};if(y)throw new Error(`Blaxel built image ${r} but no tag appeared`)}if(d==="FAILED"||d==="TERMINATED"){const m=h?.metadata?.events??[];throw new Error(`building image ${r} ${d.toLowerCase()}: ${m[m.length-1]?.message??"no message"}`)}if(n()>F)throw new Error(`building image ${r} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${d??"none"})`);await a(o.pollMs??3e3)}}c(wt,"buildImage");const gt=c(t=>`env-${t}`,"environmentImageName");function Et(t){W(t,{recursive:!0,force:!0})}c(Et,"removeBuildDir");export{tt as NODE_BASE_IMAGE,A as RECIPE_PI_AGENT_DIR,L as REPOS_DIR,f as RUN_USER,et as SANDBOX_API_IMAGE,P as SETUP_FAILED_FILE,D as SETUP_LOG_FILE,b as SETUP_SCRIPT_FILE,wt as buildImage,mt as deleteImage,gt as environmentImageName,G as getImage,ht as prepareBuildDir,st as recipeDockerfile,Et as removeBuildDir,it as zipDirectory};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as
|
|
1
|
+
var p=Object.defineProperty;var o=(e,r)=>p(e,"name",{value:r,configurable:!0});import{createHash as E}from"node:crypto";import{copyFileSync as f,mkdtempSync as g,readFileSync as w,writeFileSync as d}from"node:fs";import{tmpdir as R}from"node:os";import{join as c}from"node:path";import{buildImage as S,NODE_BASE_IMAGE as h,removeBuildDir as b,RUN_USER as n,SANDBOX_API_IMAGE as u}from"./image-build.js";const x="/opt/crtr/releases",y=".sha256",I=".complete",i="runtime.tar.gz",A=/^[0-9a-f]{64}$/,O=/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$/,l=o(e=>`releases/${e}/sandbox-image.json`,"releaseImageKey");function $(e){if(!O.test(e))throw new Error(`${JSON.stringify(e)} is not a release version`);const r=`crtr-release-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`;if(r.length>63)throw new Error(`image name ${r} is longer than 63 characters`);return r}o($,"releaseImageName");function N(e,r){if(!A.test(r))throw new Error("sha256 must be 64 lowercase hex characters");$(e);const a=`${x}/${e}`;return[`FROM ${h} AS release`,`COPY ${i} /tmp/${i}`,`RUN mkdir -p ${a} && tar -xzf /tmp/${i} -C ${a} && echo ${r} > ${a}/${y} && : > ${a}/${I}`,"",`FROM ${h}`,"RUN apk add --no-cache bash git curl ripgrep python3",`COPY --from=${u} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${n} -s /bin/sh ${n} && mkdir -p /run/crtr /var/lib/crtr /work/.crtr && chown -R ${n} /run/crtr /var/lib/crtr /work`,"COPY --from=release /opt/crtr /opt/crtr",`USER ${n}`,"WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""].join(`
|
|
2
2
|
`)}o(N,"releaseImageDockerfile");function C(e){return`${JSON.stringify(e)}
|
|
3
|
-
`}o(C,"releaseImagePointerText");function
|
|
3
|
+
`}o(C,"releaseImagePointerText");function U(e,r,a){let s;try{s=JSON.parse(e)}catch{throw new Error(`${l(r)} is not JSON`)}const t=s;if(t===null||typeof t!="object"||typeof t.release!="string"||typeof t.sha256!="string"||typeof t.image!="string"||t.image==="")throw new Error(`${l(r)} must hold {release, sha256, image}`);if(t.release!==r)throw new Error(`${l(r)} names release ${t.release}`);if(t.sha256!==a)throw new Error(`${l(r)} was built from tarball ${t.sha256}, not ${a}`);return t.image}o(U,"parseReleaseImagePointer");async function M(e,r,a={}){const s=E("sha256").update(w(r.tarball)).digest("hex");if(s!==r.sha256)throw new Error(`${r.tarball} has sha256 ${s}, not ${r.sha256}`);const t=g(c(R(),"crtr-release-image-"));try{f(r.tarball,c(t,i)),d(c(t,"Dockerfile"),N(r.release,r.sha256));const m=await S(e,$(r.release),t,a);return{pointer:{release:r.release,sha256:r.sha256,image:m.ref},built:m}}finally{b(t)}}o(M,"buildReleaseImage");export{x as RELEASES_DIR,I as RELEASE_COMPLETE_FILE,y as RELEASE_SHA_FILE,i as RELEASE_TARBALL_FILE,M as buildReleaseImage,U as parseReleaseImagePointer,N as releaseImageDockerfile,l as releaseImageKey,$ as releaseImageName,C as releaseImagePointerText};
|
|
@@ -2,6 +2,11 @@ import { type MachineOp, type MachineOpTable } from './ops.js';
|
|
|
2
2
|
/** Seconds a caller waits: `start` 60, every other op 15 (design). The `worktree.*` ops run Git under a repository lock that waits up to
|
|
3
3
|
* 25 s, so they get 60 too (`worktree.finalize` also asks origin, bounded at 10 s). */
|
|
4
4
|
export declare const MACHINE_CALL_TIMEOUT_S: Record<MachineOp, number>;
|
|
5
|
+
/** When a call was queued and when its holder settled it (epoch ms), for the create request's step timings. Null when the row is gone or unsettled. */
|
|
6
|
+
export declare function callTimes(callId: string): Promise<{
|
|
7
|
+
createdAt: number;
|
|
8
|
+
finishedAt: number;
|
|
9
|
+
} | null>;
|
|
5
10
|
export interface CallMachineOptions {
|
|
6
11
|
timeoutMs?: number;
|
|
7
12
|
rereadMs?: number;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var p=Object.defineProperty;var s=(e,
|
|
1
|
+
var p=Object.defineProperty;var s=(e,a)=>p(e,"name",{value:a,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as w,withCanvasWrite as m}from"../../../canvas/db.js";import{brokerSignalBus as g}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as S,MachineLostError as c,MachineOfflineError as _}from"./ops.js";const N={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"job.stop":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60,"repo.identify":15},M=1e3;async function A(e){const a=await(await w()).prepare("SELECT created_at, finished_at FROM machine_calls WHERE call_id = ?").get(e);return a===void 0||a.finished_at===null?null:{createdAt:Date.parse(a.created_at),finishedAt:Date.parse(a.finished_at)}}s(A,"callTimes");async function k(e,a,n){const r=E(),o=new Date().toISOString();if(!await m(async t=>await t.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,o)===void 0?!1:(await t.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(r,e,a,JSON.stringify(n),o),await t.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new _(e,"no live link");return r}s(k,"enqueueMachineCall");async function L(e,a,n,r={}){return await D(e,a,await k(e,a,n),r)}s(L,"callMachine");async function D(e,a,n,r={}){const o=Date.now()+(r.timeoutMs??N[a]*1e3);let l,t=!1;const i=await g.subscribe(u=>{u===n&&(t=!0,l?.())},{kinds:["machine_call"]});try{return await O(e,a,n,o,r.rereadMs??M,u=>new Promise(f=>{if(t){t=!1,f();return}const h=setTimeout(()=>{l=void 0,f()},u);l=s(()=>{clearTimeout(h),l=void 0,t=!1,f()},"wake")}))}finally{i()}}s(D,"awaitMachineCall");async function O(e,a,n,r,o,l){for(;;){const t=await(await w()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(n);if(t===void 0)throw new c(e,n);if(t.state==="done")return t.result_json===null?null:JSON.parse(t.result_json);if(t.state==="failed"){const i=t.result_json===null?{}:JSON.parse(t.result_json);throw i.code==="machine_offline"?new _(e,i.message,i.sent===!0):i.code==="machine_lost"?new c(e,n):new S(e,a,i.message??"unknown")}if(t.claimed_generation!==null&&t.lease_expires_at!==null&&t.lease_expires_at<=new Date().toISOString()){if(await d(n,"lease expired")===void 0)continue;throw new c(e,n)}if(Date.now()>=r){const i=await d(n,"timed out");if(i===void 0)continue;throw i===null?new _(e,"no holder claimed the call"):new c(e,n)}await l(Math.min(o,Math.max(0,r-Date.now())))}}s(O,"waitForCall");async function d(e,a){const n=await(await w()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?, args_json = '{}',
|
|
2
2
|
result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
|
|
3
|
-
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:
|
|
3
|
+
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:a,sent:!1}),JSON.stringify({code:"machine_lost",message:a}),e);return n===void 0?void 0:n.claimed_generation===null?null:Number(n.claimed_generation)}s(d,"failOpenCall");export{N as MACHINE_CALL_TIMEOUT_S,D as awaitMachineCall,L as callMachine,A as callTimes,k as enqueueMachineCall};
|
|
@@ -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,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Te}from"./nodes.js";import{resolveProfileOperand as Pe}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as _,brokerLaunchFailed as K}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as w,fullName as we,jobDir as dn,recordExecutionPid as sn,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 ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as U,conversationStore as R}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Y}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as k}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as S}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Q,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Cn}from"../canvas/person.js";import{recordLaunch as Sn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as Z,timedStep as X}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Tn,unregisteredConcreteModel as Pn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}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 qn(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 and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}l(qn,"launchBrokerOrCrash");function Gn(e){return _n({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(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(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(Vn,"notReadyDescription");async function Jn(e,r){try{await S(e,"crash",{reason:"launch_failed",outcome:E(r)})}catch{}try{Q.teardown(e)}catch{}}l(Jn,"crashAndTearDown");async function Yn(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(Yn,"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 Yn(r)}l(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Pe(e).profileId:r!==null?(await w(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}l(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Tn(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 zn(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 Pn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw _(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(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 Zn(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(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(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(er,"recordStartCallTimings");async function nr(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 Dn())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 vn(e.node_id,o,e.cwd);await En(d,s);const P=d;await X("warm_repos",async()=>await bn(await gn(),e.node_id));const $=e.sub??await Cn(),L=await X("start_bundle",()=>t({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:$,launchJson:s,runner:"machine"}));c=await X("render_transaction",()=>yn(async v=>{const M=await a(e.node_id),F=await xn(v,P,e.node_id,new Date().toISOString());return await On(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 In(r,"start",c)}catch(s){return k({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof Mn||s instanceof Fn&&s.sent?"uncertain":(await T(d,{reason:"launch_failed"}),"failed")}try{await er(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",()=>Sn(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(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),d=e.root===!0,c=Zn(e.parent,a.nodeId??null,d),m=e.mode??"base",s=e.rootLifecycle??(d?"resident":"terminal"),P=d&&s==="resident",$=c===null?null:await w(c),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Te(e.nodeId);const v=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,M=v===void 0?null:await De(v),F=await Un([$,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,O=D?e.run!==void 0&&d&&!F?e.cwd:Re(Me(e.run?.grantee??$?.grantee??"app:terminal").nodes,h):e.cwd;const p=await Qn(e.profile,c,O),A=D?null:await je(p,e.worktreeCwd??O);A!==null&&(O=A,h??=await le());const N=e.worktree===!0||A!==null,ne=e.run?.grant_id??$?.grant_id??null,B=e.run??L??$??M,re=await ke((await ce(e.kind,m,{lifecycle:s,hasManager:!d,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:p,app:B?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:O,profileId:p}),await Xn({grantee:B?.grantee??"app:terminal",sub:B?.sub,grant_id:B?.grant_id});const te=M?.node_id??null;let y,W=O;const j=N&&await ze(p)?await He(p,A??e.worktreeCwd??e.cwd,h,e.worktreeBase):void 0,z=N&&j===void 0?await Ge(p):null;try{N&&j===void 0&&(y=z!==null?await Xe(z,e.worktreeCwd??e.cwd,h,e.worktreeBase):await Ke(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 Fe({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 jn(n.node_id,te??null)}catch(i){throw await S(n.node_id,"crash",{reason:"launch_failed",outcome:E(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(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?`${nn(e.wakeOrigin)}
|
|
2
2
|
|
|
3
|
-
`:""}${e.prompt}`;
|
|
3
|
+
`:""}${e.prompt}`;m==="orchestrator"&&await en(n.node_id,{goal:e.prompt.trim()}),await rr(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=We(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Be(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[tn]=rn(i),await on(g,n)}const b=me();if(await fn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await $n(n.profile_id??null):null;if(u!==null){Z("birth",performance.now()-t);const C=await nr(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}}if(Je()&&!$e(n.cwd))throw new Ve({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await b.reserveSlot(n.node_id),x=ie?await un(n.node_id):null;if(x?.verdict==="too_small"){b.releaseReservation(n.node_id);const i=cn(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 kn(n.node_id),{automaticReviveCap:xe}=Y();let I;try{I=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:I};let H;try{H=await qn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await T(I,{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(I,{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 sn(I,n.node_id,H.pid)==="shutdown")throw await T(I,{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 pn(n.node_id,H.exited);if(!i.ready){const u=Vn(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 Jn(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&&Bn("user").auto_open_child_viewers)try{const i=await mn(c);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await wn(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=hn(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 qe(z,y):await Ue(y)),f}}l(ge,"spawnChildPrepared");async function ct(e){return ge(e)}l(ct,"spawnChild");async function rr(e){const r=Hn(e.cwd,e.profile_id).plans.get("node:start")??[];await Kn(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:dn(e.node_id)},runtime:{isBirth:!0,canvasHome:an(),profile:e.profile_id??null}})}l(rr,"invokeBirthLifecycleHooks");const tr=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function ut(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);ln(await J(e),d,await J(c),m,tr)})}l(ut,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,ut as forkNode,rr as invokeBirthLifecycleHooks,pe as resolveForkSource,Qn as resolveProfileId,Zn as resolveSpawner,ct 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};
|
|
@@ -56,7 +56,7 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
|
|
|
56
56
|
applies: string;
|
|
57
57
|
group: "updates";
|
|
58
58
|
order: number;
|
|
59
|
-
format: (config: ScopeConfig) => "
|
|
59
|
+
format: (config: ScopeConfig) => "notify" | "off" | "apply";
|
|
60
60
|
cycle: (config: ScopeConfig, delta: number) => void;
|
|
61
61
|
setFromString: (config: ScopeConfig, raw: string) => "auto_update.crtr must be notify, apply, or false" | null;
|
|
62
62
|
};
|
|
@@ -68,7 +68,7 @@ export declare const CONFIG_SETTINGS_COVERAGE: {
|
|
|
68
68
|
applies: string;
|
|
69
69
|
group: "updates";
|
|
70
70
|
order: number;
|
|
71
|
-
format: (config: ScopeConfig) => "
|
|
71
|
+
format: (config: ScopeConfig) => "notify" | "off" | "apply";
|
|
72
72
|
cycle: (config: ScopeConfig, delta: number) => void;
|
|
73
73
|
setFromString: (config: ScopeConfig, raw: string) => "auto_update.content must be notify, apply, or false" | null;
|
|
74
74
|
};
|
|
@@ -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>;
|