@north-light/cli 0.3.789 → 0.3.790
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/clients/attach/viewer.js +255 -255
- package/dist/commands/canvas-history/shared.js +1 -1
- package/dist/commands/node/create.js +2 -2
- package/dist/commands/person-settings.js +1 -1
- package/dist/commands/profile/daemon-profiles.js +4 -4
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/history.d.ts +2 -8
- package/dist/core/canvas/history.js +9 -9
- package/dist/core/canvas/node-tokens.js +3 -3
- package/dist/core/canvas/person-state.d.ts +5 -7
- package/dist/core/canvas/person-state.js +1 -1
- package/dist/core/canvas/person.d.ts +3 -30
- package/dist/core/canvas/person.js +1 -11
- package/dist/core/config.d.ts +4 -1
- package/dist/core/config.js +1 -1
- package/dist/core/directory/join.d.ts +4 -6
- package/dist/core/directory/join.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/requests.d.ts +11 -1
- package/dist/core/human/requests.js +22 -22
- package/dist/core/review/store.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/launch-config-worker.js +1 -1
- package/dist/core/runtime/launch-target.d.ts +6 -4
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/core/runtime/launch.d.ts +5 -1
- package/dist/core/runtime/launch.js +2 -2
- package/dist/core/runtime/runner/machine/runner.js +1 -1
- package/dist/core/runtime/spawn-env-rows.js +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/secrets/environment-owner.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +5 -5
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/human/sweep.js +1 -1
- package/dist/daemon/peer/ingress.d.ts +2 -2
- package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
- package/dist/daemon/runs/observer.js +6 -5
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +2 -2
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
- package/packages/crouter-api/dist/core/config.js +10 -0
- package/packages/crouter-api/dist/core/directory/join.js +11 -45
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/join.d.ts +0 -3
- package/dist/commands/sys/join.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var Fe=Object.defineProperty;var d=(e,n)=>Fe(e,"name",{value:n,configurable:!0});import{randomUUID as Ge}from"node:crypto";import{envProfileId as xe}from"../../../shared/env.js";import{pausedCanvasProfiles as Be}from"../../../core/profiles/manifest.js";import{existsSync as $,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as We,formatSituationalProse as Ue}from"../../../core/runtime/situational-context.js";import{closeNode as Ve}from"../../../core/runtime/close.js";import{reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ke,assertLaunchModelRegistered as V,forkNode as Je,resolveForkSource as se,spawnChildPrepared as ze}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as He,claimCreateLease as fe,createLeaseLive as Ye,renewCreateLease as Qe,childrenOf as Xe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Ze,reserveCreateRequest as we,reserveCreateRequestNode as qe,listNodes as en,recordRespawnAttempt as he,subscribersOf as nn,subscriptionsOf as ye,updateNode as T}from"../../../core/canvas/canvas.js";import{armControllerWait as tn,liveControllerWaits as rn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as on}from"../../../core/canvas/recovery.js";import{nodeObject as an}from"../../../core/graph/objects.js";import{recordActedOn as dn}from"../../../core/graph/edges.js";import{publish as sn}from"../../../core/graph/events.js";import{readerFor as ln}from"../reader.js";import{relocateSessionCwd as cn,unbindSession as un}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as fn}from"../../../core/canvas/attention.js";import{isSafeNodeId as pn}from"../../../core/canvas/paths.js";import{contextDir as _e,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as mn,cronRefusalError as wn}from"../../cron/authority.js";import{cronBirthPlacement as hn}from"../../cron/armed-context.js";import{existsBeneath as yn,isAbsentOrRefused as _n,isBeneathRefusal as gn,readdirBeneath as bn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as vn,readNodeSession as kn,readNodeSnapshot as Sn,transcriptMarkdown as In}from"../../../core/runtime/node-read.js";import{toolCallIds as Rn,withoutImages as ge}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as En}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as On}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as Cn,requestYieldAsync as $n,reshapeNodeAsync as z}from"../../../core/runtime/promote.js";import{recycleNode as Tn}from"../../../core/runtime/recycle.js";import{relaunchRoot as Nn}from"../../../core/runtime/reset.js";import{assertReopenGate as Pn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Dn}from"./broker-recovery.js";import{readOutputRequest as Ln}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Mn,readGoal as jn,captureGoalIfAbsent as Fn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Gn,hasRoadmap as xn}from"../../../core/runtime/roadmap.js";import{renameWindow as Bn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Wn,explicitModelIntent as Un,normalizeModel as Vn,readMergedLaunchConfigAsync as be}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Kn}from"../../../core/model-routes.js";import{persistDormantModel as Jn,setModelLive as zn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ve}from"../../../core/runtime/view-socket.js";import{viewTransport as Hn}from"../../runs/observer.js";import{BrokerUnreachableError as Yn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Qn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Xn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ke}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Zn}from"../../../core/human/action-binding.js";import{resolveHumanAction as qn}from"../../../core/human-actions.js";import{parseDurationMs as et}from"../../../core/wake.js";import{claimWarmNode as nt,refillWarmPool as Se,resumeWarmClaim as tt,warmPoolEnabled as it}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as rt,resolveLaunchTarget as ot}from"../../../core/runtime/launch-target.js";import{fullName as at}from"../../../core/canvas/labels.js";import{reportsForNode as Ie}from"./reports.js";import{requireUsableProfile as dt}from"./profiles.js";import{assertProfileActive as st,isProfilePaused as lt,loadExactProfileManifest as ct}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ut}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as ft}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as pt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as mt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as wt,validateScopes as Re}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as ht,toNodeDetailDTO as Q,toNodeSummaryDTO as yt,toReviveResultDTO as _t}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as gt,liveExecutionForNode as X,requestExecutionStop as bt}from"../../../core/canvas/executions.js";import{runnerForExecution as vt}from"../../../core/runtime/runner/index.js";import{wakeResident as kt}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as St}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Ee}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as It}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Rt}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as Et,readableNodeIds as Ot,resolvedScopes as At}from"../router.js";import{forwardVerb as Ct,queryWithoutMachine as $t,relayError as Tt,unknownError as Nt,withMachine as Pt}from"../../peer/forward.js";import{fileRoot as Dt}from"../../../core/spaces/file-root.js";import{activeGrant as Lt,payerOfGrant as Mt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as jt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Ft}from"../../../core/grants/terminal.js";import{appRungForGrant as Gt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as xt}from"../../../core/model-routes.js";import{listProfileEnvNames as Bt}from"../../../core/profiles/env-store.js";import{environmentPayerOfProfile as Wt}from"../../../core/ledger/index.js";import{hasConfiguredProviderCredential as Ut,NO_PROVIDER_CREDENTIAL_MESSAGE as Oe}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Vt,mapAsync as Ae}from"../../../core/async-array.js";import{addStepTiming as Kt,collectStepTimings as Jt,serverTimingHeader as zt,sinceCollectionStart as Ht,timedStep as Yt}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Z(e){return{subscribesTo:await ye(e),subscribers:await nn(e),children:await Xe(e)}}d(Z,"edgesFor");async function v(e){const n=await h(e);return await Q(n,await Z(e))}d(v,"detailOf");async function Qt(e){let n=(await Ie(e)).length;try{n+=bn(await J(e),await _e(e)).length}catch(t){if(!_n(t))throw t}return n}d(Qt,"countFiles");function Xt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Re(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Xt,"parseCreateBody");function Zt(e){if(e===void 0)return;const n=et(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Zt,"parseDeadline");function qt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Zn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ke)throw new p(413,"payload_too_large",`serialized payload exceeds ${ke} bytes`)}return e}}d(qt,"parseOutcomeDelivery");function ei(e,n){const t=qn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(ei,"resolveOutcomeDelivery");function ni(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(ni,"buildRecipe");function ti(e,n,t){return!it()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ti,"warmRequestFor");import{resolveCreateKind as Eo}from"../../../core/runtime/launch-target.js";function Ce(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Kn(e.model,n,e.modelExact===!0)}d(Ce,"requestFromLaunch");function ii(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ii,"withinCeiling");async function $e(e,n,t){const r=(await Wn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ce(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d($e,"assertNodeModelChangeRegistered");async function ri(e){if(!Rt()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await It(n)!==null}d(ri,"callerRunsOnMachine");async function Te(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ri(t))return;const r=Dt({app:t.app,resolved:await At(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(Te,"assertCallerReaches");const q=new Map;async function oi(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Jt(()=>ai(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":zt(a)}}}d(oi,"handleCreate");async function ai(e,n,t){const r=ii(Xt(e.body),e.ceiling);if(e.principal.class==="broker"){const s=e.principal;if(r.prefer_warm===!0&&s.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await h(r.parent);if(o.grantee!==s.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await A(s,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==s.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==s.app||!await A(s,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=s.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const s=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,s?.node_id])if(o!=null&&await b(o)!==null&&!await Et(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const s=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new p(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),s.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,s.app));const o=await mn({grantee:s.app,sub:s.sub,grant_id:s.grant,scopes:s.scopes,from_exec:s.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw wn(o);if(r.scopes!==void 0){const l=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(s.scopes,m));if(l!==void 0)throw new p(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&wt(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&pn(r.node_id)&&await b(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const c=di(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}d(ai,"createWithinTimings");const Ne=`${process.pid}:${Ge()}`,ee="create_request_in_progress";async function Pe(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await Ye(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new p(409,ee,"another create with this request_key is in progress; retry it")}d(Pe,"awaitForeignCreate");async function di(e,n,t,r,i){const a=await we(t),c=Ne;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Pe(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const s=setInterval(()=>{Qe(t,c).catch(()=>{})},He);try{return await si(e,n,t,r,i,a)}finally{clearInterval(s)}}d(di,"handleKeyedCreateRequest");async function si(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,c.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(c){if(c instanceof p&&c.code===ee)throw c;const s=await we(t);throw(s.nodeId===null||await b(s.nodeId)===null)&&await ue(t,s.nodeId),c}}d(si,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Zt(n.deadline),c=qt(n.outcome_delivery),s=e.principal.class==="cron"?await hn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;s!==null&&(n.root=s.root===!0);const o=s?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw y("output_schema must be a JSON schema object");await Xn(l)}const m=await ot(n,{validateKind:je,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!$(_)&&await Ee(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Te(e,_),n.worktree!==void 0&&await Te(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:ei(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ce(await Ke(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Mt(te)!=="app"&&await Wt(f)===null&&!await Ut(f===null?[]:await Bt(f))&&!await jt(m))throw new p(412,"no_provider_credential",Oe,{error:"no_provider_credential",message:Oe,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ti(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Ee(f)!==null)?ie:null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Qn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await tt(O,i.nodeId,B);if(g===null)throw await ue(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await nt(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await pe(i.requestKey,g),Se(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const g=await qe(i.requestKey,D,Ne);if(g!==D)return await Pe(e,i.requestKey,g)}const R=ni(D===void 0?k:{...k,node_id:D},o,_);s!==null&&(s.rootLifecycle!==void 0&&(R.rootLifecycle=s.rootLifecycle),s.scopes!==void 0&&k.scopes===void 0&&(R.scopes=s.scopes),s.run!==void 0&&(R.run=s.run),s.withinCreate!==void 0&&(R.withinCreate=s.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Kt("handler_checks",Ht());const re=await ze(R,B,()=>{x!==null&&Se(x)});return i!==void 0&&await Ze(i.requestKey,re.node.node_id),{status:201,body:await Yt("response_detail",()=>v(re.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(ne,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function li(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),s=S(e,"profile_prefix"),o=S(e,"parent"),l=ne(S(e,"top_level"),"top_level"),m=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...s!==void 0?{profile_prefix:s}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(li,"parseListQuery");async function ci(e){const n=li(e);let t=await en({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Ot(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await fn(t.map(o=>o.node_id)):null,a=t.length>0?Be():new Set,c=new Map((await rn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Ae(t,async o=>{const l=await yt(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await Ie(o.node_id);l.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return l})}}d(ci,"handleList");async function ui(e){const n=e.params.id,t=await Ct(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:$t(e)});if(t.kind==="unknown")throw Nt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Tt(t.status,t.body);return{status:t.status,body:Pt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(ui,"handleDetail");async function fi(e){const n=e.params.id;await h(n);const t=await Sn(n),{start:r}=En(t.snapshot.messages,s=>JSON.stringify(ge(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>ge(s,n)),a=Rn(i);return{status:200,body:{node_id:n,snapshot:{messages:i,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(r)},messageVisibility:t.snapshot.messageVisibility.slice(r),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([s])=>a.has(s)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(s=>({name:s.name,description:s.description,source:s.source})),captured_at:U()}}}d(fi,"handleSnapshot");async function pi(e){const n=e.params.id,t=await On(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(pi,"handleSubject");function mi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(mi,"parseMessagesQuery");async function wi(e){const n=e.params.id,t=await vn(n,mi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(wi,"handleMessages");async function hi(e){const n=e.params.id;await h(n);const t=await kn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(hi,"handleSession");async function yi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await In(n)}}}d(yi,"handleTranscript");async function _i(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await _e(i),self:a,files:await Qt(i)}),"root"),r=await Vt([await t(n,!0),...await Ae(await ye(n),async i=>await t(i.node_id,!1))],async i=>await gi(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(_i,"handleContext");async function gi(e,n){try{return yn(await J(e),n)}catch(t){if(gn(t))return!1;throw t}}d(gi,"hasDir");async function bi(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Je(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(bi,"handleFork");const vi=1e4;async function ki(e){const n=e.params.id,t=await h(n),r=await X(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!St(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await bt(n,{afterTurn:!1,reason:"revive_now"});const i=await vt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await gt(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(ki,"handleKick");async function Si(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;await Pn(n,a,e.principal.class==="broker"?e.principal.node:null);const c=!i&&r?.cron_id!==void 0?await Y(r.cron_id):null,s=await X(n);if(i&&s!==null&&s.runner!=="process"&&s.state==="running"&&!lt(t.profile_id))try{await ft({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>kt(s))}catch(u){if(!(u instanceof ut))throw u}await he(n,{failures:0,notBefore:null});const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await pt(c,"schedule_revive")}:{}});o.outcome==="already-live"&&await he(n,{failures:t.respawn_failures??0,notBefore:t.respawn_not_before??null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await ve(n,m,vi);return{status:200,body:_t(n,o,l,f)}}d(Si,"handleRevive");async function Ii(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Nn(n))?.newNodeId??null}}}d(Ii,"handleRelaunchRoot");async function Ri(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=mt(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Ve(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:ht(a)}}d(Ri,"handleClose");async function Ei(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await on(n),{status:204}}d(Ei,"handleMarkRead");async function Oi(e){const n=e.params.id;await h(n);const t=await Tn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Oi,"handleRecycle");async function Ai(e){const n=e.params.id;return await h(n),await z(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Ai,"handleDemote");async function Ci(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await $e(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await Cn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await Z(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}d(Ci,"handlePromote");async function $i(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Ln(n)}}}d($i,"handleBrokerStructuredRequest");async function Ti(e){const n=e.params.id,t=e.body??{};if(await Dn(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Fn(n,t.text)}}}d(Ti,"handleBrokerGoal");async function Ni(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await H(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await $e(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Mn(t,a);const c=await $n(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await Z(t))}}d(Ni,"handleYield");async function Pi(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await tn(n,t.controller),{status:200,body:await v(n)}}d(Pi,"handleWait");async function Di(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Di,"handleReviveAll");const Li=new Set(["interrupt","steer","after-turn","next-turn"]);function Mi(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Li.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Mi,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await an(i,n),c=await ln(i,e),s=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await dn(i,s,a),await sn(i,{event:"configured",object:a,actor:s,attrs:{changed:t.join(",")}})})}d(C,"recordConfigured");function De(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(De,"restartLiveBroker");function Le(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(Le,"sameDirectory");async function ji(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),l=await dt(e,i.profile);st(l.profileId);const m=ct(l.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(rt(o.kind)?(await H(o.kind,o.cwd,l.profileId),await z(t,{profileId:l.profileId})):await T(t,{profile_id:l.profileId}),await C(e,t,["profile"])),i.restart===!0&&De(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(t),m=$(l.cwd);if(i.keep_session===!0||m&&W(o)&&$(o)&&Le(l.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!Le(l.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=l.cwd;return I!==u&&(await K(async k=>{await T(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await cn(t,I,u)}),await C(e,t,["cwd"])),i.restart===!0&&De(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if($(l.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!$(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await T(t,{cwd:f}),await un(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const c=i.listen===void 0?void 0:Mi(i.listen);if(i.scopes!==void 0){const o=Re(i.scopes),l=a.grantee==="app:terminal"?await Ft(a):a.grant_id?await Lt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&l!==null&&E(l.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await T(t,{scopes:o})}if(i.situational_context!==void 0&&await We(t,Ue(i.situational_context)),i.model!==void 0){const o=(await be(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Un(i.model,o),m=await Gt(a.grant_id,i.model,l===void 0),f=m?{family:xt,strength:m.strength}:l,u=m?m.model:Vn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await X(t))?.runner==="machine"||await ve(t,_.get(t)?.handle.exited))&&(I=await zn(t,u,f,await Hn(t)).then(()=>!0,k=>{if(k instanceof Yn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await Jn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await je(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;l==="orchestrator"&&!await xn(t)&&(f=d(async()=>{const u=await jn(t);await Gn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await z(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await T(t,{name:i.name}),a.window&&Bn(a.window,at(a)));const s=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,s,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}d(ji,"handleConfig");async function Me(e="app:terminal"){return(await be(process.cwd(),xe()||null,e)).kinds}d(Me,"daemonKinds");async function je(e,n="app:terminal"){const t=Object.keys(await Me(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(je,"assertKindServer");async function Fi(){const e=await Me();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(Fi,"handleListKinds");const So=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:oi},{method:"GET",pattern:"/v1/nodes",handler:ci},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Fi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Di},{method:"GET",pattern:"/v1/nodes/:id",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:pi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:yi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:_i},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:bi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ni},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:$i},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Ti},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Pi},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ji}];export{ji as handleConfig,oi as handleCreate,bi as handleFork,ci as handleList,Ci as handlePromote,Ni as handleYield,So as nodeRoutes,Eo as resolveCreateKind};
|
|
1
|
+
var Me=Object.defineProperty;var s=(e,n)=>Me(e,"name",{value:n,configurable:!0});import{randomUUID as je}from"node:crypto";import{pausedCanvasProfiles as Fe}from"../../../core/profiles/manifest.js";import{existsSync as T,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as U,resolve as L}from"node:path";import{appendSituationalContext as Ge,formatSituationalProse as Be}from"../../../core/runtime/situational-context.js";import{closeNode as xe}from"../../../core/runtime/close.js";import{reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as V}from"../../../core/fs-utils.js";import{appPaidLaunch as We,assertLaunchModelRegistered as J,forkNode as Ue,resolveForkSource as se,spawnChildPrepared as Ve}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as Je,claimCreateLease as fe,createLeaseLive as ze,renewCreateLease as Ke,childrenOf as He,completeCreateRequest as pe,findCreateRequest as me,getNode as g,recordCreateRequestNode as Ye,reserveCreateRequest as we,reserveCreateRequestNode as Qe,listNodes as Xe,recordRespawnAttempt as he,subscribersOf as Ze,subscriptionsOf as ye,updateNode as $}from"../../../core/canvas/canvas.js";import{armControllerWait as qe,liveControllerWaits as en}from"../../../core/canvas/waits.js";import{withCanvasWrite as z}from"../../../core/canvas/db.js";import{markNodeRead as nn}from"../../../core/canvas/recovery.js";import{nodeObject as tn}from"../../../core/graph/objects.js";import{recordActedOn as rn}from"../../../core/graph/edges.js";import{publish as on}from"../../../core/graph/events.js";import{readerFor as an}from"../reader.js";import{relocateSessionCwd as dn,unbindSession as sn}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as ln}from"../../../core/canvas/attention.js";import{isSafeNodeId as cn}from"../../../core/canvas/paths.js";import{contextDir as _e,nodeAgentDir as K}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as un,cronRefusalError as fn}from"../../cron/authority.js";import{cronBirthPlacement as pn}from"../../cron/armed-context.js";import{existsBeneath as mn,isAbsentOrRefused as wn,isBeneathRefusal as hn,readdirBeneath as yn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as _n,readNodeSession as gn,readNodeSnapshot as bn,transcriptMarkdown as vn}from"../../../core/runtime/node-read.js";import{toolCallIds as kn,withoutImages as ge}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as Sn}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as In}from"../../../core/substrate/subject.js";import{reviveAll as Rn}from"../../../core/runtime/revive-all.js";import{promoteAsync as En,requestYieldAsync as On,reshapeNodeAsync as H}from"../../../core/runtime/promote.js";import{recycleNode as An}from"../../../core/runtime/recycle.js";import{relaunchRoot as Cn}from"../../../core/runtime/reset.js";import{assertReopenGate as Tn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as $n}from"./broker-recovery.js";import{readOutputRequest as Nn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Pn,readGoal as Dn,captureGoalIfAbsent as Ln}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Mn,hasRoadmap as jn}from"../../../core/runtime/roadmap.js";import{renameWindow as Fn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Gn,explicitModelIntent as Bn,normalizeModel as xn,readMergedLaunchConfigAsync as be}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Wn}from"../../../core/model-routes.js";import{persistDormantModel as Un,setModelLive as Vn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ve}from"../../../core/runtime/view-socket.js";import{viewTransport as Jn}from"../../runs/observer.js";import{BrokerUnreachableError as zn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Kn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Hn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ke}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Yn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Qn}from"../../../core/human-actions.js";import{parseDurationMs as Xn}from"../../../core/wake.js";import{claimWarmNode as Zn,refillWarmPool as Se,resumeWarmClaim as qn,warmPoolEnabled as et}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as j,isLaunchKind as nt,resolveLaunchTarget as tt}from"../../../core/runtime/launch-target.js";import{fullName as it}from"../../../core/canvas/labels.js";import{reportsForNode as Ie}from"./reports.js";import{requireUsableProfile as rt}from"./profiles.js";import{assertProfileActive as ot,isProfilePaused as at,loadExactProfileManifest as dt}from"../../../core/profiles/manifest.js";import{MachineOfflineError as st}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as lt}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as ct}from"../../../core/runtime/bearings.js";import{boundDaemonControl as ut}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as ft,validateScopes as Re}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as pt,toNodeDetailDTO as Q,toNodeSummaryDTO as mt,toReviveResultDTO as wt}from"../map.js";import{ApiError as m}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as ht,liveExecutionForNode as X,requestExecutionStop as yt}from"../../../core/canvas/executions.js";import{runnerForExecution as _t}from"../../../core/runtime/runner/index.js";import{wakeResident as gt}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as bt}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Ee}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as vt}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as kt}from"../../../core/canvas/person-state.js";import{actsAsPerson as F,appOf as St,canReadNode as A,mayOnNode as It,readableNodeIds as Rt,resolvedScopes as Et}from"../router.js";import{forwardVerb as Ot,queryWithoutMachine as At,relayError as Ct,unknownError as Tt,withMachine as $t}from"../../peer/forward.js";import{fileRoot as Nt}from"../../../core/spaces/file-root.js";import{activeGrant as Pt,payerOfGrant as Dt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Lt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Mt}from"../../../core/grants/terminal.js";import{appRungForGrant as jt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Ft}from"../../../core/model-routes.js";import{listProfileEnvNames as Gt}from"../../../core/profiles/env-store.js";import{environmentPayerOfProfile as Bt}from"../../../core/ledger/index.js";import{hasConfiguredProviderCredential as xt,NO_PROVIDER_CREDENTIAL_MESSAGE as Oe}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Wt,mapAsync as Ae}from"../../../core/async-array.js";import{addStepTiming as Ut,collectStepTimings as Vt,serverTimingHeader as Jt,sinceCollectionStart as zt,timedStep as Kt}from"../../../core/step-timings.js";async function h(e){const n=await g(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}s(h,"requireMeta");async function Z(e){return{subscribesTo:await ye(e),subscribers:await Ze(e),children:await He(e)}}s(Z,"edgesFor");async function v(e){const n=await h(e);return await Q(n,await Z(e))}s(v,"detailOf");async function Ht(e){let n=(await Ie(e)).length;try{n+=yn(await K(e),await _e(e)).length}catch(t){if(!wn(t))throw t}return n}s(Ht,"countFiles");function Yt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Re(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new m(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new m(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}s(Yt,"parseCreateBody");function Qt(e){if(e===void 0)return;const n=Xn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new m(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(Qt,"parseDeadline");function Xt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Yn.test(e.action))throw new m(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ke)throw new m(413,"payload_too_large",`serialized payload exceeds ${ke} bytes`)}return e}}s(Xt,"parseOutcomeDelivery");function Zt(e,n){const t=Qn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new m(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new m(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(Zt,"resolveOutcomeDelivery");function qt(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(qt,"buildRecipe");function ei(e,n,t){return!et()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(ei,"warmRequestFor");import{resolveCreateKind as So}from"../../../core/runtime/launch-target.js";function Ce(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Wn(e.model,n,e.modelExact===!0)}s(Ce,"requestFromLaunch");function ni(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new m(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s(ni,"withinCeiling");async function Te(e,n,t){const r=(await Gn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await J(Ce(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(Te,"assertNodeModelChangeRegistered");async function ti(e){if(!kt()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await g(e.node))?.profile_id??null:e.cron===null?null:(await Y(e.cron))?.profile??null;return n!==null&&await vt(n)!==null}s(ti,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ti(t))return;const r=Nt({app:t.app,resolved:await Et(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new m(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s($e,"assertCallerReaches");const q=new Map;async function ii(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Vt(()=>ri(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":Jt(a)}}}s(ii,"handleCreate");async function ri(e,n,t){const r=ni(Yt(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await h(r.parent);if(o.grantee!==d.app)throw new m(403,"other_app_run","cannot create a child under another app's node");if(!await A(d,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new m(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==d.app||!await A(d,o.grantee,o.node_id))throw new m(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await g(o)!==null&&!await It(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new m(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),d.isolated&&(r.isolated=!0,r.cwd=await K(r.node_id,d.app));const o=await un({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw fn(o);if(r.scopes!==void 0){const l=r.scopes.find(p=>!E(o.effectiveScopes,p)||!E(d.scopes,p));if(l!==void 0)throw new m(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&ft(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&cn(r.node_id)&&await g(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const c=oi(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}s(ri,"createWithinTimings");const Ne=`${process.pid}:${je()}`,ee="create_request_in_progress";async function Pe(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await g(t);if(a!==null){if(!F(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new m(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await ze(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(c=>setTimeout(c,100))}throw new m(409,ee,"another create with this request_key is in progress; retry it")}s(Pe,"awaitForeignCreate");async function oi(e,n,t,r,i){const a=await we(t),c=Ne;if(a.nodeId!==null&&a.state==="reserved"&&await g(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Pe(e,t,a.nodeId)}catch(o){if(!(o instanceof m)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const d=setInterval(()=>{Ke(t,c).catch(()=>{})},Je);try{return await ai(e,n,t,r,i,a)}finally{clearInterval(d)}}s(oi,"handleKeyedCreateRequest");async function ai(e,n,t,r,i,a){if(a.nodeId!==null&&await g(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await g(a.nodeId);if(!F(e.principal)&&!await A(e.principal,c.grantee??"app:terminal",a.nodeId))throw new m(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof m&&c.code===ee)throw c;const d=await we(t);throw(d.nodeId===null||await g(d.nodeId)===null)&&await ue(t,d.nodeId),c}}s(ai,"keyedCreateOwned");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??Qt(n.deadline),c=Xt(n.outcome_delivery),d=e.principal.class==="cron"?await pn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Y(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw y("output_schema must be a JSON schema object");await Hn(l)}const p=await tt(n,{...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=p;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!T(_)&&await Ee(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await $e(e,_),n.worktree!==void 0&&await $e(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=c===void 0?void 0:Zt(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await g(o))?.grant_id??null);if(await J(Ce(await We(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Dt(te)!=="app"&&await Bt(f)===null&&!await xt(f===null?[]:await Gt(f))&&!await Lt(p))throw new m(412,"no_provider_credential",Oe,{error:"no_provider_credential",message:Oe,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ei(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Ee(f)!==null)?ie:null,W=l===null&&r.beforeBrokerLaunch===void 0?void 0:async b=>{l!==null&&await Kn(b,"terminal",l),r.beforeBrokerLaunch?.(b)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const b=O===null?null:await qn(O,i.nodeId,W);if(b===null)throw await ue(i.requestKey,i.nodeId),new m(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,b),{status:201,body:await v(b)}}if(O!==null){const b=await Zn(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},W);if(b!==null)return i!==void 0&&await pe(i.requestKey,b),Se(O),{status:201,body:await v(b)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const b=await Qe(i.requestKey,D,Ne);if(b!==D)return await Pe(e,i.requestKey,b)}const R=qt(D===void 0?k:{...k,node_id:D},o,_);d!==null&&(d.rootLifecycle!==void 0&&(R.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&k.scopes===void 0&&(R.scopes=d.scopes),d.run!==void 0&&(R.run=d.run),d.withinCreate!==void 0&&(R.withinCreate=d.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Ut("handler_checks",zt());const re=await Ve(R,W,()=>{x!==null&&Se(x)});return i!==void 0&&await Ye(i.requestKey,re.node.node_id),{status:201,body:await Kt("response_detail",()=>v(re.node.node_id))}}}s(G,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}s(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}s(ne,"optionalBoolean");function B(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}s(B,"oneOf");function di(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=B(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=B(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=B(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),d=S(e,"profile_prefix"),o=S(e,"parent"),l=ne(S(e,"top_level"),"top_level"),p=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=B(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}s(di,"parseListQuery");async function si(e){const n=di(e);let t=await Xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Rt(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await ln(t.map(o=>o.node_id)):null,a=t.length>0?Fe():new Set,c=new Map((await en()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Ae(t,async o=>{const l=await mt(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const p=await Ie(o.node_id);l.activity={latest_report:p[0]??null,final_report:o.final_report===null?null:p.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return l})}}s(si,"handleList");async function li(e){const n=e.params.id,t=await Ot(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:At(e)});if(t.kind==="unknown")throw Tt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Ct(t.status,t.body);return{status:t.status,body:$t(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}s(li,"handleDetail");async function ci(e){const n=e.params.id;await h(n);const t=await bn(n),{start:r}=Sn(t.snapshot.messages,d=>JSON.stringify(ge(d,n)).length),i=t.snapshot.messages.slice(r).map(d=>ge(d,n)),a=kn(i);return{status:200,body:{node_id:n,snapshot:{messages:i,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(r)},messageVisibility:t.snapshot.messageVisibility.slice(r),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([d])=>a.has(d)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(d=>({name:d.name,description:d.description,source:d.source})),captured_at:V()}}}s(ci,"handleSnapshot");async function ui(e){const n=e.params.id,t=await In(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(ui,"handleSubject");function fi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(fi,"parseMessagesQuery");async function pi(e){const n=e.params.id,t=await _n(n,fi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:V()}}}s(pi,"handleMessages");async function mi(e){const n=e.params.id;await h(n);const t=await gn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:V()}}}s(mi,"handleSession");async function wi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await vn(n)}}}s(wi,"handleTranscript");async function hi(e){const n=e.params.id;await h(n);const t=s(async(i,a)=>({node_id:i,label:(await g(i))?.name??i,dir:await _e(i),self:a,files:await Ht(i)}),"root"),r=await Wt([await t(n,!0),...await Ae(await ye(n),async i=>await t(i.node_id,!1))],async i=>await yi(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(hi,"handleContext");async function yi(e,n){try{return mn(await K(e),n)}catch(t){if(hn(t))return!1;throw t}}s(yi,"hasDir");async function _i(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Ue(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}s(_i,"handleFork");const gi=1e4;async function bi(e){const n=e.params.id,t=await h(n),r=await X(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!bt(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await yt(n,{afterTurn:!1,reason:"revive_now"});const i=await _t("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await ht(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}s(bi,"handleKick");async function vi(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;await Tn(n,a,e.principal.class==="broker"?e.principal.node:null);const c=!i&&r?.cron_id!==void 0?await Y(r.cron_id):null,d=await X(n);if(i&&d!==null&&d.runner!=="process"&&d.state==="running"&&!at(t.profile_id))try{await lt({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>gt(d))}catch(u){if(!(u instanceof st))throw u}await he(n,{failures:0,notBefore:null});const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await ct(c,"schedule_revive")}:{}});o.outcome==="already-live"&&await he(n,{failures:t.respawn_failures??0,notBefore:t.respawn_not_before??null});const l=(await g(n))?.status??"active",p=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await ve(n,p,gi);return{status:200,body:wt(n,o,l,f)}}s(vi,"handleRevive");async function ki(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Cn(n))?.newNodeId??null}}}s(ki,"handleRelaunchRoot");async function Si(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=ut(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await xe(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:pt(a)}}s(Si,"handleClose");async function Ii(e){if(!F(e.principal))throw new m(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await nn(n),{status:204}}s(Ii,"handleMarkRead");async function Ri(e){const n=e.params.id;await h(n);const t=await An(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Ri,"handleRecycle");async function Ei(e){const n=e.params.id;return await h(n),await H(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}s(Ei,"handleDemote");async function Oi(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await j(i.kind,r.cwd,r.profile_id??null,r.grantee??"app:terminal"),i.model!==void 0&&await Te(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await En(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await Z(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}s(Oi,"handlePromote");async function Ai(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Nn(n)}}}s(Ai,"handleBrokerStructuredRequest");async function Ci(e){const n=e.params.id,t=e.body??{};if(await $n(n,t.expected_execution_id),typeof t.text!="string")throw new m(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Ln(n,t.text)}}}s(Ci,"handleBrokerGoal");async function Ti(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await j(i.kind,r.cwd,r.profile_id??null,r.grantee??"app:terminal"),i.model!==void 0&&await Te(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Pn(t,a);const c=await On(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await Z(t))}}s(Ti,"handleYield");async function $i(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await g(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new m(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await qe(n,t.controller),{status:200,body:await v(n)}}s($i,"handleWait");async function Ni(e){const n=e.principal,t=await Rn(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!F(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(Ni,"handleReviveAll");const Pi=new Set(["interrupt","steer","after-turn","next-turn"]);function Di(e){if(e===null)return null;const n=s(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Pi.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(Di,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await z(async i=>{if(r?.(i),t.length===0)return;const a=await tn(i,n),c=await an(i,e),d=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await rn(i,d,a),await on(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s(C,"recordConfigured");function De(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(De,"restartLiveBroker");function Le(e,n){try{return oe(e)===oe(n)}catch{return!1}}s(Le,"sameDirectory");async function Li(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),l=await rt(e,i.profile);ot(l.profileId);const p=dt(l.profileId).manifest.grantee??"app:terminal";if(p!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(nt(o.kind)?(await j(o.kind,o.cwd,l.profileId,p),await H(t,{profileId:l.profileId})):await $(t,{profile_id:l.profileId}),await C(e,t,["profile"])),i.restart===!0&&De(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(t),p=T(l.cwd);if(i.keep_session===!0||p&&U(o)&&T(o)&&Le(l.cwd,o)){if(!U(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Le(l.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=l.cwd;return I!==u&&(await z(async k=>{await $(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await dn(t,I,u)}),await C(e,t,["cwd"])),i.restart===!0&&De(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new m(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(T(l.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!U(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!T(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await z(async()=>{await $(t,{cwd:f}),await sn(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const c=i.listen===void 0?void 0:Di(i.listen);if(i.scopes!==void 0){const o=Re(i.scopes),l=a.grantee==="app:terminal"?await Mt(a):a.grant_id?await Pt(a.grant_id):null;if(!o.every(p=>E(a.scopes,p)&&l!==null&&E(l.resolved,p)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new m(400,"invalid_scope","crtr:act requires crtr:llm");a=await $(t,{scopes:o})}if(i.situational_context!==void 0&&await Ge(t,Be(i.situational_context)),i.model!==void 0){const o=(await be(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Bn(i.model,o),p=await jt(a.grant_id,i.model,l===void 0),f=p?{family:Ft,strength:p.strength}:l,u=p?p.model:xn(i.model,o);await J({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await X(t))?.runner==="machine"||await ve(t,_.get(t)?.handle.exited))&&(I=await Vn(t,u,f,await Jn(t)).then(()=>!0,k=>{if(k instanceof zn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new m(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await Un(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await j(i.kind,a.cwd,a.profile_id??null,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let f;l==="orchestrator"&&!await jn(t)&&(f=s(async()=>{const u=await Dn(t);await Mn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await H(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},f)}i.name!==void 0&&(a=await $(t,{name:i.name}),a.window&&Fn(a.window,it(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,d,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await v(t)}}s(Li,"handleConfig");async function Mi(e){const{principal:n}=e,t=n.class==="broker"?n.node:n.class==="cron"?n.anchor:null,r=t!==null?(await g(t))?.profile_id??null:e.query.get("profile"),i=(await be(null,r,St(e.principal)??"app:terminal")).kinds;return{status:200,body:{kinds:Object.keys(i).sort().map(c=>({kind:c,when_to_use:i[c]?.whenToUse??null,available_to:i[c]?.availableTo??null}))}}}s(Mi,"handleListKinds");const bo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ii},{method:"GET",pattern:"/v1/nodes",handler:si},{method:"GET",pattern:"/v1/kinds",handler:Mi},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Ni},{method:"GET",pattern:"/v1/nodes/:id",handler:li},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:ci},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:pi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:mi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:hi},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:_i},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:vi},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:bi},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:$i},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Li}];export{Li as handleConfig,ii as handleCreate,_i as handleFork,si as handleList,Oi as handlePromote,Ti as handleYield,bo as nodeRoutes,So as resolveCreateKind};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var M=Object.defineProperty;var o=(t,e)=>M(t,"name",{value:e,configurable:!0});import{openDb as S}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as $}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as F}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as V}from"../../../core/graph/jobs.js";import{boundFleet as C}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as B}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as G}from"../reader.js";import{canRead as H}from"../../../core/graph/access.js";import{ownersByHandle as K}from"../../../core/graph/names.js";import{reposForCwd as U,warmCheckoutIdentities as W}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as J}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as f}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as Y}from"../../../core/env-name.js";import{listProfileEnvNames as z,removeProfileEnvVar as Q,setProfileEnvVar as X}from"../../../core/profiles/env-store.js";import{isDeploymentName as Z,listAppEnvNames as x,removeAppEnvVar as ee,setAppEnvVar as te}from"../../../core/profiles/app-env-store.js";import{addProfileProject as A,addProfileRepo as ae,assertDeliveryLimits as re,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as ie,listProfiles as u,loadProfileManifest as E,pauseProfile as ne,removeProfileProject as oe,renameProfile as se,resumeProfile as de,setProfileDefaultKind as fe,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as le}from"../../profile-delete.js";import{brokerSignalBus as me}from"../../broker-signals/bus.js";import{toProfileDTO as ue}from"../map.js";import{isCloudRole as I,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as k}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const O="root",ye=4096;function v(t,e=[]){return{...ue(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await k()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function R(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new f(400,"invalid_request",`${t} already has a profile named ${e}`)}o(R,"assertNameFree");async function m(t,e){const r=await N(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new f(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();R(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(p=>typeof p!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const p=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(p)}}if(!I())throw new f(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new f(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await J(a,t,r),await se(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){if(I()){await A(t,r);return}await W(r);const i=(await w(async n=>await U(n,r)))[0];await A(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function Ee(t,e,r,a){const i=await w(async n=>{const s=await G(n,t);for(const p of await K(n,a,"repo"))if(await H(n,s,p))return p;return null});if(i===null)throw new f(404,"not_found",`no repo you can read is named ${a}`);await ae(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Ee,"addRepoWithDefaultLimit");async function ge(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&R(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&re({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await fe(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Ee(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await oe(e,a.remove_project),{status:200,body:await l(E(e))}}o(ge,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await z(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=Y(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function q(t){const e=D(t);if(Z(e)&&!g(t.principal))throw new f(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(q,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await X(e,r,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Q(e,r)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===O&&a==="app:terminal")return{status:200,body:await l(await ie())};if(e===O)throw new f(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(p=>typeof p!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=E(t.params.name),r=await ne(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=C();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&B(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=E(t.params.name),r=await de(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await F(a.node_id)!==null)&&me.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await $(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>V(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function L(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await S(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await he(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(!ve(e)||T(e.scopes,s))})}o(L,"visibleProfiles");async function N(t,e){const r=await L(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new f(404,"not_found","profile not found");if(i.length>1)throw new f(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(N,"requireUsableProfile");async function Re(t){const e=await k();return{status:200,body:(await L(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await N(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return le((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await x(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=q(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await te(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await ee(c(t),q(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:ge},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,N as requireUsableProfile};
|
|
1
|
+
var M=Object.defineProperty;var o=(t,e)=>M(t,"name",{value:e,configurable:!0});import{openDb as S}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as $}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as F}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as V}from"../../../core/graph/jobs.js";import{boundFleet as C}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as B}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as G}from"../reader.js";import{canRead as H}from"../../../core/graph/access.js";import{ownersByHandle as K}from"../../../core/graph/names.js";import{reposForCwd as U,warmCheckoutIdentities as W}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as J}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as f}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as Y}from"../../../core/env-name.js";import{listProfileEnvNames as z,removeProfileEnvVar as Q,setProfileEnvVar as X}from"../../../core/profiles/env-store.js";import{isDeploymentName as Z,listAppEnvNames as x,removeAppEnvVar as ee,setAppEnvVar as te}from"../../../core/profiles/app-env-store.js";import{addProfileProject as A,addProfileRepo as ae,assertDeliveryLimits as ie,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as g,pauseProfile as ne,removeProfileProject as oe,renameProfile as se,resumeProfile as de,setProfileDefaultKind as fe,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as le}from"../../profile-delete.js";import{brokerSignalBus as me}from"../../broker-signals/bus.js";import{toProfileDTO as ue}from"../map.js";import{isCloudRole as I,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as k}from"../../../core/environment-repos.js";import{actsAsPerson as E,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const O="root",ye=4096;function v(t,e=[]){return{...ue(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await k()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function R(t,e,i=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==i&&(a.manifest.grantee??"app:terminal")===t))throw new f(400,"invalid_request",`${t} already has a profile named ${e}`)}o(R,"assertNameFree");async function m(t,e){const i=await N(t,e),a=i.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!E(t.principal)&&a!==j(t.principal))throw new f(403,"permission_error",`profile ${i.profileId} belongs to ${a}; only that app changes it`);return i}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const i=c(t),a=e.name.trim();R(i,a),e.default_kind!==void 0&&await h(e.default_kind,null,null,i);const r=e.repositories??[];if(!Array.isArray(r)||r.some(p=>typeof p!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(r.length===0){const p=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:i});return{status:201,body:v(p)}}if(!I())throw new f(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new f(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),r),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:i,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const i=e.trim();if(i==="")throw d("profile name must not be empty");return await w(async a=>(await J(a,t,i),await se(t,i)))}o(be,"renameProfileAndHandle");async function Pe(t,e,i){if(I()){await A(t,i);return}await W(i);const r=(await w(async n=>await U(n,i)))[0];await A(t,i,r?.id),r!==void 0&&e[r.name]===void 0&&e[`repo:${r.name}`]===void 0&&await _(t,r.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function ge(t,e,i,a){const r=await w(async n=>{const s=await G(n,t);for(const p of await K(n,a,"repo"))if(await H(n,s,p))return p;return null});if(r===null)throw new f(404,"not_found",`no repo you can read is named ${a}`);await ae(e,r.id),i[r.name]===void 0&&i[`repo:${r.name}`]===void 0&&await _(e,r.name,"preview")}o(ge,"addRepoWithDefaultLimit");async function Ee(t){const{profileId:e,manifest:i}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&R(i.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,null,e,i.grantee??"app:terminal"),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ie({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await fe(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,i.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await ge(t,e,i.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await oe(e,a.remove_project),{status:200,body:await l(g(e))}}o(Ee,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await z(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,i=Y(e);if(!i.isValid)throw d(`invalid env var name: ${i.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function q(t){const e=D(t);if(Z(e)&&!E(t.principal))throw new f(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(q,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),i=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await X(e,i,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),i=D(t);return{status:200,body:{profile_id:e,changed:await Q(e,i)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,i=t.body??{};i.projects!==void 0&&b(i.projects);const a=c(t);if(e===O&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===O)throw new f(403,"permission_error","root belongs to the terminal app");const r=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(r!==void 0)return{status:200,body:await l(r)};i.default_kind!==void 0&&await h(i.default_kind,null,null,a);const n=await P(e,i.projects??[],{defaultKind:i.default_kind,metadata:i.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),i=t.body??{};if(typeof i!="object"||i===null||Array.isArray(i))throw d("profile metadata body must be an object",{field:"body"});const a=i,r=a.unset===void 0?[]:a.unset;if(!Array.isArray(r)||r.some(p=>typeof p!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,r);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=g(t.params.name),i=await ne(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:i.manifest.paused_at}};const r=C();for(const n of a){const s=r.get(n.node_id);if(s!==void 0){await r.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&B(n.pi_pid,n.pi_pid_identity)==="alive"&&await r.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:i.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=g(t.params.name),i=await de(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await F(a.node_id)!==null)&&me.markMail(a.node_id);if(i.pausedAt!==null){const a=Date.parse(i.pausedAt);if(!Number.isNaN(a)){const r=Math.max(0,Date.now()-a);await $(e.profileId,r);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>V(s,n.node_id,r))}}return{status:200,body:{profile_id:e.profileId,paused_at:i.manifest.paused_at}}}o(Oe,"handleResume");async function L(t){const e=t.principal;if(E(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await S(),r=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>r.has(n))}const i=await he(e);return u().filter(({profileId:a,manifest:r})=>{const n=r.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(i,s)&&(!ve(e)||T(e.scopes,s))})}o(L,"visibleProfiles");async function N(t,e){const i=await L(t),a=i.find(({profileId:n})=>n===e),r=a?[a]:i.filter(({manifest:n})=>n.name===e);if(r.length===0)throw new f(404,"not_found","profile not found");if(r.length>1)throw new f(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return r[0]}o(N,"requireUsableProfile");async function Re(t){const e=await k();return{status:200,body:(await L(t)).map(i=>v(i,e.get(i.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await N(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return le((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await x(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=q(t),{value:i}=t.body??{};if(typeof i!="string"||!i)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await te(c(t),e,i)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await ee(c(t),q(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:Ee},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,N as requireUsableProfile};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{setTimeout as R}from"node:timers/promises";import{CRON_DEATH_POLL_MS as x,CRON_KILL_GRACE_MS as O,EMPTY_STDOUT_SHA256 as h}from"./capture.js";import{cronDaemonInstanceId as
|
|
1
|
+
var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{setTimeout as R}from"node:timers/promises";import{CRON_DEATH_POLL_MS as x,CRON_KILL_GRACE_MS as O,EMPTY_STDOUT_SHA256 as h}from"./capture.js";import{cronDaemonInstanceId as p,cronOwnerAlive as v,ensureCronOwnerLease as D}from"./live-runs.js";import{crashedOneShotSummary as L,escalateFailure as C}from"./escalation.js";import{settleRun as I}from"./settle.js";import{adoptCronRunId as E,getCron as g,runningCrons as M,stopLeasedCronRun as S,setCronState as T,verifyLeasedCronRun as _}from"../../core/canvas/crons.js";import{claimReconcilerLease as H,releaseReconcilerLease as b,renewReconcilerLease as N}from"../../core/canvas/reconciler-leases.js";import{emitEvent as l}from"../../core/events/emit.js";import{openDb as $}from"../../core/canvas/db.js";import{asPerson as k}from"../reconcilers/node-lifecycle/node-person.js";import{cronEnvironment as G,fireInSandbox as P,resumeMachineFire as U}from"./machine-fire.js";const c="cron-recovery",f=3e4;async function B(e){const t=w();if(await H(c,e,t,f)===void 0)return;let n=!1;const r=s(async()=>{if(n)return!1;try{n=!await N(c,e,t,f)}catch{n=!0}return!n},"holds"),a=setInterval(()=>{r()},f/3);return a.unref(),{holds:r,release:s(async()=>{clearInterval(a),await b(c,e,t)},"release")}}s(B,"claimRecovery");async function F(e){const t=await g(e.cron_id);if(t===null||t.run_state!=="running"||t.run_execution_id!==e.run_execution_id||t.run_started_at!==e.run_started_at||t.run_lease_owner!==e.run_lease_owner||t.run_lease_owner!==null&&await v(t.run_lease_owner))return null;if(t.run_execution_id!==null)return t;const n=w();return await E(t,n)?{...t,run_execution_id:n}:null}s(F,"reverifyAbandoned");async function se(e,t={}){await D();for(const n of await M()){if(n.run_lease_owner===p||n.run_lease_owner!==null&&await v(n.run_lease_owner))continue;const r=n.run_pid===null&&n.run_execution_id!==null?await G(n):null,a=r===null&&(n.run_pid===null||!_(n));if(r===null&&!a&&e-(n.run_started_at!=null?new Date(n.run_started_at).getTime():e)<n.run_timeout_s*1e3)continue;const o=await B(n.cron_id);if(o===void 0)continue;let i;try{i=await F(n)}catch(u){throw await o.release(),u}if(i===null){await o.release();continue}if(r!==null){Y(i,r,t,o);continue}if(a){j(i,e,t,o);continue}K(i,e,t,o)}}s(se,"recoverStaleCronLeases");function K(e,t,n,r){const a=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,o={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:-1,timedOut:!0,runTimeoutS:e.run_timeout_s,processErrorMessage:null,stdoutHead:"",stdoutSha256:h,stderrHead:`run timed out after ${e.run_timeout_s}s (recovered stale lease from a prior daemon instance)`},i=(async()=>{await r.holds()&&(await S(e),await W(e),await r.holds()&&await I(e,{outOfBand:!1,outcome:{kind:"disposed",ctx:o},record:{runId:o.runId,startedAtIso:o.startedAtIso,finishedAtMs:t,durationMs:t-a,exitCode:-1,stdoutHead:null,stderrHead:o.stderrHead},lease:{kind:"clear"}}))})().finally(()=>r.release());n.register?.(i),i.catch(u=>{l({level:"error",event:"cron.stale_lease.settle_failed",error:u,fields:{cron_id:e.cron_id}})})}s(K,"recoverTimedOutRun");function Y(e,t,n,r){const a=(async()=>{await r.holds()&&await V(e)&&await k(e.sub,async()=>{t.kind==="machine"?await U(e,t.id):await P(e,{runId:e.run_execution_id,outOfBand:e.run_out_of_band,startedAtIso:e.run_started_at,startedAtMs:Date.parse(e.run_started_at)},()=>{},!0)})})().finally(()=>r.release());n.register?.(a),a.catch(o=>{l({level:"error",event:"cron.machine_resume.failed",error:o,fields:{cron_id:e.cron_id,run_id:e.run_execution_id}})})}s(Y,"resumeMachineRun");async function V(e){const t=await(await $()).prepare("UPDATE crons SET run_lease_owner = ?, updated = ? WHERE cron_id = ? AND run_state = 'running' AND run_execution_id = ? AND run_lease_owner IS NOT DISTINCT FROM ?").run(p,new Date().toISOString(),e.cron_id,e.run_execution_id,e.run_lease_owner);return Number(t.changes)>0}s(V,"takeOverLease");async function W(e){if(!await y(e)&&(await S(e,"SIGKILL"),!await y(e)))throw new Error(`cron ${e.cron_id} run ${e.run_pid} survived SIGKILL`)}s(W,"awaitLeasedRunDeath");async function y(e){const t=Date.now()+O;for(;Date.now()<t;){if(!_(e))return!0;await R(x)}return!_(e)}s(y,"pollLeasedRunGone");function j(e,t,n,r){const a=e.recur==null,o=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,i=e.run_pid===null?"the daemon life that claimed this run ended before its launch pid was recorded \u2014 the command may have started and its outcome is unknown":"the daemon life that owned this run ended before it settled \u2014 the process is gone and its outcome was never observed",u={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:null,timedOut:!1,runTimeoutS:e.run_timeout_s,processErrorMessage:i,stdoutHead:"",stdoutSha256:h,stderrHead:`run outcome unobserved: ${i}`},m=(async()=>{let d=`crashed: ${i}${a?"":" \u2014 the next occurrence is unaffected"}`;if(a){if(!await r.holds())return;if(await T(e.cron_id,"paused"),e.on_output==="silent")d=`crashed: ${i} \u2014 one-shot paused, not re-fired (silent: not escalated)`;else{if(!await r.holds())return;d=`crashed one-shot: ${await C(e,u,L(i))}`}}await r.holds()&&(await I(e,{outOfBand:!1,outcome:{kind:"stated",delivered:d,paused:a},record:{runId:u.runId,startedAtIso:u.startedAtIso,finishedAtMs:t,durationMs:Math.max(0,t-o),exitCode:null,stdoutHead:null,stderrHead:u.stderrHead},lease:"release"}),l({level:"warn",event:"cron.run.unobserved",fields:{cron_id:e.cron_id,name:e.name,one_shot:a}}))})().finally(()=>r.release());n.register?.(m),m.catch(d=>{l({level:"error",event:"cron.crashed_run.settle_failed",error:d,fields:{cron_id:e.cron_id}})})}s(j,"settleCrashedRun");export{se as recoverStaleCronLeases};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var n=(e,o)=>d(e,"name",{value:o,configurable:!0});import{existsSync as m,readdirSync as p,rmSync as w}from"node:fs";import{reviewsRoot as a}from"../../core/canvas/paths.js";import{listBindingRequests as f,listRequests as y,listReviewRequestIds as R,listUnprojectedReviews as q,markProjectionError as v}from"../../core/human/requests.js";import{projectAndRetire as u}from"./settle.js";function h(e){return e instanceof Error?e.message:String(e)}n(h,"errorText");async function T(){}n(T,"reconcileUndeliveredTickets");async function k(e){let o=0,c=0,s=0,l=0,r=0;for(const t of await f())try{await e.realizeReview(t.request_id),o+=1}catch{r+=1}try{const t=new Set(await R());if(m(a()))for(const i of p(a(),{withFileTypes:!0}))i.isDirectory()&&!t.has(i.name)&&(w(`${a()}/${i.name}`,{recursive:!0,force:!0}),c+=1)}catch{r+=1}for(const t of await q())try{await u(t,{project:e.projectReview,retire:e.retireCompanion}),s+=1}catch(i){await v(t.request_id,h(i)),r+=1}for(const t of await y({state:"settled"}))if(!(t.companion_node_id===null||t.companion_retired_at!==null))try{await u(t,{retire:e.retireCompanion}),l+=1}catch{r+=1}return{realized:o,collected:c,reprojected:s,retired:l,failed:r}}n(k,"sweepHumanRequests");export{T as reconcileUndeliveredTickets,k as sweepHumanRequests};
|
|
@@ -22,8 +22,8 @@ export interface PeerIngressContext {
|
|
|
22
22
|
}
|
|
23
23
|
/** Whether the daemon's own route table serves this request: the routes `servePeer` hands to its router (`peer.*` and every daemon route a forwarded call reaches). */
|
|
24
24
|
export declare function isDaemonRoute(method: string, pathname: string): Promise<boolean>;
|
|
25
|
-
/** The account owner this runtime belongs to: the owner a successful `crtr sys
|
|
26
|
-
* provisioned without
|
|
25
|
+
/** The account owner this runtime belongs to: the owner a successful `crtr sys signin` registration recorded (a laptop), else — on a hosted runtime, which is
|
|
26
|
+
* provisioned without registration — the one `sub` its mirrored grants all carry. Null when neither names exactly one owner. Never throws. */
|
|
27
27
|
export declare function runtimeOwner(): Promise<string | null>;
|
|
28
28
|
/** A bearer the caller already tried to verify and that failed: `servePeer` answers it as its own refusal (and audits it). */
|
|
29
29
|
export interface PeerRefusal {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var I=Object.defineProperty;var l=(e,t)=>I(e,"name",{value:t,configurable:!0});import{spawn as T}from"node:child_process";import{statSync as j}from"node:fs";import{delimiter as R,join as b}from"node:path";import{getRow as G,listNodes as C}from"../../core/canvas/index.js";import{isSafeNodeId as E}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as x,recordedPidLiveness as L}from"../../core/canvas/pid.js";import{emitEvent as m}from"../../core/events/emit.js";import{operationIdContext as y}from"../../core/events/operation-id.js";import{isParked as P}from"../../core/runtime/lifecycle.js";import{runThrottledLane as M}from"./throttled-lane.js";const O=60*1e3,V=3,B=300*1e3,W=300*1e3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)&&!P(e)}l(g,"isClosed");function k(){const e=process.env.PATH;if(e===void 0)return null;for(const t of e.split(R)){const o=b(t===""?
|
|
1
|
+
var I=Object.defineProperty;var l=(e,t)=>I(e,"name",{value:t,configurable:!0});import{spawn as T}from"node:child_process";import{statSync as j}from"node:fs";import{delimiter as R,join as b}from"node:path";import{getRow as G,listNodes as C}from"../../core/canvas/index.js";import{isSafeNodeId as E}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as x,recordedPidLiveness as L}from"../../core/canvas/pid.js";import{emitEvent as m}from"../../core/events/emit.js";import{operationIdContext as y}from"../../core/events/operation-id.js";import{isParked as P}from"../../core/runtime/lifecycle.js";import{runThrottledLane as M}from"./throttled-lane.js";const O=60*1e3,V=3,B=300*1e3,W=300*1e3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)&&!P(e)}l(g,"isClosed");function k(){const e=process.env.PATH;if(e===void 0)return null;for(const t of e.split(R)){const o=b(t===""?".":t,"grove");try{const r=j(o);if(r.isFile()&&(r.mode&73)!==0)return o}catch{}}return null}l(k,"resolveGroveBinary");function D(e,t){return new Promise(o=>{let r;try{r=T(e,[...t],{stdio:["ignore","pipe","pipe"]})}catch(i){o({code:null,signal:null,stdout:"",stderr:"",error:i instanceof Error?i:new Error(String(i))});return}let s="",d="",a=!1;const u=l(i=>{a||(a=!0,o(i))},"settle");r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{d+=i.toString()}),r.on("error",i=>u({code:null,signal:null,stdout:s,stderr:d,error:i})),r.on("close",(i,c)=>u({code:i,signal:c,stdout:s,stderr:d}))})}l(D,"executeGrove");const F={resolveBinary:k,listTerminalNodes:l(async()=>await C({status:[...N]}),"listTerminalNodes"),getNodeRow:G,execute:D,captureLiveness:x};function Y(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||!Array.isArray(t.projects))return null;const o=[];for(const r of t.projects){if(typeof r!="object"||r===null)continue;const s=r.name,d=r.instances;if(!(typeof s!="string"||!Array.isArray(d)))for(const a of d){if(typeof a!="object"||a===null)continue;const u=a.name,i=a.slot,c=a.spec?.labels,p=typeof c=="object"&&c!==null?c.owner:void 0;typeof u=="string"&&typeof i=="number"&&typeof p=="string"&&o.push({project:s,name:u,slot:i,owner:p})}}return o}l(Y,"instancesFromInventory");async function $(e,t,o){return g(e)&&!await t.isClaimed(e.node_id)&&e.frozen_at===null&&L(e.pi_pid,e.pi_pid_identity,o)==="dead"}l($,"engineIsGone");async function z(e,t,o){if(await t.isClaimed(e.node_id))return!1;const r=await o(e.node_id);return r!==null&&g(r)&&r.frozen_at===null&&r.pi_pid===e.pi_pid&&r.pi_pid_identity===e.pi_pid_identity}l(z,"stillEligible");function S(e){if(e.error!==void 0)return e.error;const t=e.stderr.trim()||e.stdout.trim()||`Grove exited with ${e.signal??e.code??"an unknown status"}`;return new Error(t)}l(S,"executionError");function h(e){return`${e.project}/${e.name}`}l(h,"instanceKey");class ne{static{l(this,"GroveInstanceSweepReconciler")}operations;retryAfter=new Map;constructor(t=F){this.operations=t}run(t,o){if(!o.lifecycle.acceptsDetachedWork())return;const r=M("grove-instance-sweep","",t,O,B,s=>this.sweep(t,o.fleet,s)).then(()=>{}).catch(s=>{y.fresh(()=>m({level:"error",event:"grove.sweep.failed",error:s}))});o.lifecycle.registerDetached(r)}async sweep(t,o,r){const s=this.operations.resolveBinary();if(s===null)return;let d;try{d=(await this.operations.listTerminalNodes()).filter(g)}catch(n){y.fresh(()=>{m({level:"error",event:"grove.sweep.scan_failed",error:n})});return}if(d.length===0)return;const a=await this.operations.execute(s,["list","--json"]);if(a.error!==void 0||a.code!==0||a.signal!==null){y.fresh(()=>{m({level:"error",event:"grove.sweep.list_failed",error:S(a)})});return}const u=Y(a.stdout);if(u===null){y.fresh(()=>{m({level:"error",event:"grove.sweep.list_failed",error:new Error("grove list --json returned invalid inventory JSON")})});return}const i=new Map(d.map(n=>[n.node_id,n])),c=u.filter(n=>i.get(n.owner)!==void 0&&(this.retryAfter.get(h(n))??Number.NEGATIVE_INFINITY)<=t).sort((n,f)=>n.project.localeCompare(f.project)||n.slot-f.slot||n.name.localeCompare(f.name));if(c.length===0)return;let p=Number(r.state??0);(!Number.isInteger(p)||p>=c.length)&&(p=0);const v=Math.min(V,c.length),A=Array.from({length:v},(n,f)=>c[(p+f)%c.length]);if(!await r.save(String((p+v)%c.length)))return;const w=await this.operations.captureLiveness();if(w!==null)for(const n of A){const f=i.get(n.owner);if(!await $(f,o,w)||!await z(f,o,this.operations.getNodeRow))continue;if(!await r.holds())return;const _=await this.operations.execute(s,["uproot",h(n),"--force"]);if(_.error===void 0&&_.code===0&&_.signal===null){this.retryAfter.delete(h(n)),y.fresh(()=>{m({level:"info",event:"grove.sweep.reconciled",outcome:"succeeded",...E(n.owner)?{node_id:n.owner}:{fields:{affected_node_id:n.owner}}})});continue}this.retryAfter.set(h(n),t+W),y.fresh(()=>{m({level:"error",event:"grove.sweep.failed",outcome:"failed",...E(n.owner)?{node_id:n.owner}:{fields:{affected_node_id:n.owner}},error:S(_)})})}}}export{V as GROVE_INSTANCE_SWEEP_BUDGET,O as GROVE_INSTANCE_SWEEP_INTERVAL_MS,W as GROVE_INSTANCE_SWEEP_RETRY_DELAY_MS,ne as GroveInstanceSweepReconciler};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],
|
|
1
|
+
var C=Object.defineProperty;var l=(i,e)=>C(i,"name",{value:e,configurable:!0});import{randomUUID as R}from"node:crypto";import{openDb as d,withCanvasWrite as M}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as D,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as y}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as T}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as E,emitRunSettlement as N,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",g=1e4,Y=250;async function w(i,e,t){return await M(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,i,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await t()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,t,n,a,r){this.nodeId=e,this.runId=t,this.owner=n,this.status=a,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,t,n){const a=await d(),r=await a.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===t?"node.settled":"child.settled"),o=await a.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),s=new v(e,t,n,o?JSON.parse(o.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await s.writeStream(null,null),await s.poll(),s}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<g/3?!0:await x(c,this.nodeId,this.owner,g)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,t,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
|
|
2
|
+
WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],t===null?null:JSON.stringify(t),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await y(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const t=e.pi_pid===null?"dormant":e.status;if(this.status!==t){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,t,e.intent??null))).held){this.close();return}this.status=t}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const o=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const s of o)await k(s.node_id,this.runId),await p.get(s.node_id)?.poll()}this.outcomeRevision=n.revision;const a=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?N(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...a===void 0?{}:{result:a}}):N(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const o=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(o,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(s=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:s}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await T(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await X(this.nodeId),t=await this.viewAdmitted();if(this.client||this.closed||!t){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:R(),attends:!1}));const a=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const o=r.message.content;if(!Array.isArray(o))return;const s=o.at(-1);if(s&&typeof s=="object"&&"type"in s&&(s.type==="toolCall"?this.block={kind:"tool_call",name:"name"in s&&typeof s.name=="string"?s.name:""}:(s.type==="text"||s.type==="thinking")&&(this.block={kind:s.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const m=o.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),f=o.filter(u=>u?.type==="text").map(u=>u.text).join(""),L=m.startsWith(this.thinking)?m.slice(this.thinking.length):m,b=f.startsWith(this.output)?f.slice(this.output.length):f;this.thinking=m,this.output=f,this.pendingThinking+=L,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>a(r)).catch(o=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:o})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,t=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!t)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await E(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),t&&await E(this.runId,this.nodeId,"node.output_text.delta",{delta:t})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await D(c,this.nodeId,this.owner)}).then(()=>{}).catch(t=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:t})});const e=this.client;this.client=void 0,e?.close()}}async function X(i){const e=await T(i);if(e===null)return new O(i,{recordsViewerFaults:!1});const t=await W(e.runner).viewerAddress(e);return t.kind==="machine"?new A(i,()=>U(t.environmentId,i)):t.kind==="unix"?new O(i,{recordsViewerFaults:!1}):new A(i,()=>q(t.url,t.headers))}l(X,"viewTransport");async function pe(i){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(i);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function me(i){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(i);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(me,"openAssistantBlock");async function fe(){const i=[...p.values()];for(const e of i)e.close();await Promise.all(i.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(fe,"closeRunObserversForTests");async function I(i){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(i,i)!==void 0}l(I,"runRootExists");const _=new Map;async function k(i,e){const t=_.get(i);if(t)return t;if(p.has(i))return;const n=$(i,e).finally(()=>_.delete(i));return _.set(i,n),n}l(k,"ensureRunObserver");async function $(i,e){if(!await I(e))return;const t=R();if(await F(c,i,t,g)!==void 0)try{if(i!==e){const n=await y(i);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,i)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(i,t,()=>E(e,i,"child.started",{child_node_id:i,kind:n.kind}))).held)return}await v.start(i,e,t)}catch(n){throw await D(c,i,t).catch(()=>{}),n}}l($,"startRunObserver");async function we(){const i=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id
|
|
3
3
|
FROM node_rows n
|
|
4
|
-
|
|
5
|
-
AND
|
|
6
|
-
|
|
4
|
+
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'
|
|
5
|
+
AND NOT EXISTS (SELECT 1 FROM run_events e WHERE e.run_id = n.run_id AND e.node_id = n.node_id
|
|
6
|
+
AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
|
|
7
|
+
AND (e.body_json::json #>> '{outcome,revision}') = COALESCE(n.outcome_revision, 1)::text)))`).all(i);for(const t of e)try{await k(t.node_id,t.run_id),S.delete(t.node_id)}catch(n){Q(t.node_id,n)}}l(we,"pollRunObservers");const S=new Map;function Q(i,e){const t=e instanceof Error?e.message:String(e);S.get(i)!==t&&(S.set(i,t),h({level:"error",event:"daemon.runs.observer_failed",node_id:i,error:e}))}l(Q,"reportObserverFailure");export{fe as closeRunObserversForTests,k as ensureRunObserver,me as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,X as viewTransport};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.790",
|
|
4
4
|
"description": "crtr — agent runtime with memory, plugins, and marketplaces",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -157,8 +157,8 @@
|
|
|
157
157
|
},
|
|
158
158
|
"license": "UNLICENSED",
|
|
159
159
|
"dependencies": {
|
|
160
|
-
"@north-light/identity": "0.3.
|
|
161
|
-
"@north-light/plugin": "0.3.
|
|
160
|
+
"@north-light/identity": "0.3.790",
|
|
161
|
+
"@north-light/plugin": "0.3.790",
|
|
162
162
|
"@earendil-works/chord": "1.5.2",
|
|
163
163
|
"@earendil-works/pi-agent-core": "1.5.2",
|
|
164
164
|
"@earendil-works/pi-ai": "1.5.2",
|
|
@@ -450,8 +450,8 @@ export class CrtrClient {
|
|
|
450
450
|
waitNode(id, req) {
|
|
451
451
|
return this.request('POST', routes.nodeWait(this.nodePath(id)), req);
|
|
452
452
|
}
|
|
453
|
-
listKinds() {
|
|
454
|
-
return this.request('GET', routes.kinds());
|
|
453
|
+
listKinds(opts = {}) {
|
|
454
|
+
return this.request('GET', withQuery(routes.kinds(), { profile: opts.profile }));
|
|
455
455
|
}
|
|
456
456
|
/** A model change may first wait up to 30 s for a starting broker's view
|
|
457
457
|
* socket and then 15 s for its ack, so it gets that budget on top. */
|
|
@@ -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.89';
|
|
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`. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// person-state.ts — the process's person binding (
|
|
1
|
+
// person-state.ts — the process's person binding (client-bound person, cloud-role flag, per-request person). Pure: no database, so the
|
|
2
2
|
// CLI-reachable settings cache can read the current person without reaching canvas state.
|
|
3
3
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
4
|
/** Thrown by `personId()` before the person is known (a hosted first boot, before its first grant snapshot). */
|
|
@@ -12,11 +12,11 @@ export class PersonOutsideRequestError extends Error {
|
|
|
12
12
|
code = 'person_outside_request';
|
|
13
13
|
constructor() { super('no person: a cloud role reads the person only inside a request, from its token'); this.name = 'PersonOutsideRequestError'; }
|
|
14
14
|
}
|
|
15
|
-
let
|
|
15
|
+
let clientPersonId;
|
|
16
16
|
let cloudRole = false;
|
|
17
17
|
const requestPersons = new AsyncLocalStorage();
|
|
18
|
-
/** crtrd
|
|
19
|
-
export function
|
|
18
|
+
/** A CLI, viewer or launch-config subprocess binds the one person it acts for (the person its settings answer named). A crtrd process never calls this: it reads the person from the request or the row it serves. */
|
|
19
|
+
export function bindClientPerson(id) { clientPersonId = id; }
|
|
20
20
|
/** crtrd calls this at boot on a cloud role, instead of resolving a person: from then on a person read outside a request throws. */
|
|
21
21
|
export function markCloudRole() { cloudRole = true; }
|
|
22
22
|
/** Whether this process is a cloud role (`markCloudRole` ran at boot). */
|
|
@@ -27,19 +27,17 @@ export function markEnginesInProcess() { enginesInProcess = true; }
|
|
|
27
27
|
export function areEnginesInProcess() { return enginesInProcess; }
|
|
28
28
|
/** Run `fn` as `person` (`user:<id>`, the request token's `sub`): every `personId()` inside it, across awaits, answers `person`. */
|
|
29
29
|
export function runAsPerson(person, fn) { return requestPersons.run(person, fn); }
|
|
30
|
-
/** The request's person; else
|
|
31
|
-
* `PersonUnresolvedError` when
|
|
30
|
+
/** The request's person; else the person a CLI-side process bound. Throws `PersonOutsideRequestError` on a cloud role outside a request and
|
|
31
|
+
* `PersonUnresolvedError` when no client-bound person exists. Tests and non-daemon processes use `personIdAsync()`. */
|
|
32
32
|
export function personId() {
|
|
33
33
|
const request = requestPersons.getStore();
|
|
34
34
|
if (request !== undefined)
|
|
35
35
|
return request;
|
|
36
36
|
if (cloudRole)
|
|
37
37
|
throw new PersonOutsideRequestError();
|
|
38
|
-
if (
|
|
38
|
+
if (clientPersonId === undefined)
|
|
39
39
|
throw new PersonUnresolvedError();
|
|
40
|
-
return
|
|
40
|
+
return clientPersonId;
|
|
41
41
|
}
|
|
42
|
-
/** The
|
|
43
|
-
export function bootPersonId() { return daemonPersonId; }
|
|
44
|
-
/** The request's person, if any (for `personIdAsync`). */
|
|
42
|
+
/** The request's person, if any. */
|
|
45
43
|
export function requestPersonId() { return requestPersons.getStore(); }
|