@north-light/cli 0.3.720 → 0.3.722

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/recovery.d.ts +2 -0
  4. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  5. package/dist/cli.js +8 -8
  6. package/dist/clients/attach/viewer.js +314 -314
  7. package/dist/commands/api-client.d.ts +2 -0
  8. package/dist/commands/api-client.js +2 -2
  9. package/dist/commands/node/inspect.js +7 -7
  10. package/dist/commands/profile/environment.js +2 -2
  11. package/dist/core/canvas/schema-pg/031-environment-pull-request-write-default.sql +2 -0
  12. package/dist/core/canvas/schema-pg/032-model-cooldown-vendor-limit.sql +4 -0
  13. package/dist/core/canvas/schema-version.d.ts +1 -1
  14. package/dist/core/canvas/schema-version.js +1 -1
  15. package/dist/core/environments.js +1 -1
  16. package/dist/core/graph/reader.js +1 -1
  17. package/dist/core/import/load/open-grants.d.ts +1 -0
  18. package/dist/core/import/load/open-grants.js +1 -0
  19. package/dist/core/import/load/run.d.ts +3 -1
  20. package/dist/core/import/load/run.js +2 -2
  21. package/dist/core/llm/run.js +2 -2
  22. package/dist/core/managed-providers.d.ts +9 -1
  23. package/dist/core/provider-failure.d.ts +2 -0
  24. package/dist/core/provider-failure.js +1 -1
  25. package/dist/core/runtime/broker/model-adapter.js +3 -3
  26. package/dist/core/runtime/revive.d.ts +2 -0
  27. package/dist/core/runtime/revive.js +2 -2
  28. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  29. package/dist/core/runtime/runner/blaxel/image-build.js +6 -6
  30. package/dist/core/subscription-state.d.ts +4 -4
  31. package/dist/core/subscription-state.js +1 -1
  32. package/dist/daemon/api/handlers/messages.js +2 -2
  33. package/dist/daemon/api/handlers/nodes.js +1 -1
  34. package/dist/daemon/api/handlers/profiles.js +1 -1
  35. package/dist/daemon/api/operations.js +1 -1
  36. package/dist/daemon/api/router.d.ts +4 -0
  37. package/dist/daemon/api/router.js +1 -1
  38. package/dist/daemon/reconcilers/broker-supervision.js +3 -3
  39. package/docs/sdk/release-notes.md +6 -0
  40. package/package.json +3 -3
  41. package/packages/crouter-api/dist/api/contract.js +1 -1
  42. package/packages/crouter-api/dist/commands/api-client.js +3 -1
  43. package/packages/crouter-api/dist/commands/node/inspect.js +2 -1
  44. package/packages/crouter-api/dist/commands/profile/environment.js +2 -2
  45. package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
  46. package/packages/crouter-api/dist/core/environments.js +1 -1
  47. package/packages/crouter-api/dist/core/graph/reader.js +3 -3
  48. package/packages/crouter-api/dist/core/llm/run.js +13 -2
  49. package/packages/crouter-api/dist/core/provider-failure.js +9 -0
  50. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +3 -1
  51. package/packages/crouter-api/dist/core/runtime/revive.js +11 -0
  52. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +16 -1
  53. package/packages/crouter-api/dist/core/subscription-state.js +26 -10
  54. package/packages/crouter-api/dist/daemon/api/operations.js +2 -2
  55. package/packages/crouter-api/dist/daemon/api/router.js +1 -1
  56. package/packages/crouter-api/dist/daemon/reconcilers/broker-supervision.js +3 -1
  57. package/packages/crouter-api/package.json +1 -1
  58. package/packages/crouter-identity/package.json +1 -1
  59. package/packages/crouter-plugin/package.json +3 -3
  60. package/runtime.lock.json +14 -14
@@ -1 +1 @@
1
- var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}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 Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}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 Ve,assertLaunchModelRegistered as V,forkNode as Ke,resolveForkSource as se,spawnChildPrepared as Je}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 ze,claimCreateLease as fe,createLeaseLive as He,renewCreateLease as Ye,childrenOf as Qe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Xe,reserveCreateRequest as we,reserveCreateRequestNode as Ze,listNodes as qe,recordRespawnAttempt as en,subscribersOf as nn,subscriptionsOf as he,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 ye,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 _e}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 ge}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 be}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 ve}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 ke,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 Se}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 Ie}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 Re}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{hasConfiguredProviderCredential as Wt,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Ut,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Vt,collectStepTimings as Kt,serverTimingHeader as Jt,sinceCollectionStart as zt,timedStep as Ht}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 he(e),subscribers:await nn(e),children:await Qe(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 Yt(e){let n=(await Se(e)).length;try{n+=bn(await J(e),await ye(e)).length}catch(t){if(!_n(t))throw t}return n}d(Yt,"countFiles");function Qt(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&&Ie(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(Qt,"parseCreateBody");function Xt(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(Xt,"parseDeadline");function Zt(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")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(Zt,"parseOutcomeDelivery");function qt(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(qt,"resolveOutcomeDelivery");function ei(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(ei,"buildRecipe");function ni(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(ni,"warmRequestFor");import{resolveCreateKind as Io}from"../../../core/runtime/launch-target.js";function Ae(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Kn(e.model,n,e.modelExact===!0)}d(Ae,"requestFromLaunch");function ti(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(ti,"withinCeiling");async function Ce(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(Ae(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Ce,"assertNodeModelChangeRegistered");async function ii(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(ii,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ii(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($e,"assertCallerReaches");const q=new Map;async function ri(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Kt(()=>oi(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":Jt(a)}}}d(ri,"handleCreate");async function oi(e,n,t){const r=ti(Qt(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=ai(e,r,i,n,t);q.set(i,c);try{return await c}finally{q.delete(i)}}d(oi,"createWithinTimings");const Te=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(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 He(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(Ne,"awaitForeignCreate");async function ai(e,n,t,r,i){const a=await we(t),c=Te;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,c))throw o}const s=setInterval(()=>{Ye(t,c).catch(()=>{})},ze);try{return await di(e,n,t,r,i,a)}finally{clearInterval(s)}}d(ai,"handleKeyedCreateRequest");async function di(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(di,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Xt(n.deadline),c=Zt(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:Me,...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 Re(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:qt(c,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ae(await Ve(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Mt(te)!=="app"&&!await Wt(f===null?[]:await Bt(f))&&!await jt(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,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"?ni(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Re(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),ke(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 Ze(i.requestKey,D,Te);if(g!==D)return await Ne(e,i.requestKey,g)}const R=ei(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",Vt("handler_checks",zt());const re=await Je(R,B,()=>{x!==null&&ke(x)});return i!==void 0&&await Xe(i.requestKey,re.node.node_id),{status:201,body:await Ht("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 si(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(si,"parseListQuery");async function li(e){const n=si(e);let t=await qe({...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?xe():new Set,c=new Map((await rn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(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 Se(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(li,"handleList");async function ci(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(ci,"handleDetail");async function ui(e){const n=e.params.id;await h(n);const t=await Sn(n),{start:r}=En(t.snapshot.messages,s=>JSON.stringify(_e(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>_e(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(ui,"handleSnapshot");async function fi(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(fi,"handleSubject");function pi(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(pi,"parseMessagesQuery");async function mi(e){const n=e.params.id,t=await vn(n,pi(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(mi,"handleMessages");async function wi(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(wi,"handleSession");async function hi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await In(n)}}}d(hi,"handleTranscript");async function yi(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 ye(i),self:a,files:await Yt(i)}),"root"),r=await Ut([await t(n,!0),...await Oe(await he(n),async i=>await t(i.node_id,!1))],async i=>await _i(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(yi,"handleContext");async function _i(e,n){try{return yn(await J(e),n)}catch(t){if(gn(t))return!1;throw t}}d(_i,"hasDir");async function gi(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 Ke(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(gi,"handleFork");const bi=1e4;async function vi(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(vi,"handleKick");async function ki(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}const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await pt(c,"schedule_revive")}:{}});o.outcome!=="already-live"&&await en(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,bi);return{status:200,body:_t(n,o,l,f)}}d(ki,"handleRevive");async function Si(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Nn(n))?.newNodeId??null}}}d(Si,"handleRelaunchRoot");async function Ii(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 Ue(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(Ii,"handleClose");async function Ri(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(Ri,"handleMarkRead");async function Ei(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(Ei,"handleRecycle");async function Oi(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(Oi,"handleDemote");async function Ai(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 Ce(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(Ai,"handlePromote");async function Ci(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Ln(n)}}}d(Ci,"handleBrokerStructuredRequest");async function $i(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($i,"handleBrokerGoal");async function Ti(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 Ce(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(Ti,"handleYield");async function Ni(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(Ni,"handleWait");async function Pi(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(Pi,"handleReviveAll");const Di=new Set(["interrupt","steer","after-turn","next-turn"]);function Li(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"||!Di.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Li,"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 Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"sameDirectory");async function Mi(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&&Pe(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)&&De(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&&!De(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&&Pe(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:Li(i.listen);if(i.scopes!==void 0){const o=Ie(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 Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(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 be(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 Me(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(Mi,"handleConfig");async function Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function ji(){const e=await Le();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(ji,"handleListKinds");const vo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ri},{method:"GET",pattern:"/v1/nodes",handler:li},{method:"GET",pattern:"/v1/kinds",handler:d(()=>ji(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Pi},{method:"GET",pattern:"/v1/nodes/:id",handler:ci},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:mi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:yi},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:gi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:vi},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:$i},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Ni},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mi}];export{Mi as handleConfig,ri as handleCreate,gi as handleFork,li as handleList,Ai as handlePromote,Ti as handleYield,vo as nodeRoutes,Io as resolveCreateKind};
1
+ var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}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 Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{assertCheckoutNotRemoved as Ve,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 nn,subscribersOf as tn,subscriptionsOf as he,updateNode as T}from"../../../core/canvas/canvas.js";import{armControllerWait as rn,liveControllerWaits as on}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as an}from"../../../core/canvas/recovery.js";import{nodeObject as dn}from"../../../core/graph/objects.js";import{recordActedOn as sn}from"../../../core/graph/edges.js";import{publish as ln}from"../../../core/graph/events.js";import{readerFor as cn}from"../reader.js";import{relocateSessionCwd as un,unbindSession as fn}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as pn}from"../../../core/canvas/attention.js";import{isSafeNodeId as mn}from"../../../core/canvas/paths.js";import{contextDir as ye,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as wn,cronRefusalError as hn}from"../../cron/authority.js";import{cronBirthPlacement as yn}from"../../cron/armed-context.js";import{existsBeneath as _n,isAbsentOrRefused as gn,isBeneathRefusal as bn,readdirBeneath as vn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as kn,readNodeSession as Sn,readNodeSnapshot as In,transcriptMarkdown as Rn}from"../../../core/runtime/node-read.js";import{toolCallIds as En,withoutImages as _e}from"../../../core/runtime/broker-protocol.js";import{welcomeWindow as On}from"../../../core/runtime/session-cycles.js";import{assembleNodeSubject as Cn}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as $n,requestYieldAsync as Tn,reshapeNodeAsync as z}from"../../../core/runtime/promote.js";import{recycleNode as Nn}from"../../../core/runtime/recycle.js";import{relaunchRoot as Pn}from"../../../core/runtime/reset.js";import{assertReopenGate as Dn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Ln}from"./broker-recovery.js";import{readOutputRequest as Mn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as jn,readGoal as Fn,captureGoalIfAbsent as Gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as xn,hasRoadmap as Bn}from"../../../core/runtime/roadmap.js";import{renameWindow as Wn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Un,explicitModelIntent as Vn,normalizeModel as Kn,readMergedLaunchConfigAsync as ge}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Jn}from"../../../core/model-routes.js";import{persistDormantModel as zn,setModelLive as Hn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as be}from"../../../core/runtime/view-socket.js";import{viewTransport as Yn}from"../../runs/observer.js";import{BrokerUnreachableError as Qn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Xn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Zn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ve}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as qn}from"../../../core/human/action-binding.js";import{resolveHumanAction as et}from"../../../core/human-actions.js";import{parseDurationMs as nt}from"../../../core/wake.js";import{claimWarmNode as tt,refillWarmPool as ke,resumeWarmClaim as it,warmPoolEnabled as rt}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as H,isLaunchKind as ot,resolveLaunchTarget as at}from"../../../core/runtime/launch-target.js";import{fullName as dt}from"../../../core/canvas/labels.js";import{reportsForNode as Se}from"./reports.js";import{requireUsableProfile as st}from"./profiles.js";import{assertProfileActive as lt,isProfilePaused as ct,loadExactProfileManifest as ut}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ft}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as pt}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Y}from"../../../core/canvas/crons.js";import{cronWakeOrigin as mt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as wt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as ht,validateScopes as Ie}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as yt,toNodeDetailDTO as Q,toNodeSummaryDTO as _t,toReviveResultDTO as gt}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as bt,liveExecutionForNode as X,requestExecutionStop as vt}from"../../../core/canvas/executions.js";import{runnerForExecution as kt}from"../../../core/runtime/runner/index.js";import{wakeResident as St}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as It}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as Rt}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Et}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as C,mayOnNode as Ot,readableNodeIds as Ct,resolvedScopes as At}from"../router.js";import{forwardVerb as $t,queryWithoutMachine as Tt,relayError as Nt,unknownError as Pt,withMachine as Dt}from"../../peer/forward.js";import{fileRoot as Lt}from"../../../core/spaces/file-root.js";import{activeGrant as Mt,payerOfGrant as jt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Ft}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Gt}from"../../../core/grants/terminal.js";import{appRungForGrant as xt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Bt}from"../../../core/model-routes.js";import{listProfileEnvNames as Wt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Ut,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Vt,mapAsync as Oe}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 he(e),subscribers:await tn(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 Se(e)).length;try{n+=vn(await J(e),await ye(e)).length}catch(t){if(!gn(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&&Ie(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=nt(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"||!qn.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")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(qt,"parseOutcomeDelivery");function ei(e,n){const t=et(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!rt()||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 Ro}from"../../../core/runtime/launch-target.js";function Ce(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Jn(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 Ae(e,n,t){const r=(await Un(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(Ae,"assertNodeModelChangeRegistered");async function ri(e){if(!Et()||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 Rt(n)!==null}d(ri,"callerRunsOnMachine");async function $e(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ri(t))return;const r=Lt({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($e,"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 C(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 C(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 Ot(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 wn({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 hn(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&&ht(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&mn(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 Te=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(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 C(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(Ne,"awaitForeignCreate");async function di(e,n,t,r,i){const a=await we(t),c=Te;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,c))try{return await Ne(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 C(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 yn({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 Zn(l)}const m=await at(n,{validateKind:Me,...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 Re(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: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 jt(te)!=="app"&&!await Ut(f===null?[]:await Wt(f))&&!await Ft(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,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 Re(f)!==null)?ie:null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Xn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await it(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 tt(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),ke(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,Te);if(g!==D)return await Ne(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&&ke(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 Ct(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await pn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,c=new Map((await on()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const l=await _t(o,o.profile_id!==null&&a.has(o.profile_id),c.get(o.node_id)??null);if(i!==null){const m=await Se(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 $t(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:Tt(e)});if(t.kind==="unknown")throw Pt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Nt(t.status,t.body);return{status:t.status,body:Dt(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 In(n),{start:r}=On(t.snapshot.messages,s=>JSON.stringify(_e(s,n)).length),i=t.snapshot.messages.slice(r).map(s=>_e(s,n)),a=En(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 Cn(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 kn(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 Sn(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 Rn(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 ye(i),self:a,files:await Qt(i)}),"root"),r=await Vt([await t(n,!0),...await Oe(await he(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 _n(await J(e),n)}catch(t){if(bn(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(!It(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 vt(n,{afterTurn:!1,reason:"revive_now"});const i=await kt("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 bt(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;Ve(n,t),await Dn(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"&&!ct(t.profile_id))try{await pt({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>St(s))}catch(u){if(!(u instanceof ft))throw u}const o=await de(n,{resume:i,capacity:"refuse",...c!==null?{wakeReason:await mt(c,"schedule_revive")}:{}});o.outcome!=="already-live"&&await nn(n,{failures:0,notBefore:null});const l=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,vi);return{status:200,body:gt(n,o,l,f)}}d(Si,"handleRevive");async function Ii(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Pn(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=wt(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await Ue(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:yt(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 an(n),{status:204}}d(Ei,"handleMarkRead");async function Oi(e){const n=e.params.id;await h(n);const t=await Nn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Oi,"handleRecycle");async function Ci(e){const n=e.params.id;return await h(n),await z(n,{lifecycle:"terminal"}),await A(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Ci,"handleDemote");async function Ai(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 Ae(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await $n(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await A(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(Ai,"handlePromote");async function $i(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Mn(n)}}}d($i,"handleBrokerStructuredRequest");async function Ti(e){const n=e.params.id,t=e.body??{};if(await Ln(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 Gn(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 Ae(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 jn(t,a);const c=await Tn(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 rn(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 C(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await C(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 A(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await dn(i,n),c=await cn(i,e),s=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await sn(i,s,a),await ln(i,{event:"configured",object:a,actor:s,attrs:{changed:t.join(",")}})})}d(A,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"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 st(e,i.profile);lt(l.profileId);const m=ut(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&&(ot(o.kind)?(await H(o.kind,o.cwd,l.profileId),await z(t,{profileId:l.profileId})):await T(t,{profile_id:l.profileId}),await A(e,t,["profile"])),i.restart===!0&&Pe(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)&&De(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&&!De(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 un(t,I,u)}),await A(e,t,["cwd"])),i.restart===!0&&Pe(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 fn(t)}),await A(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=Ie(i.scopes),l=a.grantee==="app:terminal"?await Gt(a):a.grant_id?await Mt(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 Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=Vn(i.model,o),m=await xt(a.grant_id,i.model,l===void 0),f=m?{family:Bt,strength:m.strength}:l,u=m?m.model:Kn(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 be(t,_.get(t)?.handle.exited))&&(I=await Hn(t,u,f,await Yn(t)).then(()=>!0,k=>{if(k instanceof Qn)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 zn(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 Me(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 Bn(t)&&(f=d(async()=>{const u=await Fn(t);await xn(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&&Wn(a.window,dt(a)));const s=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await A(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 Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function Fi(){const e=await Le();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 ko=[{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:Ci},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{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,Ai as handlePromote,Ni as handleYield,ko as nodeRoutes,Ro as resolveCreateKind};
@@ -1 +1 @@
1
- var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as $}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as F}from"../../../core/graph/jobs.js";import{boundFleet as S}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as A}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,resolvedScopes as ve}from"../router.js";const I="root",he=4096;function v(t,e=[]){return{...me(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 A()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function ye(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();k(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(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(f)}}if(!ue())throw new p(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 p(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:he,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(ye,"handleCreate");async function _e(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await U(a,t,r),await oe(t,r)))}o(_e,"renameProfileAndHandle");async function be(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(be,"addProjectWithDefaultLimit");async function Pe(t,e,r,a){const i=await w(async n=>{const s=await C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Pe,"addRepoWithDefaultLimit");async function Ee(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&k(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&&ae({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await _e(e,a.name),a.default_kind!==void 0&&await de(e,a.default_kind),a.add_project?.path!==void 0?await be(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Pe(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 ne(e,a.remove_project),{status:200,body:await l(E(e))}}o(Ee,"handleUpdate");async function ge(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await J(e)}}}o(ge,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"requireSelfEnvVarName");async function je(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 z(e,r,a)}}}o(je,"handleEnvSet");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Y(e,r)}}}o(De,"handleEnvRemove");async function Te(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===I&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===I)throw new p(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(Te,"handleEnsure");async function Ae(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(f=>typeof f!="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(Ae,"handleSetMetadata");async function Ie(t){const e=E(t.params.name),r=await ie(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=S();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&&V(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(Ie,"handlePause");async function ke(t){const e=E(t.params.name),r=await se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await $(a.node_id)!==null)&&le.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 M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>F(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),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 ve(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)&&(e.class!=="broker"||T(e.scopes,s))})}o(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Oe(t){const e=await A();return{status:200,body:(await R(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Oe,"handleList");async function Re(t){return{status:200,body:await l(await q(t,t.params.name))}}o(Re,"handleGet");async function qe(t){return fe((await m(t,t.params.name)).profileId,t.body)}o(qe,"handleDelete");const ot=[{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=O(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 x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Te},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:Ie},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:ke},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ae},{method:"POST",pattern:"/v1/profiles",handler:ye},{method:"PATCH",pattern:"/v1/profiles/:name",handler:Ee},{method:"GET",pattern:"/v1/profiles/:name/env",handler:ge},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:je},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name",handler:qe},{method:"GET",pattern:"/v1/profiles",handler:Oe},{method:"GET",pattern:"/v1/profiles/:name",handler:Re}];export{be as addProjectWithDefaultLimit,ot as profileRoutes,_e as renameProfileAndHandle,q as requireUsableProfile};
1
+ var L=Object.defineProperty;var o=(t,e)=>L(t,"name",{value:e,configurable:!0});import{openDb as N}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as M}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as $}from"../../../core/graph/jobs.js";import{boundFleet as F}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as V}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as C}from"../reader.js";import{canRead as B}from"../../../core/graph/access.js";import{ownersByHandle as G}from"../../../core/graph/names.js";import{reposForCwd as H,warmCheckoutIdentities as K}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as U}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as W}from"../../../core/env-name.js";import{listProfileEnvNames as J,removeProfileEnvVar as Y,setProfileEnvVar as z}from"../../../core/profiles/env-store.js";import{isDeploymentName as Q,listAppEnvNames as X,removeAppEnvVar as Z,setAppEnvVar as x}from"../../../core/profiles/app-env-store.js";import{addProfileProject as ee,addProfileRepo as te,assertDeliveryLimits as ae,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as E,pauseProfile as ie,removeProfileProject as ne,renameProfile as oe,resumeProfile as se,setProfileDefaultKind as de,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as fe}from"../../profile-delete.js";import{brokerSignalBus as le}from"../../broker-signals/bus.js";import{toProfileDTO as me}from"../map.js";import{isCloudRole as ue,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as A}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const I="root",ye=4096;function v(t,e=[]){return{...me(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 A()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function k(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new p(400,"invalid_request",`${t} already has a profile named ${e}`)}o(k,"assertNameFree");async function m(t,e){const r=await q(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new p(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();k(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(f=>typeof f!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const f=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(f)}}if(!ue())throw new p(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 p(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 U(a,t,r),await oe(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){await K(r);const i=(await w(async n=>await H(n,r)))[0];await ee(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 C(n,t);for(const f of await G(n,a,"repo"))if(await B(n,s,f))return f;return null});if(i===null)throw new p(404,"not_found",`no repo you can read is named ${a}`);await te(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&&k(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&&ae({[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 de(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 ne(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 J(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=W(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function O(t){const e=D(t);if(Q(e)&&!g(t.principal))throw new p(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(O,"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 z(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 Y(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===I&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===I)throw new p(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(f=>typeof f!="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 ie(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=F();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&&V(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 se(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await S(a.node_id)!==null)&&le.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 M(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>$(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function R(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await N(),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(R,"visibleProfiles");async function q(t,e){const r=await R(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new p(404,"not_found","profile not found");if(i.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(q,"requireUsableProfile");async function Re(t){const e=await A();return{status:200,body:(await R(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await q(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return fe((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=O(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 x(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await Z(c(t),O(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,q as requireUsableProfile};