@north-light/cli 0.3.674 → 0.3.676
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/session/connection.d.ts +2 -1
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/viewer.d.ts +11 -1
- package/dist/clients/attach/viewer.js +524 -524
- package/dist/commands/person-settings.d.ts +5 -0
- package/dist/commands/person-settings.js +1 -1
- package/dist/core/graph/reader.d.ts +2 -1
- package/dist/core/graph/reader.js +3 -3
- package/dist/core/graph/repo-sync/repos.d.ts +24 -3
- package/dist/core/graph/repo-sync/repos.js +4 -4
- package/dist/core/profiles/select.d.ts +3 -1
- package/dist/core/profiles/select.js +25 -25
- package/dist/core/runtime/bearings.d.ts +3 -3
- package/dist/core/runtime/bearings.js +6 -6
- package/dist/core/runtime/boot-root.d.ts +3 -3
- package/dist/core/runtime/boot-root.js +6 -4
- package/dist/core/runtime/deliver-live.js +1 -1
- package/dist/core/runtime/front-door.js +1 -1
- package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
- package/dist/core/runtime/starting-screen.d.ts +12 -0
- package/dist/core/runtime/starting-screen.js +9 -0
- package/dist/core/substrate/delivery/deliver.d.ts +1 -1
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/subject.d.ts +3 -1
- package/dist/core/substrate/subject.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/delivery.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/session/connection.js +3 -2
- package/packages/crouter-api/dist/clients/attach/viewer.js +16 -7
- package/packages/crouter-api/dist/commands/person-settings.js +10 -3
- package/packages/crouter-api/dist/core/graph/reader.js +9 -4
- package/packages/crouter-api/dist/core/graph/repo-sync/repos.js +56 -13
- package/packages/crouter-api/dist/core/profiles/select.js +17 -7
- package/packages/crouter-api/dist/core/runtime/bearings.js +11 -12
- package/packages/crouter-api/dist/core/runtime/deliver-live.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +13 -5
- package/packages/crouter-api/dist/core/substrate/delivery/deliver.js +3 -3
- package/packages/crouter-api/dist/core/substrate/subject.js +4 -4
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +6 -4
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -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
|
|
2
|
-
`),delivered:[...e.delivered,...n.delivered]}}l(je,"hypotheticalBearings");async function
|
|
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 k,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 ae}from"../subject-fields.js";import{spineDepth as re}from"../subject.js";import{appForNode as ie}from"../../canvas/node-agent-paths.js";import{interpolateNodePaths as se}from"../../canvas/paths.js";import{readableProjectForScopes as N}from"../../spaces/permissions.js";import{ApiError as m}from"../../../api/errors.js";import{buildContextBearings as ce}from"../../runtime/bearings.js";import{deliveryDocOf as O,listingCorpora as de,loadCorpus as w,nodeSubject as R,primeBodies as le,viewOwners as pe}from"./corpus.js";import{listingPrefixes as ue}from"./listings.js";import{planDelivery as me}from"./plan.js";import{renderEvent as _,renderExplicitRead as S}from"./render-event.js";import{renderConfigDelta as fe,renderKnowledge as we,renderPreferences as E,renderWorkspaceOpen as D}from"./render-boot.js";import{mapAsync as C}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 I="hypothetical";function v(t){return t.node.id===I}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 ye(t,e,n,o=async(a,c)=>await h(t,a,c)){const a=f(e).node,c=new Set,r=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:a,object:d.object,start:"deliver",opts:{readHeadsKey:d.headsKey}}),s.push({name:d.name,scope:d.ownerHandle,at:r,type:"loaded"}));await U(t,i),await J(t,i.map(d=>({event:"read",object:d.object,actor:a,attrs:{}})),o),v(f(e))||await q(t,a.id,s)}l(ye,"recordContentDelivery");async function A(t,e,n){if(await b(t,e,n))return e;const o=(await h(t,P(n))).filter(a=>!e.repos.some(c=>c.id===a.repo.id));return o.length===0?e:{...e,repos:[...e.repos,...o.map(a=>a.repo)],checkouts:[...e.checkouts,...o]}}l(A,"fileReadReader");async function b(t,e,n){const o=await g(t,e);return o==="app:terminal"&&T()&&e.profile!=null&&await H(e.profile.id)!==null&&!N(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:a,repo:c}of e.checkouts)n.startsWith(a.endsWith("/")?a:`${a}/`)&&!o.has(c.id)&&o.set(c.id,a);return{absoluteFile:n,readFrontmatter:{},repoRoots:o,remotePath:!0}}l(F,"fileReadPayload");async function he(t,e,n){const o=await g(t,e);if(!(n.startsWith("/")&&(process.platform!=="linux"&&o==="app:terminal"||await b(t,e,n)||N(n,o,e.scopes??[],null))))throw new m(403,"scope_missing","read file is outside the run mounts")}l(he,"assertReadableFile");async function ve(t){const e=f(t.reader),n=e.node,o=await g(t.db,e),a=await w(t.db,t.reader,["slash-command"]);await le(t.db,a);const c=await C(a,async r=>{const s=await r.body();return{name:r.displayName,command_name:r.displayName,description:r.preview,canonical_body:s,execution_body:se(s,n.id,o)}});return{docs:a,commands:c}}l(ve,"slashCommands");function ge(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(ge,"scopeOf");async function be(t,e){const n=[],o=new Set,a=await pe(t,e),c=await de(t,e,a);for(const r of a){const s=c.get(r.id);for(const i of s){n.push({name:i.displayName,kind:i.kind,scope:ge(i),shortForm:i.preview,gatewayVisible:!i.shipped}),o.add(i.displayName);const d=i.displayName===i.name?"":`${i.ownerHandle}/`;for(const p of ue(s,i.name))o.add(`${d}${p}`)}}return{refs:n,names:[...o]}}l(be,"composerNames");async function L(t,e){const n=f(t.reader),{db:o,ledger:a}=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 a.objects)if(d.transcript===void 0)a.objects.delete(i);else{const{system:p,...u}=d;a.objects.set(i,u)}for(const[i,d]of a.listed)d.transcript===void 0?a.listed.delete(i):a.listed.set(i,{transcript:d.transcript});return a.preferenceSnapshot=null,{result:{content:"",inherited:!0},delivered:[]}}const r=v(n)?await je(t):await ce(n.node.id,t),s=await E({...t,channel:"system"});return k(a,s.content),{result:{content:r.content},delivered:[...r.delivered,...s.delivered]}}case"system-prompt":{if(a.preferenceSnapshot!==null)return{result:{content:a.preferenceSnapshot},delivered:[]};const r=await E({...t,channel:"system"});return{result:{content:k(a,r.content)},delivered:r.delivered}}case"compact":{for(const r of await w(o,n,["pre-command"]))x(a,r.object.id);return{result:{content:""},delivered:[]}}case"persona":{const r=await fe(t);return{result:{content:r.content},delivered:r.delivered}}case"file-read":{const r=c();await he(o,n,r);const s=await A(o,n,r),i={...t,reader:s},d=await _(i,"file-read",await F(o,n,r),await w(o,s,["file-read"]));return{result:{content:d.content},delivered:d.delivered}}case"command":case"pre-command":{const r=await _(t,e.activity,{command:c()});return{result:{content:r.content},delivered:r.delivered}}case"slash-command":{const{docs:r,commands:s}=await ve(t);if(e.subject===void 0||e.subject==="")return{result:{content:"",commands:s},delivered:[]};const i=r.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=r[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 r=await D(t);return{result:{content:r.content},delivered:r.delivered}}case"document-read":{const r=await M(o,n,c()),s=await S(t,await O(o,n,r),!0);return{result:{content:s.attachments},delivered:s.delivered}}case"names":return{result:{content:"",...await be(o,n)},delivered:[]};default:throw new m(400,"usage",`unknown delivery activity ${String(e.activity)}`)}}l(L,"render");async function je(t){const e=await we(t),n=await D(t);return{content:[e.content,n.content].filter(o=>o!=="").join(`
|
|
2
|
+
`),delivered:[...e.delivered,...n.delivered]}}l(je,"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 et(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 a=f(e).node;n.activity==="boot"&&n.inherited!==!0&&await W(t,a.id);const c=await Y(t,a.id),r={db:t,reader:e,subject:o??await R(t,e),ledger:c,channel:"transcript"},{result:s,delivered:i}=await L(r,n);return await ye(t,e,i),await B(t,c),s}l(et,"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 tt(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 re(t)}}l(tt,"hypotheticalFrom");function Oe(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(Oe,"resolveProfileId");async function nt(t,e){const n=await X(t,e.grantee??"app:terminal"),o=Oe(e.profile,e.cwd),a=await G(t,e.cwd,o,async(p,u,y)=>await h(t,p,u,y),K(t)),{repos:c}=a,r=e.mode??"base",i={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,...a,profile:o===null?null:await V(t,o,n)},d={kind:e.kind??"general",mode:r,lifecycle:e.lifecycle??(r==="orchestrator"?"resident":"terminal"),hasManager:e.hasManager??!0,cwd:e.cwd,scope:ae(e.cwd),orchestration:{depth:e.depth??0},profile:oe(o),app:e.grantee??"app:terminal",scopes:ne(null),repo:[...c,...a.projectRepos].map(p=>p.name)};return{reader:i,subject:d}}l(nt,"hypotheticalReader");async function ot(t,e,n,o,a){const r={node:f(e).node.id,preferenceSnapshot:null,objects:new Map,listed:new Map},s={...a??await R(t,e),...o},i={db:t,reader:e,subject:s,ledger:r,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 O(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 me(t,s,j,await w(t,j,[p]),p,y)}return{result:d,plan:u}}l(ot,"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
|
|
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
|
|
6
|
+
GROUP BY o.id ORDER BY o.seq`).all(e.id,n,e.id);return await C(o,async({to_seq:a,authors:c,...r})=>{const s=await t.prepare("SELECT MAX(number) AS seq FROM revisions WHERE document = ? AND created_at <= ?").get(r.id,n);return{doc:r,from:s.seq,to:a,authors:c===null?[]:c.split(",")}})}l(at,"changedWhileDone");export{ke as DRY_RUN_ONLY,at as changedWhileDone,et as deliver,tt as hypotheticalFrom,nt as hypotheticalReader,ot as inspect,ye as recordContentDelivery};
|
|
@@ -6,7 +6,9 @@ export type { NodeConfigSubject } from './subject-fields.js';
|
|
|
6
6
|
* walking the `parent` chain (canvas-db rows) until a row with no parent (the
|
|
7
7
|
* root). The root is depth 0. Cycle-guarded (parents must not cycle, but never
|
|
8
8
|
* loop forever) — mirrors `rootOfSpine` in runtime/placement.ts. */
|
|
9
|
-
export declare function spineDepth(nodeId: string
|
|
9
|
+
export declare function spineDepth(nodeId: string, own?: {
|
|
10
|
+
parent?: string | null;
|
|
11
|
+
}): Promise<number>;
|
|
10
12
|
/** Assemble the node-config subject for `nodeId` from its `NodeMeta` + the
|
|
11
13
|
* derived fields. Returns `null` when the node has no canvas-db row (an
|
|
12
14
|
* unknown id). Pure aside from the canvas-db + profile-manifest reads. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var a=(o,r)=>c(o,"name",{value:r,configurable:!0});import{getNode as s,getRow as l}from"../canvas/index.js";import{appForNode as f}from"../canvas/node-agent-paths.js";import{openDb as m}from"../canvas/db.js";import{checkoutsForCwd as u}from"../graph/repo-sync/repos.js";import{liveLookups as w,viewRepos as d}from"../graph/reader.js";import{effectiveScopes as b,scopeForCwd as h,profileNameFor as k}from"./subject-fields.js";import{effectiveScopes as L,scopeForCwd as M,profileNameFor as q}from"./subject-fields.js";async function y(o,r){let e=o;const t=new Set;let p=0;for(;!t.has(e);){t.add(e);const i=e===o&&r!==void 0?r:await l(e);if(i===null||i.parent==null)break;e=i.parent,p++}return p}a(y,"spineDepth");async function F(o,r){const e=await m(),t=await d(e,o,r,async(p,i,n)=>await u(e,p,i,n),w(e));return[...t.repos,...t.projectRepos]}a(F,"eligibleRepos");async function j(o,r){const e=await s(o);return e===null?null:{kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,hasManager:(e.parent??null)!==null,cwd:e.cwd,scope:h(e.cwd),orchestration:{depth:await y(o,e)},profile:k(e.profile_id),app:e.grantee??await f(o),scopes:b(e.scopes),repo:(r??await F(e.cwd,e.profile_id??null)).map(t=>t.name)}}a(j,"assembleNodeSubject");export{j as assembleNodeSubject,L as effectiveScopes,q as profileNameFor,M as scopeForCwd,y as spineDepth};
|
|
@@ -1 +1 @@
|
|
|
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 g,getNodes as Z,isWarmSpare as I,recordLaunch as q,recordRespawnAttempt as ee,recordSettledTurn as te,setPresence as x,subscriptionsOf as ne,updateNode as _,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{openDb as A,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as pe}from"../../../core/graph/jobs.js";import{notFound as R,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as C,releaseExecutionMail as fe}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as me}from"../../../core/runtime/kickoff.js";import{readRoadmap as we}from"../../../core/runtime/roadmap.js";import{forkSourceNode as ye}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{confirmViewer as F,probeViewer as T,tearDownNode as B}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as he}from"../viewer-presence.js";import{evaluateStop as be}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as N}from"../../../core/runtime/output-result.js";import{clearFault as y,readFault as _e,recordFault as ke}from"../../../core/canvas/recovery.js";import{updateModelRecipe as ve}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as ge}from"../../review/finish.js";import{emitEvent as L}from"../../../core/events/emit.js";import{consumePendingPark as xe,recordPendingParkActivity as Se}from"../../park-pending.js";import{shouldParkAfterSummary as Pe}from"../../park-activity.js";import{ownerOnly as Re}from"../router.js";import{situationalContextEnvelope as Oe}from"../../../core/runtime/situational-context.js";import{recoveryState as Ee,requireCurrentExecution as u}from"./broker-recovery.js";import{runAttachments as Ae}from"./node-records.js";import{readerForNode as Ce,warmNodeRepos as Fe}from"../../../core/graph/reader.js";import{checkoutsForCwd as Te}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{ensureRunObserver as Be}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Ne,writeNodeTelemetryRecord as Le}from"./telemetry-record.js";import{mapAsync as De}from"../../../core/async-array.js";import{crtrVersion as D}from"../../../shared/crtr-version.js";import{buildPiArgv as Me}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ve}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as $e,cycleCompatible as je}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Ue,drainBearings as We}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as He}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Je}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as Ge}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Ye}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Ke}from"../../../api/errors.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}s(p,"objectBody");function M(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}s(M,"parseSessionBoundBody");function ze(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}s(ze,"parseSettleBody");function Qe(t){const e=p(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}s(Qe,"parseCycleBody");function Xe(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}s(Xe,"parseParkCompleteBody");function Ze(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=Ne(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(Ze,"parseTelemetryBody");function Ie(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}s(Ie,"parseModelCommitBody");async function m(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");async function v(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(v,"extensionNode");async function V(t){const e=await m(t),n=[],r=new Set([t]);let i=e.parent??null;for(;i!==null&&i!==""&&!r.has(i);){r.add(i);const d=await g(i);if(d===null)break;n.unshift(await v(d)),i=d.parent??null}const a=await De((await Z((await ne(t)).map(d=>d.node_id))).filter(d=>d.kind!=="human").sort((d,h)=>d.status===h.status?0:d.status==="active"?-1:h.status==="active"?1:0),v),o=typeof e.fork_source_file=="string"?await ye(e.fork_source_file):null,c=await ue(t);if(c===null)throw R(`unknown node: ${t}`,{received:t});return{node:await v(e),warm_spare:await I(t),situational_card:await Oe(t),ancestors:n,children:a,fork_source:o===null?null:await v(o),subject:c,roadmap:await we(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function qe(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}s(qe,"parseGeneratedNameBody");function et(t){const e=p(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw l(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(et,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:Q(e.sessionFile);return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t);if(await oe(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 X(n);if(o!==null&&o.node_id!==t){if(le(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 se(o.node_id);if(c===null||await ce({fromNodeId:o.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 me(t),i.intent==="refresh"&&await k(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function tt(t){return{status:200,body:await $(t.params.id,M(t.body))}}s(tt,"handleSessionBound");function nt(t){const e=M(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw l("bearings must be fresh, inherited or present");return e}s(nt,"parseCycleStartBody");async function it(t,e,n,r,i=!1){const a=e.warm_spare||r,o=!a&&n!=="present";return i||await Fe(await A(),t),await f(async c=>{const d=await Ce(c,t,async(Y,K)=>await Te(c,Y,K)),h=await O(c,d,{activity:"names"}),w=o?await O(c,d,{activity:"boot",...n==="inherited"?{inherited:!0}:{}}):void 0,b=a?void 0:await O(c,d,{activity:"system-prompt"});return{names:{refs:h.refs,names:h.names},...w===void 0?{}:{boot:{content:w.content,...w.inherited===!0?{inherited:!0}:{}}},...b===void 0?{}:{system_prompt:b.content}}})}s(it,"startupDelivery");async function j(t,e,n,r=!1){const i=await V(t),a=await it(t,i,e,n,r);if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,d=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(d,o)||await G(t,d,o)}return{state:i,delivery:a}}s(j,"renderStartData");async function ln(t){const{state:e,delivery:n}=await j(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(ln,"renderCarriedStart");async function rt(t){const e=t.params.id,n=nt(t.body),r=await m(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await u(e,n.executionId);else{const{action:w}=await $(e,n);if(w!=="none")return{status:200,body:{action:w}}}const{state:c,delivery:d}=await j(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...d,recovery:await Ee(e),attachments:(await Ae(e)).map(({path:w,sha256:b})=>({path:w,sha256:b})),structured_request:await N(e)}}}s(rt,"handleCycleStart");async function U(t,e){return e.live!==null||await he(t)||await C(t)}s(U,"isHeldAwake");async function W(t,e){return(await S(t))?.runner==="blaxel"&&!await U(t,e)&&(await pe(await A(),t)).length===0}s(W,"residentBlaxelCanIdle");function H(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(H,"refreshDirective");async function ot(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await 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(r.status==="active"||r.status==="idle")&&r.intent===null&&(await k(t,"finish"),await y(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await y(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:H(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await _e(t))?.retry.disposition==="fatal"&&await N(t)===null&&await W(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await y(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await y(t),{directive:H(e),closePane:!1};const a=await be(t,i);if(await y(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await C(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await U(t,n);return(await S(t))?.runner==="blaxel"?{directive:await W(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await k(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ot,"settleBroker");async function at(t){const e=t.params.id,n=Qe(t.body);await u(e,n.expected_execution_id);const r=await m(e);if(r.intent!=="refresh")throw new Ke(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=Me(r);return n.brokerVersion===D()&&(i.release===null||i.release===D())&&je(i.launchJson,await Ve(e,a,r.cwd))?{status:200,body:await st(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(at,"handleCycle");async function st(t,e,n,r){e.cycles=(e.cycles??0)+1,await fe(t,n);const i=await We(e,n),a=await Ue(e,i);await He(t),await Je(t,e,!1),await Ge(t),await y(t,{preserveEpisode:!0}),await q(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});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:Ye({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(st,"startCycleRecord");async function ct(t){const e=t.params.id,n=p(t.body,"broker idle");return await u(e,n.expected_execution_id),await re(n.expected_execution_id),{status:204}}s(ct,"handleIdle");async function dt(t){const e=t.params.id,n=ze(t.body);await u(e,n.expected_execution_id);const r=await T(e),{directive:i,closePane:a}=await f(async()=>await ot(e,n,await F(r)));return a&&await B(e),i.action!=="reprompt"&&ge(e).catch(o=>L({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(dt,"handleSettle");async function lt(t){const e=t.params.id,n=Xe(t.body);await u(e,n.expected_execution_id);const r=await T(e),i=await f(async()=>{const a=await xe(e);if(a===void 0)return{action:"stay_dormant"};const o=await m(e);return await Pe(e,o,a,await F(r))?(await y(e),await k(e,"park"),await x(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 B(e),{status:200,body:i}}s(lt,"handleParkComplete");async function ut(t){const e=t.params.id;return await u(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await Se(e)?"recorded":"none"}))}}s(ut,"handleParkActivity");async function pt(t){const e=t.params.id,n=Ze(t.body);return await u(e,n.expected_execution_id),await f(async()=>{await ie(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),Le(e,n)}),{status:204}}s(pt,"handleTelemetry");async function ft(t){const e=t.params.id,n=Ie(t.body);return await u(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await ve(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}s(ft,"handleModelCommit");let J=!0;function un(t){J=t}s(un,"setRequestsStartRunObservers");async function mt(t){const e=t.params.id,n=await m(e);return n.run_id&&J&&await Be(e,n.run_id),{status:200,body:await V(e)}}s(mt,"handleExtensionState");async function wt(t){const e=t.params.id,n=qe(t.body);return await u(e,n.expected_execution_id),{status:200,body:await f(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await m(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const d=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(wt,"handleGeneratedName");async function yt(t){const e=t.params.id,n=et(t.body);return await u(e,n.expected_execution_id),{status:200,body:{applied:await G(e,n.from,n.to)}}}s(yt,"handlePersonaAck");async function G(t,e,n){return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(G,"applyPersonaAck");const pn=Re([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:tt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:at},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ct},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:lt},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:ft},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:yt}]);export{pn as brokerOperationRoutes,v as extensionNode,ln as renderCarriedStart,j as renderStartData,un as setRequestsStartRunObservers};
|
|
1
|
+
var X=Object.defineProperty;var s=(t,e)=>X(t,"name",{value:e,configurable:!0});import{canonicalSessionFile as Z,findNodeBySessionFile as I,getNode as g,getNodes as q,isWarmSpare as ee,recordLaunch as te,recordRespawnAttempt as ne,recordSettledTurn as ie,setPresence as x,subscriptionsOf as re,updateNode as _,updateNodeTelemetry as oe}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S,recordExecutionIdle as ae,recordExecutionPid as se}from"../../../core/canvas/executions.js";import{bindSession as ce,readLiveSession as de,transferSession as le}from"../../../core/canvas/sessions.js";import{isSafeNodeId as ue}from"../../../core/canvas/paths.js";import{isPidAlive as pe}from"../../../core/canvas/pid.js";import{editorLabel as P}from"../../../core/canvas/labels.js";import{assembleNodeSubject as fe}from"../../../core/substrate/subject.js";import{openDb as C,withCanvasWrite as f}from"../../../core/canvas/db.js";import{runningJobs as me}from"../../../core/graph/jobs.js";import{notFound as R,usage as l}from"../../../core/errors.js";import{hasUnseenWakeMail as F,releaseExecutionMail as we}from"../../../core/canvas/deliveries.js";import{clearYieldMessage as ye}from"../../../core/runtime/kickoff.js";import{readRoadmap as he}from"../../../core/runtime/roadmap.js";import{forkSourceNode as be}from"../../../core/runtime/nodes.js";import{transition as k}from"../../../core/runtime/lifecycle.js";import{confirmViewer as T,probeViewer as B,tearDownNode as N}from"../../../core/runtime/placement.js";import{hasAttachedBrokerViewers as _e}from"../viewer-presence.js";import{evaluateStop as ke}from"../../../core/runtime/stop-guard.js";import{readOutputRequest as L}from"../../../core/runtime/output-result.js";import{clearFault as h,readFault as ve,recordFault as ge}from"../../../core/canvas/recovery.js";import{updateModelRecipe as xe}from"../../../core/runtime/model-swap.js";import{completeCompanionRequestedSubmit as Se}from"../../review/finish.js";import{emitEvent as D}from"../../../core/events/emit.js";import{consumePendingPark as Pe,recordPendingParkActivity as Re}from"../../park-pending.js";import{shouldParkAfterSummary as Oe}from"../../park-activity.js";import{ownerOnly as Ee}from"../router.js";import{situationalContextEnvelope as Ae}from"../../../core/runtime/situational-context.js";import{recoveryState as Ce,requireCurrentExecution as u}from"./broker-recovery.js";import{runAttachments as Fe}from"./node-records.js";import{readerForNode as Te,warmNodeRepos as Be}from"../../../core/graph/reader.js";import{checkoutsForCwd as Ne}from"../../../core/graph/repo-sync/repos.js";import{deliver as O}from"../../../core/substrate/delivery/deliver.js";import{nodeSubject as Le}from"../../../core/substrate/delivery/corpus.js";import{ensureRunObserver as De}from"../../runs/observer.js";import{parseNodeTelemetryRecord as Me,writeNodeTelemetryRecord as je}from"./telemetry-record.js";import{mapAsync as Ve}from"../../../core/async-array.js";import{crtrVersion as M}from"../../../shared/crtr-version.js";import{buildPiArgv as $e}from"../../../core/runtime/launch.js";import{brokerLaunchJson as Ue}from"../../../core/runtime/host.js";import{CYCLE_APPLIED_ENV as We,cycleCompatible as He}from"../../../core/runtime/launch-recipe.js";import{buildReviveKickoff as Je,drainBearings as Ge}from"../../../core/runtime/kickoff.js";import{clearNodeLedger as Ye}from"../../../core/runtime/ledger.js";import{runNodeStartHooks as Ke}from"../../../core/runtime/revive.js";import{consumeDeadlineOnWake as ze}from"../../../core/feed/messages.js";import{encodeKickoffOrigin as Qe}from"../../../core/runtime/stamp/protocol.js";import{ApiError as Xe}from"../../../api/errors.js";function p(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw l(`${e} requires a JSON body`);return t}s(p,"objectBody");function j(t){const e=p(t,"broker session-bound");if(typeof e.executionId!="string"||e.executionId==="")throw l("executionId must be a non-empty string");if(typeof e.piSessionId!="string"||e.piSessionId==="")throw l("piSessionId must be a non-empty string");if(e.sessionFile!==null&&typeof e.sessionFile!="string")throw l("sessionFile must be a string or null");if(!Number.isSafeInteger(e.pid)||e.pid<=0)throw l("pid must be a positive safe integer");if(e.reason!==null&&typeof e.reason!="string")throw l("reason must be a string or null");if(!Array.isArray(e.reviewBoundaryIds)||!e.reviewBoundaryIds.every(n=>typeof n=="string"))throw l("reviewBoundaryIds must be an array of strings");return e}s(j,"parseSessionBoundBody");function Ze(t){const e=p(t,"broker settle");if(typeof e.stopReason!="string")throw l("stopReason must be a string");for(const n of["pushedFinal"])if(typeof e[n]!="boolean")throw l(`${n} must be a boolean`);return e}s(Ze,"parseSettleBody");function Ie(t){const e=p(t,"broker cycle");if(typeof e.brokerVersion!="string"||e.brokerVersion==="")throw l("brokerVersion must be a non-empty string");return e}s(Ie,"parseCycleBody");function qe(t){const e=p(t,"broker park-complete");if(e.outcome!=="completed"&&e.outcome!=="failed")throw l("outcome must be completed or failed");return e}s(qe,"parseParkCompleteBody");function et(t){const e=p(t,"broker telemetry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw l("expected_execution_id must be a non-empty string");const n=Me(e);return{...n,expected_execution_id:e.expected_execution_id,updated_at:new Date(n.updated_at).toISOString()}}s(et,"parseTelemetryBody");function tt(t){const e=p(t,"broker model");if(typeof e.spec!="string"||e.spec.trim()==="")throw l("spec must be a non-empty string");const n=e.intent;if(n!==void 0){const r=n!==null&&typeof n=="object"?n:void 0;if(r===void 0||typeof r.family!="string"||r.family===""||!["ultra","strong","medium","light"].includes(r.strength))throw l("intent must be { family, strength } with strength ultra|strong|medium|light when present")}if(typeof e.userSelected!="boolean")throw l("userSelected must be a boolean");return e}s(tt,"parseModelCommitBody");async function m(t){const e=await g(t);if(e===null)throw R(`unknown node: ${t}`,{received:t});return e}s(m,"requireNode");async function v(t){return{node_id:t.node_id,grantee:t.grantee,name:t.name,...t.description===void 0?{}:{description:t.description},...t.title===void 0?{}:{title:t.title},...t.icon===void 0?{}:{icon:t.icon},kind:t.kind,mode:t.mode,lifecycle:t.lifecycle,status:t.status,cwd:t.cwd,parent:t.parent??null,fork_from:t.fork_from??null,profile_id:t.profile_id??null,...t.managed_worktree===void 0?{}:{managed_worktree:t.managed_worktree===null?null:{state:t.managed_worktree.state,...t.managed_worktree.cleanup===void 0?{}:{cleanup:t.managed_worktree.cleanup},path:t.managed_worktree.path,branch:t.managed_worktree.branch,base_ref:t.managed_worktree.base_ref,base_sha:t.managed_worktree.base_sha}},...t.review_binding===void 0?{}:{review_binding:t.review_binding??null},intent:t.intent??null,...t.persona_ack===void 0?{}:{persona_ack:t.persona_ack},created:t.created}}s(v,"extensionNode");async function V(t){const e=await m(t),n=[],r=new Set([t]);let i=e.parent??null;for(;i!==null&&i!==""&&!r.has(i);){r.add(i);const d=await g(i);if(d===null)break;n.unshift(await v(d)),i=d.parent??null}const a=await Ve((await q((await re(t)).map(d=>d.node_id))).filter(d=>d.kind!=="human").sort((d,w)=>d.status===w.status?0:d.status==="active"?-1:w.status==="active"?1:0),v),o=typeof e.fork_source_file=="string"?await be(e.fork_source_file):null,c=await fe(t);if(c===null)throw R(`unknown node: ${t}`,{received:t});return{node:await v(e),warm_spare:await ee(t),situational_card:await Ae(t),ancestors:n,children:a,fork_source:o===null?null:await v(o),subject:c,roadmap:await he(t)}}s(V,"extensionState");function E(t,e){return t?.kind===e.kind&&t?.mode===e.mode&&t?.lifecycle===e.lifecycle}s(E,"samePersona");function nt(t){const e=p(t,"broker generated-name");if(e.kind!=="initial"&&e.kind!=="recap")throw l("kind must be initial or recap");if(typeof e.description!="string"||typeof e.title!="string"||typeof e.icon!="string")throw l("description, title, and icon must be strings");if(e.kind==="initial")return e;const n=e.expected;if(typeof n!="object"||n===null||Array.isArray(n)||["name","description","title","icon","kind"].some(r=>typeof n[r]!="string"))throw l("recap expected must contain name, description, title, icon, and kind strings");return e}s(nt,"parseGeneratedNameBody");function it(t){const e=p(t,"broker persona-ack"),n=s(r=>{const i=e[r];if(typeof i!="object"||i===null||Array.isArray(i)||typeof i.kind!="string"||i.mode!=="base"&&i.mode!=="orchestrator"||i.lifecycle!=="terminal"&&i.lifecycle!=="resident")throw l(`${r} must be a persona state`);return i},"parse");return{expected_execution_id:e.expected_execution_id,from:n("from"),to:n("to")}}s(it,"parsePersonaAckBody");async function $(t,e){const n=e.sessionFile===null?null:Z(e.sessionFile);return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t);if(await se(e.executionId,t,e.pid)==="shutdown")return{action:"shutdown"};const a=i.review_binding?.review_id;if(a!==void 0&&!e.reviewBoundaryIds.includes(a))return{action:"shutdown"};if(e.reason==="new"&&i.parent==null)return{action:"relaunch_root"};if(e.reason!=="new"&&i.fork_from!=null&&i.pi_session_id==null&&n===null)return{action:"shutdown"};const o=n===null?null:await I(n);if(o!==null&&o.node_id!==t){if(pe(o.pi_pid))return await ge(t,{link:"daemon\u2192node",op:"session-file-ownership",kind:"protocol",retry:{disposition:"fatal"},message:`refusing to bind ${n}: it is owned by live node ${o.node_id}`}),{action:"shutdown"};const c=await de(o.node_id);if(c===null||await le({fromNodeId:o.node_id,fromBindingId:c.bindingId,toNodeId:t,executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})!=="transferred")return{action:"shutdown"}}else if(await ce(t,{executionId:e.executionId,sessionId:e.piSessionId,transcriptPath:n})==="shutdown")return{action:"shutdown"};return e.reason!=="new"&&(await ye(t),i.intent==="refresh"&&await k(t,"revive")),{action:"none"}})}s($,"commitSessionBound");async function rt(t){return{status:200,body:await $(t.params.id,j(t.body))}}s(rt,"handleSessionBound");function ot(t){const e=j(t);if(e.bearings!=="fresh"&&e.bearings!=="inherited"&&e.bearings!=="present")throw l("bearings must be fresh, inherited or present");return e}s(ot,"parseCycleStartBody");async function at(t,e,n,r,i=!1){const a=e.warm_spare||r,o=!a&&n!=="present";return i||await Be(await C(),t),await f(async c=>{const d=await Te(c,t,async(K,z,Q)=>await Ne(c,K,z,Q)),w=await Le(c,d),y=await O(c,d,{activity:"names"},w),b=o?await O(c,d,{activity:"boot",...n==="inherited"?{inherited:!0}:{}},w):void 0,A=a?void 0:await O(c,d,{activity:"system-prompt"},w);return{names:{refs:y.refs,names:y.names},...b===void 0?{}:{boot:{content:b.content,...b.inherited===!0?{inherited:!0}:{}}},...A===void 0?{}:{system_prompt:A.content}}})}s(at,"startupDelivery");async function U(t,e,n,r=!1){const i=await V(t),a=await at(t,i,e,n,r);if(a.boot!==void 0){const o={kind:i.node.kind,mode:i.node.mode,lifecycle:i.node.lifecycle},c=i.node.persona_ack,d=c===void 0?o:{kind:c.kind??i.node.kind,mode:c.mode,lifecycle:c.lifecycle};E(d,o)||await Y(t,d,o)}return{state:i,delivery:a}}s(U,"renderStartData");async function mn(t){const{state:e,delivery:n}=await U(t,"fresh",!1,!0);return{action:"none",state:e,names:n.names,...n.boot===void 0?{}:{boot:n.boot},...n.system_prompt===void 0?{}:{system_prompt:n.system_prompt}}}s(mn,"renderCarriedStart");async function st(t){const e=t.params.id,n=ot(t.body),r=await m(e),i=r.review_binding?.review_id,a=i!==void 0&&!n.reviewBoundaryIds.includes(i),o=a||r.cycle_pending===!0||r.intent==="refresh"||r.pi_session_id==null;if(o)await u(e,n.executionId);else{const{action:y}=await $(e,n);if(y!=="none")return{status:200,body:{action:y}}}const{state:c,delivery:d}=await U(e,n.bearings,a);return{status:200,body:{action:"none",...o?{bind_pending:!0}:{},state:c,...d,recovery:await Ce(e),attachments:(await Fe(e)).map(({path:y,sha256:b})=>({path:y,sha256:b})),structured_request:await L(e)}}}s(st,"handleCycleStart");async function W(t,e){return e.live!==null||await _e(t)||await F(t)}s(W,"isHeldAwake");async function H(t,e){return(await S(t))?.runner==="blaxel"&&!await W(t,e)&&(await me(await C(),t)).length===0}s(H,"residentBlaxelCanIdle");function J(t){return t.inPlaceCycle===!0?{action:"new_cycle"}:{action:"shutdown"}}s(J,"refreshDirective");async function ct(t,e,n){const r=await g(t);if(r===null){if(e.pushedFinal)return{directive:{action:"shutdown"},closePane:!1};throw R(`unknown node: ${t}`,{received:t})}if(await ie(t,new Date().toISOString()),(e.stopReason==="stop"||e.stopReason==="length")&&await ne(t,{failures:0,notBefore:null}),e.stopReason==="quit"){let c=!1;return(r.status==="active"||r.status==="idle")&&r.intent===null&&(await k(t,"finish"),await h(t),await x(t,{pane:null,tmux_session:null,window:null}),c=!0),{directive:{action:"shutdown"},closePane:c}}if(e.stopReason!=="stop"&&e.stopReason!=="length")return await h(t,{link:"daemon\u2192node"}),r.intent==="refresh"?{directive:J(e),closePane:!1}:e.stopReason==="error"&&e.faultSettled===!0&&(await ve(t))?.retry.disposition==="fatal"&&await L(t)===null&&await H(t,n)?{directive:{action:"stay_resident"},closePane:!1}:{directive:{action:"stay_dormant"},closePane:!1};const i={pushedFinal:e.pushedFinal};if(i.pushedFinal||r.status==="done")return await h(t),await x(t,{pane:null,tmux_session:null,window:null}),{directive:{action:"shutdown"},closePane:!0};if(r.intent==="refresh")return await h(t),{directive:J(e),closePane:!1};const a=await ke(t,i);if(await h(t),a.action==="reprompt")return{directive:{action:"reprompt",prompt:a.message},closePane:!1};if(a.reason==="finished")return{directive:await F(t)?{action:"stay_dormant"}:{action:"shutdown"},closePane:!1};const o=await W(t,n);return(await S(t))?.runner==="blaxel"?{directive:await H(t,n)?{action:"stay_resident"}:{action:"stay_dormant"},closePane:!1}:a.reason!=="awaiting"&&a.reason!=="scheduled"?{directive:{action:"stay_dormant"},closePane:!1}:o?{directive:{action:"stay_dormant"},closePane:!1}:(await k(t,"release"),{directive:{action:"shutdown"},closePane:!1})}s(ct,"settleBroker");async function dt(t){const e=t.params.id,n=Ie(t.body);await u(e,n.expected_execution_id);const r=await m(e);if(r.intent!=="refresh")throw new Xe(409,"not_yielding",`${e} has no pending yield`);const i=await S(e),a=$e(r);return n.brokerVersion===M()&&(i.release===null||i.release===M())&&He(i.launchJson,await Ue(e,a,r.cwd))?{status:200,body:await lt(e,r,i.executionId,a.env)}:{status:200,body:{action:"restart"}}}s(dt,"handleCycle");async function lt(t,e,n,r){e.cycles=(e.cycles??0)+1,await we(t,n);const i=await Ge(e,n),a=await Je(e,i);await Ye(t),await Ke(t,e,!1),await ze(t),await h(t,{preserveEpisode:!0}),await te(t,new Date().toISOString()),await _(t,{cycles:e.cycles,cycle_pending:!0});const o={};for(const c of We)r[c]!==void 0&&(o[c]=r[c]);return o.CRTR_CYCLES=String(e.cycles),{action:"cycle",cycle:e.cycles,prompt:a,origin:Qe({type:"runtime",kind:"revive",cycle:e.cycles}),messageIds:e.run_id?i.unreadMessageIds??[]:[],env:o,...e.launch?.model!==void 0?{model:e.launch.model}:{},modelExact:e.launch?.modelExact===!0,editorLabel:P(e)}}s(lt,"startCycleRecord");async function ut(t){const e=t.params.id,n=p(t.body,"broker idle");return await u(e,n.expected_execution_id),await ae(n.expected_execution_id),{status:204}}s(ut,"handleIdle");async function pt(t){const e=t.params.id,n=Ze(t.body);await u(e,n.expected_execution_id);const r=await B(e),{directive:i,closePane:a}=await f(async()=>await ct(e,n,await T(r)));return a&&await N(e),i.action!=="reprompt"&&Se(e).catch(o=>D({level:"error",event:"api.broker_ops.companion_submit_failed",node_id:e,error:o})),{status:200,body:i}}s(pt,"handleSettle");async function ft(t){const e=t.params.id,n=qe(t.body);await u(e,n.expected_execution_id);const r=await B(e),i=await f(async()=>{const a=await Pe(e);if(a===void 0)return{action:"stay_dormant"};const o=await m(e);return await Oe(e,o,a,await T(r))?(await h(e),await k(e,"park"),await x(e,{pane:null,tmux_session:null,window:null}),D({level:n.outcome==="completed"?"info":"warn",event:"broker.park.complete",...ue(e)?{node_id:e}:{},outcome:n.outcome==="completed"?"succeeded":"failed"}),{action:"shutdown"}):{action:"stay_dormant"}});return i.action==="shutdown"&&await N(e),{status:200,body:i}}s(ft,"handleParkComplete");async function mt(t){const e=t.params.id;return await u(e,p(t.body,"broker park-activity").expected_execution_id),{status:200,body:await f(async()=>({activity:await Re(e)?"recorded":"none"}))}}s(mt,"handleParkActivity");async function wt(t){const e=t.params.id,n=et(t.body);return await u(e,n.expected_execution_id),await f(async()=>{await oe(e,{tokensIn:n.tokens_in,contextTokens:n.context_tokens,lastActivity:n.last_activity,updatedAt:n.updated_at}),je(e,n)}),{status:204}}s(wt,"handleTelemetry");async function yt(t){const e=t.params.id,n=tt(t.body);return await u(e,n.expected_execution_id),{status:200,body:{modelOverride:(await f(async()=>await xe(await m(e),n.spec,n.intent,n.userSelected))).model_override}}}s(yt,"handleModelCommit");let G=!0;function wn(t){G=t}s(wn,"setRequestsStartRunObservers");async function ht(t){const e=t.params.id,n=await m(e);return n.run_id&&G&&await De(e,n.run_id),{status:200,body:await V(e)}}s(ht,"handleExtensionState");async function bt(t){const e=t.params.id,n=nt(t.body);return await u(e,n.expected_execution_id),{status:200,body:await f(async i=>{await i.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(e);const a=await m(e);if(n.kind==="initial"){if((a.description??"").trim()!=="")return{applied:!1};const d=await _(e,{description:n.description,...n.title.trim()===""?{}:{title:n.title},...n.icon.trim()===""?{}:{icon:n.icon}});return{applied:!0,editorLabel:P(d),description:d.description??"",title:d.title??"",icon:d.icon??""}}const o=n.expected;if(a.name!==o.name||(a.description??"")!==o.description||(a.title??"")!==o.title||(a.icon??"")!==o.icon||a.kind!==o.kind)return{applied:!1};const c=await _(e,{description:n.description,title:n.title.trim()===""?void 0:n.title,icon:n.icon.trim()===""?void 0:n.icon});return{applied:!0,editorLabel:P(c),description:c.description??"",title:c.title??"",icon:c.icon??""}})}}s(bt,"handleGeneratedName");async function _t(t){const e=t.params.id,n=it(t.body);return await u(e,n.expected_execution_id),{status:200,body:{applied:await Y(e,n.from,n.to)}}}s(_t,"handlePersonaAck");async function Y(t,e,n){return await f(async r=>{await r.prepareUncached("SELECT 1 FROM nodes WHERE node_id = ? FOR UPDATE").get(t);const i=await m(t),a={kind:i.kind,mode:i.mode,lifecycle:i.lifecycle},o=i.persona_ack,c=o===void 0?a:{kind:o.kind??i.kind,mode:o.mode,lifecycle:o.lifecycle};return!E(a,n)||!E(c,e)?!1:(await _(t,{persona_ack:n}),!0)})}s(Y,"applyPersonaAck");const yn=Ee([{method:"POST",pattern:"/v1/nodes/:id/broker/session-bound",handler:rt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle-start",handler:st},{method:"POST",pattern:"/v1/nodes/:id/broker/settle",handler:pt},{method:"POST",pattern:"/v1/nodes/:id/broker/cycle",handler:dt},{method:"POST",pattern:"/v1/nodes/:id/broker/idle",handler:ut},{method:"POST",pattern:"/v1/nodes/:id/broker/park-complete",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/broker/park-activity",handler:mt},{method:"POST",pattern:"/v1/nodes/:id/broker/telemetry",handler:wt},{method:"POST",pattern:"/v1/nodes/:id/broker/model",handler:yt},{method:"GET",pattern:"/v1/nodes/:id/broker/extension-state",handler:ht},{method:"POST",pattern:"/v1/nodes/:id/broker/generated-name",handler:bt},{method:"POST",pattern:"/v1/nodes/:id/broker/persona-ack",handler:_t}]);export{yn as brokerOperationRoutes,v as extensionNode,mn as renderCarriedStart,U as renderStartData,wn as setRequestsStartRunObservers};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.676",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -156,8 +156,8 @@
|
|
|
156
156
|
},
|
|
157
157
|
"license": "UNLICENSED",
|
|
158
158
|
"dependencies": {
|
|
159
|
-
"@north-light/identity": "0.3.
|
|
160
|
-
"@north-light/plugin": "0.3.
|
|
159
|
+
"@north-light/identity": "0.3.676",
|
|
160
|
+
"@north-light/plugin": "0.3.676",
|
|
161
161
|
"@earendil-works/chord": "1.5.2",
|
|
162
162
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -63,7 +63,7 @@ export async function preWaitForViewSocket(nodeId) {
|
|
|
63
63
|
/** Resolve the target, revive the node if it is dormant (server-side), and dial
|
|
64
64
|
* the broker. Rejects with a plain `InputError` — no terminal has been taken
|
|
65
65
|
* over at this point, so a failure here is an ordinary non-zero CLI exit. */
|
|
66
|
-
export async function connectToNode(nodeId, canvasName, wakeParked = true) {
|
|
66
|
+
export async function connectToNode(nodeId, canvasName, wakeParked = true, known) {
|
|
67
67
|
// An imported Mac has no local canvas API: its canvas and its brokers' viewer channels are reached through the cloud control plane,
|
|
68
68
|
// so attach without `--canvas` dials the cloud with the person's sign-in. It is still the person's own attach, not a `--canvas` view:
|
|
69
69
|
// `remote` stays false, so the viewer claims the controller role like any local attach.
|
|
@@ -95,7 +95,8 @@ export async function connectToNode(nodeId, canvasName, wakeParked = true) {
|
|
|
95
95
|
transport = new RelayTransport(nodeId, resolveRemoteCanvasTarget(canvasName));
|
|
96
96
|
}
|
|
97
97
|
else {
|
|
98
|
-
|
|
98
|
+
// A caller that just created the node already holds its detail: no second read.
|
|
99
|
+
const localMeta = known ?? await canvasSource.getNode(nodeId);
|
|
99
100
|
if (localMeta === null) {
|
|
100
101
|
throw new InputError({
|
|
101
102
|
error: 'not_found',
|
|
@@ -57,7 +57,7 @@ import { loadProfileManifest } from '../../core/profiles/manifest.js';
|
|
|
57
57
|
import { watchInboxActivity } from '../../core/human/root.js';
|
|
58
58
|
import { byNewestFirst, inboxRowFromDTO } from '../inbox/dto-adapt.js';
|
|
59
59
|
import { cliClient } from '../../commands/api-client.js';
|
|
60
|
-
import { loadPersonSettingsViaApi } from '../../commands/person-settings.js';
|
|
60
|
+
import { installPersonSettingsDto, loadPersonSettingsViaApi } from '../../commands/person-settings.js';
|
|
61
61
|
import { buildBannerInfo } from './session/banner.js';
|
|
62
62
|
import { backgroundBashHint, detachBindingHint, detachHint, inboxOpenHint, refreshAttachBindingSnapshot } from './session/bindings.js';
|
|
63
63
|
import { connectToNode, resolveHelloRole } from './session/connection.js';
|
|
@@ -82,10 +82,17 @@ function quoteIfNeeded(word) {
|
|
|
82
82
|
* always restoring the terminal first. `canvasName`, when set, attaches over
|
|
83
83
|
* a relayed WebSocket to that `remoteCanvas.targets.<name>` instead of the
|
|
84
84
|
* local unix socket — see the `--canvas` flag on `attachToLeaf`. */
|
|
85
|
-
export async function runAttach(nodeId, observer, canvasName, wakeParked = true
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
85
|
+
export async function runAttach(nodeId, observer, canvasName, wakeParked = true,
|
|
86
|
+
/** What a caller that just created the node already holds: the node's detail, the person's settings answer, and whether to play the first-prompt animation. */
|
|
87
|
+
held,
|
|
88
|
+
/** Called synchronously just before the viewer takes the terminal. */
|
|
89
|
+
onConnected) {
|
|
90
|
+
// The viewer is its own esbuild bundle with its own copy of the settings cache: install the person's settings before anything
|
|
91
|
+
// calls readConfig (theme, keybindings, ChatView's field initializers all do). A caller that holds them hands them over.
|
|
92
|
+
if (held === undefined)
|
|
93
|
+
await loadPersonSettingsViaApi();
|
|
94
|
+
else
|
|
95
|
+
installPersonSettingsDto(held.settings);
|
|
89
96
|
// 1. Get onto the broker before anything paints (session/connection.ts):
|
|
90
97
|
// resolve local-vs-relay, revive the node server-side if it is dormant,
|
|
91
98
|
// and win the connect race. A failure here is still a plain CLI error.
|
|
@@ -94,7 +101,7 @@ export async function runAttach(nodeId, observer, canvasName, wakeParked = true)
|
|
|
94
101
|
// read, native slash command, pane tag and lifecycle action gates on it,
|
|
95
102
|
// and no collaborator may re-derive it.
|
|
96
103
|
mark('viewer.connect_start', { node: nodeId });
|
|
97
|
-
const connection = await connectToNode(nodeId, canvasName, wakeParked);
|
|
104
|
+
const connection = await connectToNode(nodeId, canvasName, wakeParked, held?.node);
|
|
98
105
|
mark(connection.initialSnapshot === undefined ? 'viewer.socket_connected' : 'viewer.offline_snapshot_ready');
|
|
99
106
|
const { remote, canvasSource, meta, socket } = connection;
|
|
100
107
|
const role = resolveHelloRole(observer);
|
|
@@ -172,7 +179,7 @@ export async function runAttach(nodeId, observer, canvasName, wakeParked = true)
|
|
|
172
179
|
});
|
|
173
180
|
containers.header.addChild(strip.component);
|
|
174
181
|
const userConfig = readConfig('user');
|
|
175
|
-
const initialWhip = process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
|
|
182
|
+
const initialWhip = held?.initialWhip ?? process.env['CRTR_ATTACH_INITIAL_WHIP'] === '1';
|
|
176
183
|
delete process.env['CRTR_ATTACH_INITIAL_WHIP'];
|
|
177
184
|
const startupReviewId = takeStartupReviewId();
|
|
178
185
|
const startupTicketId = process.env['CRTR_ATTACH_OPEN_TICKET'];
|
|
@@ -678,6 +685,8 @@ export async function runAttach(nodeId, observer, canvasName, wakeParked = true)
|
|
|
678
685
|
// 6. Lay out, paint, start, then handshake — starting before the handshake
|
|
679
686
|
// means the welcome's applySnapshot renders into a live TUI.
|
|
680
687
|
layout.mount();
|
|
688
|
+
// Synchronous with tui.start(): the caller's screen gives the terminal back and the viewer takes it in the same tick, with no cooked-mode gap.
|
|
689
|
+
onConnected?.();
|
|
681
690
|
tui.start();
|
|
682
691
|
if (connection.initialSnapshot !== undefined) {
|
|
683
692
|
// Seed the same state/transcript owners a broker welcome feeds. No socket
|
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
// A CLI or viewer process holds no database: it reads the person's settings snapshot from crtrd once, then every settings write
|
|
2
2
|
// goes back as `PUT /v1/settings` ops (core/scoped-state/person-store.ts holds the one write algorithm).
|
|
3
3
|
import { ApiError } from '../api/index.js';
|
|
4
|
-
import { setPersonId } from '../core/canvas/person-state.js';
|
|
5
|
-
import { installPersonSnapshot, setSettingsReloader, setSettingsTransport, SettingsRevisionConflictError } from '../core/scoped-state/person-store.js';
|
|
4
|
+
import { personId, setPersonId } from '../core/canvas/person-state.js';
|
|
5
|
+
import { currentSnapshot, installPersonSnapshot, setSettingsReloader, setSettingsTransport, SettingsRevisionConflictError } from '../core/scoped-state/person-store.js';
|
|
6
6
|
import { cliClient } from './api-client.js';
|
|
7
7
|
const fromDto = (dto) => dto.snapshot;
|
|
8
|
+
/** This process's live settings (every write it has made included), for handing to a viewer bundle that holds its own cache. */
|
|
9
|
+
export function loadedPersonSettings() {
|
|
10
|
+
return { person: personId(), snapshot: currentSnapshot() };
|
|
11
|
+
}
|
|
8
12
|
export async function loadPersonSettingsViaApi() {
|
|
9
|
-
|
|
13
|
+
installPersonSettingsDto(await cliClient().getSettings());
|
|
14
|
+
}
|
|
15
|
+
/** Install a settings answer already in hand (no request) and wire this process's reload and write transports. */
|
|
16
|
+
export function installPersonSettingsDto(loaded) {
|
|
10
17
|
setPersonId(loaded.person);
|
|
11
18
|
installPersonSnapshot(loaded.person, fromDto(loaded));
|
|
12
19
|
setSettingsReloader(async () => fromDto(await cliClient().getSettings()));
|
|
@@ -16,13 +16,18 @@ import { warmCheckoutDirs } from '../checkout-identities.js';
|
|
|
16
16
|
import { fillProfileProjectRepo } from '../profiles/manifest.js';
|
|
17
17
|
import { emitEvent } from '../events/emit.js';
|
|
18
18
|
import { isCloudRole } from '../canvas/person-state.js';
|
|
19
|
-
import { mayRead, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
|
|
19
|
+
import { loadReadAccess, mayRead, prefetchRepoReads, reposForCwd, warmCheckoutIdentities } from './repo-sync/repos.js';
|
|
20
20
|
/** A node's view of repos: for the checkouts enclosing its cwd, every repo object of their remotes the person may read (own first, then oldest), then
|
|
21
21
|
* the repos its profile names (an entry's `repo`, and the checkouts of its `path`), in manifest order, each repo once. A repo entry needs no folder or
|
|
22
22
|
* git; one the person may not read adds nothing. A project path that no longer exists, is not in a repo, or has no work tree contributes nothing. */
|
|
23
23
|
export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
|
|
24
24
|
const projects = profileId === null ? [] : lookups.projects(profileId);
|
|
25
|
-
|
|
25
|
+
// One load of the permission inputs serves the cwd and every project entry.
|
|
26
|
+
const who = projects.length === 0 ? undefined : person ?? await personIdAsync();
|
|
27
|
+
const access = who === undefined ? undefined : await loadReadAccess(db, who);
|
|
28
|
+
if (access !== undefined && who !== undefined)
|
|
29
|
+
await prefetchRepoReads(db, who, [cwd, ...projects.flatMap((p) => p.path !== undefined && (isCloudRole() || existsSync(p.path)) ? [p.path] : [])], access);
|
|
30
|
+
const checkouts = await reposFn(cwd, person, access);
|
|
26
31
|
const seen = new Set(checkouts.map((c) => c.repo.id));
|
|
27
32
|
const projectRepos = [];
|
|
28
33
|
const projectCheckouts = [];
|
|
@@ -30,7 +35,7 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
|
|
|
30
35
|
if (project.repo !== undefined && !seen.has(project.repo)) {
|
|
31
36
|
const repo = await lookups.object(project.repo);
|
|
32
37
|
if (repo !== null && repo.type === 'repo' && repo.deleted_at === null
|
|
33
|
-
&& await mayRead(db, person ?? await personIdAsync(), repo.id)) {
|
|
38
|
+
&& await mayRead(db, who ?? person ?? await personIdAsync(), repo.id, access)) {
|
|
34
39
|
seen.add(repo.id);
|
|
35
40
|
projectRepos.push(repo);
|
|
36
41
|
}
|
|
@@ -40,7 +45,7 @@ export async function viewRepos(db, cwd, profileId, reposFn, lookups, person) {
|
|
|
40
45
|
continue;
|
|
41
46
|
let found;
|
|
42
47
|
try {
|
|
43
|
-
found = await reposFn(project.path, person);
|
|
48
|
+
found = await reposFn(project.path, person, access);
|
|
44
49
|
}
|
|
45
50
|
catch (e) {
|
|
46
51
|
if (e instanceof CrtrError && e.code === 'git-lookup-failed')
|
|
@@ -33,23 +33,65 @@ export async function ensureRepo(db, id, handle) {
|
|
|
33
33
|
free = `${wanted}-${n}`;
|
|
34
34
|
return await ensureOwner(db, 'repo', id.scheme, id.externalId, free);
|
|
35
35
|
}
|
|
36
|
+
export async function loadReadAccess(db, person) {
|
|
37
|
+
return { defs: await loadDefinitions(db), subjects: await subjectSet(db, person.replace(/^user:/, '')) };
|
|
38
|
+
}
|
|
36
39
|
/** Whether `person` may read the object `id` by permission facts alone (no ceiling): the gate for a repo a profile names. */
|
|
37
|
-
export async function mayRead(db, person, id) {
|
|
38
|
-
const
|
|
40
|
+
export async function mayRead(db, person, id, access) {
|
|
41
|
+
const { defs, subjects } = access ?? await loadReadAccess(db, person);
|
|
42
|
+
const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', f `${id}::text`);
|
|
39
43
|
const row = await db.prepareUncached(`SELECT ${read.sql} AS ok`).get(...read.params);
|
|
40
44
|
return row?.ok === true;
|
|
41
45
|
}
|
|
42
46
|
/** The repo objects of one remote identity, any person's, that `person` may read (permission facts only, no ceiling), the person's own first and
|
|
43
47
|
* then by age, oldest first. `heldByPerson` says whether the person has an identity row for it at all, readable or not. */
|
|
44
|
-
export async function readableRepos(db, person, scheme, externalId) {
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
+
export async function readableRepos(db, person, scheme, externalId, access) {
|
|
49
|
+
const key = `${scheme}\0${externalId}`;
|
|
50
|
+
const prefetched = access?.readable?.get(key);
|
|
51
|
+
if (prefetched !== undefined)
|
|
52
|
+
return { readable: [...prefetched.readable], heldByPerson: prefetched.heldByPerson };
|
|
53
|
+
return (await readableReposFor(db, person, [{ scheme, externalId }], access)).get(key);
|
|
54
|
+
}
|
|
55
|
+
/** `readableRepos` for several identities in one read. */
|
|
56
|
+
async function readableReposFor(db, person, ids, access) {
|
|
57
|
+
const { defs, subjects } = access ?? await loadReadAccess(db, person);
|
|
58
|
+
const read = compilePermission(defs, subjects, OBJECT_TYPE, 'read', raw('o.id'));
|
|
59
|
+
const rows = ids.length === 0 ? [] : await db.prepareUncached(`SELECT o.*, i.person AS holder, i.scheme AS id_scheme, i.external_id AS id_external, ${read.sql} AS ok FROM identities i JOIN objects o ON o.id = i.object
|
|
60
|
+
WHERE o.type = 'repo' AND o.deleted_at IS NULL AND (i.scheme, i.external_id) IN (SELECT * FROM unnest(?::text[], ?::text[]))`)
|
|
61
|
+
.all(...read.params, ids.map((i) => i.scheme), ids.map((i) => i.externalId));
|
|
48
62
|
const mine = `user:${person.replace(/^user:/, '')}`;
|
|
49
63
|
const own = (r) => r.holder === mine && r.owner === null;
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
64
|
+
const out = new Map();
|
|
65
|
+
for (const id of ids) {
|
|
66
|
+
const mineRows = rows.filter((r) => r.id_scheme === id.scheme && r.id_external === id.externalId);
|
|
67
|
+
const readable = mineRows.filter((r) => r.ok).sort((a, b) => Number(own(b)) - Number(own(a)) || a.created_at.localeCompare(b.created_at) || a.seq - b.seq)
|
|
68
|
+
.map(({ holder: _holder, ok: _ok, id_scheme: _s, id_external: _e, ...repo }) => repo);
|
|
69
|
+
out.set(`${id.scheme}\0${id.externalId}`, { readable, heldByPerson: mineRows.some((r) => r.holder === mine) });
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
const localPathRepos = async (db) => await db.prepare(`SELECT o.*, i.external_id AS path, i.person AS person FROM identities i JOIN objects o ON o.id = i.object
|
|
74
|
+
WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();
|
|
75
|
+
/** For a request that resolves many directories for one person: read once what each `checkoutsForCwd` would read per directory (the readable
|
|
76
|
+
* repos of every git identity in `dirs`, and the local-path repos) and store it on `access`. */
|
|
77
|
+
export async function prefetchRepoReads(db, person, dirs, access) {
|
|
78
|
+
const ids = new Map();
|
|
79
|
+
for (const cwd of dirs) {
|
|
80
|
+
let chain;
|
|
81
|
+
try {
|
|
82
|
+
chain = await checkoutChainOf(db, realpathOrSelf(resolve(cwd)), async () => person);
|
|
83
|
+
}
|
|
84
|
+
catch (e) {
|
|
85
|
+
if (e instanceof CrtrError && e.code === 'git-lookup-failed')
|
|
86
|
+
continue; // the loop reports it
|
|
87
|
+
throw e;
|
|
88
|
+
}
|
|
89
|
+
for (const id of chain)
|
|
90
|
+
if (id.ok)
|
|
91
|
+
ids.set(`${id.scheme}\0${id.externalId}`, { scheme: id.scheme, externalId: id.externalId });
|
|
92
|
+
}
|
|
93
|
+
access.readable = await readableReposFor(db, person, [...ids.values()], access);
|
|
94
|
+
access.localPaths = await localPathRepos(db);
|
|
53
95
|
}
|
|
54
96
|
/** Repos enclosing `cwd`, nearest first: every enclosing git checkout (created
|
|
55
97
|
* on first sight) and every existing local-path repo whose path is `cwd` or
|
|
@@ -65,23 +107,24 @@ export async function warmCheckoutIdentities(cwd) {
|
|
|
65
107
|
/** `reposForCwd` with the directory each repo is checked out at. Each git checkout yields every repo object of its remote that `person` (default: the
|
|
66
108
|
* request's person) may read: their own first, then the others oldest first. A personal repo object is created only when the person holds none for the
|
|
67
109
|
* remote; one they hold but may no longer read (a group they left) contributes nothing. */
|
|
68
|
-
export async function checkoutsForCwd(db, cwd, person) {
|
|
110
|
+
export async function checkoutsForCwd(db, cwd, person, access) {
|
|
69
111
|
const dir = realpathOrSelf(resolve(cwd));
|
|
70
112
|
const found = [];
|
|
113
|
+
let loaded = access;
|
|
71
114
|
for (const id of await checkoutChainOf(db, dir, async () => person ?? await personIdAsync())) {
|
|
72
115
|
if (!id.ok) {
|
|
73
116
|
throw new CrtrError('git-lookup-failed', `cannot identify the repo at ${id.dir}: ${id.reason}`, ExitCode.GENERAL, { dir: id.dir });
|
|
74
117
|
}
|
|
75
118
|
const who = person ?? await personIdAsync();
|
|
76
|
-
|
|
119
|
+
loaded ??= await loadReadAccess(db, who);
|
|
120
|
+
const { readable, heldByPerson } = await readableRepos(db, who, id.scheme, id.externalId, loaded);
|
|
77
121
|
if (readable.length === 0 && !heldByPerson)
|
|
78
122
|
readable.push(await ensureRepo(db, id));
|
|
79
123
|
for (const repo of readable)
|
|
80
124
|
found.push({ root: id.root, repo });
|
|
81
125
|
}
|
|
82
126
|
// Every person's local-path repos are read, and the request's person is asked for only when one of them encloses `dir`: a folder in no repo needs no person.
|
|
83
|
-
const paths = await db
|
|
84
|
-
WHERE o.type = 'repo' AND i.scheme = 'local-path'`).all();
|
|
127
|
+
const paths = access?.localPaths ?? await localPathRepos(db);
|
|
85
128
|
const enclosing = paths.filter(({ path }) => dir === path || dir.startsWith(path.endsWith(sep) ? path : path + sep));
|
|
86
129
|
const holder = enclosing.length > 0 ? person ?? await personIdAsync() : '';
|
|
87
130
|
for (const { path, person: owner, ...repo } of enclosing) {
|
|
@@ -10,7 +10,9 @@
|
|
|
10
10
|
import { projectPaths } from '../../api/dto/profiles.js';
|
|
11
11
|
import { spawnSync } from 'node:child_process';
|
|
12
12
|
import { existsSync, realpathSync } from 'node:fs';
|
|
13
|
-
import { basename, resolve as resolvePath, sep } from 'node:path';
|
|
13
|
+
import { basename, join, resolve as resolvePath, sep } from 'node:path';
|
|
14
|
+
import { appendRotatingRecord } from '../log.js';
|
|
15
|
+
import { crtrHome } from '../canvas/paths.js';
|
|
14
16
|
import { createInterface } from 'node:readline/promises';
|
|
15
17
|
import { emitKeypressEvents } from 'node:readline';
|
|
16
18
|
import { listProfiles, loadProfileManifest, resolveProfileOperand, updateProfileLastUsed, createProfile, addProfileProject, ensureRootProfile, ROOT_PROFILE_ID, } from './manifest.js';
|
|
@@ -669,7 +671,15 @@ async function promptPickProfileOrCreate(candidates, cwd, exact, pinnedId, bindi
|
|
|
669
671
|
* the root profile. Non-interactive (no TTY):
|
|
670
672
|
* default to the root profile and print the recovery instruction to STDERR —
|
|
671
673
|
* never stdout, which the caller may be piping. */
|
|
672
|
-
export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = false
|
|
674
|
+
export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = false,
|
|
675
|
+
/** The front door's startup does not hold the start on the last-used write (a timestamp nothing in this start reads back); crtrd's callers wait for it. */
|
|
676
|
+
waitForLastUsed = true) {
|
|
677
|
+
const touch = async (profileId) => {
|
|
678
|
+
if (waitForLastUsed)
|
|
679
|
+
await updateProfileLastUsed(profileId);
|
|
680
|
+
else
|
|
681
|
+
updateProfileLastUsed(profileId).catch((error) => appendRotatingRecord(join(crtrHome(), 'attach-invariants.log'), `${new Date().toISOString()} profile.last_used ${profileId} ${String(error).replaceAll(/[\r\n]/g, ' ')}`));
|
|
682
|
+
};
|
|
673
683
|
const resolvedCwd = resolveCwd(cwd);
|
|
674
684
|
const bindings = resolveUserKeybindings();
|
|
675
685
|
if (explicitProfile !== undefined && explicitProfile !== null && explicitProfile !== '') {
|
|
@@ -679,7 +689,7 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
|
|
|
679
689
|
if (!profileCoversCwd(entry, resolvedCwd) && isInteractive()) {
|
|
680
690
|
await promptAddDirToProfile(entry, resolvedCwd);
|
|
681
691
|
}
|
|
682
|
-
await
|
|
692
|
+
await touch(entry.profileId);
|
|
683
693
|
return entry.profileId;
|
|
684
694
|
}
|
|
685
695
|
// Looped for the one gate that changes the world before it answers: `v` opens
|
|
@@ -700,14 +710,14 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
|
|
|
700
710
|
// hint, so a boot-time breadcrumb here would just be redundant.
|
|
701
711
|
// `crtr --pick-profile` (forcePicker) re-opens the menu to re-pin/unpin.
|
|
702
712
|
if (pinned !== null && !forcePicker) {
|
|
703
|
-
await
|
|
713
|
+
await touch(pinned.profileId);
|
|
704
714
|
return pinned.profileId;
|
|
705
715
|
}
|
|
706
716
|
// Exactly one profile's project dir IS cwd — unambiguous project root, use it
|
|
707
717
|
// silently, never a prompt. (Several exact claims fall through to the menu.)
|
|
708
718
|
// Suppressed under forcePicker so `--pick-profile` can pin even a lone owner.
|
|
709
719
|
if (!forcePicker && pinned === null && exact.length === 1) {
|
|
710
|
-
await
|
|
720
|
+
await touch(exact[0].profileId);
|
|
711
721
|
return exact[0].profileId;
|
|
712
722
|
}
|
|
713
723
|
// Non-interactive: cannot prompt. Prefer an exact claimant, else any covering
|
|
@@ -716,7 +726,7 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
|
|
|
716
726
|
const pool = exact.length > 0 ? exact : covering;
|
|
717
727
|
if (pool.length > 0) {
|
|
718
728
|
const winner = pickMostRecent(pool);
|
|
719
|
-
await
|
|
729
|
+
await touch(winner.profileId);
|
|
720
730
|
return winner.profileId;
|
|
721
731
|
}
|
|
722
732
|
const root = await ensureRootProfile();
|
|
@@ -734,7 +744,7 @@ export async function selectProfileForCwd(cwd, explicitProfile, forcePicker = fa
|
|
|
734
744
|
: await promptCreateOrRoot(resolvedCwd, bindings);
|
|
735
745
|
if (chosen === MANAGED)
|
|
736
746
|
continue;
|
|
737
|
-
await
|
|
747
|
+
await touch(chosen);
|
|
738
748
|
return chosen;
|
|
739
749
|
}
|
|
740
750
|
}
|