@north-light/cli 0.3.683 → 0.3.685

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/core/canvas/db.d.ts +3 -0
  2. package/dist/core/canvas/db.js +4 -4
  3. package/dist/core/checkout-identities.d.ts +3 -0
  4. package/dist/core/checkout-identities.js +3 -3
  5. package/dist/core/graph/reader.js +3 -3
  6. package/dist/core/graph/repo-sync/repos.d.ts +5 -2
  7. package/dist/core/graph/repo-sync/repos.js +4 -4
  8. package/dist/core/runtime/runner/blaxel/image-build.d.ts +2 -0
  9. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  10. package/dist/core/runtime/spawn.js +2 -2
  11. package/dist/core/step-timings.d.ts +4 -0
  12. package/dist/core/step-timings.js +1 -1
  13. package/dist/core/substrate/delivery/corpus.d.ts +3 -0
  14. package/dist/core/substrate/delivery/corpus.js +2 -2
  15. package/dist/daemon/api/handlers/broker-ops.d.ts +1 -1
  16. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  17. package/package.json +3 -3
  18. package/packages/crouter-api/dist/core/canvas/db.js +15 -2
  19. package/packages/crouter-api/dist/core/checkout-identities.js +25 -9
  20. package/packages/crouter-api/dist/core/graph/reader.js +5 -2
  21. package/packages/crouter-api/dist/core/graph/repo-sync/repos.js +15 -18
  22. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +5 -2
  23. package/packages/crouter-api/dist/core/runtime/spawn.js +18 -4
  24. package/packages/crouter-api/dist/core/step-timings.js +23 -2
  25. package/packages/crouter-api/dist/core/substrate/delivery/corpus.js +32 -4
  26. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +21 -19
  27. package/packages/crouter-api/package.json +1 -1
  28. package/packages/crouter-identity/package.json +1 -1
  29. package/packages/crouter-plugin/package.json +3 -3
  30. package/runtime.lock.json +14 -14
@@ -1 +1 @@
1
- var X=Object.defineProperty;var s=(t,e)=>X(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Z,findNodeBySessionFile as I,getNode as g,getNodes as q,isWarmSpare as ee,recordLaunch as te,recordRespawnAttempt as ne,recordSettledTurn as ie,setPresence as x,subscriptionsOf as re,updateNode as _,updateNodeTelemetry as oe}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ae,recordExecutionPid as se}from"../../../core/canvas/executions.js";import{bindSession as ce,readLiveSession as de,transferSession as le}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ue}from"../../../core/canvas/paths.js";import{isPidAlive as pe}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as fe}from"../../../core/substrate/subject.js";import{openDb as C,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as me}from"../../../core/graph/jobs.js";import{notFound as R,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as F,releaseExecutionMail as we}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as ye}from"../../../core/runtime/kickoff.js";import{readRoadmap as he}from"../../../core/runtime/roadmap.js";import{forkSourceNode as be}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{confirmViewer as T,probeViewer as B,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as _e}from"../viewer-presence.js";import{evaluateStop as ke}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as L}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as ve,recordFault as ge}from"../../../core/canvas/recovery.js";import{updateModelRecipe as xe}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as Se}from"../../review/finish.js";import{emitEvent as D}from"../../../core/events/emit.js";import{consumePendingPark as Pe,recordPendingParkActivity as Re}from"../../park-pending.js";import{shouldParkAfterSummary as Oe}from"../../park-activity.js";import{ownerOnly as Ee}from"../router.js";import{situationalContextEnvelope as Ae}from"../../../core/runtime/situational-context.js";import{recoveryState as Ce,requireCurrentExecution as u}from"./broker-recovery.js";import{runAttachments as Fe}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Be}from"../../../core/graph/reader.js";import{checkoutsForCwd as Ne}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Le}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as De}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Me,writeNodeTelemetryRecord as je}from"./telemetry-record.js";import{mapAsync as Ve}from"../../../core/async-array.js";import{crtrVersion as M}from"../../../shared/crtr-version.js";import{buildPiArgv as $e}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ue}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as We,cycleCompatible as He}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Je,drainBearings as Ge}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Ye}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ke}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as ze}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Qe}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Xe}from"../../../api/errors.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}s(p,"objectBody");function j(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}s(j,"parseSessionBoundBody");function Ze(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}s(Ze,"parseSettleBody");function Ie(t){const e=p(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}s(Ie,"parseCycleBody");function qe(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}s(qe,"parseParkCompleteBody");function et(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=Me(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(et,"parseTelemetryBody");function tt(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}s(tt,"parseModelCommitBody");async function m(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");async function v(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(v,"extensionNode");async function V(t){const e=await m(t),n=[],r=new Set([t]);let i=e.parent??null;for(;i!==null&&i!==""&&!r.has(i);){r.add(i);const d=await g(i);if(d===null)break;n.unshift(await v(d)),i=d.parent??null}const a=await Ve((await q((await re(t)).map(d=>d.node_id))).filter(d=>d.kind!=="human").sort((d,w)=>d.status===w.status?0:d.status==="active"?-1:w.status==="active"?1:0),v),o=typeof e.fork_source_file=="string"?await be(e.fork_source_file):null,c=await fe(t);if(c===null)throw R(`unknown node: ${t}`,{received:t});return{node:await v(e),warm_spare:await ee(t),situational_card:await Ae(t),ancestors:n,children:a,fork_source:o===null?null:await v(o),subject:c,roadmap:await he(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function nt(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}s(nt,"parseGeneratedNameBody");function it(t){const e=p(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw l(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(it,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:Z(e.sessionFile);return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t);if(await se(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await I(n);if(o!==null&&o.node_id!==t){if(pe(o.pi_pid))return await ge(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await de(o.node_id);if(c===null||await le({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ce(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await ye(t),i.intent==="refresh"&&await k(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function rt(t){return{status:200,body:await $(t.params.id,j(t.body))}}s(rt,"handleSessionBound");function ot(t){const e=j(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw l("bearings must be fresh, inherited or present");return e}s(ot,"parseCycleStartBody");async function at(t,e,n,r,i=!1){const a=e.warm_spare||r,o=!a&&n!=="present";return i||await Be(await C(),t),await f(async c=>{const d=await Te(c,t,async(K,z,Q)=>await Ne(c,K,z,Q)),w=await Le(c,d),y=await O(c,d,{activity:"names"},w),b=o?await O(c,d,{activity:"boot",...n==="inherited"?{inherited:!0}:{}},w):void 0,A=a?void 0:await O(c,d,{activity:"system-prompt"},w);return{names:{refs:y.refs,names:y.names},...b===void 0?{}:{boot:{content:b.content,...b.inherited===!0?{inherited:!0}:{}}},...A===void 0?{}:{system_prompt:A.content}}})}s(at,"startupDelivery");async function U(t,e,n,r=!1){const i=await V(t),a=await at(t,i,e,n,r);if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,d=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(d,o)||await Y(t,d,o)}return{state:i,delivery:a}}s(U,"renderStartData");async function mn(t){const{state:e,delivery:n}=await U(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(mn,"renderCarriedStart");async function st(t){const e=t.params.id,n=ot(t.body),r=await m(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await u(e,n.executionId);else{const{action:y}=await $(e,n);if(y!=="none")return{status:200,body:{action:y}}}const{state:c,delivery:d}=await U(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...d,recovery:await Ce(e),attachments:(await Fe(e)).map(({path:y,sha256:b})=>({path:y,sha256:b})),structured_request:await L(e)}}}s(st,"handleCycleStart");async function W(t,e){return e.live!==null||await _e(t)||await F(t)}s(W,"isHeldAwake");async function H(t,e){return(await S(t))?.runner==="blaxel"&&!await W(t,e)&&(await me(await C(),t)).length===0}s(H,"residentBlaxelCanIdle");function J(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(J,"refreshDirective");async function ct(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ie(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ne(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await k(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:J(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await ve(t))?.retry.disposition==="fatal"&&await L(t)===null&&await H(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:J(e),closePane:!1};const a=await ke(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await F(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await W(t,n);return(await S(t))?.runner==="blaxel"?{directive:await H(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await k(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ct,"settleBroker");async function dt(t){const e=t.params.id,n=Ie(t.body);await u(e,n.expected_execution_id);const r=await m(e);if(r.intent!=="refresh")throw new Xe(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=$e(r);return n.brokerVersion===M()&&(i.release===null||i.release===M())&&He(i.launchJson,await Ue(e,a,r.cwd))?{status:200,body:await lt(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(dt,"handleCycle");async function lt(t,e,n,r){e.cycles=(e.cycles??0)+1,await we(t,n);const i=await Ge(e,n),a=await Je(e,i);await Ye(t),await Ke(t,e,!1),await ze(t),await h(t,{preserveEpisode:!0}),await te(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of We)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Qe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(lt,"startCycleRecord");async function ut(t){const e=t.params.id,n=p(t.body,"broker idle");return await u(e,n.expected_execution_id),await ae(n.expected_execution_id),{status:204}}s(ut,"handleIdle");async function pt(t){const e=t.params.id,n=Ze(t.body);await u(e,n.expected_execution_id);const r=await B(e),{directive:i,closePane:a}=await f(async()=>await ct(e,n,await T(r)));return a&&await N(e),i.action!=="reprompt"&&Se(e).catch(o=>D({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(pt,"handleSettle");async function ft(t){const e=t.params.id,n=qe(t.body);await u(e,n.expected_execution_id);const r=await B(e),i=await f(async()=>{const a=await Pe(e);if(a===void 0)return{action:"stay_dormant"};const o=await m(e);return await Oe(e,o,a,await T(r))?(await h(e),await k(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),D({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ue(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await N(e),{status:200,body:i}}s(ft,"handleParkComplete");async function mt(t){const e=t.params.id;return await u(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await Re(e)?"recorded":"none"}))}}s(mt,"handleParkActivity");async function wt(t){const e=t.params.id,n=et(t.body);return await u(e,n.expected_execution_id),await f(async()=>{await oe(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),je(e,n)}),{status:204}}s(wt,"handleTelemetry");async function yt(t){const e=t.params.id,n=tt(t.body);return await u(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await xe(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}s(yt,"handleModelCommit");let G=!0;function wn(t){G=t}s(wn,"setRequestsStartRunObservers");async function ht(t){const e=t.params.id,n=await m(e);return n.run_id&&G&&await De(e,n.run_id),{status:200,body:await V(e)}}s(ht,"handleExtensionState");async function bt(t){const e=t.params.id,n=nt(t.body);return await u(e,n.expected_execution_id),{status:200,body:await f(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await m(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const d=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(bt,"handleGeneratedName");async function _t(t){const e=t.params.id,n=it(t.body);return await u(e,n.expected_execution_id),{status:200,body:{applied:await Y(e,n.from,n.to)}}}s(_t,"handlePersonaAck");async function Y(t,e,n){return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(Y,"applyPersonaAck");const yn=Ee([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:bt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:_t}]);export{yn as brokerOperationRoutes,v as extensionNode,mn as renderCarriedStart,U as renderStartData,wn as setRequestsStartRunObservers};
1
+ var K=Object.defineProperty;var s=(t,e)=>K(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as z,findNodeBySessionFile as Q,getNode as g,getNodes as X,isWarmSpare as Z,recordLaunch as I,recordRespawnAttempt as q,recordSettledTurn as ee,setPresence as x,subscriptionsOf as te,updateNode as b,updateNodeTelemetry as ne}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ie,recordExecutionPid as re}from"../../../core/canvas/executions.js";import{bindSession as oe,readLiveSession as ae,transferSession as se}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ce}from"../../../core/canvas/paths.js";import{isPidAlive as de}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as le}from"../../../core/substrate/subject.js";import{shareCorpusReads as ue}from"../../../core/substrate/delivery/corpus.js";import{openDb as A,withCanvasWrite as w}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as R,usage as d}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as _}from"../../../core/runtime/lifecycle.js";import{confirmViewer as F,probeViewer as T,tearDownNode as B}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as be}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as N}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as _e,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as xe,recordPendingParkActivity as Se}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ee,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Ce,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Te}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Be}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as Ne}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Le,writeNodeTelemetryRecord as De}from"./telemetry-record.js";import{mapAsync as Me}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Ve}from"../../../core/runtime/launch.js";import{brokerLaunchJson as $e}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as je,cycleCompatible as Ue}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as We,drainBearings as He}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Je}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ge}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ye}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ke}from"../../../core/runtime/stamp/protocol.js";import{ApiError as ze}from"../../../api/errors.js";function m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw d(`${e} requires a JSON body`);return t}s(m,"objectBody");function M(t){const e=m(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw d("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw d("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw d("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw d("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw d("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw d("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Qe(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw d("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw d(`${n} must be a boolean`);return e}s(Qe,"parseSettleBody");function Xe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw d("brokerVersion must be a non-empty string");return e}s(Xe,"parseCycleBody");function Ze(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw d("outcome must be completed or failed");return e}s(Ze,"parseParkCompleteBody");function Ie(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw d("expected_execution_id must be a non-empty string");const n=Le(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ie,"parseTelemetryBody");function qe(t){const e=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw d("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw d("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw d("userSelected must be a boolean");return e}s(qe,"parseModelCommitBody");async function y(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(y,"requireNode");async function k(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(k,"extensionNode");async function V(t,e){const n=await y(t),r=[],i=new Set([t]);let a=n.parent??null;for(;a!==null&&a!==""&&!i.has(a);){i.add(a);const u=await g(a);if(u===null)break;r.unshift(await k(u)),a=u.parent??null}const o=await Me((await X((await te(t)).map(u=>u.node_id))).filter(u=>u.kind!=="human").sort((u,p)=>u.status===p.status?0:u.status==="active"?-1:p.status==="active"?1:0),k),c=typeof n.fork_source_file=="string"?await ye(n.fork_source_file):null,l=e??await le(t);if(l===null)throw R(`unknown node: ${t}`,{received:t});return{node:await k(n),warm_spare:await Z(t),situational_card:await Oe(t),ancestors:r,children:o,fork_source:c===null?null:await k(c),subject:l,roadmap:await we(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function et(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw d("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw d("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw d("recap expected must contain name, description, title, icon, and kind strings");return e}s(et,"parseGeneratedNameBody");function tt(t){const e=m(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw d(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(tt,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:z(e.sessionFile);return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t);if(await re(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await Q(n);if(o!==null&&o.node_id!==t){if(de(o.pi_pid))return await ke(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await ae(o.node_id);if(c===null||await se({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await oe(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await me(t),i.intent==="refresh"&&await _(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function nt(t){return{status:200,body:await $(t.params.id,M(t.body))}}s(nt,"handleSessionBound");function it(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw d("bearings must be fresh, inherited or present");return e}s(it,"parseCycleStartBody");async function rt(t,e,n,r,i,a){const o=r.warm_spare||a,c=!o&&i!=="present",l=await O(t,e,{activity:"names"},n),u=c?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{}},n):void 0,p=o?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...u===void 0?{}:{boot:{content:u.content,...u.inherited===!0?{inherited:!0}:{}}},...p===void 0?{}:{system_prompt:p.content}}}s(rt,"startupDelivery");async function j(t,e,n,r=!1){r||await Fe(await A(),t);const{state:i,delivery:a}=await w(async o=>{const c=await Ce(o,t,async(p,v,Y)=>await Te(o,p,v,Y));ue(c);const l=await Be(o,c),u=await V(t,l);return{state:u,delivery:await rt(o,c,l,u,e,n)}});if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,l=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(l,o)||await G(t,l,o)}return{state:i,delivery:a}}s(j,"renderStartData");async function fn(t){const{state:e,delivery:n}=await j(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(fn,"renderCarriedStart");async function ot(t){const e=t.params.id,n=it(t.body),r=await y(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await f(e,n.executionId);else{const{action:p}=await $(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:l}=await j(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...l,recovery:await Ee(e),attachments:(await Ae(e)).map(({path:p,sha256:v})=>({path:p,sha256:v})),structured_request:await N(e)}}}s(ot,"handleCycleStart");async function U(t,e){return e.live!==null||await he(t)||await C(t)}s(U,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await U(t,e)&&(await pe(await A(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function at(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ee(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await q(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await _(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await _e(t))?.retry.disposition==="fatal"&&await N(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:H(e),closePane:!1};const a=await be(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await U(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await _(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(at,"settleBroker");async function st(t){const e=t.params.id,n=Xe(t.body);await f(e,n.expected_execution_id);const r=await y(e);if(r.intent!=="refresh")throw new ze(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=Ve(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&Ue(i.launchJson,await $e(e,a,r.cwd))?{status:200,body:await ct(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(st,"handleCycle");async function ct(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await He(e,n),a=await We(e,i);await Je(t),await Ge(t,e,!1),await Ye(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await b(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of je)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Ke({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(ct,"startCycleRecord");async function dt(t){const e=t.params.id,n=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await ie(n.expected_execution_id),{status:204}}s(dt,"handleIdle");async function lt(t){const e=t.params.id,n=Qe(t.body);await f(e,n.expected_execution_id);const r=await T(e),{directive:i,closePane:a}=await w(async()=>await at(e,n,await F(r)));return a&&await B(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(lt,"handleSettle");async function ut(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const r=await T(e),i=await w(async()=>{const a=await xe(e);if(a===void 0)return{action:"stay_dormant"};const o=await y(e);return await Pe(e,o,a,await F(r))?(await h(e),await _(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ce(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await B(e),{status:200,body:i}}s(ut,"handleParkComplete");async function pt(t){const e=t.params.id;return await f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await w(async()=>({activity:await Se(e)?"recorded":"none"}))}}s(pt,"handleParkActivity");async function ft(t){const e=t.params.id,n=Ie(t.body);return await f(e,n.expected_execution_id),await w(async()=>{await ne(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),De(e,n)}),{status:204}}s(ft,"handleTelemetry");async function mt(t){const e=t.params.id,n=qe(t.body);return await f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await w(async()=>await ve(await y(e),n.spec,n.intent,n.userSelected))).model_override}}}s(mt,"handleModelCommit");let J=!0;function mn(t){J=t}s(mn,"setRequestsStartRunObservers");async function wt(t){const e=t.params.id,n=await y(e);return n.run_id&&J&&await Ne(e,n.run_id),{status:200,body:await V(e)}}s(wt,"handleExtensionState");async function yt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),{status:200,body:await w(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await y(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const l=await b(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(l),description:l.description??"",title:l.title??"",icon:l.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await b(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(yt,"handleGeneratedName");async function ht(t){const e=t.params.id,n=tt(t.body);return await f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(ht,"handlePersonaAck");async function G(t,e,n){return await w(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await y(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await b(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const wn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:nt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:ot},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:mt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:ht}]);export{wn as brokerOperationRoutes,k as extensionNode,fn as renderCarriedStart,j as renderStartData,mn as setRequestsStartRunObservers};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.683",
3
+ "version": "0.3.685",
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.683",
160
- "@north-light/plugin": "0.3.683",
159
+ "@north-light/identity": "0.3.685",
160
+ "@north-light/plugin": "0.3.685",
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",
@@ -8,6 +8,7 @@ import { publishFileExclusive } from '../fs-utils.js';
8
8
  import { initializeEmptyLayout, runtimeRoot } from '../layout.js';
9
9
  import { translatePlaceholders, translateOnce } from '../statements.js';
10
10
  import { ensureHome } from './paths.js';
11
+ import { addStepTiming, isCollectingStepTimings, statementLabel } from '../step-timings.js';
11
12
  import { emitEvent } from '../events/emit.js';
12
13
  import { ensureSchema } from './schema-chain.js';
13
14
  import { canvasDatabaseSchema, canvasSchemaDatabaseUrl, canvasSearchPathOptions } from './schema-version.js';
@@ -165,7 +166,9 @@ class Handle {
165
166
  return await transaction.client.query(config);
166
167
  }
167
168
  finally {
168
- transaction.statementMs += performance.now() - began;
169
+ const ms = performance.now() - began;
170
+ transaction.statementMs += ms;
171
+ transaction.statements?.push({ text: config.text, ms });
169
172
  }
170
173
  }
171
174
  return await this.connections().query(config);
@@ -382,7 +385,11 @@ export async function withCanvasWrite(body, options = {}) {
382
385
  return result;
383
386
  }
384
387
  const entry = new Error('canvas write transaction entered here');
388
+ const timingName = isCollectingStepTimings() ? options.timingName : undefined;
389
+ const waitStart = performance.now();
385
390
  const client = await handle.checkout();
391
+ if (timingName !== undefined)
392
+ addStepTiming(`${timingName}_checkout_wait`, performance.now() - waitStart);
386
393
  // The pool removes its own 'error' listener while a connection is checked out. A server error or a dropped socket that
387
394
  // arrives between statements (a body awaiting non-database work) has no active query to fail, so without a listener of
388
395
  // ours it is an unhandled 'error' event and kills the process. Record it: the client is no longer queryable, so the
@@ -393,7 +400,7 @@ export async function withCanvasWrite(body, options = {}) {
393
400
  const started = performance.now();
394
401
  let committed = false;
395
402
  let failed = false;
396
- const transaction = { handle, client, open: true, afterCommit: [], statementMs: 0 };
403
+ const transaction = { handle, client, open: true, afterCommit: [], statementMs: 0, ...(timingName === undefined ? {} : { statements: [] }) };
397
404
  try {
398
405
  await client.query('BEGIN');
399
406
  try {
@@ -416,6 +423,12 @@ export async function withCanvasWrite(body, options = {}) {
416
423
  finally {
417
424
  transaction.open = false;
418
425
  const held = performance.now() - started;
426
+ if (timingName !== undefined && transaction.statements !== undefined) {
427
+ addStepTiming(`${timingName}_statements_count`, transaction.statements.length);
428
+ addStepTiming(`${timingName}_statements_ms`, transaction.statementMs);
429
+ addStepTiming(`${timingName}_other_ms`, held - transaction.statementMs);
430
+ [...transaction.statements].sort((a, b) => b.ms - a.ms).slice(0, 3).forEach((st, i) => addStepTiming(`${timingName}_slow${i + 1}_${statementLabel(st.text)}`, st.ms));
431
+ }
419
432
  // A failed transaction rethrows its error to the caller; warning here would print ahead of it and hide the cause.
420
433
  if (!failed && held - transaction.statementMs > SLOW_TRANSACTION_MS) {
421
434
  console.warn(`[canvas db] write transaction held its connection ${Math.round(held)}ms (${Math.round(transaction.statementMs)}ms in its statements); its body did non-db work while holding a pooled connection and its row locks\n${entry.stack}`);
@@ -62,21 +62,37 @@ function chainOf(stored) {
62
62
  /** The chain of `dir` as this process knows it: git here on a Mac or self-hosted install; on a cloud role the row the person's machine reported
63
63
  * most recently, git where nothing is stored (a Mac path is a missing directory there: `not-a-repo`, no git spawned, no error). */
64
64
  export async function checkoutChainOf(db, dir, person) {
65
- if (!isCloudRole())
66
- return await checkoutChain(dir);
67
- // A cloud role's node on a person's machine has no checkout here: its answer is the stored row. A node with no stored row (a profile on no machine) keeps git.
65
+ const resolved = resolve(dir);
66
+ return (await checkoutChainsOf(db, [resolved], person)).get(resolved);
67
+ }
68
+ /** The chains of several directories in one read, keyed by directory (as given; each already resolved). On a cloud role, the newest row the person's
69
+ * machine reported for each; git where none is stored, or where the process has no person (a profile on no machine). Elsewhere, git. */
70
+ export async function checkoutChainsOf(db, dirs, person) {
71
+ const out = new Map();
72
+ const unique = [...new Set(dirs)];
73
+ if (!isCloudRole()) {
74
+ for (const dir of unique)
75
+ out.set(dir, await checkoutChain(dir));
76
+ return out;
77
+ }
68
78
  let who;
69
79
  try {
70
80
  who = await person();
71
81
  }
72
82
  catch (error) {
73
- if (error instanceof PersonOutsideRequestError)
74
- return await checkoutChain(dir);
75
- throw error;
83
+ if (!(error instanceof PersonOutsideRequestError))
84
+ throw error;
85
+ for (const dir of unique)
86
+ out.set(dir, await checkoutChain(dir));
87
+ return out;
76
88
  }
77
- const row = await db.prepare(`SELECT c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
78
- WHERE p.person IN (?, ?) AND c.dir = ? ORDER BY c.observed_at DESC LIMIT 1`).get(who.replace(/^user:/, ''), `user:${who.replace(/^user:/, '')}`, resolve(dir));
79
- return row === undefined ? await checkoutChain(dir) : chainOf(row.chain_json);
89
+ const bare = who.replace(/^user:/, '');
90
+ const rows = unique.length === 0 ? [] : await db.prepare(`SELECT DISTINCT ON (c.dir) c.dir, c.chain_json FROM checkout_identities c JOIN profiles p ON p.environment_id = c.environment
91
+ WHERE p.person IN (?, ?) AND c.dir = ANY(?::text[]) ORDER BY c.dir, c.observed_at DESC`).all(bare, `user:${bare}`, unique);
92
+ const stored = new Map(rows.map((r) => [r.dir, r.chain_json]));
93
+ for (const dir of unique)
94
+ out.set(dir, stored.has(dir) ? chainOf(stored.get(dir)) : await checkoutChain(dir));
95
+ return out;
80
96
  }
81
97
  /** Run the checkout lookups for `dirs` before a canvas write opens: on the machine environment of `profileId` (cloud role) ask the Mac and store
82
98
  * the answer; otherwise run git here. */
@@ -16,7 +16,7 @@ import { warmCheckoutDirs } from '../checkout-identities.js';
16
16
  import { fillProfileProjectRepo } from '../profiles/manifest.js';
17
17
  import { emitEvent } from '../events/emit.js';
18
18
  import { isCloudRole } from '../canvas/person-state.js';
19
- import { loadReadAccess, mayRead, prefetchRepoReads, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
19
+ import { loadReadAccess, readableAmong, prefetchRepoReads, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
20
20
  /** A node's view of repos: for the checkouts enclosing its cwd, every repo object of their remotes the person may read (own first, then oldest), then
21
21
  * the repos its profile names (an entry's `repo`, and the checkouts of its `path`), in manifest order, each repo once. A repo entry needs no folder or
22
22
  * git; one the person may not read adds nothing. A project path that no longer exists, is not in a repo, or has no work tree contributes nothing. */
@@ -27,6 +27,9 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
27
27
  const access = who === undefined ? undefined : await loadReadAccess(db, who);
28
28
  if (access !== undefined && who !== undefined)
29
29
  await prefetchRepoReads(db, who, [cwd, ...projects.flatMap((p) => p.path !== undefined && (isCloudRole() || existsSync(p.path)) ? [p.path] : [])], access);
30
+ // One read answers whether the person may read every repo the profile's entries name.
31
+ const named = projects.flatMap((p) => p.repo === undefined ? [] : [p.repo]);
32
+ const readable = who === undefined ? new Set() : await readableAmong(db, who, named, access);
30
33
  const checkouts = await reposFn(cwd, person, access);
31
34
  const seen = new Set(checkouts.map((c) => c.repo.id));
32
35
  const projectRepos = [];
@@ -35,7 +38,7 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
35
38
  if (project.repo !== undefined && !seen.has(project.repo)) {
36
39
  const repo = await lookups.object(project.repo);
37
40
  if (repo !== null && repo.type === 'repo' && repo.deleted_at === null
38
- && await mayRead(db, who ?? person ?? await personIdAsync(), repo.id, access)) {
41
+ && readable.has(repo.id)) {
39
42
  seen.add(repo.id);
40
43
  projectRepos.push(repo);
41
44
  }
@@ -6,11 +6,11 @@ import { ExitCode } from '../../../types.js';
6
6
  import { personIdAsync } from '../../canvas/person.js';
7
7
  import { ensureOwner } from '../objects.js';
8
8
  import { checkoutChain, handleHint } from './identity.js';
9
- import { checkoutChainOf } from '../../checkout-identities.js';
9
+ import { checkoutChainOf, checkoutChainsOf } from '../../checkout-identities.js';
10
10
  import { subjectSet } from '../../permissions/evaluator.js';
11
11
  import { loadDefinitions } from '../../permissions/schemas.js';
12
12
  import { compilePermission } from '../../permissions/compile.js';
13
- import { f, raw } from '../../permissions/sql.js';
13
+ import { raw } from '../../permissions/sql.js';
14
14
  import { OBJECT_TYPE } from '../../permissions/builtin.js';
15
15
  export { handleHint };
16
16
  async function existingRepo(db, person, scheme, externalId) {
@@ -36,12 +36,15 @@ export async function ensureRepo(db, id, handle) {
36
36
  export async function loadReadAccess(db, person) {
37
37
  return { defs: await loadDefinitions(db), subjects: await subjectSet(db, person.replace(/^user:/, '')) };
38
38
  }
39
- /** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
40
- export async function mayRead(db, person, id, access) {
39
+ /** The ids among `ids` that `person` may read by permission facts alone (no ceiling), in one read: the gate for the repos a profile names. */
40
+ export async function readableAmong(db, person, ids, access) {
41
+ if (ids.length === 0)
42
+ return new Set();
41
43
  const { defs, subjects } = access ?? await loadReadAccess(db, person);
42
- const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', f `${id}::text`);
43
- const row = await db.prepareUncached(`SELECT ${read.sql} AS ok`).get(...read.params);
44
- return row?.ok === true;
44
+ const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', raw('o.id'));
45
+ const rows = await db.prepareUncached(`SELECT o.id FROM objects o WHERE o.id = ANY(?::text[]) AND ${read.sql}`)
46
+ .all(ids, ...read.params);
47
+ return new Set(rows.map((r) => r.id));
45
48
  }
46
49
  /** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
47
50
  * then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
@@ -76,16 +79,10 @@ const localPathRepos = async (db) => await db.prepare(`SELECT o.*, i.external_id
76
79
  * repos of every git identity in `dirs`, and the local-path repos) and store it on `access`. */
77
80
  export async function prefetchRepoReads(db, person, dirs, access) {
78
81
  const ids = new Map();
79
- for (const cwd of dirs) {
80
- let chain;
81
- try {
82
- chain = await checkoutChainOf(db, realpathOrSelf(resolve(cwd)), async () => person);
83
- }
84
- catch (e) {
85
- if (e instanceof CrtrError && e.code === 'git-lookup-failed')
86
- continue; // the loop reports it
87
- throw e;
88
- }
82
+ const chains = await checkoutChainsOf(db, dirs.map((cwd) => realpathOrSelf(resolve(cwd))), async () => person);
83
+ // A chain with a failed lookup is not the answer: `checkoutsForCwd` looks that directory up itself, as it did before this prefetch kept chains.
84
+ access.chains = new Map([...chains].filter(([, chain]) => chain.every((id) => id.ok)));
85
+ for (const chain of chains.values()) {
89
86
  for (const id of chain)
90
87
  if (id.ok)
91
88
  ids.set(`${id.scheme}\0${id.externalId}`, { scheme: id.scheme, externalId: id.externalId });
@@ -111,7 +108,7 @@ export async function checkoutsForCwd(db, cwd, person, access) {
111
108
  const dir = realpathOrSelf(resolve(cwd));
112
109
  const found = [];
113
110
  let loaded = access;
114
- for (const id of await checkoutChainOf(db, dir, async () => person ?? await personIdAsync())) {
111
+ for (const id of access?.chains?.get(dir) ?? await checkoutChainOf(db, dir, async () => person ?? await personIdAsync())) {
115
112
  if (!id.ok) {
116
113
  throw new CrtrError('git-lookup-failed', `cannot identify the repo at ${id.dir}: ${id.reason}`, ExitCode.GENERAL, { dir: id.dir });
117
114
  }
@@ -197,6 +197,8 @@ export async function getImage(config, name) {
197
197
  export async function deleteImage(config, name) {
198
198
  await api(config, 'DELETE', `/images/sandbox/${encodeURIComponent(name)}`, undefined, [404]);
199
199
  }
200
+ /** How long a build may stay BUILDING: the crouter-cloud image takes ~30-33 min on Blaxel. */
201
+ export const BUILD_TIMEOUT_MS = 60 * 60_000;
200
202
  /** Uploads `dir` (Dockerfile and context) as a build of sandbox image `name` and waits for it. A failed build throws with Blaxel's last event message. */
201
203
  export async function buildImage(config, name, dir, options = {}) {
202
204
  const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
@@ -214,7 +216,8 @@ export async function buildImage(config, name, dir, options = {}) {
214
216
  const put = await (config.fetch ?? fetch)(uploadUrl, { method: 'PUT', headers: { 'content-type': 'application/zip' }, body: new Uint8Array(zipDirectory(dir)) });
215
217
  if (!put.ok)
216
218
  throw new Error(`uploading the build context of image ${name} failed (${put.status}): ${(await put.text()).slice(0, 300)}`);
217
- const deadline = started + (options.timeoutMs ?? 20 * 60_000);
219
+ const timeoutMs = options.timeoutMs ?? BUILD_TIMEOUT_MS;
220
+ const deadline = started + timeoutMs;
218
221
  let builtAt = null;
219
222
  for (;;) {
220
223
  const image = await getImage(config, name);
@@ -244,7 +247,7 @@ export async function buildImage(config, name, dir, options = {}) {
244
247
  throw new Error(`building image ${name} ${status.toLowerCase()}: ${events[events.length - 1]?.message ?? 'no message'}`);
245
248
  }
246
249
  if (now() > deadline)
247
- throw new Error(`building image ${name} did not finish within ${options.timeoutMs ?? 20 * 60_000} ms (last status ${status ?? 'none'})`);
250
+ throw new Error(`building image ${name} did not finish within ${timeoutMs} ms (last status ${status ?? 'none'})`);
248
251
  await sleep(options.pollMs ?? 3000);
249
252
  }
250
253
  }
@@ -289,6 +289,7 @@ async function recordStartCallTimings(callId, answer) {
289
289
  * 'uncertain': the call was sent and its answer lost, so the Mac may have a broker: the execution stays launching and the node stays active, and the
290
290
  * tick's `status` of that execution decides (the machine runner's rule). 'full': the daemon is drained or at its broker cap, so nothing was begun. */
291
291
  async function startOnMachine(meta, environmentId, inv) {
292
+ const setupStart = performance.now();
292
293
  // Loaded here: the handlers import the runtime that imports this module.
293
294
  const { buildStartBundle } = await import('../../daemon/api/handlers/execution-start.js');
294
295
  const { renderCarriedStart } = await import('../../daemon/api/handlers/broker-ops.js');
@@ -311,9 +312,22 @@ async function startOnMachine(meta, environmentId, inv) {
311
312
  const launchJson = await brokerLaunchJson(meta.node_id, inv, meta.cwd);
312
313
  await setExecutionLaunchJson(executionId, launchJson);
313
314
  const execId = executionId;
314
- await timedStep('warm_repos', async () => await warmNodeRepos(await openDb(), meta.node_id));
315
- const sub = meta.sub ?? await personIdAsync();
316
- const bundle = await timedStep('start_bundle', () => buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' }));
315
+ addStepTiming('execution_setup', performance.now() - setupStart);
316
+ // Warm-up and the bundle are independent (the bundle reads the node, profile metadata, environment and secrets; warm-up writes checkout identities and a
317
+ // profile project's `repo`), so they run together. Both settle before the render transaction opens, and warm-up's error wins if both fail. The
318
+ // `warm_repos` and `start_bundle` marks each measure their own step and overlap; `warm_and_bundle` is the joined interval.
319
+ const [warmed, bundled] = await timedStep('warm_and_bundle', async () => await Promise.allSettled([
320
+ timedStep('warm_repos', async () => await warmNodeRepos(await openDb(), meta.node_id)),
321
+ timedStep('start_bundle', async () => {
322
+ const sub = meta.sub ?? await personIdAsync();
323
+ return await buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' });
324
+ }),
325
+ ]));
326
+ if (warmed.status === 'rejected')
327
+ throw warmed.reason;
328
+ if (bundled.status === 'rejected')
329
+ throw bundled.reason;
330
+ const bundle = bundled.value;
317
331
  callId = await timedStep('render_transaction', () => withCanvasWrite(async (db) => {
318
332
  // The reader is built here, after the goal and every birth write have landed, so the rendered bearings see them.
319
333
  const start = await renderCarriedStart(meta.node_id);
@@ -322,7 +336,7 @@ async function startOnMachine(meta, environmentId, inv) {
322
336
  executionId: execId, nodeId: meta.node_id, attempt: 1, sandboxName: null, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
323
337
  nodeToken, bundle, start,
324
338
  });
325
- }));
339
+ }, { timingName: 'render_tx' }));
326
340
  }
327
341
  catch (error) {
328
342
  emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
@@ -5,12 +5,33 @@
5
5
  // `Server-Timing` response header. A request opts in by running inside `collectStepTimings`; `timedStep` / `addStepTiming` record nothing
6
6
  // outside one. Names and durations only: never a token, secret, env value or document body.
7
7
  import { AsyncLocalStorage } from 'node:async_hooks';
8
+ import { monitorEventLoopDelay } from 'node:perf_hooks';
8
9
  const stepTimings = new AsyncLocalStorage();
9
10
  /** Run `fn`, collecting the steps recorded beneath it. */
10
11
  export async function collectStepTimings(fn) {
11
12
  const steps = [];
12
- const value = await stepTimings.run({ steps, start: performance.now() }, fn);
13
- return { value, steps };
13
+ // How long the event loop was blocked while the request ran: a blocked loop delays every await in it, and shows as time no step explains.
14
+ const loop = monitorEventLoopDelay({ resolution: 5 });
15
+ loop.enable();
16
+ try {
17
+ const value = await stepTimings.run({ steps, start: performance.now() }, fn);
18
+ return { value, steps };
19
+ }
20
+ finally {
21
+ loop.disable();
22
+ if (loop.count > 0)
23
+ steps.push(['event_loop_delay_max', loop.max / 1e6], ['event_loop_delay_p99', loop.percentile(99) / 1e6]);
24
+ }
25
+ }
26
+ /** True when the running request is collecting steps. */
27
+ export function isCollectingStepTimings() {
28
+ return stepTimings.getStore() !== undefined;
29
+ }
30
+ /** A short stable label for a statement: its verb and first table (`select_nodes`, `insert_run_events`), never its parameters or text. */
31
+ export function statementLabel(text) {
32
+ const verb = /^\s*(select|insert|update|delete|with|savepoint|release|rollback)\b/i.exec(text)?.[1]?.toLowerCase() ?? 'other';
33
+ const table = /\b(?:from|into|update)\s+(?:only\s+)?([a-z_][a-z0-9_.]*)/i.exec(text)?.[1]?.toLowerCase().replace(/\W/g, '_');
34
+ return table === undefined ? verb : `${verb}_${table}`;
14
35
  }
15
36
  /** Record a step's duration in ms, when a request is collecting. */
16
37
  export function addStepTiming(name, ms) {
@@ -41,6 +41,27 @@ async function readerManifest(db, reader) {
41
41
  throw new Error(`profile object ${reader.profile.id} has no profile identity`);
42
42
  return loadExactProfileManifest(profileId).manifest;
43
43
  }
44
+ /** Readers whose corpus reads are shared for as long as the reader lives (`shareCorpusReads`). */
45
+ const sharing = new WeakSet();
46
+ const shared = new WeakMap();
47
+ /** Make every document, head, rule, name and body read this reader's deliveries make run once per distinct input. Only for a reader built for one
48
+ * render that writes no documents while it lives: the answers are those of the first read, whatever changes after. */
49
+ export function shareCorpusReads(reader) { sharing.add(reader); }
50
+ function once(reader, key, load) {
51
+ if (!sharing.has(reader))
52
+ return load();
53
+ let reads = shared.get(reader);
54
+ if (reads === undefined)
55
+ shared.set(reader, reads = new Map());
56
+ const id = JSON.stringify(key);
57
+ let hit = reads.get(id);
58
+ if (hit === undefined) {
59
+ hit = load();
60
+ reads.set(id, hit);
61
+ hit.catch(() => reads.delete(id));
62
+ }
63
+ return hit;
64
+ }
44
65
  /** One scope per reader object. A reader is built for one request and its view, subjects and read rule are facts of that reader, so every
45
66
  * corpus of one delivery shares them: the `names` activity loads one corpus per owner in the view and a boot one per linked document, and
46
67
  * rebuilding the scope for each cost about thirty statements a time. */
@@ -64,12 +85,18 @@ export async function readRule(db, reader) {
64
85
  }
65
86
  /** The live documents satisfying `where` that the reader may read. */
66
87
  async function documentRows(db, scope, where, args) {
88
+ return [...await once(scope.reader, ['docs', where, args], async () => await documentRowsNow(db, scope, where, args))];
89
+ }
90
+ async function documentRowsNow(db, scope, where, args) {
67
91
  return await db.prepareUncached(`SELECT o.*, d.heads_key, d.unlisted, d.source_path FROM objects o JOIN documents d ON d.object = o.id
68
92
  WHERE o.type = 'document' AND o.deleted_at IS NULL AND ${where} AND ${scope.read.sql} ORDER BY o.seq`)
69
93
  .all(...args, ...scope.read.params);
70
94
  }
71
95
  /** Each document's current body hash: the highest-numbered of its head revisions, for all of `docs` in one query. */
72
- async function headBodyHashes(db, docs) {
96
+ async function headBodyHashes(db, scope, docs) {
97
+ return await once(scope.reader, ['heads', docs.map((d) => [d.id, d.heads_key])], async () => await headBodyHashesNow(db, docs));
98
+ }
99
+ async function headBodyHashesNow(db, docs) {
73
100
  const heads = [...new Set(docs.flatMap((d) => d.heads_key.split(',')))];
74
101
  const rows = heads.length === 0 ? [] : await db.prepare('SELECT rev_id, document, number, body_hash FROM revisions WHERE rev_id = ANY(?::text[])')
75
102
  .all(heads);
@@ -105,9 +132,10 @@ async function toDeliveryDocs(db, scope, rows, rulesByDoc) {
105
132
  for (const o of await db.prepare('SELECT * FROM objects WHERE id = ANY(?::text[])').all(outside))
106
133
  owners.set(o.id, o);
107
134
  }
108
- const rules = rulesByDoc ?? await rulesOfMany(db, rows.map((r) => r.id));
109
- const hashes = await headBodyHashes(db, rows);
110
- const resolvedNames = await viewResolutions(db, context, rows.map((r) => r.name));
135
+ const ruleIds = rows.map((r) => r.id);
136
+ const rules = rulesByDoc ?? await once(reader, ['rules', ruleIds], async () => await rulesOfMany(db, ruleIds));
137
+ const hashes = await headBodyHashes(db, scope, rows);
138
+ const resolvedNames = await once(reader, ['names', rows.map((r) => r.name)], async () => await viewResolutions(db, context, rows.map((r) => r.name)));
111
139
  return await mapAsync(rows, async (doc) => {
112
140
  const owner = owners.get(doc.owner);
113
141
  if (owner === undefined)
@@ -8,6 +8,7 @@ import { isSafeNodeId } from '../../../core/canvas/paths.js';
8
8
  import { isPidAlive } from '../../../core/canvas/pid.js';
9
9
  import { editorLabel } from '../../../core/canvas/labels.js';
10
10
  import { assembleNodeSubject } from '../../../core/substrate/subject.js';
11
+ import { shareCorpusReads } from '../../../core/substrate/delivery/corpus.js';
11
12
  import { openDb, withCanvasWrite } from '../../../core/canvas/db.js';
12
13
  import { runningJobs } from '../../../core/graph/jobs.js';
13
14
  import { notFound, usage } from '../../../core/errors.js';
@@ -160,7 +161,7 @@ export async function extensionNode(node) {
160
161
  created: node.created,
161
162
  };
162
163
  }
163
- async function extensionState(nodeId) {
164
+ async function extensionState(nodeId, gate) {
164
165
  const node = await requireNode(nodeId);
165
166
  const ancestors = [];
166
167
  const seen = new Set([nodeId]);
@@ -179,7 +180,7 @@ async function extensionState(nodeId) {
179
180
  const source = typeof node.fork_source_file === 'string'
180
181
  ? await forkSourceNode(node.fork_source_file)
181
182
  : null;
182
- const subject = await assembleNodeSubject(nodeId);
183
+ const subject = gate ?? await assembleNodeSubject(nodeId);
183
184
  if (subject === null)
184
185
  throw notFound(`unknown node: ${nodeId}`, { received: nodeId });
185
186
  return {
@@ -295,30 +296,31 @@ function parseCycleStartBody(body) {
295
296
  /** The names, bearings and first system-prompt block a cycle opens with, delivered in one write the way the
296
297
  * delivery route would deliver each. A warm spare is owed no bearings and no system prompt: its claim delivers them.
297
298
  * `namesOnly` gives a node the same treatment while its bind is undecided. */
298
- async function startupDelivery(nodeId, state, bearings, namesOnly, warmed = false) {
299
+ async function startupDelivery(db, reader, subject, state, bearings, namesOnly) {
299
300
  const warm = state.warm_spare || namesOnly;
300
301
  const bootOwed = !warm && bearings !== 'present';
302
+ const names = await deliver(db, reader, { activity: 'names' }, subject);
303
+ const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}) }, subject) : undefined;
304
+ const system = warm ? undefined : await deliver(db, reader, { activity: 'system-prompt' }, subject);
305
+ return {
306
+ names: { refs: names.refs, names: names.names },
307
+ ...(boot === undefined ? {} : { boot: { content: boot.content, ...(boot.inherited === true ? { inherited: true } : {}) } }),
308
+ ...(system === undefined ? {} : { system_prompt: system.content }),
309
+ };
310
+ }
311
+ /** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
312
+ * awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
313
+ * or system prompt until the bind commits. The node's repository view is built once and serves both the state's subject and the delivery. */
314
+ export async function renderStartData(nodeId, bearings, namesOnly, warmed = false) {
301
315
  if (!warmed)
302
316
  await warmNodeRepos(await openDb(), nodeId);
303
- return await withCanvasWrite(async (db) => {
317
+ const { state, delivery } = await withCanvasWrite(async (db) => {
304
318
  const reader = await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access));
319
+ shareCorpusReads(reader);
305
320
  const subject = await nodeSubject(db, reader);
306
- const names = await deliver(db, reader, { activity: 'names' }, subject);
307
- const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}) }, subject) : undefined;
308
- const system = warm ? undefined : await deliver(db, reader, { activity: 'system-prompt' }, subject);
309
- return {
310
- names: { refs: names.refs, names: names.names },
311
- ...(boot === undefined ? {} : { boot: { content: boot.content, ...(boot.inherited === true ? { inherited: true } : {}) } }),
312
- ...(system === undefined ? {} : { system_prompt: system.content }),
313
- };
321
+ const state = await extensionState(nodeId, subject);
322
+ return { state, delivery: await startupDelivery(db, reader, subject, state, bearings, namesOnly) };
314
323
  });
315
- }
316
- /** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
317
- * awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
318
- * or system prompt until the bind commits. */
319
- export async function renderStartData(nodeId, bearings, namesOnly, warmed = false) {
320
- const state = await extensionState(nodeId);
321
- const delivery = await startupDelivery(nodeId, state, bearings, namesOnly, warmed);
322
324
  // The bearings just rendered are the persona baseline; the broker does not acknowledge it separately.
323
325
  if (delivery.boot !== undefined) {
324
326
  const current = { kind: state.node.kind, mode: state.node.mode, lifecycle: state.node.lifecycle };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.683",
3
+ "version": "0.3.685",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.683",
3
+ "version": "0.3.685",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.683",
3
+ "version": "0.3.685",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.683",
31
- "@north-light/identity": "0.3.683"
30
+ "@north-light/api": "0.3.685",
31
+ "@north-light/identity": "0.3.685"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {