@north-light/cli 0.3.717 → 0.3.719

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- var $=Object.defineProperty;var l=(t,e)=>$(t,"name",{value:e,configurable:!0});import{dirname as P}from"node:path";import{isCloudRole as T}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as H}from"../../runtime/runner/machine/environment.js";import{clearLedger as W,demoteTranscript as x,freezePreferences as O,loadLedger as Y,saveLedger as B}from"../../graph/exposures.js";import{recordWatches as U}from"../../graph/watches.js";import{publishMany as J}from"../../graph/events.js";import{checkoutsForCwd as h}from"../../graph/repo-sync/repos.js";import{liveLookups as K,profileObject as V,viewRepos as G}from"../../graph/reader.js";import{ownerForGrantee as X}from"../../graph/objects.js";import{resolveName as z}from"../../graph/names.js";import{SCOPE_VOCABULARY as Q}from"../../scopes.js";import{getNode as Z}from"../../canvas/index.js";import{recordMemoryReadsIn as q}from"../../canvas/memory-reads.js";import{lookupProfile as ee}from"../../profiles/manifest.js";import{getDefaultProfileId as te}from"../../profiles/default-binding.js";import{effectiveScopes as ne,profileNameFor as oe,scopeForCwd as re}from"../subject-fields.js";import{spineDepth as ae}from"../subject.js";import{appForNode as ie}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as k}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce}from"../../runtime/bearings.js";import{deliveryDocOf as N,listingCorpora as de,loadCorpus as w,nodeSubject as R,primeBodies as le,profileIdOfObject as pe,viewOwners as ue}from"./corpus.js";import{listingPrefixes as me}from"./listings.js";import{planDelivery as fe}from"./plan.js";import{renderEvent as _,renderExplicitRead as S}from"./render-event.js";import{renderConfigDelta as we,renderKnowledge as ye,renderPreferences as E,renderWorkspaceOpen as D}from"./render-boot.js";import{mapAsync as I}from"../../async-array.js";function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const C="hypothetical";function v(t){return t.node.id===C}l(v,"isHypothetical");async function g(t,e){if(!v(e))return await ie(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(g,"granteeOf");async function he(t,e,n,o=async(r,c)=>await h(t,r,c)){const r=f(e).node,c=new Set,a=new Date().toISOString(),s=[],i=[];for(const{doc:d,level:p}of n)p!=="content"||c.has(d.object.id)||(c.add(d.object.id),i.push({watcher:r,object:d.object,start:"deliver",opts:{readHeadsKey:d.headsKey}}),s.push({name:d.name,scope:d.ownerHandle,at:a,type:"loaded"}));await U(t,i),await J(t,i.map(d=>({event:"read",object:d.object,actor:r,attrs:{}})),o),v(f(e))||await q(t,r.id,s)}l(he,"recordContentDelivery");async function A(t,e,n){if(await b(t,e,n))return e;const o=(await h(t,P(n))).filter(r=>!e.repos.some(c=>c.id===r.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(r=>r.repo)],checkouts:[...e.checkouts,...o]}}l(A,"fileReadReader");async function b(t,e,n){const o=await g(t,e);if(o!=="app:terminal"||!T()||e.profile==null)return!1;const r=await pe(t,e.profile.id);return r!==null&&await H(r)!==null&&!k(n,o,e.scopes??[],null)}l(b,"isMacEnforcedRead");async function F(t,e,n){if(!await b(t,e,n))return{absoluteFile:n};const o=new Map;for(const{root:r,repo:c}of e.checkouts)n.startsWith(r.endsWith("/")?r:`${r}/`)&&!o.has(c.id)&&o.set(c.id,r);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(F,"fileReadPayload");async function ve(t,e,n){const o=await g(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await b(t,e,n)||k(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(ve,"assertReadableFile");async function ge(t){const e=f(t.reader),n=e.node,o=await g(t.db,e),r=await w(t.db,t.reader,["slash-command"]);await le(t.db,r);const c=await I(r,async a=>{const s=await a.body();return{name:a.displayName,command_name:a.displayName,description:a.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:r,commands:c}}l(ge,"slashCommands");function be(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(be,"scopeOf");async function je(t,e){const n=[],o=new Set,r=await ue(t,e),c=await de(t,e,r);for(const a of r){const s=c.get(a.id);for(const i of s){n.push({name:i.displayName,kind:i.kind,scope:be(i),shortForm:i.preview,gatewayVisible:!i.shipped}),o.add(i.displayName);const d=i.displayName===i.name?"":`${i.ownerHandle}/`;for(const p of me(s,i.name))o.add(`${d}${p}`)}}return{refs:n,names:[...o]}}l(je,"composerNames");async function L(t,e){const n=f(t.reader),{db:o,ledger:r}=t,c=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[i,d]of r.objects)if(d.transcript===void 0)r.objects.delete(i);else{const{system:p,...u}=d;r.objects.set(i,u)}for(const[i,d]of r.listed)d.transcript===void 0?r.listed.delete(i):r.listed.set(i,{transcript:d.transcript});return r.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const a=v(n)?await Oe(t):await ce(n.node.id,t),s=await E({...t,channel:"system"});return O(r,s.content),{result:{content:a.content},delivered:[...a.delivered,...s.delivered]}}case"system-prompt":{if(r.preferenceSnapshot!==null)return{result:{content:r.preferenceSnapshot},delivered:[]};const a=await E({...t,channel:"system"});return{result:{content:O(r,a.content)},delivered:a.delivered}}case"compact":{for(const a of await w(o,n,["pre-command"]))x(r,a.object.id);return{result:{content:""},delivered:[]}}case"persona":{const a=await we(t);return{result:{content:a.content},delivered:a.delivered}}case"file-read":{const a=c();await ve(o,n,a);const s=await A(o,n,a),i={...t,reader:s},d=await _(i,"file-read",await F(o,n,a),await w(o,s,["file-read"]));return{result:{content:d.content},delivered:d.delivered}}case"command":case"pre-command":{const a=await _(t,e.activity,{command:c()});return{result:{content:a.content},delivered:a.delivered}}case"slash-command":{const{docs:a,commands:s}=await ge(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const i=a.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(i<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const d=a[i],p=await S(t,d,!0);return{result:{content:"",execution_body:s[i].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:d,level:"content"},...p.delivered]}}case"workspace-open":{const a=await D(t);return{result:{content:a.content},delivered:a.delivered}}case"document-read":{const a=await M(o,n,c()),s=await S(t,await N(o,n,a),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await je(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(L,"render");async function Oe(t){const e=await ye(t),n=await D(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
2
- `),delivered:[...e.delivered,...n.delivered]}}l(Oe,"hypotheticalBearings");async function M(t,e,n){const o=await z(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(M,"readDocument");const ke=["workspace-open","document-read"];async function tt(t,e,n,o){if(ke.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const r=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await W(t,r.id);const c=await Y(t,r.id),a={db:t,reader:e,subject:o??await R(t,e),ledger:c,channel:"transcript"},{result:s,delivered:i}=await L(a,n);return await he(t,e,i),await B(t,c),s}l(tt,"deliver");const Ne={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function nt(t,e){const n=await Z(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await ae(t)}}l(nt,"hypotheticalFrom");function Re(t,e){if(t===null)return null;if(t===void 0||t==="")return te(e);const n=ee(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(Re,"resolveProfileId");async function ot(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Re(e.profile,e.cwd),r=await G(t,e.cwd,o,async(p,u,y)=>await h(t,p,u,y),K(t)),{repos:c}=r,a=e.mode??"base",i={class:"node",node:{id:C,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...Q],cwd:e.cwd,...r,profile:o===null?null:await V(t,o,n)},d={kind:e.kind??"general",mode:a,lifecycle:e.lifecycle??(a==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:re(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...c,...r.projectRepos].map(p=>p.name)};return{reader:i,subject:d}}l(ot,"hypotheticalReader");async function rt(t,e,n,o,r){const a={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...r??await R(t,e),...o},i={db:t,reader:e,subject:s,ledger:a,channel:"transcript"},{result:d}=await L(i,n),p=Ne[n.activity];let u=null;if(p!==void 0){const y=n.activity==="file-read"?await F(t,f(e),n.subject):n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await N(t,e,await M(t,e,n.subject))}:{},j=n.activity==="file-read"&&n.subject!==void 0?await A(t,f(e),n.subject):e;u=await fe(t,s,j,await w(t,j,[p]),p,y)}return{result:d,plan:u}}l(rt,"inspect");async function at(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
1
+ var L=Object.defineProperty;var l=(t,e)=>L(t,"name",{value:e,configurable:!0});import{dirname as M}from"node:path";import{isCloudRole as $}from"../../canvas/person-state.js";import{machineEnvironmentOfProfile as T}from"../../runtime/runner/machine/environment.js";import{clearLedger as H,demoteTranscript as W,freezePreferences as N,loadLedger as Y,saveLedger as B}from"../../graph/exposures.js";import{recordWatches as U}from"../../graph/watches.js";import{publishMany as J}from"../../graph/events.js";import{checkoutsForCwd as h}from"../../graph/repo-sync/repos.js";import{liveLookups as K,profileObject as V,viewRepos as G}from"../../graph/reader.js";import{ownerForGrantee as X}from"../../graph/objects.js";import{resolveName as z}from"../../graph/names.js";import{SCOPE_VOCABULARY as Q}from"../../scopes.js";import{getNode as Z}from"../../canvas/index.js";import{recordMemoryReadsIn as q}from"../../canvas/memory-reads.js";import{lookupProfile as ee}from"../../profiles/manifest.js";import{getDefaultProfileId as te}from"../../profiles/default-binding.js";import{effectiveScopes as ne,profileNameFor as oe,scopeForCwd as re}from"../subject-fields.js";import{spineDepth as ie}from"../subject.js";import{appForNode as ae}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as O}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce,projectContextForNode as de}from"../../runtime/bearings.js";import{deliveryDocOf as k,listingCorpora as le,loadCorpus as w,nodeSubject as R,primeBodies as pe,profileIdOfObject as ue,viewOwners as me}from"./corpus.js";import{listingPrefixes as fe}from"./listings.js";import{planDelivery as we}from"./plan.js";import{renderEvent as _,renderExplicitRead as C}from"./render-event.js";import{renderConfigDelta as ye,renderKnowledge as he,renderPreferences as S,renderWorkspaceOpen as E}from"./render-boot.js";import{mapAsync as D}from"../../async-array.js";async function ot(t,e){return e.activity==="boot"&&e.inherited!==!0?{...e,projectContext:await de(t)}:e}l(ot,"withProjectContext");function f(t){if(t.class!=="node")throw new Error(`delivery needs a node reader, got ${t.class}`);return t}l(f,"nodeOf");const I="hypothetical";function v(t){return t.node.id===I}l(v,"isHypothetical");async function g(t,e){if(!v(e))return await ae(e.node.id);const n=await t.prepare("SELECT external_id FROM identities WHERE object = ?").get(e.app.id);if(!n)throw new Error(`app object ${e.app.id} has no identity`);return n.external_id}l(g,"granteeOf");async function ve(t,e,n,o=async(r,c)=>await h(t,r,c)){const r=f(e).node,c=new Set,i=new Date().toISOString(),s=[],a=[];for(const{doc:d,level:p}of n)p!=="content"||c.has(d.object.id)||(c.add(d.object.id),a.push({watcher:r,object:d.object,start:"deliver",opts:{readHeadsKey:d.headsKey}}),s.push({name:d.name,scope:d.ownerHandle,at:i,type:"loaded"}));await U(t,a),await J(t,a.map(d=>({event:"read",object:d.object,actor:r,attrs:{}})),o),v(f(e))||await q(t,r.id,s)}l(ve,"recordContentDelivery");async function F(t,e,n){if(await b(t,e,n))return e;const o=(await h(t,M(n))).filter(r=>!e.repos.some(c=>c.id===r.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(r=>r.repo)],checkouts:[...e.checkouts,...o]}}l(F,"fileReadReader");async function b(t,e,n){const o=await g(t,e);if(o!=="app:terminal"||!$()||e.profile==null)return!1;const r=await ue(t,e.profile.id);return r!==null&&await T(r)!==null&&!O(n,o,e.scopes??[],null)}l(b,"isMacEnforcedRead");async function P(t,e,n){if(!await b(t,e,n))return{absoluteFile:n};const o=new Map;for(const{root:r,repo:c}of e.checkouts)n.startsWith(r.endsWith("/")?r:`${r}/`)&&!o.has(c.id)&&o.set(c.id,r);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(P,"fileReadPayload");async function ge(t,e,n){const o=await g(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await b(t,e,n)||O(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(ge,"assertReadableFile");async function be(t){const e=f(t.reader),n=e.node,o=await g(t.db,e),r=await w(t.db,t.reader,["slash-command"]);await pe(t.db,r);const c=await D(r,async i=>{const s=await i.body();return{name:i.displayName,command_name:i.displayName,description:i.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:r,commands:c}}l(be,"slashCommands");function je(t){if(t.shipped)return"builtin";switch(t.owner.type){case"node":return"node";case"repo":return"project";case"profile":return"profile";default:return"user"}}l(je,"scopeOf");async function Ne(t,e){const n=[],o=new Set,r=await me(t,e),c=await le(t,e,r);for(const i of r){const s=c.get(i.id);for(const a of s){n.push({name:a.displayName,kind:a.kind,scope:je(a),shortForm:a.preview,gatewayVisible:!a.shipped}),o.add(a.displayName);const d=a.displayName===a.name?"":`${a.ownerHandle}/`;for(const p of fe(s,a.name))o.add(`${d}${p}`)}}return{refs:n,names:[...o]}}l(Ne,"composerNames");async function x(t,e){const n=f(t.reader),{db:o,ledger:r}=t,c=l(()=>{if(typeof e.subject!="string"||e.subject==="")throw new m(400,"usage",`delivery activity ${e.activity} requires a subject`);return e.subject},"requireSubject");switch(e.activity){case"boot":{if(e.inherited===!0){for(const[a,d]of r.objects)if(d.transcript===void 0)r.objects.delete(a);else{const{system:p,...u}=d;r.objects.set(a,u)}for(const[a,d]of r.listed)d.transcript===void 0?r.listed.delete(a):r.listed.set(a,{transcript:d.transcript});return r.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const i=v(n)?await ke(t):await ce(n.node.id,t,Oe(e)),s=await S({...t,channel:"system"});return N(r,s.content),{result:{content:i.content},delivered:[...i.delivered,...s.delivered]}}case"system-prompt":{if(r.preferenceSnapshot!==null)return{result:{content:r.preferenceSnapshot},delivered:[]};const i=await S({...t,channel:"system"});return{result:{content:N(r,i.content)},delivered:i.delivered}}case"compact":{for(const i of await w(o,n,["pre-command"]))W(r,i.object.id);return{result:{content:""},delivered:[]}}case"persona":{const i=await ye(t);return{result:{content:i.content},delivered:i.delivered}}case"file-read":{const i=c();await ge(o,n,i);const s=await F(o,n,i),a={...t,reader:s},d=await _(a,"file-read",await P(o,n,i),await w(o,s,["file-read"]));return{result:{content:d.content},delivered:d.delivered}}case"command":case"pre-command":{const i=await _(t,e.activity,{command:c()});return{result:{content:i.content},delivered:i.delivered}}case"slash-command":{const{docs:i,commands:s}=await be(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const a=i.findIndex(u=>u.displayName===e.subject||u.name===e.subject);if(a<0)throw new m(404,"not_found",`no slash command named ${e.subject}`);const d=i[a],p=await C(t,d,!0);return{result:{content:"",execution_body:s[a].execution_body,blocks:p.attachments===""?[]:[p.attachments]},delivered:[{doc:d,level:"content"},...p.delivered]}}case"workspace-open":{const i=await E(t);return{result:{content:i.content},delivered:i.delivered}}case"document-read":{const i=await A(o,n,c()),s=await C(t,await k(o,n,i),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await Ne(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(x,"render");function Oe(t){if(t.projectContext===void 0)throw new Error("a node boot delivery needs its project context built before the transaction: pass the request through withProjectContext");return t.projectContext}l(Oe,"requireProjectContext");async function ke(t){const e=await he(t),n=await E(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
2
+ `),delivered:[...e.delivered,...n.delivered]}}l(ke,"hypotheticalBearings");async function A(t,e,n){const o=await z(t,e,n);if("object"in o&&o.object.type==="document")return o.object;throw"ambiguous"in o?new m(409,"ambiguous",`${n} names ${o.ambiguous.length} documents; name one as <type>:<owner>/<name>`):new m(404,"not_found",`no document ${n} the reader can read`)}l(A,"readDocument");const Re=["workspace-open","document-read"];async function rt(t,e,n,o){if(Re.includes(n.activity))throw new m(400,"usage",`delivery activity ${n.activity} is available to a dry run only`);const r=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await H(t,r.id);const c=await Y(t,r.id),i={db:t,reader:e,subject:o??await R(t,e),ledger:c,channel:"transcript"},{result:s,delivered:a}=await x(i,n);return await ve(t,e,a),await B(t,c),s}l(rt,"deliver");const _e={boot:"boot","workspace-open":"workspace-open","file-read":"file-read","document-read":"document-read",command:"command","pre-command":"pre-command","slash-command":"slash-command"};async function it(t,e){const n=await Z(t);if(n===null)throw new m(404,"not_found",`no node ${t}`);return{cwd:e.cwd??n.cwd,profile:e.profile!==void 0?e.profile:n.profile_id,grantee:e.grantee??n.grantee,kind:e.kind??n.kind,mode:e.mode??n.mode,lifecycle:e.lifecycle??n.lifecycle,hasManager:e.hasManager??(n.parent??null)!==null,depth:e.depth??await ie(t)}}l(it,"hypotheticalFrom");function Ce(t,e){if(t===null)return null;if(t===void 0||t==="")return te(e);const n=ee(t);if(n.kind!=="resolved"){const o=`no profile ${t}`;throw new m(404,"not_found",o,{error:"not_found",message:o,next:"List profile ids and names with `crtr profile list`."})}return n.entry.profileId}l(Ce,"resolveProfileId");async function at(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Ce(e.profile,e.cwd),r=await G(t,e.cwd,o,async(p,u,y)=>await h(t,p,u,y),K(t)),{repos:c}=r,i=e.mode??"base",a={class:"node",node:{id:I,seq:0,type:"node",kind:e.kind??"general",owner:n.id,privacy:"private",name:"hypothetical",preview:"",created_at:new Date(0).toISOString(),deleted_at:null},app:n,scopes:[...Q],cwd:e.cwd,...r,profile:o===null?null:await V(t,o,n)},d={kind:e.kind??"general",mode:i,lifecycle:e.lifecycle??(i==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:re(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...c,...r.projectRepos].map(p=>p.name)};return{reader:a,subject:d}}l(at,"hypotheticalReader");async function st(t,e,n,o,r){const i={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...r??await R(t,e),...o},a={db:t,reader:e,subject:s,ledger:i,channel:"transcript"},{result:d}=await x(a,n),p=_e[n.activity];let u=null;if(p!==void 0){const y=n.activity==="file-read"?await P(t,f(e),n.subject):n.activity==="command"||n.activity==="pre-command"?{command:n.subject}:n.activity==="document-read"&&n.subject!==void 0?{doc:await k(t,e,await A(t,e,n.subject))}:{},j=n.activity==="file-read"&&n.subject!==void 0?await F(t,f(e),n.subject):e;u=await we(t,s,j,await w(t,j,[p]),p,y)}return{result:d,plan:u}}l(st,"inspect");async function ct(t,e,n){const o=await t.prepare(`SELECT o.*, MAX(r.number) AS to_seq, string_agg(DISTINCT a.id, ',') AS authors
3
3
  FROM watches w JOIN objects o ON o.id = w.object AND o.type = 'document' AND o.deleted_at IS NULL
4
4
  JOIN revisions r ON r.document = o.id LEFT JOIN objects a ON a.id = r.author
5
5
  WHERE w.watcher = ? AND r.created_at > ? AND (r.author IS NULL OR r.author != ?)
6
- GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await I(o,async({to_seq:r,authors:c,...a})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(a.id,n);return{doc:a,from:s.seq,to:r,authors:c===null?[]:c.split(",")}})}l(at,"changedWhileDone");export{ke as DRY_RUN_ONLY,at as changedWhileDone,tt as deliver,nt as hypotheticalFrom,ot as hypotheticalReader,rt as inspect,he as recordContentDelivery};
6
+ GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await D(o,async({to_seq:r,authors:c,...i})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(i.id,n);return{doc:i,from:s.seq,to:r,authors:c===null?[]:c.split(",")}})}l(ct,"changedWhileDone");export{Re as DRY_RUN_ONLY,ct as changedWhileDone,rt as deliver,it as hypotheticalFrom,at as hypotheticalReader,st as inspect,ve as recordContentDelivery,ot as withProjectContext};
@@ -1 +1 @@
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 v,getNodes as X,isWarmSpare as Z,recordLaunch as I,recordRespawnAttempt as q,recordSettledTurn as ee,setPresence as g,subscriptionsOf as te,updateNode as S,updateNodeTelemetry as ne}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as x,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 R,withCanvasWrite as w}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as E,usage as d}from"../../../core/errors.js";import{hasUnseenWakeMail as T,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 b}from"../../../core/runtime/lifecycle.js";import{confirmViewer as C,probeViewer as F,tearDownNode as N}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 B}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 Se,recordPendingParkActivity as xe}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Ee}from"../../../core/runtime/situational-context.js";import{recoveryState as Oe,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Ce}from"../../../core/graph/reader.js";import{checkoutsForCwd as Fe}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Ne}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as Be}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 Ue}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ve}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as $e,cycleCompatible as We}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as je,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 v(t);if(e===null)throw E(`unknown node: ${t}`,{received:t});return e}s(y,"requireNode");async function _(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(_,"extensionNode");async function U(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 v(a);if(u===null)break;r.unshift(await _(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),_),c=typeof n.fork_source_file=="string"?await ye(n.fork_source_file):null,l=e??await le(t);if(l===null)throw E(`unknown node: ${t}`,{received:t});return{node:await _(n),warm_spare:await Z(t),situational_card:await Ee(t),ancestors:r,children:o,fork_source:c===null?null:await _(c),subject:l,roadmap:await we(t)}}s(U,"extensionState");function A(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(A,"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 V(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 b(t,"revive")),{action:"none"}})}s(V,"commitSessionBound");async function nt(t){return{status:200,body:await V(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 $(t,e,n,r=!1){r||await Ce(await R(),t);const{state:i,delivery:a}=await w(async o=>{const c=await Te(o,t,async(p,k,Y)=>await Fe(o,p,k,Y));ue(c);const l=await Ne(o,c),u=await U(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};A(l,o)||await G(t,l,o)}return{state:i,delivery:a}}s($,"renderStartData");async function fn(t){const{state:e,delivery:n}=await $(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.pi_session_id==null;if(o)await f(e,n.executionId);else{const{action:p}=await V(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:l}=await $(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...l,recovery:await Oe(e),attachments:(await Ae(e)).map(({path:p,sha256:k})=>({path:p,sha256:k})),structured_request:await B(e)}}}s(ot,"handleCycleStart");async function W(t,e){return e.live!==null||await he(t)||await T(t)}s(W,"isHeldAwake");async function j(t,e){return(await x(t))?.runner==="blaxel"&&!await W(t,e)&&(await pe(await R(),t)).length===0}s(j,"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 v(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw E(`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 b(t,"finish"),await h(t),await g(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 B(t)===null&&await j(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 g(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 T(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await W(t,n);return(await x(t))?.runner==="blaxel"?{directive:await j(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 b(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 x(e),a=Ue(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&We(i.launchJson,await Ve(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 je(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(await R()).prepare("UPDATE nodes SET cycles = ?, cycle_pending = 1, intent = NULL WHERE node_id = ?").run(e.cycles,t);const o={};for(const c of $e)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 F(e),{directive:i,closePane:a}=await w(async()=>await at(e,n,await C(r)));return a&&await N(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 F(e),i=await w(async()=>{const a=await Se(e);if(a===void 0)return{action:"stay_dormant"};const o=await y(e);return await Pe(e,o,a,await C(r))?(await h(e),await b(e,"park"),await g(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 N(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 xe(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 Be(e,n.run_id),{status:200,body:await U(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 S(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 S(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!A(a,n)||!A(c,e)?!1:(await S(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,_ as extensionNode,fn as renderCarriedStart,$ as renderStartData,mn as setRequestsStartRunObservers};
1
+ var z=Object.defineProperty;var s=(t,e)=>z(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Q,findNodeBySessionFile as X,getNode as v,getNodes as Z,isWarmSpare as q,recordLaunch as I,recordRespawnAttempt as ee,recordSettledTurn as te,setPresence as g,subscriptionsOf as ne,updateNode as x,updateNodeTelemetry as ie}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as re,recordExecutionPid as oe}from"../../../core/canvas/executions.js";import{bindSession as ae,readLiveSession as se,transferSession as ce}from"../../../core/canvas/sessions.js";import{isSafeNodeId as de}from"../../../core/canvas/paths.js";import{isPidAlive as le}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as ue}from"../../../core/substrate/subject.js";import{shareCorpusReads as pe}from"../../../core/substrate/delivery/corpus.js";import{openDb as R,withCanvasWrite as y}from"../../../core/canvas/db.js";import{runningJobs as fe}from"../../../core/graph/jobs.js";import{notFound as E,usage as u}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as me}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as we}from"../../../core/runtime/kickoff.js";import{readRoadmap as ye}from"../../../core/runtime/roadmap.js";import{forkSourceNode as he}from"../../../core/runtime/nodes.js";import{transition as _}from"../../../core/runtime/lifecycle.js";import{confirmViewer as T,probeViewer as F,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as be}from"../viewer-presence.js";import{evaluateStop as _e}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as B}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as ke,recordFault as ve}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ge}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as xe}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as Se,recordPendingParkActivity as Pe}from"../../park-pending.js";import{shouldParkAfterSummary as Re}from"../../park-activity.js";import{ownerOnly as Ee}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ae,requireCurrentExecution as f}from"./broker-recovery.js";import{runAttachments as Ce}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Ne}from"../../../core/graph/repo-sync/repos.js";import{deliver as O,withProjectContext as Be}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 Ue}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 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 m(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw u(`${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 u("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw u("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw u("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw u("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw u("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw u("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function Ze(t){const e=m(t,"broker settle");if(typeof e.stopReason!="string")throw u("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw u(`${n} must be a boolean`);return e}s(Ze,"parseSettleBody");function qe(t){const e=m(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw u("brokerVersion must be a non-empty string");return e}s(qe,"parseCycleBody");function Ie(t){const e=m(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw u("outcome must be completed or failed");return e}s(Ie,"parseParkCompleteBody");function et(t){const e=m(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw u("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=m(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw u("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const o=n!==null&&typeof n=="object"?n:void 0;if(o===void 0||typeof o.family!="string"||o.family===""||!["ultra","strong","medium","light"].includes(o.strength))throw u("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw u("userSelected must be a boolean");return e}s(tt,"parseModelCommitBody");async function w(t){const e=await v(t);if(e===null)throw E(`unknown node: ${t}`,{received:t});return e}s(w,"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 j(t,e){const n=await w(t),o=[],i=new Set([t]);let r=n.parent??null;for(;r!==null&&r!==""&&!i.has(r);){i.add(r);const l=await v(r);if(l===null)break;o.unshift(await k(l)),r=l.parent??null}const a=await Ue((await Z((await ne(t)).map(l=>l.node_id))).filter(l=>l.kind!=="human").sort((l,p)=>l.status===p.status?0:l.status==="active"?-1:p.status==="active"?1:0),k),c=typeof n.fork_source_file=="string"?await he(n.fork_source_file):null,d=e??await ue(t);if(d===null)throw E(`unknown node: ${t}`,{received:t});return{node:await k(n),warm_spare:await q(t),situational_card:await Oe(t),ancestors:o,children:a,fork_source:c===null?null:await k(c),subject:d,roadmap:await ye(t)}}s(j,"extensionState");function A(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(A,"samePersona");function nt(t){const e=m(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw u("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw u("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(o=>typeof n[o]!="string"))throw u("recap expected must contain name, description, title, icon, and kind strings");return e}s(nt,"parseGeneratedNameBody");function it(t){const e=m(t,"broker persona-ack"),n=s(o=>{const i=e[o];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 u(`${o} 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 U(t,e){const n=e.sessionFile===null?null:Q(e.sessionFile);return await y(async o=>{await o.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await w(t);if(await oe(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const r=i.review_binding?.review_id;if(r!==void 0&&!e.reviewBoundaryIds.includes(r))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 a=n===null?null:await X(n);if(a!==null&&a.node_id!==t){if(le(a.pi_pid))return await ve(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${a.node_id}`}),{action:"shutdown"};const c=await se(a.node_id);if(c===null||await ce({fromNodeId:a.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ae(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await we(t),i.intent==="refresh"&&await _(t,"revive")),{action:"none"}})}s(U,"commitSessionBound");async function rt(t){return{status:200,body:await U(t.params.id,M(t.body))}}s(rt,"handleSessionBound");function ot(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw u("bearings must be fresh, inherited or present");return e}s(ot,"parseCycleStartBody");async function at(t,e,n,o,i,r,a){const c=o.warm_spare||r,d=!c&&i!=="present",l=await O(t,e,{activity:"names"},n),p=d?await O(t,e,{activity:"boot",...i==="inherited"?{inherited:!0}:{},...a===void 0?{}:{projectContext:a}},n):void 0,b=c?void 0:await O(t,e,{activity:"system-prompt"},n);return{names:{refs:l.refs,names:l.names},...p===void 0?{}:{boot:{content:p.content,...p.inherited===!0?{inherited:!0}:{}}},...b===void 0?{}:{system_prompt:b.content}}}s(at,"startupDelivery");async function V(t,e,n,o=!1){o||await Fe(await R(),t);const i=!n&&e==="fresh"?(await Be(t,{activity:"boot"})).projectContext:void 0,{state:r,delivery:a}=await y(async c=>{const d=await Te(c,t,async(b,Y,K)=>await Ne(c,b,Y,K));pe(d);const l=await Le(c,d),p=await j(t,l);return{state:p,delivery:await at(c,d,l,p,e,n,i)}});if(a.boot!==void 0){const c={kind:r.node.kind,mode:r.node.mode,lifecycle:r.node.lifecycle},d=r.node.persona_ack,l=d===void 0?c:{kind:d.kind??r.node.kind,mode:d.mode,lifecycle:d.lifecycle};A(l,c)||await G(t,l,c)}return{state:r,delivery:a}}s(V,"renderStartData");async function wn(t){const{state:e,delivery:n}=await V(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(wn,"renderCarriedStart");async function st(t){const e=t.params.id,n=ot(t.body),o=await w(e),i=o.review_binding?.review_id,r=i!==void 0&&!n.reviewBoundaryIds.includes(i),a=r||o.cycle_pending===!0||o.pi_session_id==null;if(a)await f(e,n.executionId);else{const{action:p}=await U(e,n);if(p!=="none")return{status:200,body:{action:p}}}const{state:c,delivery:d}=await V(e,n.bearings,r);return{status:200,body:{action:"none",...a?{bind_pending:!0}:{},state:c,...d,recovery:await Ae(e),attachments:(await Ce(e)).map(({path:p,sha256:b})=>({path:p,sha256:b})),structured_request:await B(e)}}}s(st,"handleCycleStart");async function $(t,e){return e.live!==null||await be(t)||await C(t)}s($,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await $(t,e)&&(await fe(await R(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function ct(t,e,n){const o=await v(t);if(o===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw E(`unknown node: ${t}`,{received:t})}if(await te(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ee(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(o.status==="active"||o.status==="idle")&&o.intent===null&&(await _(t,"finish"),await h(t),await g(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"}),o.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await ke(t))?.retry.disposition==="fatal"&&await B(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||o.status==="done")return await h(t),await g(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(o.intent==="refresh")return await h(t),{directive:H(e),closePane:!1};const r=await _e(t,i);if(await h(t),r.action==="reprompt")return{directive:{action:"reprompt",prompt:r.message},closePane:!1};if(r.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const a=await $(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:r.reason!=="awaiting"&&r.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:a?{directive:{action:"stay_dormant"},closePane:!1}:(await _(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ct,"settleBroker");async function dt(t){const e=t.params.id,n=qe(t.body);await f(e,n.expected_execution_id);const o=await w(e);if(o.intent!=="refresh")throw new Xe(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),r=Ve(o);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&He(i.launchJson,await $e(e,r,o.cwd))?{status:200,body:await lt(e,o,i.executionId,r.env)}:{status:200,body:{action:"restart"}}}s(dt,"handleCycle");async function lt(t,e,n,o){e.cycles=(e.cycles??0)+1,await me(t,n);const i=await Ge(e,n),r=await Je(e,i);await Ye(t),await Ke(t,e,!1),await ze(t),await h(t,{preserveEpisode:!0}),await I(t,new Date().toISOString()),await(await R()).prepare("UPDATE nodes SET cycles = ?, cycle_pending = 1, intent = NULL WHERE node_id = ?").run(e.cycles,t);const a={};for(const c of We)o[c]!==void 0&&(a[c]=o[c]);return a.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:r,origin:Qe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:a,...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=m(t.body,"broker idle");return await f(e,n.expected_execution_id),await re(n.expected_execution_id),{status:204}}s(ut,"handleIdle");async function pt(t){const e=t.params.id,n=Ze(t.body);await f(e,n.expected_execution_id);const o=await F(e),{directive:i,closePane:r}=await y(async()=>await ct(e,n,await T(o)));return r&&await N(e),i.action!=="reprompt"&&xe(e).catch(a=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:a})),{status:200,body:i}}s(pt,"handleSettle");async function ft(t){const e=t.params.id,n=Ie(t.body);await f(e,n.expected_execution_id);const o=await F(e),i=await y(async()=>{const r=await Se(e);if(r===void 0)return{action:"stay_dormant"};const a=await w(e);return await Re(e,a,r,await T(o))?(await h(e),await _(e,"park"),await g(e,{pane:null,tmux_session:null,window:null}),L({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...de(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 f(e,m(t.body,"broker park-activity").expected_execution_id),{status:200,body:await y(async()=>({activity:await Pe(e)?"recorded":"none"}))}}s(mt,"handleParkActivity");async function wt(t){const e=t.params.id,n=et(t.body);return await f(e,n.expected_execution_id),await ie(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 f(e,n.expected_execution_id),{status:200,body:{modelOverride:(await y(async()=>await ge(await w(e),n.spec,n.intent,n.userSelected))).model_override}}}s(yt,"handleModelCommit");let J=!0;function yn(t){J=t}s(yn,"setRequestsStartRunObservers");async function ht(t){const e=t.params.id,n=await w(e);return n.run_id&&J&&await De(e,n.run_id),{status:200,body:await j(e)}}s(ht,"handleExtensionState");async function bt(t){const e=t.params.id,n=nt(t.body);return await f(e,n.expected_execution_id),{status:200,body:await y(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const r=await w(e);if(n.kind==="initial"){if((r.description??"").trim()!=="")return{applied:!1};const d=await x(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 a=n.expected;if(r.name!==a.name||(r.description??"")!==a.description||(r.title??"")!==a.title||(r.icon??"")!==a.icon||r.kind!==a.kind)return{applied:!1};const c=await x(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 f(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(_t,"handlePersonaAck");async function G(t,e,n){return await y(async o=>{await o.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await w(t),r={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},a=i.persona_ack,c=a===void 0?r:{kind:a.kind??i.kind,mode:a.mode,lifecycle:a.lifecycle};return!A(r,n)||!A(c,e)?!1:(await x(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const hn=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{hn as brokerOperationRoutes,k as extensionNode,wn as renderCarriedStart,V as renderStartData,yn as setRequestsStartRunObservers};
@@ -1 +1 @@
1
- var k=Object.defineProperty;var d=(e,n)=>k(e,"name",{value:n,configurable:!0});import{ApiError as r}from"../../../api/errors.js";import{dirname as N}from"node:path";import{openDb as q,withCanvasWrite as h}from"../../../core/canvas/db.js";import{readerForNode as p,warmNodeDirs as b,warmNodeRepos as A}from"../../../core/graph/reader.js";import{checkoutsForCwd as y}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as D,deliver as R,hypotheticalFrom as C,hypotheticalReader as O,inspect as w}from"../../../core/substrate/delivery/deliver.js";import{actsAsPerson as S,mayOnNode as P}from"../router.js";import{requireCurrentExecution as T}from"./broker-recovery.js";const E=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...D];function g(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","delivery requires a JSON body");const n=e;if(!E.includes(n.activity))throw new r(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new r(400,"usage","delivery subject must be a string");return n}d(g,"parse");async function v(e,n,i){const t=e.principal;if(t.class==="person"&&t.sub!==void 0){if(i!==void 0)throw new r(403,"permission_error","a hypothetical delivery dry run is not available to a person bearer; name a node you can read");if(n===void 0||!await P(t,"read",n))throw new r(404,"not_found","node not found");return}F(e)}d(v,"requireDryRunCaller");function F(e){if(!S(e.principal)&&e.principal.class!=="broker")throw new r(403,"permission_error","a delivery dry run is available to a person or a node only")}d(F,"requirePerson");function W(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new r(400,"usage","hypothetical must be an object");const n=d((o,s)=>{if(o!==void 0){if(typeof o!="string"||o==="")throw new r(400,"usage",`hypothetical.${s} must be a non-empty string`);return o}},"str"),i=n(e.cwd,"cwd");if(i!==void 0&&!i.startsWith("/"))throw new r(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new r(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new r(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new r(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new r(400,"usage","hypothetical.depth must be a non-negative integer");const t={};i!==void 0&&(t.cwd=i),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const u=n(e.grantee,"grantee");u!==void 0&&(t.grantee=u);const a=n(e.kind,"kind");return a!==void 0&&(t.kind=a),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}d(W,"hypotheticalOf");async function m(e,n,i){const t=await q();e!==void 0&&await A(t,e),n&&await b(t,e,[n]),i!==void 0&&i.startsWith("/")&&await b(t,e,[N(i)])}d(m,"warmDeliveryCwds");async function I(e){const n=g(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new r(400,"usage","node must be a node id");await v(e,n.node,n.hypothetical);const i={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}};await m(n.node,n.hypothetical?.cwd,n.activity==="file-read"?n.subject:void 0);const{result:t,plan:u}=await h(async a=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new r(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return await w(a,await p(a,n.node,async(l,j,_)=>await y(a,l,j,_)),i,n.subject_override)}const o=W(n.hypothetical),s=n.node!==void 0?await C(n.node,o):{...o,cwd:o.cwd??""};if(s.cwd==="")throw new r(400,"usage","a hypothetical node needs a cwd");const{reader:c,subject:f}=await O(a,s);return await w(a,c,i,n.subject_override,f)},{rollback:!0});return{status:200,body:{...t,plan:u}}}d(I,"handleDryRun");async function Y(e){const n=e.params.id,i=g(e.body),t={activity:i.activity,...i.subject!==void 0?{subject:i.subject}:{},...i.inherited===!0?{inherited:!0}:{}};if(i.dry_run===!0){await v(e,n,void 0),await m(n,void 0,i.activity==="file-read"?i.subject:void 0);const{result:a,plan:o}=await h(async s=>await w(s,await p(s,n,async(c,f,l)=>await y(s,c,f,l)),t,i.subject_override),{rollback:!0});return{status:200,body:{...a,plan:o}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new r(403,"permission_error","delivery is performed by the node's own broker");return await T(n,i.expected_execution_id),await m(n,void 0,i.activity==="file-read"?i.subject:void 0),{status:200,body:await h(async a=>await R(a,await p(a,n,async(o,s,c)=>await y(a,o,s,c)),t))}}d(Y,"handleDelivery");const H=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:Y},{method:"POST",pattern:"/v1/delivery/dry-run",handler:I}];export{H as deliveryRoutes};
1
+ var q=Object.defineProperty;var s=(e,n)=>q(e,"name",{value:n,configurable:!0});import{ApiError as a}from"../../../api/errors.js";import{dirname as A}from"node:path";import{openDb as C,withCanvasWrite as y}from"../../../core/canvas/db.js";import{readerForNode as w,warmNodeDirs as j,warmNodeRepos as D}from"../../../core/graph/reader.js";import{checkoutsForCwd as m}from"../../../core/graph/repo-sync/repos.js";import{DRY_RUN_ONLY as R,deliver as O,hypotheticalFrom as P,hypotheticalReader as S,inspect as b,withProjectContext as g}from"../../../core/substrate/delivery/deliver.js";import{actsAsPerson as T,mayOnNode as E}from"../router.js";import{requireCurrentExecution as F}from"./broker-recovery.js";const W=["boot","system-prompt","compact","persona","file-read","command","pre-command","slash-command","names",...R];function _(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new a(400,"usage","delivery requires a JSON body");const n=e;if(!W.includes(n.activity))throw new a(400,"usage",`invalid delivery activity: ${String(n.activity)}`);if(n.subject!==void 0&&typeof n.subject!="string")throw new a(400,"usage","delivery subject must be a string");return n}s(_,"parse");async function k(e,n,i){const t=e.principal;if(t.class==="person"&&t.sub!==void 0){if(i!==void 0)throw new a(403,"permission_error","a hypothetical delivery dry run is not available to a person bearer; name a node you can read");if(n===void 0||!await E(t,"read",n))throw new a(404,"not_found","node not found");return}I(e)}s(k,"requireDryRunCaller");function I(e){if(!T(e.principal)&&e.principal.class!=="broker")throw new a(403,"permission_error","a delivery dry run is available to a person or a node only")}s(I,"requirePerson");function Y(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new a(400,"usage","hypothetical must be an object");const n=s((r,o)=>{if(r!==void 0){if(typeof r!="string"||r==="")throw new a(400,"usage",`hypothetical.${o} must be a non-empty string`);return r}},"str"),i=n(e.cwd,"cwd");if(i!==void 0&&!i.startsWith("/"))throw new a(400,"usage","hypothetical.cwd must be an absolute path");if(e.mode!==void 0&&e.mode!=="base"&&e.mode!=="orchestrator")throw new a(400,"usage","hypothetical.mode must be base or orchestrator");if(e.lifecycle!==void 0&&e.lifecycle!=="terminal"&&e.lifecycle!=="resident")throw new a(400,"usage","hypothetical.lifecycle must be terminal or resident");if(e.has_manager!==void 0&&typeof e.has_manager!="boolean")throw new a(400,"usage","hypothetical.has_manager must be a boolean");if(e.depth!==void 0&&(!Number.isInteger(e.depth)||e.depth<0))throw new a(400,"usage","hypothetical.depth must be a non-negative integer");const t={};i!==void 0&&(t.cwd=i),e.profile!==void 0&&(t.profile=e.profile===null?null:n(e.profile,"profile"));const u=n(e.grantee,"grantee");u!==void 0&&(t.grantee=u);const f=n(e.kind,"kind");return f!==void 0&&(t.kind=f),e.mode!==void 0&&(t.mode=e.mode),e.lifecycle!==void 0&&(t.lifecycle=e.lifecycle),e.has_manager!==void 0&&(t.hasManager=e.has_manager),e.depth!==void 0&&(t.depth=e.depth),t}s(Y,"hypotheticalOf");async function v(e,n,i){const t=await C();e!==void 0&&await D(t,e),n&&await j(t,e,[n]),i!==void 0&&i.startsWith("/")&&await j(t,e,[A(i)])}s(v,"warmDeliveryCwds");async function $(e){const n=_(e.body);if(n.node!==void 0&&typeof n.node!="string")throw new a(400,"usage","node must be a node id");await k(e,n.node,n.hypothetical);const i={activity:n.activity,...n.subject!==void 0?{subject:n.subject}:{}};await v(n.node,n.hypothetical?.cwd,n.activity==="file-read"?n.subject:void 0);const t=n.hypothetical===void 0&&n.node!==void 0?await g(n.node,i):i,{result:u,plan:f}=await y(async r=>{if(n.hypothetical===void 0){if(n.node===void 0)throw new a(400,"usage","a delivery dry run names a node, a hypothetical node, or both");return await b(r,await w(r,n.node,async(h,p,N)=>await m(r,h,p,N)),t,n.subject_override)}const o=Y(n.hypothetical),c=n.node!==void 0?await P(n.node,o):{...o,cwd:o.cwd??""};if(c.cwd==="")throw new a(400,"usage","a hypothetical node needs a cwd");const{reader:d,subject:l}=await S(r,c);return await b(r,d,t,n.subject_override,l)},{rollback:!0});return{status:200,body:{...u,plan:f}}}s($,"handleDryRun");async function J(e){const n=e.params.id,i=_(e.body),t={activity:i.activity,...i.subject!==void 0?{subject:i.subject}:{},...i.inherited===!0?{inherited:!0}:{}};if(i.dry_run===!0){await k(e,n,void 0),await v(n,void 0,i.activity==="file-read"?i.subject:void 0);const r=await g(n,t),{result:o,plan:c}=await y(async d=>await b(d,await w(d,n,async(l,h,p)=>await m(d,l,h,p)),r,i.subject_override),{rollback:!0});return{status:200,body:{...o,plan:c}}}if(e.principal.class==="broker"&&e.principal.node!==n)throw new a(403,"permission_error","delivery is performed by the node's own broker");await F(n,i.expected_execution_id),await v(n,void 0,i.activity==="file-read"?i.subject:void 0);const u=await g(n,t);return{status:200,body:await y(async r=>await O(r,await w(r,n,async(o,c,d)=>await m(r,o,c,d)),u))}}s(J,"handleDelivery");const Q=[{method:"POST",pattern:"/v1/nodes/:id/delivery",handler:J},{method:"POST",pattern:"/v1/delivery/dry-run",handler:$}];export{Q as deliveryRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.717",
3
+ "version": "0.3.719",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -158,8 +158,8 @@
158
158
  },
159
159
  "license": "UNLICENSED",
160
160
  "dependencies": {
161
- "@north-light/identity": "0.3.717",
162
- "@north-light/plugin": "0.3.717",
161
+ "@north-light/identity": "0.3.719",
162
+ "@north-light/plugin": "0.3.719",
163
163
  "@earendil-works/chord": "1.5.2",
164
164
  "@earendil-works/pi-agent-core": "1.5.2",
165
165
  "@earendil-works/pi-ai": "1.5.2",
@@ -50,7 +50,11 @@ export function socketFetch(socketPath) {
50
50
  if (payload !== undefined)
51
51
  headers['content-length'] = String(Buffer.byteLength(payload));
52
52
  return new Promise((resolvePromise, reject) => {
53
- const req = httpRequest({ socketPath, path: url.pathname + url.search, method, headers }, (res) => {
53
+ // `agent: false` = a private connection per request. The global agent pools sockets, and crtrd closes an idle one at its
54
+ // `keepAliveTimeout` without reading what is already written to it, so a POST landing on a socket the daemon is closing
55
+ // resets (ECONNRESET) and, being a mutation, is never replayed: `daemon_request_interrupted`. A fresh unix-socket connect
56
+ // costs microseconds; no pooled socket means no window. Every client of api.sock must do the same.
57
+ const req = httpRequest({ socketPath, path: url.pathname + url.search, method, headers, agent: false }, (res) => {
54
58
  const body = new ReadableStream({
55
59
  start(controller) {
56
60
  res.on('data', (chunk) => controller.enqueue(new Uint8Array(chunk)));
@@ -398,19 +398,24 @@ export async function dropLocalGrantMirror(db) {
398
398
  export async function backfillComputedRev() {
399
399
  return await withCanvasWrite(async (db) => Number((await db.prepare('UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL').run()).changes));
400
400
  }
401
- /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. */
401
+ /** The `teams` a grant sync answer carried; absent (an unjoined install, an older directory) reads as none. Team
402
+ * membership is advisory next to the grants the same answer carries, so an entry that is not a directory team
403
+ * (`team:<id>`, e.g. a canvas group row echoed back) is dropped rather than failing the sync. */
402
404
  export function teamsOf(value) {
403
405
  if (value === undefined)
404
406
  return [];
405
407
  if (!Array.isArray(value))
406
408
  throw new TypeError('invalid grant sync response');
407
- return value.map((entry) => {
409
+ const teams = [];
410
+ for (const entry of value) {
408
411
  const { team, members } = (entry ?? {});
409
- if (typeof team !== 'string' || !/^team:\S+$/.test(team) || !Array.isArray(members) ||
410
- members.some((member) => typeof member !== 'string' || !/^user:[^\s*]+$/.test(member)))
412
+ if (typeof team !== 'string' || !/^team:\S+$/.test(team))
413
+ continue;
414
+ if (!Array.isArray(members) || members.some((member) => typeof member !== 'string' || !/^user:[^\s*]+$/.test(member)))
411
415
  throw new TypeError('invalid grant sync response');
412
- return { team, members };
413
- });
416
+ teams.push({ team, members });
417
+ }
418
+ return teams;
414
419
  }
415
420
  /** Replace the mirror with `grants` and the `written_by = 'directory'` team `member` facts with `teams`, in one transaction. The
416
421
  * ledger's `grant:<id>` limit rows follow from the `grants` trigger `crtr_grant_limit` (schema delta 002). */
@@ -5,24 +5,28 @@
5
5
  // headers. `-status` is `allowed` | `allowed_warning` | `rejected`;
6
6
  // `-representative-claim` names the binding window (`five_hour`, `seven_day`,
7
7
  // `seven_day_opus`, `seven_day_sonnet`, `seven_day_overage_included`,
8
- // `overage`, …); `-reset` is the epoch second it frees up. The grammar is read
9
- // from Claude Code's client, not from published docs, so the classifier fails
10
- // safe: only a rejected response whose claim is a per-model weekly window that
11
- // matches the requested model's family is model-scoped. Anything else —
12
- // unknown claims, missing status, a claim for a different family, other
13
- // providers — cools the whole account exactly as before.
8
+ // `overage`, …); `-reset` is the epoch second it frees up; `-5h-status` and
9
+ // `-7d-status` report the account-wide windows on their own. The grammar is
10
+ // read from Claude Code's client, not from published docs, so the classifier
11
+ // fails safe. A rejected response is model-scoped when its claim is a known
12
+ // per-model weekly window matching the requested model's family, or when its
13
+ // claim is not a known account-wide window and the response itself reports the
14
+ // account-wide weekly window as not rejected (a per-model window such as the
15
+ // Fable weekly cap, whatever its claim is called). Anything else — missing
16
+ // status, no account-window evidence, a known window for a different family,
17
+ // models with no family, other providers — cools the whole account.
14
18
  const MODEL_CLAIMS = { seven_day_opus: 'opus', seven_day_sonnet: 'sonnet' };
19
+ /** Claims that name an account-wide window: never model-scoped, whatever the per-window statuses say. */
20
+ const ACCOUNT_CLAIMS = new Set(['five_hour', 'seven_day', 'seven_day_overage_included', 'overage']);
21
+ const FAMILIES = ['opus', 'sonnet', 'haiku', 'fable', 'mythos'];
15
22
  const MAX_HEADERS = 48;
16
23
  const MAX_VALUE = 256;
17
24
  /** The cooldown family a model id belongs to, or undefined when only account-wide cooldowns apply to it. */
18
25
  export function modelCooldownFamily(modelId) {
19
26
  if (!modelId)
20
27
  return undefined;
21
- if (/opus/i.test(modelId))
22
- return 'opus';
23
- if (/sonnet/i.test(modelId))
24
- return 'sonnet';
25
- return undefined;
28
+ const id = modelId.toLowerCase();
29
+ return FAMILIES.find((family) => id.includes(family));
26
30
  }
27
31
  function entries(headers) {
28
32
  if (!headers)
@@ -56,7 +60,13 @@ export function classifyRateLimit(headers, modelId, now = Date.now()) {
56
60
  const resetAt = rejected && Number.isFinite(resetSeconds) && resetSeconds > 0 && resetSeconds * 1000 > now ? resetSeconds * 1000 : undefined;
57
61
  const claimed = claim === undefined ? undefined : MODEL_CLAIMS[claim];
58
62
  const family = modelCooldownFamily(modelId);
59
- const scope = rejected && claimed !== undefined && claimed === family ? { kind: 'model', family: claimed } : { kind: 'account' };
63
+ // The response reports the account-wide weekly window and it is not what refused the call (the five-hour window, when reported, neither).
64
+ const weekly = recorded['anthropic-ratelimit-unified-7d-status']?.trim();
65
+ const fiveHour = recorded['anthropic-ratelimit-unified-5h-status']?.trim();
66
+ const accountWindowsOpen = weekly !== undefined && weekly !== 'rejected' && fiveHour !== 'rejected';
67
+ const unknownWindow = claim !== undefined && claimed === undefined && !ACCOUNT_CLAIMS.has(claim);
68
+ const scopedFamily = claimed !== undefined ? (claimed === family ? family : undefined) : unknownWindow && accountWindowsOpen ? family : undefined;
69
+ const scope = rejected && scopedFamily !== undefined ? { kind: 'model', family: scopedFamily } : { kind: 'account' };
60
70
  return { scope, ...(claim !== undefined ? { claim } : {}), ...(resetAt !== undefined ? { resetAt } : {}), headers: recorded };
61
71
  }
62
72
  export function describeRateLimitScope(scope) {
@@ -160,7 +160,7 @@ function managedWorktreeNote(node) {
160
160
  * AGENTS.md/CLAUDE.md injection stays suppressed (`noContextFiles` in
161
161
  * broker.ts); `crtr sys sync project-guidance` imports that guidance into
162
162
  * documents owned by the directory's repo (its `<repo>/index` is the workspace front door). */
163
- async function bearingsShell(nodeId, knowledge, workspaceContext) {
163
+ async function bearingsShell(nodeId, knowledge, workspaceContext, projectCtx) {
164
164
  const node = await getNode(nodeId);
165
165
  const execution = await latestExecutionForNode(nodeId);
166
166
  const bearings = ['<crtr-bearings>', await buildIdentityAssertion(nodeId, node)];
@@ -187,16 +187,22 @@ async function bearingsShell(nodeId, knowledge, workspaceContext) {
187
187
  // nested card inside the outer envelope. Never routed through the visible
188
188
  // chat/digest path. '' when nothing was ever set.
189
189
  const situational = await situationalContextEnvelope(nodeId) ?? '';
190
- const projectCtx = node?.cwd !== undefined && execution?.runner === 'process' ? buildProjectContextBlock(node.cwd) : ''; // reads this host
191
190
  return [bearings.join('\n'), knowledge, workspaceContext, situational, projectCtx]
192
191
  .filter((s) => s !== '')
193
192
  .join('\n');
194
193
  }
194
+ /** The `<project_context>` snapshot of the node's cwd: it spawns git and tmux and reads this host's disk, so a caller builds it BEFORE
195
+ * opening the delivery transaction and passes it in as `projectContext`; '' when the node's engine does not run on this host. */
196
+ export async function projectContextForNode(nodeId) {
197
+ const node = await getNode(nodeId);
198
+ const execution = await latestExecutionForNode(nodeId);
199
+ return node?.cwd !== undefined && execution?.runner === 'process' ? buildProjectContextBlock(node.cwd) : '';
200
+ }
195
201
  /** The bearings on the row-backed delivery engine: the knowledge catalog and
196
202
  * the workspace-open documents render against `ctx`'s ledger; `delivered`
197
203
  * lists what they delivered, for the caller to record. */
198
- export async function buildContextBearings(nodeId, ctx) {
204
+ export async function buildContextBearings(nodeId, ctx, projectContext) {
199
205
  const knowledge = await renderKnowledge(ctx);
200
206
  const workspace = await renderWorkspaceOpen(ctx);
201
- return { content: await bearingsShell(nodeId, knowledge.content, workspace.content), delivered: [...knowledge.delivered, ...workspace.delivered] };
207
+ return { content: await bearingsShell(nodeId, knowledge.content, workspace.content, projectContext), delivered: [...knowledge.delivered, ...workspace.delivered] };
202
208
  }
@@ -21,7 +21,7 @@ import { getNode } from '../canvas/index.js';
21
21
  import { openDb, withCanvasWrite } from '../canvas/db.js';
22
22
  import { readerForNode, warmNodeRepos } from '../graph/reader.js';
23
23
  import { checkoutsForCwd } from '../graph/repo-sync/repos.js';
24
- import { deliver } from '../substrate/delivery/deliver.js';
24
+ import { deliver, withProjectContext } from '../substrate/delivery/deliver.js';
25
25
  import { oneShotControllerRequest } from './broker-request.js';
26
26
  import { isBrokerLive } from './model-swap.js';
27
27
  import { CONTEXT_INTRO_CUSTOM_TYPE } from './bearings.js';
@@ -75,7 +75,8 @@ export async function deliverBearingsLive(nodeId) {
75
75
  // The boot delivery clears and rewrites the ledger and freezes preferences in
76
76
  // one transaction before Pi receives the bearings.
77
77
  await warmNodeRepos(await openDb(), nodeId);
78
- const { content } = await withCanvasWrite(async (db) => await deliver(db, await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access)), { activity: 'boot' }));
78
+ const request = await withProjectContext(nodeId, { activity: 'boot' });
79
+ const { content } = await withCanvasWrite(async (db) => await deliver(db, await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access)), request));
79
80
  await deliverCustomMessageLive(nodeId, {
80
81
  customType: CONTEXT_INTRO_CUSTOM_TYPE,
81
82
  content: formatCard('bearings', {}, content),
@@ -24,13 +24,18 @@ import { appForNode } from '../../canvas/node-agent-paths.js';
24
24
  import { interpolateNodePaths } from '../../canvas/paths.js';
25
25
  import { readableProjectForScopes } from '../../spaces/permissions.js';
26
26
  import { ApiError } from '../../../api/errors.js';
27
- import { buildContextBearings } from '../../runtime/bearings.js';
27
+ import { buildContextBearings, projectContextForNode } from '../../runtime/bearings.js';
28
28
  import { deliveryDocOf, listingCorpora, loadCorpus, nodeSubject, primeBodies, profileIdOfObject, viewOwners } from './corpus.js';
29
29
  import { listingPrefixes } from './listings.js';
30
30
  import { planDelivery } from './plan.js';
31
31
  import { renderEvent, renderExplicitRead } from './render-event.js';
32
32
  import { renderConfigDelta, renderKnowledge, renderPreferences, renderWorkspaceOpen } from './render-boot.js';
33
33
  import { mapAsync } from '../../async-array.js';
34
+ /** `req` with what a `boot` of node `nodeId` reads from this host's disk and processes (git, tmux, a directory listing), computed now so the
35
+ * delivery transaction that follows holds its pooled connection for db statements only. Call before `withCanvasWrite`. */
36
+ export async function withProjectContext(nodeId, req) {
37
+ return req.activity === 'boot' && req.inherited !== true ? { ...req, projectContext: await projectContextForNode(nodeId) } : req;
38
+ }
34
39
  function nodeOf(reader) {
35
40
  if (reader.class !== 'node')
36
41
  throw new Error(`delivery needs a node reader, got ${reader.class}`);
@@ -173,7 +178,7 @@ async function render(ctx, req) {
173
178
  ledger.preferenceSnapshot = null;
174
179
  return { result: { content: '', inherited: true }, delivered: [] };
175
180
  }
176
- const bearings = isHypothetical(reader) ? await hypotheticalBearings(ctx) : await buildContextBearings(reader.node.id, ctx);
181
+ const bearings = isHypothetical(reader) ? await hypotheticalBearings(ctx) : await buildContextBearings(reader.node.id, ctx, requireProjectContext(req));
177
182
  const prefs = await renderPreferences({ ...ctx, channel: 'system' });
178
183
  freezePreferences(ledger, prefs.content);
179
184
  return { result: { content: bearings.content }, delivered: [...bearings.delivered, ...prefs.delivered] };
@@ -235,6 +240,11 @@ async function render(ctx, req) {
235
240
  throw new ApiError(400, 'usage', `unknown delivery activity ${String(req.activity)}`);
236
241
  }
237
242
  }
243
+ function requireProjectContext(req) {
244
+ if (req.projectContext === undefined)
245
+ throw new Error('a node boot delivery needs its project context built before the transaction: pass the request through withProjectContext');
246
+ return req.projectContext;
247
+ }
238
248
  /** A hypothetical node has no bearings of its own: its boot content is the
239
249
  * knowledge catalog and the workspace-open documents. */
240
250
  async function hypotheticalBearings(ctx) {
@@ -33,7 +33,7 @@ import { recoveryState, requireCurrentExecution } from './broker-recovery.js';
33
33
  import { runAttachments } from './node-records.js';
34
34
  import { readerForNode, warmNodeRepos } from '../../../core/graph/reader.js';
35
35
  import { checkoutsForCwd } from '../../../core/graph/repo-sync/repos.js';
36
- import { deliver } from '../../../core/substrate/delivery/deliver.js';
36
+ import { deliver, withProjectContext } from '../../../core/substrate/delivery/deliver.js';
37
37
  import { nodeSubject } from '../../../core/substrate/delivery/corpus.js';
38
38
  import { ensureRunObserver } from '../../runs/observer.js';
39
39
  import { parseNodeTelemetryRecord, writeNodeTelemetryRecord } from './telemetry-record.js';
@@ -296,11 +296,11 @@ function parseCycleStartBody(body) {
296
296
  /** The names, bearings and first system-prompt block a cycle opens with, delivered in one write the way the
297
297
  * delivery route would deliver each. A warm spare is owed no bearings and no system prompt: its claim delivers them.
298
298
  * `namesOnly` gives a node the same treatment while its bind is undecided. */
299
- async function startupDelivery(db, reader, subject, state, bearings, namesOnly) {
299
+ async function startupDelivery(db, reader, subject, state, bearings, namesOnly, projectContext) {
300
300
  const warm = state.warm_spare || namesOnly;
301
301
  const bootOwed = !warm && bearings !== 'present';
302
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;
303
+ const boot = bootOwed ? await deliver(db, reader, { activity: 'boot', ...(bearings === 'inherited' ? { inherited: true } : {}), ...(projectContext === undefined ? {} : { projectContext }) }, subject) : undefined;
304
304
  const system = warm ? undefined : await deliver(db, reader, { activity: 'system-prompt' }, subject);
305
305
  return {
306
306
  names: { refs: names.refs, names: names.names },
@@ -314,12 +314,14 @@ async function startupDelivery(db, reader, subject, state, bearings, namesOnly)
314
314
  export async function renderStartData(nodeId, bearings, namesOnly, warmed = false) {
315
315
  if (!warmed)
316
316
  await warmNodeRepos(await openDb(), nodeId);
317
+ // A fresh boot's project-context snapshot (git, tmux, a directory listing) is built before the transaction, so it holds its connection for db statements only.
318
+ const projectContext = !namesOnly && bearings === 'fresh' ? (await withProjectContext(nodeId, { activity: 'boot' })).projectContext : undefined;
317
319
  const { state, delivery } = await withCanvasWrite(async (db) => {
318
320
  const reader = await readerForNode(db, nodeId, async (cwd, person, access) => await checkoutsForCwd(db, cwd, person, access));
319
321
  shareCorpusReads(reader);
320
322
  const subject = await nodeSubject(db, reader);
321
323
  const state = await extensionState(nodeId, subject);
322
- return { state, delivery: await startupDelivery(db, reader, subject, state, bearings, namesOnly) };
324
+ return { state, delivery: await startupDelivery(db, reader, subject, state, bearings, namesOnly, projectContext) };
323
325
  });
324
326
  // The bearings just rendered are the persona baseline; the broker does not acknowledge it separately.
325
327
  if (delivery.boot !== undefined) {
@@ -589,15 +591,14 @@ async function handleTelemetry(ctx) {
589
591
  const nodeId = ctx.params['id'];
590
592
  const request = parseTelemetryBody(ctx.body);
591
593
  await requireCurrentExecution(nodeId, request.expected_execution_id);
592
- await withCanvasWrite(async () => {
593
- await updateNodeTelemetry(nodeId, {
594
- tokensIn: request.tokens_in,
595
- contextTokens: request.context_tokens,
596
- lastActivity: request.last_activity,
597
- updatedAt: request.updated_at,
598
- });
599
- writeNodeTelemetryRecord(nodeId, request);
594
+ // One statement, atomic on its own; the node-local file is filesystem work and must not hold a pooled connection.
595
+ await updateNodeTelemetry(nodeId, {
596
+ tokensIn: request.tokens_in,
597
+ contextTokens: request.context_tokens,
598
+ lastActivity: request.last_activity,
599
+ updatedAt: request.updated_at,
600
600
  });
601
+ writeNodeTelemetryRecord(nodeId, request);
601
602
  return { status: 204 };
602
603
  }
603
604
  async function handleModelCommit(ctx) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.717",
3
+ "version": "0.3.719",
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.717",
3
+ "version": "0.3.719",
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.717",
3
+ "version": "0.3.719",
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.717",
31
- "@north-light/identity": "0.3.717"
30
+ "@north-light/api": "0.3.719",
31
+ "@north-light/identity": "0.3.719"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {