@north-light/cli 0.3.747 → 0.3.748
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/objects.d.ts +6 -1
- package/dist/api/dto/plugins.d.ts +2 -0
- package/dist/commands/canvas/list.js +2 -2
- package/dist/commands/canvas/read.js +4 -4
- package/dist/commands/canvas/search.js +1 -1
- package/dist/core/canvas/canvas.js +1 -1
- package/dist/core/canvas/schema-pg/035-environment-payer.sql +2 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command-manifests/registry.d.ts +2 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/command.d.ts +11 -0
- package/dist/core/command.js +9 -9
- package/dist/core/environments.d.ts +2 -1
- package/dist/core/environments.js +1 -1
- package/dist/core/grants/mirror.d.ts +4 -0
- package/dist/core/grants/mirror.js +8 -6
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/ledger/environment-payer.d.ts +2 -0
- package/dist/core/ledger/environment-payer.js +1 -0
- package/dist/core/ledger/index.d.ts +1 -0
- package/dist/core/ledger/index.js +1 -1
- package/dist/core/ledger/payer.d.ts +4 -1
- package/dist/core/ledger/payer.js +1 -1
- package/dist/core/llm/run.d.ts +1 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/permissions/evaluator.js +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runs/node-sub.d.ts +2 -0
- package/dist/core/runs/node-sub.js +1 -0
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/runtime/start-check.d.ts +1 -0
- package/dist/core/runtime/start-check.js +1 -1
- package/dist/core/runtime/warm-pool.js +1 -1
- package/dist/core/spaces/process.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +2 -2
- package/dist/daemon/api/handlers/hook-exec.js +1 -1
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/commands/canvas/list.js +3 -1
- package/packages/crouter-api/dist/commands/canvas/read.js +4 -2
- package/packages/crouter-api/dist/commands/canvas/search.js +3 -1
- package/packages/crouter-api/dist/core/canvas/canvas.js +1 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/command-plugins/compose.js +5 -3
- package/packages/crouter-api/dist/core/command.js +33 -1
- package/packages/crouter-api/dist/core/environments.js +2 -2
- package/packages/crouter-api/dist/core/grants/mirror.js +16 -1
- package/packages/crouter-api/dist/core/grants/on-sync.js +2 -2
- package/packages/crouter-api/dist/core/ledger/environment-payer.js +15 -0
- package/packages/crouter-api/dist/core/ledger/index.js +1 -0
- package/packages/crouter-api/dist/core/ledger/payer.js +4 -0
- package/packages/crouter-api/dist/core/llm/run.js +2 -1
- package/packages/crouter-api/dist/core/permissions/evaluator.js +5 -3
- package/packages/crouter-api/dist/core/providers/call.js +2 -2
- package/packages/crouter-api/dist/core/runs/node-sub.js +10 -0
- package/packages/crouter-api/dist/core/runtime/host.js +2 -2
- package/packages/crouter-api/dist/core/runtime/spawn.js +1 -1
- package/packages/crouter-api/dist/core/runtime/start-check.js +2 -2
- package/packages/crouter-api/dist/core/runtime/warm-pool.js +1 -1
- package/packages/crouter-api/dist/core/spaces/process.js +5 -4
- package/packages/crouter-api/dist/daemon/api/handlers/bash-jobs.js +1 -1
- 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,3 +1,3 @@
|
|
|
1
|
-
var Se=Object.defineProperty;var c=(e,r)=>Se(e,"name",{value:r,configurable:!0});import{accessSync as Ce,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Pe}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as U}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as p,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as L,setFrozen as V}from"../canvas/index.js";import{contextDir as J,nodeAgentDir as Y}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as X,conversationStore as D}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Q}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as I}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Sn}from"../canvas/person.js";import{recordLaunch as Cn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as q,timedStep as A}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Pn,unregisteredConcreteModel as Tn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function R(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}c(R,"launchFailureOutcome");async function qn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await I(e,"crash",{reason:"launch_failed",outcome:R(t)})}catch{}const a=t.message;throw U(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}c(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}c(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:s}=r.status;return{text:`exited (code ${a??"null"}, signal ${s??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:s,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}c(Vn,"notReadyDescription");async function Jn(e,r){try{await I(e,"crash",{reason:"launch_failed",outcome:R(r)})}catch{}try{Z.teardown(e)}catch{}}c(Jn,"crashAndTearDown");async function Yn(e){const r=(await D().list()).map(({conversation_id:a,path:s})=>({id:a,path:s})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}c(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=X(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await D().header(t)).path}const o=await p(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=X(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await D().header(a)).path}return await Yn(r)}c(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await p(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}c(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Pn(e.model,r,e.modelExact===!0)}c(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:s,...d}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...d,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}c(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Tn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}c(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}c(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&q("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))q(`mac_${t}`,a)}c(er,"recordStartCallTimings");async function nr(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:s}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Q().automaticReviveCap,runner:"machine",release:he()})}catch(l){return l instanceof ue?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),"failed")}let w;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const l=await vn(e.node_id,o,e.cwd);await En(d,l);const b=d;q("execution_setup",performance.now()-t);const[N,m]=await A("warm_and_bundle",async()=>await Promise.allSettled([A("warm_repos",async()=>await bn(await gn(),e.node_id)),A("start_bundle",async()=>{const x=e.sub??await Sn();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:l,runner:"machine"})})]));if(N.status==="rejected")throw N.reason;if(m.status==="rejected")throw m.reason;const B=m.value;w=await A("render_transaction",()=>yn(async x=>{const S=await s(e.node_id),f=await xn(x,b,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,release:he(),launchJson:l,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:B,start:S})},{timingName:"render_tx"}))}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),await L(d,{reason:"launch_failed"}),"failed"}let y;try{y=await In(r,"start",w)}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),l instanceof Mn||l instanceof Fn&&l.sent?"uncertain":(await L(d,{reason:"launch_failed"}),"failed")}try{await er(w,y)}catch(l){v({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:l})}try{await A("record_launch",()=>Cn(e.node_id,new Date().toISOString()))}catch(l){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:l})}return"started"}c(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),s=e.root===!0,d=Zn(e.parent,a.nodeId??null,s),w=e.mode??"base",y=e.rootLifecycle??(s?"resident":"terminal"),l=s&&y==="resident",b=d===null?null:await p(d),N=e.creator===void 0||e.creator===null?null:await p(e.creator);e.nodeId!==void 0&&await Pe(e.nodeId);const m=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,B=m===void 0?null:await De(m),x=await Un([b,N,B],async h=>h?.isolated===!0||h?.run_id!=null&&(await p(h.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await le():e.nodeId,M=S?e.run!==void 0&&s&&!x?e.cwd:Re(Me(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const _=await Qn(e.profile,d,M),W=S?null:await je(_,e.worktreeCwd??M);W!==null&&(M=W,f??=await le());const P=e.worktree===!0||W!==null,ne=e.run?.grant_id??b?.grant_id??null,T=e.run??N??b??B,re=await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:M,profileId:_}),await Xn({grantee:T?.grantee??"app:terminal",sub:T?.sub,grant_id:T?.grant_id});const te=B?.node_id??null;let C,j=M;const z=P&&await ze(_)?await He(_,W??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,H=P&&z===void 0?await Ge(_):null;try{P&&z===void 0&&(C=H!==null?await Xe(H,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,f,e.worktreeBase),j=C.path);const h=P?await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:j,profileId:_,app:T?.grantee??"app:terminal"})).launch,ne,e.model):re;z!==void 0&&(h.worktree=z),P&&await ve(_e(h),{cwd:j,profileId:_});const n=await Fe({kind:e.kind,mode:w,lifecycle:y,cwd:j,name:e.name??e.kind,description:e.description,parent:s?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:s?d??void 0:void 0,profile_id:_,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:m,modelOverride:e.model===void 0?void 0:h.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:h});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const G=e.prompt!=="",ye=`${G&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
|
|
1
|
+
var Se=Object.defineProperty;var c=(e,r)=>Se(e,"name",{value:r,configurable:!0});import{accessSync as Ce,constants as Ee,existsSync as $e}from"node:fs";import{isAbsolute as Oe,resolve as Ie,join as Re}from"node:path";import{appSpace as Me}from"../layout.js";import{ApiError as se}from"../../api/errors.js";import{spawnNode as Fe,forkSourceNode as De,currentNodeContext as Ne,rootOfSpine as Be,newNodeId as le,preflightNodeId as Pe}from"./nodes.js";import{resolveProfileOperand as Te}from"../profiles/manifest.js";import{selectProfileForCwd as Le,selectProfileForCwdReadOnly as Ae}from"../profiles/select.js";import{buildLaunchSpecAsync as ce,buildPiArgv as We}from"./launch.js";import{devEnvironmentCwd as je,runsOnBlaxel as ze,sandboxWorktreeRequest as He}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ke,rollbackManagedWorktreeAsync as Ue}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Xe,rollbackManagedWorktreeOnMachine as qe,worktreeMachineOf as Ge}from"../worktree-machine.js";import{usage as k,brokerLaunchFailed as U}from"../errors.js";import{InputError as Ve}from"../io.js";import{isCloudRole as Je}from"../canvas/person-state.js";import{writeGoal as Ye}from"./kickoff.js";import{appendSituationalContext as Qe,formatSituationalProse as Ze}from"./situational-context.js";import{ensureRoadmap as en}from"./roadmap.js";import{buildWakeBearings as nn}from"./bearings.js";import{encodeKickoffOrigin as rn,KICKOFF_ORIGIN_ENV as tn}from"./stamp/protocol.js";import{carryInitialInput as on}from"../runs/initial-input.js";import{ExecutionCapReached as ue,beginExecution as fe,crtrHome as an,getNode as _,fullName as we,jobDir as dn,recordExecutionPid as sn,abortExecution as L,setFrozen as V}from"../canvas/index.js";import{contextDir as J,nodeAgentDir as Y}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as ln}from"../spaces/open-beneath.js";import{conversationIdFromPath as X,conversationStore as D}from"../conversation-store/index.js";import{appMemoryTooSmall as cn,boundFleet as me,brokerThresholdsForDaemon as Q}from"./fleet.js";import{admitBrokerMemory as un}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as fn}from"./blaxel-environment.js";import{openViewerWindow as wn,focusOf as mn,windowOfPane as hn}from"./placement.js";import{awaitBrokerViewSocket as pn}from"./view-socket.js";import{readLogSnapshot as _n}from"../events/read.js";import{transition as I}from"./lifecycle.js";import{beginBootFaultAttempt as kn}from"../canvas/recovery.js";import{headlessBrokerHost as Z,brokerLaunchJson as vn}from"./host.js";import{openDb as gn,withCanvasWrite as yn}from"../canvas/db.js";import{warmNodeRepos as bn}from"../graph/reader.js";import{mintNodeToken as xn}from"../canvas/node-tokens.js";import{personIdAsync as Sn}from"../canvas/person.js";import{recordLaunch as Cn}from"../canvas/canvas.js";import{setExecutionLaunchJson as En}from"../canvas/executions.js";import{acceptedRelease as he,remoteMachineEnvironmentOf as $n}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as On,awaitMachineCall as In,callTimes as Rn}from"./runner/machine/call.js";import{addStepTiming as q,timedStep as A}from"../step-timings.js";import{MachineLostError as Mn,MachineOfflineError as Fn}from"./runner/machine/ops.js";import{isDrained as Dn}from"../../daemon/drain.js";import{ensureDaemon as Nn}from"../../daemon/manage.js";import{readConfig as Bn}from"../config.js";import{modelRequestFromConfig as Pn,unregisteredConcreteModel as Tn,unroutableConcreteModel as Ln}from"../model-routes.js";import{openModelRegistry as An}from"./model-registry.js";import{MODEL_SPEC_NEXT as Wn}from"./model-selection.js";import{forkNodeLedger as jn}from"./ledger.js";import{appRungForGrant as zn}from"../llm/app-rungs.js";import{APP_FAMILY as ee}from"../model-routes.js";import{discoverLifecycleHookRegistry as Hn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Kn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Un}from"../async-array.js";import{checkStart as Xn}from"./start-check.js";function R(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}c(R,"launchFailureOutcome");async function qn(e,r,o){try{return await Z.launch(e,r,o)}catch(t){try{await I(e,"crash",{reason:"launch_failed",outcome:R(t)})}catch{}const a=t.message;throw U(a.startsWith("[broker]")?a:`[broker] refusing to launch ${e}: ${a}`,`Inspect the cause above and \`crtr sys logs --node ${e}\`, fix the launch recipe or environment, then retry.`)}}c(qn,"launchBrokerOrCrash");function Gn(e){return _n({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(o=>o.kind==="event"&&o.envelope.event.startsWith("broker.startup.")&&o.envelope.event!=="broker.startup.warning"?[o.envelope.event.slice(15)]:[]).at(-1)??null}c(Gn,"lastStartupStep");function Vn(e,r){const o=Gn(e),t=o===null?"it had logged no startup step":`the last startup step it logged was \`${o}\``;if(r.reason==="exited"){const{code:a,signal:s}=r.status;return{text:`exited (code ${a??"null"}, signal ${s??"null"}) before binding its view socket; ${t}`,fields:{reason:"exited",code:a,signal:s,last_startup_step:o}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${t}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:o}}}c(Vn,"notReadyDescription");async function Jn(e,r){try{await I(e,"crash",{reason:"launch_failed",outcome:R(r)})}catch{}try{Z.teardown(e)}catch{}}c(Jn,"crashAndTearDown");async function Yn(e){const r=(await D().list()).map(({conversation_id:a,path:s})=>({id:a,path:s})),o=r.filter(a=>a.id===e),t=o.length>0?o:r.filter(a=>a.id.startsWith(e));if(t.length===0)throw k(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(t.length>1)throw k(`--fork-from '${e}': ambiguous \u2014 ${t.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return t[0].path}c(Yn,"resolveSessionUuid");async function pe(e){const r=e.trim();if(r==="")throw k("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const t=X(Oe(r)?r:Ie(process.cwd(),r));if(t===null)throw k(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await D().header(t)).path}const o=await _(r);if(o!==null){const t=o.pi_session_file;if(t==null||t==="")throw k(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const a=X(t);if(a===null)throw k(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await D().header(a)).path}return await Yn(r)}c(pe,"resolveForkSource");async function Qn(e,r,o,t={}){return e===null?null:e!==void 0&&e!==""?Te(e).profileId:r!==null?(await _(r))?.profile_id??null:t.readOnlySelection===!0?Ae(o):Le(o)}c(Qn,"resolveProfileId");function _e(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Pn(e.model,r,e.modelExact===!0)}c(_e,"requestFromLaunch");async function ke(e,r,o){const t=o??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),a=await zn(r,t,e.modelExact===!0);if(a===null)return e;const{CRTR_MODEL_INTENT:s,...d}=e.env??{};return{...e,model:a.model,modelIntent:{family:ee,strength:a.strength},modelExact:void 0,env:{...d,CRTR_MODEL_INTENT:`${ee}/${a.strength}`}}}c(ke,"appPaidLaunch");async function ve(e,r,o){if(e===void 0||e.kind==="logical"&&e.family!==ee)return;const t=await Tn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,o??await An(),r);if(t!==void 0)throw k(`model '${t.request.spec}' is not registered in this daemon.`,{received:t.request.spec,next:Wn});const a=await Ln(e,r);if(a!==void 0)throw k(`model '${a.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:a.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}c(ve,"assertLaunchModelRegistered");function Zn(e,r,o){const t=e??r??null;if(!o&&t===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return t}c(Zn,"resolveSpawner");async function er(e,r){const o=await Rn(e);o!==null&&q("start_enqueue_to_answer",o.finishedAt-o.createdAt);for(const[t,a]of Object.entries(r?.timings??{}))q(`mac_${t}`,a)}c(er,"recordStartCallTimings");async function nr(e,r,o){const t=performance.now(),{buildStartBundle:a}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:s}=await import("../../daemon/api/handlers/broker-ops.js");if(await Dn())return"full";let d;try{d=await fe(e.node_id,{daemonEpoch:me().epoch(),cap:Q().automaticReviveCap,runner:"machine",release:he()})}catch(l){return l instanceof ue?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),"failed")}let w;try{o.env={...o.env,CRTR_EXECUTION_ID:d};const l=await vn(e.node_id,o,e.cwd);await En(d,l);const b=d;q("execution_setup",performance.now()-t);const[N,m]=await A("warm_and_bundle",async()=>await Promise.allSettled([A("warm_repos",async()=>await bn(await gn(),e.node_id)),A("start_bundle",async()=>{const x=e.sub??await Sn();return await a({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:x,launchJson:l,runner:"machine"})})]));if(N.status==="rejected")throw N.reason;if(m.status==="rejected")throw m.reason;const B=m.value;w=await A("render_transaction",()=>yn(async x=>{const S=await s(e.node_id),f=await xn(x,b,e.node_id,new Date().toISOString());return await On(r,"start",{executionId:b,nodeId:e.node_id,attempt:1,release:he(),launchJson:l,cwd:e.cwd,resuming:!1,nodeToken:f,bundle:B,start:S})},{timingName:"render_tx"}))}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),await L(d,{reason:"launch_failed"}),"failed"}let y;try{y=await In(r,"start",w)}catch(l){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:l}),l instanceof Mn||l instanceof Fn&&l.sent?"uncertain":(await L(d,{reason:"launch_failed"}),"failed")}try{await er(w,y)}catch(l){v({level:"warn",event:"broker.create_start_timing_failed",node_id:e.node_id,error:l})}try{await A("record_launch",()=>Cn(e.node_id,new Date().toISOString()))}catch(l){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:l})}return"started"}c(nr,"startOnMachine");async function ge(e,r,o){const t=performance.now();try{Nn()}catch{}const a=Ne(),s=e.root===!0,d=Zn(e.parent,a.nodeId??null,s),w=e.mode??"base",y=e.rootLifecycle??(s?"resident":"terminal"),l=s&&y==="resident",b=d===null?null:await _(d),N=e.creator===void 0||e.creator===null?null:await _(e.creator);e.nodeId!==void 0&&await Pe(e.nodeId);const m=e.forkFrom!==void 0?await pe(e.forkFrom):void 0,B=m===void 0?null:await De(m),x=await Un([b,N,B],async p=>p?.isolated===!0||p?.run_id!=null&&(await _(p.run_id))?.isolated===!0);if(x&&e.isolated===!1)throw new se(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const S=x||e.isolated===!0;if(S&&e.worktree===!0)throw new se(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let f=S||e.worktree===!0?e.nodeId??await le():e.nodeId,M=S?e.run!==void 0&&s&&!x?e.cwd:Re(Me(e.run?.grantee??b?.grantee??"app:terminal").nodes,f):e.cwd;const h=await Qn(e.profile,d,M),W=S?null:await je(h,e.worktreeCwd??M);W!==null&&(M=W,f??=await le());const P=e.worktree===!0||W!==null,ne=e.run?.grant_id??b?.grant_id??null,T=e.run??N??b??B,re=await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:h,app:T?.grantee??"app:terminal"})).launch,ne,e.model);await ve(_e(re),{cwd:M,profileId:h}),await Xn({grantee:T?.grantee??"app:terminal",sub:T?.sub,grant_id:T?.grant_id,profile_id:h});const te=B?.node_id??null;let C,j=M;const z=P&&await ze(h)?await He(h,W??e.worktreeCwd??e.cwd,f,e.worktreeBase):void 0,H=P&&z===void 0?await Ge(h):null;try{P&&z===void 0&&(C=H!==null?await Xe(H,e.worktreeCwd??e.cwd,f,e.worktreeBase):await Ke(e.worktreeCwd??e.cwd,f,e.worktreeBase),j=C.path);const p=P?await ke((await ce(e.kind,w,{lifecycle:y,hasManager:!s,model:e.model,modelOverride:e.model!==void 0,cwd:j,profileId:h,app:T?.grantee??"app:terminal"})).launch,ne,e.model):re;z!==void 0&&(p.worktree=z),P&&await ve(_e(p),{cwd:j,profileId:h});const n=await Fe({kind:e.kind,mode:w,lifecycle:y,cwd:j,name:e.name??e.kind,description:e.description,parent:s?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:te,spawnedBy:s?d??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:S,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:m,modelOverride:e.model===void 0?void 0:p.model,...C!==void 0?{managedWorktree:C}:{},...f!==void 0?{nodeId:f}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:p});if(o?.(n.node_id),e.forkFrom!==void 0)try{await jn(n.node_id,te??null)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(await Ye(n.node_id,e.prompt),e.situationalContext!==void 0&&await Qe(n.node_id,Ze(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const G=e.prompt!=="",ye=`${G&&e.wakeOrigin!==void 0?`${nn(e.wakeOrigin)}
|
|
2
2
|
|
|
3
|
-
`:""}${e.prompt}`;w==="orchestrator"&&await en(n.node_id,{goal:e.prompt.trim()}),await rr(n);let oe;if(m!==void 0)try{const i=X(m);if(i===null)throw new Error(`invalid fork source ${m}`);const u=await D().fork(i,n.node_id);oe=(await D().header(u)).path}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const g=We(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Be(n.node_id)},G){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[tn]=rn(i),await on(g,n)}const E=me();if(await fn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await $n(n.profile_id??null):null;if(u!==null){q("birth",performance.now()-t);const O=await nr(n,u,g);if(O==="started"||O==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await V(n.node_id,i),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}if(Je()&&!$e(n.cwd))throw new Ve({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await E.reserveSlot(n.node_id),$=ie?await un(n.node_id):null;if($?.verdict==="too_small"){E.releaseReservation(n.node_id);const i=cn($);throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(!ie||$?.verdict==="denied")return $?.verdict==="denied"&&E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:$?.verdict==="denied"?{reason:"app_memory",free_bytes:$.free_bytes,needed_bytes:$.needed_bytes}:{reason:"broker_cap",live_count:await E.occupancy(),hard_cap:Q().automaticReviveCap}}),{node:await
|
|
3
|
+
`:""}${e.prompt}`;w==="orchestrator"&&await en(n.node_id,{goal:e.prompt.trim()}),await rr(n);let oe;if(m!==void 0)try{const i=X(m);if(i===null)throw new Error(`invalid fork source ${m}`);const u=await D().fork(i,n.node_id);oe=(await D().header(u)).path}catch(i){throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}const g=We(n,{prompt:ye,resumeSessionPath:oe});if(g.env={...g.env,CRTR_SUBTREE:await Be(n.node_id)},G){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};g.env[tn]=rn(i),await on(g,n)}const E=me();if(await fn(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await $n(n.profile_id??null):null;if(u!==null){q("birth",performance.now()-t);const O=await nr(n,u,g);if(O==="started"||O==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await V(n.node_id,i),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}if(Je()&&!$e(n.cwd))throw new Ve({error:"profile_environment_missing",message:`${n.cwd} does not exist on the control plane, and profile ${n.profile_id??"(none)"} has no environment to run it in.`,next:"Bind the profile to the environment of the computer that holds this directory, then retry."});const ie=await E.reserveSlot(n.node_id),$=ie?await un(n.node_id):null;if($?.verdict==="too_small"){E.releaseReservation(n.node_id);const i=cn($);throw await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),i}if(!ie||$?.verdict==="denied")return $?.verdict==="denied"&&E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:$?.verdict==="denied"?{reason:"app_memory",free_bytes:$.free_bytes,needed_bytes:$.needed_bytes}:{reason:"broker_cap",live_count:await E.occupancy(),hard_cap:Q().automaticReviveCap}}),{node:await _(n.node_id),frozen:!0,window:null,session:null};const be=await kn(n.node_id),{automaticReviveCap:xe}=Q();let F;try{F=await fe(n.node_id,{daemonEpoch:E.epoch(),cap:xe})}catch(i){if(!(i instanceof ue))throw i;return E.releaseReservation(n.node_id),await V(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await _(n.node_id),frozen:!0,window:null,session:null}}g.env={...g.env,CRTR_EXECUTION_ID:F};let K;try{K=await qn(n.node_id,g,{cwd:n.cwd,name:we(n),resuming:!1})}catch(i){throw await L(F,{reason:"launch_failed"}),i}finally{E.releaseReservation(n.node_id)}if(K.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await L(F,{reason:"launch_failed"}),await I(n.node_id,"crash",{reason:"launch_failed",outcome:R(i)}),U(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await sn(F,n.node_id,K.pid)==="shutdown")throw await L(F,{reason:"superseded"}),Z.teardown(n.node_id),U(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(l&&e.readiness==="await"){const i=await pn(n.node_id,K.exited);if(!i.ready){const u=Vn(n.node_id,i);v({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const O=await be.explanation();throw await Jn(n.node_id,new Error(O??u.text)),U(O!==null?`the root broker ${n.node_id} could not start \u2014 ${O}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,O!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let ae=null,de=null;if(!s&&d!==null&&Bn("user").auto_open_child_viewers)try{const i=await mn(d);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await wn(n.node_id,i.session??"",{name:we(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:G});u!==null&&u.pane!==null&&u.pane!==""&&(de=u.session,ae=hn(u.pane))}}catch{}return{node:await _(n.node_id),frozen:!1,window:ae,session:de}}catch(p){throw C!==void 0&&f!==void 0&&await _(f)===null&&(H!==null?await qe(H,C):await Ue(C)),p}}c(ge,"spawnChildPrepared");async function ct(e){return ge(e)}c(ct,"spawnChild");async function rr(e){const r=Hn(e.cwd,e.profile_id).plans.get("node:start")??[];await Kn(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await Y(e.node_id),contextDir:await J(e.node_id),jobDir:dn(e.node_id)},runtime:{isBirth:!0,canvasHome:an(),profile:e.profile_id??null}})}c(rr,"invokeBirthLifecycleHooks");const tr=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function ut(e,r,o){const t=await _(e);if(t===null)throw k(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const a=await pe(e),s=await J(e);try{await D().header(X(a)),Ce(s,Ee.R_OK)}catch(d){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${d.message}`)}return ge({kind:t.kind,mode:"base",cwd:t.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...o===void 0?{}:{actor:o},profile:t.profile_id,model:t.model_override??void 0,...r===void 0?{}:{scopes:r}},async d=>{const w=await J(d);ln(await Y(e),s,await Y(d),w,tr)})}c(ut,"forkNode");export{ke as appPaidLaunch,ve as assertLaunchModelRegistered,ut as forkNode,rr as invokeBirthLifecycleHooks,pe as resolveForkSource,Qn as resolveProfileId,Zn as resolveSpawner,ct as spawnChild,ge as spawnChildPrepared};
|
|
@@ -4,6 +4,7 @@ export interface StartIdentity {
|
|
|
4
4
|
grantee?: string;
|
|
5
5
|
sub?: string | null;
|
|
6
6
|
grant_id?: string | null;
|
|
7
|
+
profile_id?: string | null;
|
|
7
8
|
}
|
|
8
9
|
/** The start candidate for an identity, or null when no person is known yet (a terminal node before its first grant snapshot). */
|
|
9
10
|
export declare function startCandidateOf(who: StartIdentity): Promise<StartCandidate | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var o=Object.defineProperty;var n=(t,a)=>o(t,"name",{value:a,configurable:!0});import{check as s,environmentPayerOfProfile as l,findRefusal as p,payerOf as u}from"../ledger/index.js";import{RunError as r}from"../runs/operations.js";import{grantStanding as f,payerOfGrant as d}from"../grants/mirror.js";import{callerTerminalGrant as m}from"../grants/terminal.js";async function i(t){const a=t.grantee??"app:terminal",e=t.sub??(a==="app:terminal"?(await m())?.sub:void 0)??null;if(e===null)return null;const c=await d(t.grant_id);return{scope:"start",payer:u({call:"start",grantPayer:c,sub:e,grantee:a,environmentPayer:await l(t.profile_id)}).payer,sub:e,grantee:a}}n(i,"startCandidateOf");async function w(t){const a=await i(t);a!==null&&await s(a)}n(w,"checkStart");async function O(t){if(!t.grant_id||(t.grantee??"app:terminal")==="app:terminal")return;const a=await f(t.grant_id);if(a.standing==="inactive"&&a.status!==null)throw new r(401,"grant_revoked","the node's grant is not active")}n(O,"checkGrantActive");async function P(t){const a=await i(t);return a===null?null:await p(a)}n(P,"startRefusal");function R(t){return t instanceof r&&(t.code==="cap_exhausted"||t.code==="grant_revoked")}n(R,"isStartRefusal");export{O as checkGrantActive,w as checkStart,R as isStartRefusal,i as startCandidateOf,P as startRefusal};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var n=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createHash as b,randomUUID as R}from"node:crypto";import{openDb as L}from"../canvas/db.js";import{claimReconcilerLease as C,releaseReconcilerLease as E,renewReconcilerLease as W}from"../canvas/reconciler-leases.js";import{claimWarmSpare as M,deleteNode as w,getNode as p,listNodes as P,listWarmSpares as u,registerWarmSpare as I,unregisterWarmSpare as y,updateNode as A,warmSpareCount as h}from"../canvas/index.js";import{recordedPidLiveness as D}from"../canvas/pid.js";import{nowIso as
|
|
1
|
+
var $=Object.defineProperty;var n=(e,r)=>$(e,"name",{value:r,configurable:!0});import{createHash as b,randomUUID as R}from"node:crypto";import{openDb as L}from"../canvas/db.js";import{claimReconcilerLease as C,releaseReconcilerLease as E,renewReconcilerLease as W}from"../canvas/reconciler-leases.js";import{claimWarmSpare as M,deleteNode as w,getNode as p,listNodes as P,listWarmSpares as u,registerWarmSpare as I,unregisterWarmSpare as y,updateNode as A,warmSpareCount as h}from"../canvas/index.js";import{recordedPidLiveness as D}from"../canvas/pid.js";import{nowIso as _}from"../fs-utils.js";import{admitNodeCreate as O}from"../command-hooks/lifecycle-create.js";import{isDrained as T}from"../../daemon/drain.js";import{spawnChildPrepared as H}from"./spawn.js";import{remoteEnvironmentOf as F}from"./blaxel-environment.js";import{newNodeId as K}from"./nodes.js";import{checkStart as U}from"./start-check.js";import{buildLaunchSpecAsync as j}from"./launch.js";import{setModelLive as B}from"./model-swap.js";import{setSituationalContextLive as G}from"./situational-live.js";import{deliverBearingsLive as J}from"./deliver-live.js";import{closeNode as g}from"./close.js";import{transition as z}from"./lifecycle.js";import{stopNodeSandboxes as Q}from"../spaces/stop.js";function v(){return process.env.CRTR_WARM_POOL!=="0"}n(v,"warmPoolEnabled");function V(e,r,a){const t=Object.entries(a.env??{}).sort(([s],[i])=>s<i?-1:s>i?1:0),o=JSON.stringify([e,r,a.tools??[],a.extensions??[],a.systemPrompt??null,t]);return b("sha256").update(o).digest("hex").slice(0,32)}n(V,"warmRecipeKey");async function d(e){const{launch:r}=await j(e.kind,e.mode,{lifecycle:"resident",hasManager:!1,...e.model!==null?{model:e.model}:{},cwd:e.cwd,profileId:e.profileId,app:"app:terminal"});return{key:V(e.cwd,e.profileId,r),launch:r,request:e}}n(d,"resolveRecipe");async function S(e){const r=e.creator===null?null:await p(e.creator);await U({grantee:r?.grantee??"app:terminal",sub:r?.sub,grant_id:r?.grant_id,profile_id:r?.profile_id})}n(S,"checkClaimantStart");async function ve(e,r={},a){await S(e);const t=await d(e);if(await h(t.key)===0)return null;const o=_(),s=await O({kind:e.kind,mode:e.mode,cwd:e.cwd,profile:e.profileId,root:!0,parentId:null,requestingNodeId:e.creator,lifecycle:"resident",replaces:null},e.creator===null?"app:terminal":await(async()=>{const c=await p(e.creator);if(!c?.grantee)throw new Error("warm node creator has no app");return c.grantee})());let i;try{i=await M(t.key,o,r)}finally{s()}return i===null?null:k(i,t,o,a)}n(ve,"claimWarmNode");async function Se(e,r,a){return await S(e),k(r,await d(e),_(),a)}n(Se,"resumeWarmClaim");async function k(e,r,a,t){const{request:o}=r,i=(await p(e))?.launch?.model;await A(e,{created:a,kind:o.kind,mode:o.mode,name:o.name??o.kind,creator:o.creator,launch:r.launch,persona_ack:{kind:o.kind,mode:o.mode,lifecycle:"resident"},...o.model!==null?{model_override:o.model}:{}});try{t?.(e)}catch(l){return await m(e,"birth preparation",l)}try{await J(e)}catch(l){return await m(e,"bearings delivery",l)}const c=r.launch.model;if(c!==void 0&&c!==i)try{await B(e,c,r.launch.modelIntent)}catch(l){return await m(e,"model swap",l)}if(o.situationalContext!==null)try{await G(e,o.situationalContext)}catch(l){return await m(e,"situational-context delivery",l)}return e}n(k,"completeWarmClaim");async function m(e,r,a){console.error(`[warm-pool] ${r} failed on claim; closing the spare: ${a.message}`);try{await g(e)}catch{}return null}n(m,"abandonSpare");const X=3600*1e3;async function ke(){const e=[];let r;try{r=await u()}catch(t){return console.error(`[warm-pool] spare scan failed: ${t.message}`),e}const a=Date.now()-X;for(const t of r){if(await Y(t.node_id))continue;const o=Date.parse(t.created),s=Number.isNaN(o)||o<a,i=D(t.pi_pid,t.pi_pid_identity),c=(t.status==="active"||t.status==="idle")&&i==="alive";if(!(c&&!s)&&!(i==="indeterminate"&&!s))try{if(!await y(t.node_id))continue;if(c)try{await g(t.node_id)}catch{}await w(t.node_id),e.push(t.node_id)}catch(l){console.error(`[warm-pool] reap failed for ${t.node_id}: ${l.message}`)}}return e}n(ke,"reapStaleSpares");async function xe(){for(const e of await u()){if(!await y(e.node_id))continue;await z(e.node_id,"cancel",{reason:"closed"});const r=await Q(e.node_id,"warm_pool_drained");if(!r.confirmed)throw new Error(`drain: the broker of spare ${e.node_id} could not be confirmed stopped: ${r.error?.message??"unknown"}`);await w(e.node_id)}}n(xe,"emptyWarmPool");const f=6e4;async function x(e,r){const a=R();if(await C(e,r,a,f)===void 0)return;const t=setInterval(()=>{W(e,r,a,f).catch(()=>{})},f/3);return t.unref(),async()=>{clearInterval(t),await E(e,r,a)}}n(x,"holdMintLease");async function Y(e){return await(await L()).prepare("SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND expires_at > ?").get("warm-pool-mint",e,new Date().toISOString())!==void 0}n(Y,"mintLeaseHeld");function Ne(e){if(v())try{d({...e,model:null,situationalContext:null}).then(N).catch(r=>console.error(`[warm-pool] recipe resolution failed: ${r.message}`))}catch(r){console.error(`[warm-pool] recipe resolution failed: ${r.message}`)}}n(Ne,"refillWarmPool");async function N(e){if(await T())return;const{key:r}=e;if(await F(e.request.profileId)!==null)return;const a=await x("warm-pool",r);if(a!==void 0){if(await h(r)>0){await a();return}Z(e,await K()).finally(()=>a().catch(()=>{}))}}n(N,"mint");async function Z({key:e,request:r},a){const t=await x("warm-pool-mint",a);if(t===void 0){console.error(`[warm-pool] mint refused for ${r.kind}: the mint lease of ${a} is held elsewhere`);return}try{await H({nodeId:a,kind:r.kind,mode:r.mode,cwd:r.cwd,prompt:"",root:!0,readiness:"await",profile:r.profileId},async o=>{await I(o,e)})}catch(o){console.error(`[warm-pool] mint failed for ${r.kind}: ${o.message}`)}finally{await t().catch(()=>{})}}n(Z,"birthSpare");const q=2;async function $e(){if(!v())return;let e;try{const r=new Set;e=[];for(const a of(await P({status:["active","idle"]})).reverse()){if(a.parent!==null||a.kind==="human")continue;const t=a.profile_id??null;if(!r.has(t??"")&&(r.add(t??""),e.push({cwd:a.cwd,profileId:t}),e.length>=q))break}}catch(r){console.error(`[warm-pool] prewarm scan failed: ${r.message}`);return}for(const r of e)try{d({kind:"general",mode:"base",cwd:r.cwd,profileId:r.profileId,model:null,situationalContext:null,name:null,creator:null}).then(N).catch(a=>console.error(`[warm-pool] prewarm failed for ${r.cwd}: ${a.message}`))}catch(a){console.error(`[warm-pool] prewarm failed for ${r.cwd}: ${a.message}`)}}n($e,"prewarmRecentRecipes");export{Z as birthSpare,ve as claimWarmNode,xe as emptyWarmPool,x as holdMintLease,$e as prewarmRecentRecipes,ke as reapStaleSpares,Ne as refillWarmPool,Se as resumeWarmClaim,v as warmPoolEnabled};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var u=(e,r)=>$(e,"name",{value:r,configurable:!0});import{existsSync as
|
|
1
|
+
var $=Object.defineProperty;var u=(e,r)=>$(e,"name",{value:r,configurable:!0});import{existsSync as _}from"node:fs";import{assertGranteeRunsHere as N}from"../runtime/unsandboxed.js";import{randomUUID as O}from"node:crypto";import{join as h}from"node:path";import{getNode as R}from"../canvas/canvas.js";import{nodeAgentDir as k,nodeHome as H,nodeRunDir as K}from"../canvas/paths.js";import{appSpace as B}from"../layout.js";import{activeGrant as g,activeGrantForApp as S,grantFor as I,grantsGeneration as y}from"../grants/mirror.js";import{emitEvent as G}from"../events/emit.js";import{ensureAppSpace as F}from"./space.js";import{compileLaunch as A,launchStillGranted as M}from"./mounts.js";import{pinSandboxRuntimeHome as j}from"./runtime-home.js";import{sandboxCacheEnv as q}from"./cache-env.js";import{launcherRequest as b}from"../../launcher/client.js";import{LAUNCHER_SOCKET as D}from"../../launcher/spec.js";import{isCloudRole as U}from"../canvas/person.js";import{launchSub as E}from"../runs/node-sub.js";function W(e){return`cron-${e}`}u(W,"cronLaunchId");function le(){if(process.platform!=="linux")return!1;if(_(D))return!0;throw new Error("root launcher socket is unavailable; refusing an unsandboxed app process")}u(le,"appProcessSandboxed");function me(){return L??(process.platform==="linux"&&_(D))}u(me,"appProcessesSandboxed");let L;function pe(e){L=e}u(pe,"__setAppProcessesSandboxedForTest");async function we(e,r,n,a=!1,o,d){const t=n===void 0?null:await R(n),s=d!==void 0?d.grantId?await g(d.grantId):await I(e,d.sub):t?null:await S(e);if((d!==void 0||!t)&&!s)throw new Error(`no active grant for ${e}`);return(await A({nodeId:n??"proc-cwd-check",app:e,...d!==void 0?{sub:d.sub,grantId:s?.id??null,scopes:d.scopes}:{sub:t?E(t.sub,t.node_id):s.sub,grantId:t?t.grant_id??null:s.id,scopes:t?.scopes??null},command:["true"],env:{},...n===void 0?{withoutNode:!0}:{},...o===void 0?{}:{folder:o},isolated:t?.isolated===!0||a,auditMissing:u(()=>{},"auditMissing")})).mounts.some(({source:c})=>r===c||r.startsWith(c==="/"?"/":`${c}/`))}u(we,"cwdIsMounted");async function P(e,r="SIGKILL",n){if(!("ok"in await b({operation:"stop",pid:e,signal:r,...n===void 0?{}:{nodeId:n}})))throw new Error("launcher did not stop process")}u(P,"stopAppProcess");function z(e,r,n,a,o){return a?o??k(e,r):n}u(z,"appProcessCwd");async function he(e){if(U())throw new Error("a cloud role launches no app process; the node runs in its sandbox");if(e.cron!==void 0&&(e.nodeId!==void 0||e.principal===void 0))throw new Error("a cron launch has a stored principal and no node");const r=e.nodeId===void 0?null:await R(e.nodeId);if(e.nodeId!==void 0&&!r)throw new Error(`missing node ${e.nodeId}`);const n=r?.grantee??e.app??"app:terminal";if(N(n),e.app!==void 0&&e.app!==n)throw new Error("app does not match node");const a=e.principal;let o=null;if(a!==void 0){if(o=a.grantId?await g(a.grantId):await I(n,a.sub),!o||o.grantee!==n||o.sub!==a.sub)throw new Error(`no active grant for ${n}`)}else if(r){if(n!=="app:terminal"&&!(r.grant_id?await g(r.grant_id):await I(n,E(r.sub,r.node_id))))throw new Error(`no active grant for ${n}`)}else if(o=await S(n),!o)throw new Error(`no active grant for ${n}`);await F(n);const d=e.cron===void 0?e.nodeId??`proc-${O()}`:W(e.cron.executionId),t=r?.isolated===!0||e.isolated===!0;if(t&&!r&&e.folder===void 0)throw new Error("isolated process requires a live node");const s=B(n),m=z(d,n,e.cwd,t,e.folder),c=r?H(d,n,t):t&&e.folder!==void 0?h(e.folder,"home"):s.home,C=j(Object.fromEntries(Object.entries({...e.env,...process.platform==="linux"?q(n):{},HOME:c,PI_CODING_AGENT_DIR:h(c,".pi","agent"),PWD:m,...e.nodeId===void 0&&e.cron===void 0?{}:{CRTR_API_SOCKET:h(K(d),"cli.sock")}}).filter(i=>i[1]!==void 0))),x=a!==void 0?{nodeId:d,app:n,sub:a.sub,grantId:o?.id??null,scopes:a.scopes}:{nodeId:d,app:n,sub:r?E(r.sub,r.node_id):o.sub,grantId:r?r.grant_id??null:o.id,scopes:r?.scopes??null},T=u(async()=>{const i=await A({...x,command:e.command,env:C,...e.nodeId===void 0?{withoutNode:!0}:{},isolated:t,cwd:m,...e.folder===void 0?{}:{folder:e.folder},...e.cron===void 0?{}:{cron:e.cron.anchorDir===void 0?{}:{anchorDir:e.cron.anchorDir}},...e.pluginRoot===void 0?{}:{pluginRoot:e.pluginRoot},auditMissing:u(w=>G({level:"warn",event:"process.mount.missing",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{source:w}}),"auditMissing")});if(e.pluginRoot!==void 0&&(i.pluginRoot=e.pluginRoot),e.capture===!1){if(e.nodeId===void 0||e.stdin!==void 0)throw new Error("uncaptured process requires a node and no stdin")}else i.capture={stdoutBytes:e.stdoutBytes??256*1024,stderrBytes:e.stderrBytes??256*1024,...e.stderrTail?{stderrTail:!0}:{},...e.stdin===void 0?{}:{stdin:e.stdin}};return i},"compile");let f;for(let i=0;i<2&&f===void 0;i++){const w=await y(),v=await T(),l=await b({operation:"launch",spec:v});if(!("pid"in l))throw new Error("launcher did not return a process id");if(await y()===w||await M(x,v)){f=l.pid;break}G({level:"info",event:"process.launch.regranted",...e.nodeId===void 0?{}:{node_id:e.nodeId},fields:{pid:l.pid}}),await P(l.pid,"SIGKILL").catch(()=>{})}if(f===void 0)throw new Error("grant changed during every launch attempt");const p=f;return{pid:p,get completion(){return b({operation:"wait",pid:p}).then(i=>{if(!("result"in i))throw new Error("launcher did not return process completion");return i.result})},stop:u((i="SIGKILL")=>P(p,i,e.cron===void 0?e.nodeId:d),"stop")}}u(he,"launchAppProcess");export{pe as __setAppProcessesSandboxedForTest,z as appProcessCwd,le as appProcessSandboxed,me as appProcessesSandboxed,W as cronLaunchId,we as cwdIsMounted,he as launchAppProcess,P as stopAppProcess};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var M=Object.defineProperty;var
|
|
1
|
+
var M=Object.defineProperty;var m=(e,t)=>M(e,"name",{value:t,configurable:!0});import{queueJobStop as C}from"../../cron/machine-fire.js";import{killBashJobObject as D,recordBashJobObject as L}from"../../../core/spaces/stop.js";import{readerFor as x}from"../reader.js";import{join as H}from"node:path";import{createFileBeneath as $,existsBeneath as k,unlinkBeneath as U}from"../../../core/spaces/open-beneath.js";import{launchAppProcess as z,appProcessSandboxed as G}from"../../../core/spaces/process.js";import{BASH_JOB_SUPERVISOR_SCRIPT as Q}from"../../../core/bash-job-supervisor.js";import{resolveAdmittedHostCommand as X}from"../../../core/runtime/spawn-env.js";import{requireCurrentExecution as E}from"./broker-recovery.js";import{isSafeNodeId as K}from"../../../core/canvas/paths.js";import{contextDir as J}from"../../../core/canvas/node-agent-paths.js";import{getNode as S}from"../../../core/canvas/canvas.js";import{isBrokerLive as W}from"../../../core/runtime/model-swap.js";import{assertNotFinalized as Y}from"../../../core/runtime/reopen.js";import{reviveNode as Z}from"../../../core/runtime/revive.js";import{checkStart as V}from"../../../core/runtime/start-check.js";import{bashJobPaths as N,isBashJobProcessGroupAlive as tt,isSafeBashJobId as O,readBashNiceness as et,signalBashJob as ot,stopBackgroundBashJob as nt}from"../../../core/bash-jobs.js";import{applyJobReport as rt,jobRow as it,ownerRunsRemotely as A,runningJobs as q,setJobDeadline as T,markJobQuietOk as at}from"../../../core/graph/jobs.js";import{withCanvasWrite as B,openDb as h}from"../../../core/canvas/db.js";import{getById as I}from"../../../core/graph/objects.js";import{blobStore as P}from"../../../core/blobs/index.js";import{ApiError as a}from"../../../api/index.js";import{BASH_JOB_OUTPUT_DEFAULT_BYTES as st,BASH_JOB_OUTPUT_MAX_BYTES as dt}from"../../../api/index.js";import{notFound as ut}from"../../../core/errors.js";import{freshChildNodeExecPath as pt}from"../../../core/runtime/branded-host.js";async function y(e){const t=e.params.id;if(t===void 0||!K(t))throw new a(400,"invalid_node_id",`invalid node id: ${JSON.stringify(t)}`);if(await S(t)===null)throw ut(`unknown node: ${t}`,{received:t});const r=e.params.jobId;if(r!==void 0){if(!O(r))throw new a(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(r)}`);return{nodeId:t,jobId:r,dir:await J(t)}}return{nodeId:t,dir:await J(t)}}m(y,"requireTarget");async function lt(e){const{nodeId:t,dir:o}=await y(e);if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may start a job");const r=e.body;if(!r||typeof r!="object"||Array.isArray(r))throw new a(400,"invalid_request","job.start requires a JSON body");const i=r;await E(t,i.expected_execution_id);const n=i.job_id,s=i.cwd,u=i.env;if(typeof n!="string"||!O(n)||typeof s!="string"||!u||typeof u!="object"||Array.isArray(u)||Object.entries(u).some(([c,p])=>!/^[A-Za-z_][A-Za-z0-9_]*$/.test(c)||typeof p!="string"))throw new a(400,"invalid_request","invalid job id, cwd or environment");const f=await S(t);if(await V({grantee:f.grantee??"app:terminal",sub:f.sub,grant_id:f.grant_id,profile_id:f.profile_id}),!G())throw new a(400,"invalid_request","job.start is only used with the root launcher");const d=N(o,n);if(!(k(d.root,d.jobRun)||k(d.root,d.jobBg))||![d.cmdSh,d.jobLog].every(c=>k(d.root,c)))throw new a(404,"job_not_found","job was not prepared by this node");const l=H(d.dir,"job.starting");try{$(d.root,l,"")}catch(c){throw c.code==="EEXIST"?new a(409,"job_already_started","job was already started"):c}let b;try{const c=u,p=X("bash",c,s),g=await S(t),j=await pt();return b=await z({nodeId:t,app:g.grantee??"app:terminal",isolated:g.isolated,cwd:s,env:c,capture:!1,command:[p,"-c",Q,"--",d.cmdSh,d.jobLog,d.jobExit,d.jobRun,d.jobDone,p,String(et(o)),j,d.jobActivity]}),$(d.root,d.jobPgid,String(b.pid),384),$(d.root,d.jobPgidIdentity,`launcher:${b.pid}`,384),{status:201,body:{pid:b.pid}}}catch(c){if(b!==void 0)try{await b.stop()}catch(p){throw new AggregateError([c,p],`job ${n} launched but could not be recorded or stopped`)}try{U(d.root,l)}catch(p){if(p.code!=="ENOENT")throw p}throw c}}m(lt,"handleStart");async function ct(e){const{nodeId:t}=await y(e),o=Date.now(),r=await A(await h(),t);return{status:200,body:(await q(await h(),t)).map(n=>({job_id:n.jobId,command:n.command,purpose:n.purpose,started_at:new Date(n.startedAtMs).toISOString(),elapsed_ms:Math.max(0,o-n.startedAtMs),output_key:n.outputKey,deadline_at:n.deadlineAtMs===null?null:new Date(n.deadlineAtMs).toISOString(),pgid:n.pgid,pgid_alive:!r&&n.pgid!==null&&n.pgidIdentity!==null&&tt(n.pgid,n.pgidIdentity)}))}}m(ct,"handleList");function R(e,t,o){const r=e.query.get(t);if(r===null)return;const i=Number(r);if(!/^[0-9]+$/.test(r)||!Number.isSafeInteger(i)||i<1||i>o)throw new a(400,"invalid_request",`${t} must be an integer from 1 to ${o}`);return i}m(R,"boundedQueryInt");async function bt(e){const{nodeId:t,jobId:o}=await y(e),r=R(e,"tail_lines",Number.MAX_SAFE_INTEGER),i=R(e,"max_bytes",dt)??st,n=await h(),s=await I(n,o??"");if(s===null||s.type!=="job"||s.owner!==t||s.deleted_at!==null)throw new a(404,"job_not_found",`no job ${String(o)} for ${t}`);const u=await it(n,s);if(u===null)throw new Error(`job object ${s.id} has no jobs row`);const f=await P(),d=await f.list(`${u.output_key}/`),v=[];let l=0,b=0,c=d.length;for(;c>0&&l<=i&&(r===void 0||b<=r+1);){const w=d[--c],_=await f.get(w);if(_===null)throw new Error(`job ${s.id} output chunk ${w} is listed but cannot be read`);v.unshift(_),l+=_.length;for(const F of _)F===10&&b++}let p=Buffer.concat(v),g=c>0;if(p.length>i){p=p.subarray(p.length-i);let w=0;for(;w<p.length&&(p[w]&192)===128;)w++;p=p.subarray(w),g=!0}let j=p.toString("utf8");if(r!==void 0){const w=j.split(`
|
|
2
2
|
`),_=w[w.length-1]===""?r+1:r;w.length>_&&(j=w.slice(w.length-_).join(`
|
|
3
|
-
`),g=!0)}return{status:200,body:{job_id:s.id,output:j,truncated:g}}}
|
|
3
|
+
`),g=!0)}return{status:200,body:{job_id:s.id,output:j,truncated:g}}}m(bt,"handleOutput");async function wt(e){const{nodeId:t,jobId:o,dir:r}=await y(e);if(o===void 0)throw new a(400,"invalid_request","a job id is required");if(e.query.get("foreground")==="1"){if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may abort its foreground job");await E(t,e.body?.expected_execution_id);const l=await nt(r,o,!0,t);if(l.kind==="missing")throw new a(404,"job_not_found",`no job ${o} for ${t}`);if(l.kind==="retired")throw new a(404,"job_not_found",`job ${o} for ${t} is no longer running`);if(l.kind==="not-stoppable")throw new a(409,"job_not_stoppable",`job ${o} recorded no trusted process identity`);return{status:200,body:{node_id:t,job_id:o,signaled:l.signaled}}}const n=(await q(await h(),t)).find(l=>l.jobId===o);if(n===void 0)throw new a(404,"job_not_found",`no running background job ${o} for ${t}`);const s=await A(await h(),t);if(!s&&(n.pgid===null||n.pgidIdentity===null))throw new a(409,"job_not_stoppable",`job ${o} reported no trusted process identity`);await Y(t);const u=s?!0:await ot(n.pgid,n.pgidIdentity,t);await D(o,async l=>{const b=await x(l,e);return b.class==="person"?b.person:b.class==="app"?b.app:b.node});let f;if(s)try{await C(t,o)}catch(l){f=l instanceof Error?l.message:String(l)}const d=await S(t);if(d!==null&&!W(d))try{await Z(t,{resume:!0,capacity:"freeze"})}catch{}return{status:200,body:{node_id:t,job_id:o,signaled:u,...s?{stop_pending_on_machine:!0}:{},...f===void 0?{}:{stop_queue_error:f}}}}m(wt,"handleStop");async function ft(e){const{nodeId:t,jobId:o,dir:r}=await y(e);if(o===void 0)throw new a(400,"invalid_request","a job id is required");if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may record its job");const i=e.body,n=N(r,o),s=i?.purpose,u=i?.deadline_at_ms;if(typeof i?.command!="string"||s!=null&&typeof s!="string"||u!=null&&!Number.isFinite(u))throw new a(400,"invalid_request","job.background requires command, and optionally purpose and deadline_at_ms");if(!await A(await h(),t)&&!k(n.root,n.jobBg))throw new a(404,"job_not_found",`job ${o} of ${t} is not backgrounded`);return{status:201,body:{id:(await L(t,o,{command:i.command,purpose:s??null,deadlineAtMs:u??null})).id}}}m(ft,"handleBackground");async function mt(e,t){if(t===void 0)throw new a(400,"invalid_request","a job id is required");const o=await I(await h(),t);if(o===null||o.type!=="job"||o.owner!==e)throw new a(404,"job_not_found",`no job ${t} for ${e}`);if(!(await q(await h(),e)).some(r=>r.jobId===t))throw new a(409,"job_not_running",`job ${t} for ${e} is no longer running`);return t}m(mt,"requireRunningJob");async function ht(e,t,o){const r=await I(await h(),t);if(r===null||r.type!=="job"||r.owner!==e)throw new a(404,"job_not_found",`no job ${String(t)} for ${e}`);if(!(await q(await h(),e)).some(s=>s.jobId===t))throw new a(409,"job_not_running",`job ${String(t)} for ${e} is no longer running`);const i=o.output;if(i!==void 0){if(!Number.isSafeInteger(i.seq)||i.seq<0||typeof i.data_base64!="string")throw new a(400,"invalid_request","output requires seq and data_base64");const s=await B(async u=>await u.prepare("SELECT output_key FROM jobs WHERE object = ?").get(t));await(await P()).put(`${s.output_key}/${String(i.seq).padStart(8,"0")}`,Buffer.from(i.data_base64,"base64"))}const n=o.activity;if(n!==void 0&&(!Number.isFinite(n.last_ms)||!Number.isFinite(n.sampled_ms)||!Array.isArray(n.files)))throw new a(400,"invalid_request","activity requires last_ms, sampled_ms and files");await B(async s=>rt(s,t,{...typeof o.pgid=="number"?{pgid:o.pgid}:{},...typeof o.pgid_identity=="string"?{pgidIdentity:o.pgid_identity}:{},...typeof o.exit_code=="number"?{exitCode:o.exit_code}:{},...o.vanished===!0?{vanished:!0}:{},...n===void 0?{}:{activity:{lastActivityMs:n.last_ms,sampledAtMs:n.sampled_ms,files:n.files}}}))}m(ht,"storeJobReport");async function _t(e){const{nodeId:t,jobId:o}=await y(e);if(e.principal.class!=="broker"||e.principal.node!==t)throw new a(403,"permission_error","only this node\u2019s broker may report its job");const r=e.body;if(!r||typeof r!="object"||Array.isArray(r))throw new a(400,"invalid_request","job.report requires a JSON body");return await E(t,r.expected_execution_id),await ht(t,o??"",r),{status:204}}m(_t,"handleReport");async function yt(e){const{nodeId:t,jobId:o}=await y(e),r=await mt(t,o),i=e.body,n=i?.deadline_at_ms,s=i?.keep===!0;if(i?.quiet_ok!==!0&&!s&&!Number.isFinite(n))throw new a(400,"invalid_request","patch requires quiet_ok, keep or deadline_at_ms");if(s&&n!==void 0)throw new a(400,"invalid_request","keep and deadline_at_ms are exclusive");return await B(async u=>{i?.quiet_ok===!0&&await at(u,r),s?await T(u,r,null):Number.isFinite(n)&&await T(u,r,n)}),{status:204}}m(yt,"handlePatch");const Qt=[{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/background",handler:ft},{method:"POST",pattern:"/v1/nodes/:id/jobs/:jobId/report",handler:_t},{method:"PATCH",pattern:"/v1/nodes/:id/jobs/:jobId",handler:yt},{method:"POST",pattern:"/v1/nodes/:id/jobs/start",handler:lt},{method:"GET",pattern:"/v1/nodes/:id/jobs",handler:ct},{method:"GET",pattern:"/v1/nodes/:id/jobs/:jobId/output",handler:bt},{method:"DELETE",pattern:"/v1/nodes/:id/jobs/:jobId",handler:wt}];export{Qt as bashJobRoutes,ht as storeJobReport};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var x=Object.defineProperty;var
|
|
1
|
+
var x=Object.defineProperty;var p=(o,n)=>x(o,"name",{value:n,configurable:!0});import{realpathSync as E}from"node:fs";import{isAbsolute as y,relative as _,sep as h}from"node:path";import{ApiError as r}from"../../../api/index.js";import{coreHookCatalog as P}from"../../../build-root.js";import{getNode as T}from"../../../core/canvas/canvas.js";import{isSafeNodeId as A,nodeAgentDir as O}from"../../../core/canvas/paths.js";import{discoverHookRegistry as S}from"../../../core/command-hooks/discovery.js";import{EXEC_HOOK_TIMEOUT_MS as I}from"../../../core/command-hooks/transport/exec-invoke.js";import{buildAppProcessEnv as H}from"../../../core/runtime/spawn-env-rows.js";import{compileLaunch as N}from"../../../core/spaces/mounts.js";import{appProcessSandboxed as M,launchAppProcess as R}from"../../../core/spaces/process.js";import{requireCurrentExecution as B}from"./broker-recovery.js";import{actsAsPerson as C}from"../router.js";import{launchSub as W}from"../../../core/runs/node-sub.js";async function k(o,n,i){const t=o.params.id;if(t===void 0?!C(o.principal):!A(t)||o.principal.class!=="broker"||o.principal.node!==t)throw new r(403,"permission_error","hook execution requires its current node, or the person for the global route");const e=t===void 0?null:await T(t);if(t!==void 0&&!e)throw new r(404,"not_found","node not found");if(t!==void 0&&await B(t,n),typeof i!="string"||!y(i))throw new r(400,"invalid_request","hook cwd must be absolute");if(!M())throw new r(400,"invalid_request","hook routes require the root launcher");let d;try{d=E(i)}catch(u){throw u.code==="ENOENT"?new r(400,"invalid_request","hook cwd does not exist"):u}if(e){if(e.isolated===!0){const a=O(t,e.grantee??"app:terminal"),s=_(a,d);if(s===".."||s.startsWith(`..${h}`)||s.startsWith(h))throw new r(403,"permission_error","hook cwd is outside the isolated node folder")}const u=await N({nodeId:t,app:o.principal.class==="broker"?o.principal.app:"app:terminal",sub:W(e.sub,t),grantId:e.grant_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,command:[],env:{},auditMissing:p(()=>{},"auditMissing")}),f=p(a=>{const s=_(a,d);return s===""||s!==".."&&!s.startsWith(`..${h}`)&&!y(s)},"within");if(!u.mounts.some(a=>f(a.source)))throw new r(403,"permission_error","hook cwd is outside the node mounts")}return{id:t,node:e,cwd:d,app:e&&o.principal.class==="broker"?o.principal.app:"app:terminal"}}p(k,"checkedContext");async function b(o,n){const i=S(await P(),o,n);if(!i.valid)throw new r(422,"hook_registry_invalid","the effective hook registry is invalid");return i}p(b,"currentRegistry");async function $(o){const{node:n,cwd:i}=await k(o,o.query.get("expected_execution_id"),o.query.get("cwd"));return{status:200,body:{hooks:(await b(i,n.profile_id??null)).hooks.filter(e=>e.plugin.scope==="user").map(e=>({id:e.id,plugin:e.plugin.name,target:e.target,phase:e.phase,op:e.op,description:e.description,effects:e.effects,declarationIndex:e.declarationIndex}))}}}p($,"handleHookPlan");async function v(o){const n=o.body;if(!n||typeof n!="object"||Array.isArray(n))throw new r(400,"invalid_request","hook execution requires a JSON body");const i=n,{id:t,node:e,cwd:d,app:u}=await k(o,i.expected_execution_id,i.cwd);if(typeof i.hook_id!="string"||typeof i.request!="string")throw new r(400,"invalid_request","hook execution requires hook_id and request");const a=(await b(d,e?.profile_id??null)).hooks.find(c=>c.id===i.hook_id);if(!a)throw new r(404,"hook_not_registered","hook id is not registered for this cwd");const s=await H(d,e?.profile_id??null,u),m=await R({...t===void 0?{}:{nodeId:t},app:u,command:[a.executable,"--crtr-hook-protocol","1"],cwd:d,pluginRoot:a.plugin.root,env:s,stdin:i.request,stdoutBytes:10*1024*1024,stderrBytes:64*1024});let l,w=!1;try{const c=await Promise.race([m.completion,new Promise((D,g)=>{l=setTimeout(()=>{w=!0,m.stop().then(()=>g(new r(504,"hook_timeout","hook executable timed out")),q=>g(q))},I)})]);if(w)throw new r(504,"hook_timeout","hook executable timed out");if(c.stdoutTruncated)throw new r(502,"hook_output_limit","hook stdout exceeded the 10 MiB cap");return{status:200,body:{stdout:c.stdout,status:c.exitCode,signal:c.signal}}}finally{l&&clearTimeout(l)}}p(v,"handleHookExec");const te=[{method:"GET",pattern:"/v1/nodes/:id/hooks/plan",handler:$},{method:"POST",pattern:"/v1/nodes/:id/hooks/exec",handler:v},{method:"POST",pattern:"/v1/hooks/exec",handler:v}];export{te as hookExecRoutes};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var R=Object.defineProperty;var d=(t,e)=>R(t,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as T}from"../../../core/llm/body-limits.js";import{llmCallerOf as k,parseLlmRequest as
|
|
2
|
-
`)}:void 0,u?{cwd:u.cwd,profileId:u.profile_id??null}:void 0,l,await
|
|
3
|
-
`),{status:200}}const u=E(r.details,
|
|
1
|
+
var R=Object.defineProperty;var d=(t,e)=>R(t,"name",{value:e,configurable:!0});import{randomUUID as v}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as T}from"../../../core/llm/body-limits.js";import{environmentPayerOfNode as x}from"../../../core/ledger/index.js";import{llmCallerOf as k,parseLlmRequest as I,runLlm as N}from"../../../core/llm/run.js";import{RunError as i}from"../../../core/runs/operations.js";import{errorCodes as P}from"../../../api/error-codes.js";import{getNode as $}from"../../../core/canvas/canvas.js";import{emitEvent as G}from"../../../core/events/emit.js";import{boundedCause as H}from"../map.js";import{socketPrincipal as c}from"../server.js";import{activeGrant as L,activeGrantForApp as A,grantFor as M,grantsSource as S,payerOfGrant as j}from"../../../core/grants/mirror.js";import{parseUsageMonth as B,usageFor as C}from"../../../core/ledger/index.js";import{admit as D}from"../../../core/llm/breaker.js";function E(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:n,...a}=t;return a}d(E,"operatorDetails");const F="app:terminal";async function O(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run,environmentPayer:await x(t.node)};if(t?.class==="app"){const n=await S();if(n===null||n==="local")return{grantee:t.app};let a;try{a=await A(t.app)}catch{throw new i(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!a)throw new i(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:a.sub}}return{grantee:F}}d(O,"spendTarget");async function U(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await L(t.grant):await M(t.app,t.sub);if(!e&&await j(t.grant)==="app")throw new i(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return k(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await S();return e===null||e==="local"?void 0:k(await A(t.app))}}d(U,"llmCaller");function q(t){const e=P[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}d(q,"errorType");function J(t){if(t.code==="payment_refused"||t.code==="all_routes_exhausted"){const n=t.details?.payment;return n===void 0?{}:{payment:n}}if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.payment!==void 0?{payment:e.payment}:{},...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}d(J,"capFields");const se=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:T,handler:d(async({body:t,res:e,req:n,causedBy:a})=>{const f=v();e.setHeader("Request-Id",f);const p=new AbortController,h=d(()=>p.abort(),"abort");e.on("close",h);let g,b,y="none",w=!1;try{const o=I(t),s=o.model===void 0?void 0:D(o.model);if(typeof s=="number")return e.setHeader("Retry-After",String(s)),{status:503,body:{error:{code:"upstream_model_unavailable",message:`${o.model} is unavailable: the gateway's breaker is open`,details:{breaker:"open"},type:"server_error",origin:"runtime",retryable:!0,request_id:f}}};b=s;const r=c(n),u=r?.class==="broker"?await $(r.node):null;if(r?.class==="broker"&&!u)throw new i(401,"unauthorized","node not found");const l={...await O(r,u??void 0),request:f};w=!0;const _=await N(o,p.signal,o.stream?m=>{typeof m.served_model=="string"&&(g=m.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(m)}
|
|
2
|
+
`)}:void 0,u?{cwd:u.cwd,profileId:u.profile_id??null}:void 0,l,await U(r),a);return y=p.signal.aborted?"none":"ok",o.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:_.completion}}catch(o){o instanceof i||G({event:"api.request.failed",level:"error",error:o instanceof Error?o:new Error(String(o)),...c(n)?.class==="broker"?{node_id:c(n).node}:{},fields:{method:"POST",path:"/v1/llm"}});const s=o instanceof i?o:new i(503,"upstream_model_unavailable",H(o));w&&s.code==="upstream_model_unavailable"&&!p.signal.aborted&&(y="fail");const r=y==="fail"&&b?.test?new i(503,s.code,s.message,s.param,{...s.details,breaker:"test"}):s;if(e.headersSent){const _=r.details&&typeof r.details=="object"&&!Array.isArray(r.details)?r.details:{},m=E(g!==void 0&&typeof _.served_model!="string"?{..._,served_model:g}:r.details,c(n)?.class);return e.end(`${JSON.stringify({error:{code:r.code,message:r.message,...m===void 0?{}:{details:m},type:"server_error",origin:"runtime",retryable:r.retryable,request_id:f}})}
|
|
3
|
+
`),{status:200}}const u=E(r.details,c(n)?.class),l=r.code==="all_routes_exhausted"?r.details.retry_after_s:void 0;return l!==void 0&&e.setHeader("Retry-After",String(l)),{status:r.status,body:{error:{code:r.code,message:r.message,...u===void 0?{}:{details:u},type:q(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:f,...l!==void 0?{retry_after_s:l}:{},...J(r)}}}}finally{e.off("close",h),b?.settle(y)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:d(async({req:t})=>{const e=v(),n={"Request-Id":e};try{const a=await O(c(t));return{status:200,headers:n,body:await C(a.grantee,B(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof i))throw a;return{status:a.status,headers:n,body:{error:{code:a.code,message:a.message,type:q(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{J as capFields,se as llmRoutes,O as spendTarget};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.748",
|
|
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.
|
|
162
|
-
"@north-light/plugin": "0.3.
|
|
161
|
+
"@north-light/identity": "0.3.748",
|
|
162
|
+
"@north-light/plugin": "0.3.748",
|
|
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",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
//
|
|
13
13
|
// PURITY (spec §3.1): Node built-ins + `src/api/*` only.
|
|
14
14
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
15
|
-
export const CONTRACT_LEVEL = '1.
|
|
15
|
+
export const CONTRACT_LEVEL = '1.75';
|
|
16
16
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
17
17
|
export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
|
|
18
18
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
|
@@ -36,7 +36,8 @@ export const listLeaf = defineLeaf({
|
|
|
36
36
|
outputKind: 'object',
|
|
37
37
|
effects: ['None. Listing records no watch.'],
|
|
38
38
|
},
|
|
39
|
-
|
|
39
|
+
actingAs: true,
|
|
40
|
+
run: async (input, context) => {
|
|
40
41
|
const query = {
|
|
41
42
|
...(input['type'] ? { type: input['type'] } : {}),
|
|
42
43
|
...(input['kind'] ? { kind: input['kind'] } : {}),
|
|
@@ -46,6 +47,7 @@ export const listLeaf = defineLeaf({
|
|
|
46
47
|
...(input['deleted'] === true ? { deleted: true } : {}),
|
|
47
48
|
...(input['shared'] === true ? { shared: true } : {}),
|
|
48
49
|
...(input['machine'] ? { machine: input['machine'] } : {}),
|
|
50
|
+
...(context?.as === undefined ? {} : { as: context.as }),
|
|
49
51
|
limit: input['limit'] ?? 50,
|
|
50
52
|
...(input['cursor'] ? { cursor: input['cursor'] } : {}),
|
|
51
53
|
};
|
|
@@ -80,9 +80,11 @@ export const readLeaf = defineLeaf({
|
|
|
80
80
|
outputKind: 'object',
|
|
81
81
|
effects: ['A live read records a watch on the object for you (every event subject) and publishes a read event to its other watchers. A deleted or remote answer records nothing.'],
|
|
82
82
|
},
|
|
83
|
-
|
|
83
|
+
actingAs: true,
|
|
84
|
+
run: async (input, context) => {
|
|
84
85
|
try {
|
|
85
|
-
|
|
86
|
+
const query = { ...(input['fields'] === true ? { fields: true } : {}), ...(context?.as === undefined ? {} : { as: context.as }) };
|
|
87
|
+
return { ...(await cliClient().objects.read(input['ref'], Object.keys(query).length === 0 ? undefined : query)) };
|
|
86
88
|
}
|
|
87
89
|
catch (err) {
|
|
88
90
|
rethrowAsCliError(err);
|
|
@@ -23,7 +23,8 @@ export const searchLeaf = defineLeaf({
|
|
|
23
23
|
outputKind: 'object',
|
|
24
24
|
effects: ['None. Searching records no watch.'],
|
|
25
25
|
},
|
|
26
|
-
|
|
26
|
+
actingAs: true,
|
|
27
|
+
run: async (input, context) => {
|
|
27
28
|
const request = {
|
|
28
29
|
text: input['text'],
|
|
29
30
|
...(input['body'] === true ? { body: true } : {}),
|
|
@@ -32,6 +33,7 @@ export const searchLeaf = defineLeaf({
|
|
|
32
33
|
...(input['kind'] ? { kind: input['kind'] } : {}),
|
|
33
34
|
...(input['owner'] ? { owner: input['owner'] } : {}),
|
|
34
35
|
...(input['limit'] ? { limit: input['limit'] } : {}),
|
|
36
|
+
...(context?.as === undefined ? {} : { as: context.as }),
|
|
35
37
|
};
|
|
36
38
|
try {
|
|
37
39
|
return { ...(await cliClient().objects.search(request)) };
|
|
@@ -61,7 +61,7 @@ async function seedRow(meta, db) {
|
|
|
61
61
|
const profile = meta.profile_id ? await profileObjectFor(db, meta.profile_id, app, meta.grantee ?? 'app:terminal') : null;
|
|
62
62
|
await createObject(db, { id: meta.node_id, type: 'node', kind: meta.kind, owner: (profile ?? app).id, privacy: 'public', name: meta.name, preview: '' });
|
|
63
63
|
// A node directly under an app is readable by the person it was made for.
|
|
64
|
-
if (profile === null && meta.sub)
|
|
64
|
+
if (profile === null && meta.sub && !meta.sub.startsWith('app:'))
|
|
65
65
|
await writeActsFor(db, meta.node_id, meta.sub);
|
|
66
66
|
await db.prepare(`INSERT INTO nodes (node_id, description, title, icon, cycles, mode, lifecycle, cwd, host_kind, profile_id, parent, spawned_by, creator, fork_from, fork_source_file, created, passive_default, cycle_pending, model_override, persona_ack_json, review_binding_json, launch_config_json, scopes_json, isolated, status, intent, final_report, finalized_at, deadline_at, "window", tmux_session, pane, sub, grant_id, client_id, metadata_json, run_id, event_cursor, deleting_at, caused_by, app) VALUES (${Array(41).fill('?').join(', ')})`)
|
|
67
67
|
.run(meta.node_id, meta.description ?? null, meta.title ?? null, meta.icon ?? null, meta.cycles ?? null, meta.mode, meta.lifecycle, meta.cwd, meta.host_kind ?? null, meta.profile_id ?? null, meta.parent ?? null, meta.spawned_by ?? null, meta.creator ?? null, meta.fork_from ?? null, meta.fork_source_file ?? null, meta.created, meta.passive_default === true ? 1 : 0, meta.cycle_pending === true ? 1 : 0, meta.model_override ?? null, jsonValue(meta.persona_ack, 'persona_ack'), jsonValue(meta.review_binding, 'review_binding'), jsonValue(meta.launch, 'launch'), jsonValue(meta.scopes, 'scopes'), meta.isolated === true ? 1 : 0, meta.status ?? 'active', meta.intent ?? null, meta.final_report ?? null, meta.finalized_at ?? null, meta.deadline_at ?? null, meta.window ?? null, meta.tmux_session ?? null, meta.pane ?? null, meta.sub ?? null, meta.grant_id ?? null, meta.client_id ?? null, meta.metadata_json ?? null, meta.run_id ?? null, meta.event_cursor ?? null, meta.deleting_at ?? null, meta.caused_by ?? null, app.id);
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
/** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
|
|
7
7
|
* `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
|
|
8
8
|
* one below the live database's `schema_min_reader`. */
|
|
9
|
-
export const CANVAS_SCHEMA_VERSION =
|
|
9
|
+
export const CANVAS_SCHEMA_VERSION = 35;
|
|
10
10
|
/** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
|
|
11
11
|
* means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
|
|
12
12
|
* it is put in a `search_path` connection option. */
|
|
@@ -56,6 +56,7 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
56
56
|
return {
|
|
57
57
|
outputKind: 'object',
|
|
58
58
|
...(machineTransport ? { machineSelector: true } : {}),
|
|
59
|
+
actingAs: true,
|
|
59
60
|
run: async (input, context) => {
|
|
60
61
|
const argumentsForDaemon = { ...input };
|
|
61
62
|
for (const param of leaf.params) {
|
|
@@ -79,7 +80,7 @@ function providerLeafAdapter(provider, tool, leaf, machineTransport = false) {
|
|
|
79
80
|
}
|
|
80
81
|
try {
|
|
81
82
|
const result = await cliClient({ timeoutMs: 0 }).request('POST', '/v1/provider/call', {
|
|
82
|
-
provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }),
|
|
83
|
+
provider, tool, arguments: argumentsForDaemon, ...(context?.machine === undefined ? {} : { machine: context.machine }), ...(context?.as === undefined ? {} : { as: context.as }),
|
|
83
84
|
}, { timeout: 0 });
|
|
84
85
|
if (filesCrossByUpload()) {
|
|
85
86
|
for (const field of leaf.output ?? []) {
|
|
@@ -201,6 +202,7 @@ function adaptLeaf(contribution, commandPathFor) {
|
|
|
201
202
|
const httpLeaf = leaf;
|
|
202
203
|
return {
|
|
203
204
|
outputKind: httpLeaf.rest.streaming === true ? 'jsonl' : 'object',
|
|
205
|
+
actingAs: true,
|
|
204
206
|
run: (input, context) => invokeHttpLeaf({
|
|
205
207
|
registration: { name: contribution.plugin.name, endpoint: transport.endpoint, ...(transport.authEnv !== undefined ? { authEnv: transport.authEnv } : {}) },
|
|
206
208
|
...(contribution.manifest?.baseUrl !== undefined ? { baseUrl: contribution.manifest.baseUrl } : {}),
|
|
@@ -209,7 +211,7 @@ function adaptLeaf(contribution, commandPathFor) {
|
|
|
209
211
|
}, input, context, {
|
|
210
212
|
// crtrd names the caller and decides, from the final URL, whether to sign. Only digests leave this process.
|
|
211
213
|
callHeaders: (plan) => cliClient().plugins.callHeaders(contribution.plugin.name, {
|
|
212
|
-
method: plan.method, url: plan.url.href, body_sha256: sha256Hex(plan.body), ...signedHeaderDigest(plan.headers),
|
|
214
|
+
method: plan.method, url: plan.url.href, body_sha256: sha256Hex(plan.body), ...signedHeaderDigest(plan.headers), ...(context?.as === undefined ? {} : { as: context.as }),
|
|
213
215
|
}).then((answer) => answer.headers, (error) => { throw error instanceof ApiError ? apiErrorToCliError(error) : error; }),
|
|
214
216
|
}),
|
|
215
217
|
};
|
|
@@ -257,5 +259,5 @@ function buildBranch(contribution, node, path, toolPrefixLength = 1, allowedTool
|
|
|
257
259
|
}
|
|
258
260
|
function buildLeaf(contribution, node, path) {
|
|
259
261
|
const adapted = contribution.adaptLeaf(node, path);
|
|
260
|
-
return defineLeaf({ name: node.name, description: node.description, whenToUse: node.whenToUse, ...(node.tier !== undefined ? { tier: node.tier } : {}), ...(contribution.plugin !== undefined ? { plugin: contribution.plugin } : {}), ...(adapted.machineSelector === true ? { machineSelector: true } : {}), help: { name: path.join(' '), summary: node.summary, ...(adapted.machineSelector === true ? { guide: MACHINE_SELECTOR_GUIDE } : {}), params: node.params, output: node.output, outputKind: adapted.outputKind, effects: [...node.effects] }, run: adapted.run });
|
|
262
|
+
return defineLeaf({ name: node.name, description: node.description, whenToUse: node.whenToUse, ...(node.tier !== undefined ? { tier: node.tier } : {}), ...(contribution.plugin !== undefined ? { plugin: contribution.plugin } : {}), ...(adapted.machineSelector === true ? { machineSelector: true } : {}), ...(adapted.actingAs === true ? { actingAs: true } : {}), help: { name: path.join(' '), summary: node.summary, ...(adapted.machineSelector === true ? { guide: MACHINE_SELECTOR_GUIDE } : {}), params: node.params, output: node.output, outputKind: adapted.outputKind, effects: [...node.effects] }, run: adapted.run });
|
|
261
263
|
}
|
|
@@ -42,6 +42,7 @@ export function defineLeaf(opts) {
|
|
|
42
42
|
hookEligible: opts.hookEligible,
|
|
43
43
|
plugin: opts.plugin,
|
|
44
44
|
machineSelector: opts.machineSelector,
|
|
45
|
+
actingAs: opts.actingAs,
|
|
45
46
|
run: opts.run,
|
|
46
47
|
render: opts.render,
|
|
47
48
|
preview: opts.preview,
|
|
@@ -720,6 +721,31 @@ export function takeMachineSelector(tokens) {
|
|
|
720
721
|
}
|
|
721
722
|
return machine === undefined ? { rest } : { rest, machine };
|
|
722
723
|
}
|
|
724
|
+
/** Take the `--as <user:id>` / `--as=<user:id>` option out of an opted-in leaf's argv. Nothing after a bare `--` is a flag. */
|
|
725
|
+
export function takeActingAs(tokens) {
|
|
726
|
+
const rest = [];
|
|
727
|
+
let as;
|
|
728
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
729
|
+
const token = tokens[i];
|
|
730
|
+
if (token === '--') {
|
|
731
|
+
rest.push(...tokens.slice(i));
|
|
732
|
+
break;
|
|
733
|
+
}
|
|
734
|
+
const inline = token.startsWith('--as=') ? token.slice('--as='.length) : undefined;
|
|
735
|
+
if (token !== '--as' && inline === undefined) {
|
|
736
|
+
rest.push(token);
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
const value = inline ?? tokens[i + 1];
|
|
740
|
+
if (value === undefined || !/^user:[^\s]+$/.test(value)) {
|
|
741
|
+
throw parseArgvError('missing_parameter', '--as requires a person id like user:<id>', '--as', 'as', 'Name the person this call acts for, for example `--as user:alice`.');
|
|
742
|
+
}
|
|
743
|
+
if (inline === undefined)
|
|
744
|
+
i++;
|
|
745
|
+
as = value;
|
|
746
|
+
}
|
|
747
|
+
return as === undefined ? { rest } : { rest, as };
|
|
748
|
+
}
|
|
723
749
|
export const GLOBAL_TOKENS = new Set(['--json', '--no-autostart']);
|
|
724
750
|
export async function runCli(root, argv) {
|
|
725
751
|
// argv is process.argv — strip node binary + script path. `--json` is a
|
|
@@ -826,6 +852,12 @@ export async function runCli(root, argv) {
|
|
|
826
852
|
leafTokens = selected.rest;
|
|
827
853
|
machine = selected.machine;
|
|
828
854
|
}
|
|
855
|
+
let acting;
|
|
856
|
+
if (leaf.actingAs === true && !params.some((param) => param.kind === 'flag' && param.name === 'as')) {
|
|
857
|
+
const taken = takeActingAs(leafTokens);
|
|
858
|
+
leafTokens = taken.rest;
|
|
859
|
+
acting = taken.as;
|
|
860
|
+
}
|
|
829
861
|
const input = await parseArgv(params, leafTokens, {
|
|
830
862
|
leafPath: path,
|
|
831
863
|
onProvidedParams: (provided) => {
|
|
@@ -835,7 +867,7 @@ export async function runCli(root, argv) {
|
|
|
835
867
|
contextFilePaths = paths;
|
|
836
868
|
},
|
|
837
869
|
});
|
|
838
|
-
const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }) };
|
|
870
|
+
const context = { providedParams, contextFilePaths, ...(machine === undefined ? {} : { machine }), ...(acting === undefined ? {} : { as: acting }) };
|
|
839
871
|
const result = await operationIdContext.fresh(() => leaf.run(input, context));
|
|
840
872
|
publishPreviewResult(result === undefined || result === null ? result : leaf.preview?.(result) ?? result);
|
|
841
873
|
if (result !== undefined && result !== null) {
|
|
@@ -5,7 +5,7 @@ import { writeActsFor } from './permissions/facts.js';
|
|
|
5
5
|
import { writeEnvironmentRecipe } from './environment-recipe.js';
|
|
6
6
|
import { setCloudProfileWriter } from './profiles/manifest.js';
|
|
7
7
|
/** A cloud profile's own `blaxel` environment (D105): an `environment` object owned by the profile's object, acting for `person`, and
|
|
8
|
-
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. Runs in the
|
|
8
|
+
* its `environments` row with the `memory_mb` (default 2048), no recipe (so the Blaxel base image) and no machine id. `payer` (null by default: the run's `sub` pays) names who pays; an app environment passes `person` and `grantee` as `app:<id>` and `payer` the same. Runs in the
|
|
9
9
|
* caller's write, before the profile row exists, so the profile and its environment commit together. The profile object is made
|
|
10
10
|
* here under `grantee`'s app, with the profile id as its handle: a cloud role serves many people and a profile name is not unique
|
|
11
11
|
* across them, while the handle is unique per object type. Returns the environment's object id. */
|
|
@@ -14,7 +14,7 @@ export async function createProfileBlaxelEnvironment(db, spec) {
|
|
|
14
14
|
const profile = await ensureOwner(db, 'profile', 'profile', spec.profileId, spec.profileId, app);
|
|
15
15
|
const object = await createObject(db, { type: 'environment', kind: 'blaxel', owner: profile.id, privacy: 'private', name: spec.profileId, preview: 'blaxel' });
|
|
16
16
|
await writeActsFor(db, object.id, spec.person);
|
|
17
|
-
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?)`).run(object.id, spec.memoryMb ?? 2048, new Date().toISOString());
|
|
17
|
+
await db.prepare(`INSERT INTO environments (object, kind, machine_id, memory_mb, allow_pull_request_write, payer, last_seen_at) VALUES (?, 'blaxel', NULL, ?, true, ?, ?)`).run(object.id, spec.memoryMb ?? 2048, spec.payer ?? null, new Date().toISOString());
|
|
18
18
|
if (spec.recipe !== undefined)
|
|
19
19
|
await writeEnvironmentRecipe(db, object.id, spec.recipe);
|
|
20
20
|
return object.id;
|