@north-light/cli 0.3.651 → 0.3.653

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 (41) hide show
  1. package/dist/build-root.js +1 -1
  2. package/dist/clients/attach/chrome/ticket-panel.js +1 -1
  3. package/dist/clients/attach/viewer.js +487 -489
  4. package/dist/clients/inbox/controller.d.ts +6 -6
  5. package/dist/clients/inbox/controller.js +1 -1
  6. package/dist/clients/inbox/tui.js +1 -1
  7. package/dist/commands/human/queue.js +1 -1
  8. package/dist/commands/sys/daemon.js +1 -1
  9. package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -1
  10. package/dist/core/canvas/managed-worktree-sweep-candidates.js +1 -1
  11. package/dist/core/canvas/schema-pg/017-machine-worktree-ops.sql +7 -0
  12. package/dist/core/canvas/schema-version.d.ts +1 -1
  13. package/dist/core/canvas/schema-version.js +1 -1
  14. package/dist/core/command-plugins/compose.d.ts +5 -1
  15. package/dist/core/command-plugins/compose.js +1 -1
  16. package/dist/core/human/convention.d.ts +1 -3
  17. package/dist/core/human/convention.js +2 -2
  18. package/dist/core/human/types.d.ts +0 -7
  19. package/dist/core/runtime/runner/machine/call.d.ts +2 -1
  20. package/dist/core/runtime/runner/machine/call.js +2 -2
  21. package/dist/core/runtime/runner/machine/executor.d.ts +1 -1
  22. package/dist/core/runtime/runner/machine/ops.d.ts +59 -1
  23. package/dist/core/runtime/runner/machine/ops.js +1 -1
  24. package/dist/core/runtime/spawn.js +2 -2
  25. package/dist/core/worktree-close.d.ts +27 -0
  26. package/dist/core/worktree-close.js +6 -6
  27. package/dist/core/worktree-machine.d.ts +27 -0
  28. package/dist/core/worktree-machine.js +1 -0
  29. package/dist/core/worktree-mutation-async.d.ts +31 -0
  30. package/dist/core/worktree-mutation-async.js +7 -7
  31. package/dist/daemon/api/handlers/human-requests.js +1 -1
  32. package/dist/daemon/api/handlers/nodes.js +1 -1
  33. package/dist/daemon/api/handlers/reports.js +5 -5
  34. package/dist/daemon/api/handlers/worktree.js +1 -1
  35. package/dist/daemon/machine-daemon.js +1 -1
  36. package/dist/daemon/manage.js +3 -3
  37. package/package.json +2 -2
  38. package/packages/crouter-identity/package.json +1 -1
  39. package/runtime.lock.json +13 -13
  40. package/dist/core/human/claim.d.ts +0 -23
  41. package/dist/core/human/claim.js +0 -3
@@ -1 +1 @@
1
- var Ee=Object.defineProperty;var s=(e,n)=>Ee(e,"name",{value:n,configurable:!0});import{envProfileId as Ne}from"../../../shared/env.js";import{pausedCanvasProfiles as Ce}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as ne,statSync as te}from"node:fs";import{isAbsolute as x,resolve as L}from"node:path";import{appendSituationalContext as Te,formatSituationalProse as Pe}from"../../../core/runtime/situational-context.js";import{closeNode as De}from"../../../core/runtime/close.js";import{reviveNode as Le}from"../../../core/runtime/revive.js";import{nowIso as V}from"../../../core/fs-utils.js";import{appPaidLaunch as je,assertLaunchModelRegistered as W,forkNode as Me,resolveForkSource as ie,spawnChildPrepared as Ge}from"../../../core/runtime/spawn.js";import{forkSourceNode as re,newNodeId as oe}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ae,childrenOf as Fe,completeCreateRequest as de,findCreateRequest as se,getNode as R,recordCreateRequestNode as Be,reserveCreateRequest as le,reserveCreateRequestNode as Ke,listNodes as xe,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as ce,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as ze}from"../../../core/canvas/waits.js";import{withCanvasWrite as z}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as ue,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn,cronRefusalError as tn}from"../../cron/authority.js";import{cronBirthPlacement as rn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as an,isBeneathRefusal as dn,readdirBeneath as sn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as ln,readNodeSession as cn,readNodeSnapshot as un,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as pn}from"../../../core/substrate/subject.js";import{reviveAll as mn}from"../../../core/runtime/revive-all.js";import{promoteAsync as wn,requestYieldAsync as hn,reshapeNodeAsync as U}from"../../../core/runtime/promote.js";import{recycleNode as yn}from"../../../core/runtime/recycle.js";import{relaunchRoot as _n}from"../../../core/runtime/reset.js";import{assertReopenGate as gn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as bn}from"./broker-recovery.js";import{readOutputRequest as vn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as kn,readGoal as Sn,captureGoalIfAbsent as Rn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as In,hasRoadmap as On}from"../../../core/runtime/roadmap.js";import{renameWindow as An}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as $n,explicitModelIntent as En,normalizeModel as Nn,readMergedLaunchConfigAsync as fe}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Cn}from"../../../core/model-routes.js";import{persistDormantModel as Tn,setModelLive as Pn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as pe}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Dn}from"../../../core/runtime/broker-request.js";import{boundFleet as j}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Ln}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as jn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as me}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Mn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Gn}from"../../../core/human-actions.js";import{parseDurationMs as Fn}from"../../../core/wake.js";import{claimWarmNode as Bn,refillWarmPool as we,resumeWarmClaim as Kn,warmPoolEnabled as xn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as Vn,resolveLaunchTarget as Wn}from"../../../core/runtime/launch-target.js";import{fullName as zn}from"../../../core/canvas/labels.js";import{reportsForNode as he}from"./reports.js";import{requireUsableProfile as Jn}from"./profiles.js";import{assertProfileActive as Un,loadExactProfileManifest as Yn}from"../../../core/profiles/manifest.js";import{getCron as ye}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Hn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Qn}from"../../control.js";import{notFound as T,usage as h}from"../../../core/errors.js";import{assertScope as Xn,validateScopes as _e}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Zn,toNodeDetailDTO as H,toNodeSummaryDTO as qn,toReviveResultDTO as et}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{runsOnBlaxel as nt}from"../environment-of.js";import{actsAsPerson as M,canReadNode as $,mayOnNode as tt,readableNodeIds as it,resolvedScopes as rt}from"../router.js";import{forwardVerb as ot,queryWithoutMachine as at,relayError as dt,unknownError as st,withMachine as lt}from"../../peer/forward.js";import{fileRoot as ct}from"../../../core/spaces/file-root.js";import{activeGrant as ut,payerOfGrant as ft}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as pt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as mt}from"../../../core/grants/terminal.js";import{appRungForGrant as wt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as ht}from"../../../core/model-routes.js";import{listProfileEnvNames as yt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as _t,NO_PROVIDER_CREDENTIAL_MESSAGE as ge}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as gt,mapAsync as be}from"../../../core/async-array.js";async function w(e){const n=await R(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}s(w,"requireMeta");async function Q(e){return{subscribesTo:await ce(e),subscribers:await We(e),children:await Fe(e)}}s(Q,"edgesFor");async function b(e){const n=await w(e);return await H(n,await Q(e))}s(b,"detailOf");async function bt(e){let n=(await he(e)).length;try{n+=sn(await J(e),await ue(e)).length}catch(t){if(!an(t))throw t}return n}s(bt,"countFiles");function vt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&_e(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("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 h("request_key must be a non-empty string of at most 128 characters when provided");return n}s(vt,"parseCreateBody");function kt(e){if(e===void 0)return;const n=Fn(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 f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(kt,"parseDeadline");function St(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Mn.test(e.action))throw new f(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 f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>me)throw new f(413,"payload_too_large",`serialized payload exceeds ${me} bytes`)}return e}}s(St,"parseOutcomeDelivery");function Rt(e,n){const t=Gn(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 f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(Rt,"resolveOutcomeDelivery");function It(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.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(It,"buildRecipe");function Ot(e,n,t){return!xn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(Ot,"warmRequestFor");import{resolveCreateKind as Tr}from"../../../core/runtime/launch-target.js";function ve(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Cn(e.model,n,e.modelExact===!0)}s(ve,"requestFromLaunch");function At(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!O(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s(At,"withinCeiling");async function ke(e,n,t){const r=(await $n(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 W(ve(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(ke,"assertNodeModelChangeRegistered");async function Se(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron")return;const r=ct({app:t.app,resolved:await rt(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s(Se,"assertCallerReaches");const X=new Map;async function $t(e,n={},t={}){const r=At(vt(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==d.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await $(d,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await re(await ie(r.fork_from))}catch{}if(o?.grantee!==d.app||!await $(d,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await re(await ie(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await R(o)!==null&&!await tt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new f(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await oe(),d.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,d.app));const o=await nn({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw tn(o);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(o.effectiveScopes,p)||!O(d.scopes,p));if(l!==void 0)throw new f(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else d.scopes!==null&&(r.scopes=[...d.scopes])}r.creator!==void 0&&Xn(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&en(r.node_id)&&await R(r.node_id)!==null&&(await se(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=X.get(i);if(a!==void 0)return a;const c=Nt(e,r,i,n,t);X.set(i,c);try{return await c}finally{X.delete(i)}}s($t,"handleCreate");const Re="create_request_in_progress";async function Et(e,n,t){const r=Date.now()+1e4;for(;t!==null;){const i=await R(t);if(i!==null){if(!M(e.principal)&&!await $(e.principal,i.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(t)}}if(Date.now()>=r||(await se(n))?.nodeId!==t)break;await new Promise(a=>setTimeout(a,100))}throw new f(409,Re,"another create with this request_key is in progress; retry it")}s(Et,"awaitForeignCreate");async function Nt(e,n,t,r,i){const a=await le(t);if(a.nodeId!==null&&await R(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await R(a.nodeId);if(!M(e.principal)&&!await $(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===Re)throw c;const d=await le(t);throw(d.nodeId===null||await R(d.nodeId)===null)&&await ae(t,d.nodeId),c}}s(Nt,"handleKeyedCreateRequest");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??kt(n.deadline),c=St(n.outcome_delivery),d=e.principal.class==="cron"?await rn({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 ye(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("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 h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await jn(l)}const p=await Wn(n,{validateKind:$e,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:m,kind:u,cwd:_,launch:S}=p;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!N(_)&&!await nt(m))throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Se(e,_),n.worktree!==void 0&&await Se(e,L(n.pin_cwd??n.cwd??_));const v={...n,kind:u},P=c===void 0?void 0:Rt(c,_),q=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await R(o))?.grant_id??null);if(await W(ve(await je(S,q,n.model)),{cwd:_,profileId:m},t.modelRegistry),await ft(q)!=="app"&&!await _t(m===null?[]:await yt(m))&&!await pt(p))throw new f(412,"no_provider_credential",ge,{error:"no_provider_credential",message:ge,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Ot(v,_,m):null,K=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Ln(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=A===null?null:await Kn(A,i.nodeId,K);if(g===null)throw await ae(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await de(i.requestKey,g),{status:201,body:await b(g)}}if(A!==null){const g=await Bn(A,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},K);if(g!==null)return i!==void 0&&await de(i.requestKey,g),we(A),{status:201,body:await b(g)};B=A}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await oe());if(i!==void 0&&i.nodeId===null){const g=await Ke(i.requestKey,D);if(g!==D)return await Et(e,i.requestKey,g)}const I=It(D===void 0?v:{...v,node_id:D},o,_);d!==null&&(d.rootLifecycle!==void 0&&(I.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&v.scopes===void 0&&(I.scopes=d.scopes),d.run!==void 0&&(I.run=d.run),d.withinCreate!==void 0&&(I.withinCreate=d.withinCreate)),a!==void 0&&(I.deadlineAt=a),P!==void 0&&(I.outcomeDelivery=P),I.readiness=n.root===!0?"await":"launch";const ee=await Ge(I,K,()=>{B!==null&&we(B)});return i!==void 0&&await Be(i.requestKey,ee.node.node_id),{status:201,body:await b(ee.node.node_id)}}}s(G,"handleCreateRequest");function k(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}s(k,"singleQueryValue");function Z(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}s(Z,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}s(F,"oneOf");function Ct(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[S]of e.query)if(!n.has(S))throw h(`unknown nodes query parameter: ${S}`);const t=F(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=k(e,"kind"),a=F(k(e,"mode"),"mode",["base","orchestrator"]),c=k(e,"profile_id"),d=k(e,"profile_prefix"),o=k(e,"parent"),l=Z(k(e,"top_level"),"top_level"),p=k(e,"under"),m=Z(k(e,"under_inclusive"),"under_inclusive"),u=Z(k(e,"hanging"),"hanging"),_=F(k(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}s(Ct,"parseListQuery");async function Tt(e){const n=Ct(e);let t=await xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await it(e.principal);r!==null&&(t=t.filter(d=>r.has(d.node_id)));const i=n.include==="activity"?await qe(t.map(d=>d.node_id)):null,a=t.length>0?Ce():new Set;return{status:200,body:await be(t,async d=>{const o=await qn(d,d.profile_id!==null&&a.has(d.profile_id));if(i!==null){const l=await he(d.node_id);o.activity={latest_report:l[0]??null,final_report:d.final_report===null?null:l.find(p=>p.name===d.final_report)??null,pending_human_count:i[d.node_id]??0}}return o})}}s(Tt,"handleList");async function Pt(e){const n=e.params.id,t=await ot(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:at(e)});if(t.kind==="unknown")throw st(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw dt(t.status,t.body);return{status:t.status,body:lt(t.body,t.machine)}}return await w(n),{status:200,body:await b(n)}}s(Pt,"handleDetail");async function Dt(e){const n=e.params.id;await w(n);const t=await un(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,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:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:V()}}}s(Dt,"handleSnapshot");async function Lt(e){const n=e.params.id,t=await pn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(Lt,"handleSubject");function jt(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("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 h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(jt,"parseMessagesQuery");async function Mt(e){const n=e.params.id,t=await ln(n,jt(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:V()}}}s(Mt,"handleMessages");async function Gt(e){const n=e.params.id;await w(n);const t=await cn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:V()}}}s(Gt,"handleSession");async function Ft(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await fn(n)}}}s(Ft,"handleTranscript");async function Bt(e){const n=e.params.id;await w(n);const t=s(async(i,a)=>({node_id:i,label:(await R(i))?.name??i,dir:await ue(i),self:a,files:await bt(i)}),"root"),r=await gt([await t(n,!0),...await be(await ce(n),async i=>await t(i.node_id,!1))],async i=>await Kt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(Bt,"handleContext");async function Kt(e,n){try{return on(await J(e),n)}catch(t){if(dn(t))return!1;throw t}}s(Kt,"hasDir");async function xt(e){const n=await w(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=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await Me(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}s(xt,"handleFork");const Vt=1e4;async function Wt(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await gn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await ye(t.cron_id):null,c=await Le(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await Hn(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const d=(await R(n))?.status??"active",o=(c.launch??j().get(n)?.handle)?.exited,l=c.outcome!=="frozen"&&await pe(n,o,Vt);return{status:200,body:et(n,c,d,l)}}s(Wt,"handleRevive");async function zt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await _n(n))?.newNodeId??null}}}s(zt,"handleRelaunchRoot");async function Jt(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Qn(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await De(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:Zn(a)}}s(Jt,"handleClose");async function Ut(e){if(!M(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await Je(n),{status:204}}s(Ut,"handleMarkRead");async function Yt(e){const n=e.params.id;await w(n);const t=await yn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Yt,"handleRecycle");async function Ht(e){const n=e.params.id;return await w(n),await U(n,{lifecycle:"terminal"}),await E(e,n,["lifecycle"]),{status:200,body:await b(n)}}s(Ht,"handleDemote");async function Qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await wn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await E(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await H(a.meta,await Q(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}s(Qt,"handlePromote");async function Xt(e){const n=e.params.id;return await w(n),{status:200,body:{request:await vn(n)}}}s(Xt,"handleBrokerStructuredRequest");async function Zt(e){const n=e.params.id,t=e.body??{};if(await bn(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Rn(n,t.text)}}}s(Zt,"handleBrokerGoal");async function qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(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 kn(t,a);const c=await hn(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 H(c.meta,await Q(t))}}s(qt,"handleYield");async function ei(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await R(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await ze(n,t.controller),{status:200,body:await b(n)}}s(ei,"handleWait");async function ni(e){const n=e.principal,t=await mn(n.class==="broker"?async i=>i.grantee===n.app&&await $(n,i.grantee,i.node_id):n.class==="person"&&!M(n)?async i=>await $(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(ni,"handleReviveAll");const ti=new Set(["interrupt","steer","after-turn","next-turn"]);function ii(e){if(e===null)return null;const n=s(r=>{throw new y({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"||!ti.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(ii,"listenJson");async function E(e,n,t,r){t.length===0&&r===void 0||await z(async i=>{if(r?.(i),t.length===0)return;const a=await Ue(i,n),c=await Qe(i,e),d=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await Ye(i,d,a),await He(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s(E,"recordConfigured");function Ie(e){const n=j().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(Ie,"restartLiveBroker");function Oe(e,n){try{return ne(e)===ne(n)}catch{return!1}}s(Oe,"sameDirectory");async function ri(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 y({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 y({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(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),l=await Jn(e,i.profile);Un(l.profileId);const p=Yn(l.profileId).manifest.grantee??"app:terminal";if(p!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(Vn(o.kind)?(await Y(o.kind,o.cwd,l.profileId),await U(t,{profileId:l.profileId})):await C(t,{profile_id:l.profileId}),await E(e,t,["profile"])),i.restart===!0&&Ie(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({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 y({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 w(t),p=N(l.cwd);if(i.keep_session===!0||p&&x(o)&&N(o)&&Oe(l.cwd,o)){if(!x(o))throw new y({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{_=te(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Oe(l.cwd,u))throw new y({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 y({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 S=l.cwd;return S!==u&&(await z(async v=>{await C(t,{cwd:u}),await v.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,S),await Xe(t,S,u)}),await E(e,t,["cwd"])),i.restart===!0&&Ie(t),{status:200,body:await b(t)}}if(await j().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(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 y({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 y({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(N(l.cwd))throw new y({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(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const m=L(o);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!te(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await z(async()=>{await C(t,{cwd:m}),await Ze(t)}),await E(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await w(t);const c=i.listen===void 0?void 0:ii(i.listen);if(i.scopes!==void 0){const o=_e(i.scopes),l=a.grantee==="app:terminal"?await mt(a):a.grant_id?await ut(a.grant_id):null;if(!o.every(p=>O(a.scopes,p)&&l!==null&&O(l.resolved,p)))throw new y({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")&&!O(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await C(t,{scopes:o})}if(i.situational_context!==void 0&&await Te(t,Pe(i.situational_context)),i.model!==void 0){const o=(await fe(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=En(i.model,o),p=await wt(a.grant_id,i.model,l===void 0),m=p?{family:ht,strength:p.strength}:l,u=p?p.model:Nn(i.model,o);await W({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=j();let S=!1;if(await _.isClaimed(t)&&await pe(t,_.get(t)?.handle.exited)&&(S=await Pn(t,u,m).then(()=>!0,v=>{if(v instanceof Dn)return!1;throw v})),!S){if(await _.isClaimed(t)){const v=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",v,{error:"broker_not_ready",message:v,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Tn(t,u,m)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await $e(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;l==="orchestrator"&&!await On(t)&&(m=s(async()=>{const u=await Sn(t);await In(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await U(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await C(t,{name:i.name}),a.window&&An(a.window,zn(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await E(e,t,d,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await b(t)}}s(ri,"handleConfig");async function Ae(e="app:terminal"){return(await fe(process.cwd(),Ne()||null,e)).kinds}s(Ae,"daemonKinds");async function $e(e,n="app:terminal"){const t=Object.keys(await Ae(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s($e,"assertKindServer");async function oi(){const e=await Ae();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}))}}}s(oi,"handleListKinds");const Er=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:$t},{method:"GET",pattern:"/v1/nodes",handler:Tt},{method:"GET",pattern:"/v1/kinds",handler:s(()=>oi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:ni},{method:"GET",pattern:"/v1/nodes/:id",handler:Pt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Dt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Lt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Mt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Gt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ft},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:xt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Wt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:zt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Jt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ut},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Yt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ht},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Qt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:qt},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Xt},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Zt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:ei},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ri}];export{ri as handleConfig,$t as handleCreate,xt as handleFork,Tt as handleList,Qt as handlePromote,qt as handleYield,Er as nodeRoutes,Tr as resolveCreateKind};
1
+ var $e=Object.defineProperty;var s=(e,n)=>$e(e,"name",{value:n,configurable:!0});import{envProfileId as Ce}from"../../../shared/env.js";import{pausedCanvasProfiles as Ne}from"../../../core/profiles/manifest.js";import{existsSync as C,realpathSync as te,statSync as ie}from"node:fs";import{isAbsolute as x,resolve as L}from"node:path";import{appendSituationalContext as Te,formatSituationalProse as Pe}from"../../../core/runtime/situational-context.js";import{closeNode as De}from"../../../core/runtime/close.js";import{reviveNode as Le}from"../../../core/runtime/revive.js";import{nowIso as V}from"../../../core/fs-utils.js";import{appPaidLaunch as Me,assertLaunchModelRegistered as W,forkNode as je,resolveForkSource as re,spawnChildPrepared as Ge}from"../../../core/runtime/spawn.js";import{forkSourceNode as oe,newNodeId as ae}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as de,childrenOf as Fe,completeCreateRequest as se,findCreateRequest as le,getNode as k,recordCreateRequestNode as Be,reserveCreateRequest as ce,reserveCreateRequestNode as Ke,listNodes as xe,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as ue,updateNode as N}from"../../../core/canvas/canvas.js";import{armControllerWait as ze}from"../../../core/canvas/waits.js";import{withCanvasWrite as z}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as fe,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn,cronRefusalError as tn}from"../../cron/authority.js";import{cronBirthPlacement as rn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as an,isBeneathRefusal as dn,readdirBeneath as sn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as ln,readNodeSession as cn,readNodeSnapshot as un,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as pn}from"../../../core/substrate/subject.js";import{reviveAll as mn}from"../../../core/runtime/revive-all.js";import{promoteAsync as wn,requestYieldAsync as hn,reshapeNodeAsync as U}from"../../../core/runtime/promote.js";import{recycleNode as yn}from"../../../core/runtime/recycle.js";import{relaunchRoot as _n}from"../../../core/runtime/reset.js";import{assertReopenGate as gn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as bn}from"./broker-recovery.js";import{readOutputRequest as vn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as kn,readGoal as Sn,captureGoalIfAbsent as Rn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as On,hasRoadmap as In}from"../../../core/runtime/roadmap.js";import{renameWindow as An}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as En,explicitModelIntent as $n,normalizeModel as Cn,readMergedLaunchConfigAsync as pe}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Nn}from"../../../core/model-routes.js";import{persistDormantModel as Tn,setModelLive as Pn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as me}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Dn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Ln}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Mn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as we}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as jn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Gn}from"../../../core/human-actions.js";import{parseDurationMs as Fn}from"../../../core/wake.js";import{claimWarmNode as Bn,refillWarmPool as he,resumeWarmClaim as Kn,warmPoolEnabled as xn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as Vn,resolveLaunchTarget as Wn}from"../../../core/runtime/launch-target.js";import{fullName as zn}from"../../../core/canvas/labels.js";import{reportsForNode as ye}from"./reports.js";import{requireUsableProfile as Jn}from"./profiles.js";import{assertProfileActive as Un,loadExactProfileManifest as Yn}from"../../../core/profiles/manifest.js";import{getCron as H}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Hn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Qn}from"../../control.js";import{notFound as T,usage as h}from"../../../core/errors.js";import{assertScope as Xn,validateScopes as _e}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Zn,toNodeDetailDTO as Q,toNodeSummaryDTO as qn,toReviveResultDTO as et}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{remoteEnvironmentOf as nt}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as tt}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as it}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as E,mayOnNode as rt,readableNodeIds as ot,resolvedScopes as at}from"../router.js";import{forwardVerb as dt,queryWithoutMachine as st,relayError as lt,unknownError as ct,withMachine as ut}from"../../peer/forward.js";import{fileRoot as ft}from"../../../core/spaces/file-root.js";import{activeGrant as pt,payerOfGrant as mt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as wt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as ht}from"../../../core/grants/terminal.js";import{appRungForGrant as yt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as _t}from"../../../core/model-routes.js";import{listProfileEnvNames as gt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as bt,NO_PROVIDER_CREDENTIAL_MESSAGE as ge}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as vt,mapAsync as be}from"../../../core/async-array.js";async function w(e){const n=await k(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}s(w,"requireMeta");async function X(e){return{subscribesTo:await ue(e),subscribers:await We(e),children:await Fe(e)}}s(X,"edgesFor");async function b(e){const n=await w(e);return await Q(n,await X(e))}s(b,"detailOf");async function kt(e){let n=(await ye(e)).length;try{n+=sn(await J(e),await fe(e)).length}catch(t){if(!an(t))throw t}return n}s(kt,"countFiles");function St(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&_e(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("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 h("request_key must be a non-empty string of at most 128 characters when provided");return n}s(St,"parseCreateBody");function Rt(e){if(e===void 0)return;const n=Fn(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 f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(Rt,"parseDeadline");function Ot(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!jn.test(e.action))throw new f(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 f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>we)throw new f(413,"payload_too_large",`serialized payload exceeds ${we} bytes`)}return e}}s(Ot,"parseOutcomeDelivery");function It(e,n){const t=Gn(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 f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(It,"resolveOutcomeDelivery");function At(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.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(At,"buildRecipe");function Et(e,n,t){return!xn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(Et,"warmRequestFor");import{resolveCreateKind as jr}from"../../../core/runtime/launch-target.js";function ve(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Nn(e.model,n,e.modelExact===!0)}s(ve,"requestFromLaunch");function $t(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!I(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s($t,"withinCeiling");async function ke(e,n,t){const r=(await En(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 W(ve(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(ke,"assertNodeModelChangeRegistered");async function Ct(e){if(!it()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await k(e.node))?.profile_id??null:e.cron===null?null:(await H(e.cron))?.profile??null;return n!==null&&await tt(n)!==null}s(Ct,"callerRunsOnMachine");async function Se(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await Ct(t))return;const r=ft({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 f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s(Se,"assertCallerReaches");const Z=new Map;async function Nt(e,n={},t={}){const r=$t(St(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==d.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await E(d,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await oe(await re(r.fork_from))}catch{}if(o?.grantee!==d.app||!await E(d,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await oe(await re(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await k(o)!==null&&!await rt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new f(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ae(),d.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,d.app));const o=await nn({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw tn(o);if(r.scopes!==void 0){const l=r.scopes.find(p=>!I(o.effectiveScopes,p)||!I(d.scopes,p));if(l!==void 0)throw new f(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else d.scopes!==null&&(r.scopes=[...d.scopes])}r.creator!==void 0&&Xn(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&en(r.node_id)&&await k(r.node_id)!==null&&(await le(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=Z.get(i);if(a!==void 0)return a;const c=Pt(e,r,i,n,t);Z.set(i,c);try{return await c}finally{Z.delete(i)}}s(Nt,"handleCreate");const Re="create_request_in_progress";async function Tt(e,n,t){const r=Date.now()+1e4;for(;t!==null;){const i=await k(t);if(i!==null){if(!j(e.principal)&&!await E(e.principal,i.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(t)}}if(Date.now()>=r||(await le(n))?.nodeId!==t)break;await new Promise(a=>setTimeout(a,100))}throw new f(409,Re,"another create with this request_key is in progress; retry it")}s(Tt,"awaitForeignCreate");async function Pt(e,n,t,r,i){const a=await ce(t);if(a.nodeId!==null&&await k(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await k(a.nodeId);if(!j(e.principal)&&!await E(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===Re)throw c;const d=await ce(t);throw(d.nodeId===null||await k(d.nodeId)===null)&&await de(t,d.nodeId),c}}s(Pt,"handleKeyedCreateRequest");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??Rt(n.deadline),c=Ot(n.outcome_delivery),d=e.principal.class==="cron"?await rn({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 H(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("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 h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await Mn(l)}const p=await Wn(n,{validateKind:Ee,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:m,kind:u,cwd:_,launch:R}=p;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!C(_)&&await nt(m)===null)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Se(e,_),n.worktree!==void 0&&await Se(e,L(n.pin_cwd??n.cwd??_));const v={...n,kind:u},P=c===void 0?void 0:It(c,_),ee=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await k(o))?.grant_id??null);if(await W(ve(await Me(R,ee,n.model)),{cwd:_,profileId:m},t.modelRegistry),await mt(ee)!=="app"&&!await bt(m===null?[]:await gt(m))&&!await wt(p))throw new f(412,"no_provider_credential",ge,{error:"no_provider_credential",message:ge,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Et(v,_,m):null,K=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Ln(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=A===null?null:await Kn(A,i.nodeId,K);if(g===null)throw await de(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await se(i.requestKey,g),{status:201,body:await b(g)}}if(A!==null){const g=await Bn(A,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},K);if(g!==null)return i!==void 0&&await se(i.requestKey,g),he(A),{status:201,body:await b(g)};B=A}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ae());if(i!==void 0&&i.nodeId===null){const g=await Ke(i.requestKey,D);if(g!==D)return await Tt(e,i.requestKey,g)}const O=At(D===void 0?v:{...v,node_id:D},o,_);d!==null&&(d.rootLifecycle!==void 0&&(O.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&v.scopes===void 0&&(O.scopes=d.scopes),d.run!==void 0&&(O.run=d.run),d.withinCreate!==void 0&&(O.withinCreate=d.withinCreate)),a!==void 0&&(O.deadlineAt=a),P!==void 0&&(O.outcomeDelivery=P),O.readiness=n.root===!0?"await":"launch";const ne=await Ge(O,K,()=>{B!==null&&he(B)});return i!==void 0&&await Be(i.requestKey,ne.node.node_id),{status:201,body:await b(ne.node.node_id)}}}s(G,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}s(S,"singleQueryValue");function q(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}s(q,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}s(F,"oneOf");function Dt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[R]of e.query)if(!n.has(R))throw h(`unknown nodes query parameter: ${R}`);const t=F(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=F(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),d=S(e,"profile_prefix"),o=S(e,"parent"),l=q(S(e,"top_level"),"top_level"),p=S(e,"under"),m=q(S(e,"under_inclusive"),"under_inclusive"),u=q(S(e,"hanging"),"hanging"),_=F(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}s(Dt,"parseListQuery");async function Lt(e){const n=Dt(e);let t=await xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await ot(e.principal);r!==null&&(t=t.filter(d=>r.has(d.node_id)));const i=n.include==="activity"?await qe(t.map(d=>d.node_id)):null,a=t.length>0?Ne():new Set;return{status:200,body:await be(t,async d=>{const o=await qn(d,d.profile_id!==null&&a.has(d.profile_id));if(i!==null){const l=await ye(d.node_id);o.activity={latest_report:l[0]??null,final_report:d.final_report===null?null:l.find(p=>p.name===d.final_report)??null,pending_human_count:i[d.node_id]??0}}return o})}}s(Lt,"handleList");async function Mt(e){const n=e.params.id,t=await dt(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:st(e)});if(t.kind==="unknown")throw ct(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw lt(t.status,t.body);return{status:t.status,body:ut(t.body,t.machine)}}return await w(n),{status:200,body:await b(n)}}s(Mt,"handleDetail");async function jt(e){const n=e.params.id;await w(n);const t=await un(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,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:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:V()}}}s(jt,"handleSnapshot");async function Gt(e){const n=e.params.id,t=await pn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(Gt,"handleSubject");function Ft(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("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 h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(Ft,"parseMessagesQuery");async function Bt(e){const n=e.params.id,t=await ln(n,Ft(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:V()}}}s(Bt,"handleMessages");async function Kt(e){const n=e.params.id;await w(n);const t=await cn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:V()}}}s(Kt,"handleSession");async function xt(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await fn(n)}}}s(xt,"handleTranscript");async function Vt(e){const n=e.params.id;await w(n);const t=s(async(i,a)=>({node_id:i,label:(await k(i))?.name??i,dir:await fe(i),self:a,files:await kt(i)}),"root"),r=await vt([await t(n,!0),...await be(await ue(n),async i=>await t(i.node_id,!1))],async i=>await Wt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(Vt,"handleContext");async function Wt(e,n){try{return on(await J(e),n)}catch(t){if(dn(t))return!1;throw t}}s(Wt,"hasDir");async function zt(e){const n=await w(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=>I(t,a)),...t.filter(a=>I(n.scopes,a))])],i=await je(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}s(zt,"handleFork");const Jt=1e4;async function Ut(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await gn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await H(t.cron_id):null,c=await Le(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await Hn(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const d=(await k(n))?.status??"active",o=(c.launch??M().get(n)?.handle)?.exited,l=c.outcome!=="frozen"&&await me(n,o,Jt);return{status:200,body:et(n,c,d,l)}}s(Ut,"handleRevive");async function Yt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await _n(n))?.newNodeId??null}}}s(Yt,"handleRelaunchRoot");async function Ht(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Qn(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await De(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:Zn(a)}}s(Ht,"handleClose");async function Qt(e){if(!j(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await Je(n),{status:204}}s(Qt,"handleMarkRead");async function Xt(e){const n=e.params.id;await w(n);const t=await yn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Xt,"handleRecycle");async function Zt(e){const n=e.params.id;return await w(n),await U(n,{lifecycle:"terminal"}),await $(e,n,["lifecycle"]),{status:200,body:await b(n)}}s(Zt,"handleDemote");async function qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await wn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await $(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await X(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}s(qt,"handlePromote");async function ei(e){const n=e.params.id;return await w(n),{status:200,body:{request:await vn(n)}}}s(ei,"handleBrokerStructuredRequest");async function ni(e){const n=e.params.id,t=e.body??{};if(await bn(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Rn(n,t.text)}}}s(ni,"handleBrokerGoal");async function ti(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(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 kn(t,a);const c=await hn(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 X(t))}}s(ti,"handleYield");async function ii(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await k(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await ze(n,t.controller),{status:200,body:await b(n)}}s(ii,"handleWait");async function ri(e){const n=e.principal,t=await mn(n.class==="broker"?async i=>i.grantee===n.app&&await E(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await E(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(ri,"handleReviveAll");const oi=new Set(["interrupt","steer","after-turn","next-turn"]);function ai(e){if(e===null)return null;const n=s(r=>{throw new y({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"||!oi.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(ai,"listenJson");async function $(e,n,t,r){t.length===0&&r===void 0||await z(async i=>{if(r?.(i),t.length===0)return;const a=await Ue(i,n),c=await Qe(i,e),d=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await Ye(i,d,a),await He(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s($,"recordConfigured");function Oe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(Oe,"restartLiveBroker");function Ie(e,n){try{return te(e)===te(n)}catch{return!1}}s(Ie,"sameDirectory");async function di(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 y({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 y({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(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),l=await Jn(e,i.profile);Un(l.profileId);const p=Yn(l.profileId).manifest.grantee??"app:terminal";if(p!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(Vn(o.kind)?(await Y(o.kind,o.cwd,l.profileId),await U(t,{profileId:l.profileId})):await N(t,{profile_id:l.profileId}),await $(e,t,["profile"])),i.restart===!0&&Oe(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({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 y({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 w(t),p=C(l.cwd);if(i.keep_session===!0||p&&x(o)&&C(o)&&Ie(l.cwd,o)){if(!x(o))throw new y({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{_=ie(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Ie(l.cwd,u))throw new y({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 y({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 R=l.cwd;return R!==u&&(await z(async v=>{await N(t,{cwd:u}),await v.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,R),await Xe(t,R,u)}),await $(e,t,["cwd"])),i.restart===!0&&Oe(t),{status:200,body:await b(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(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 y({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 y({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(C(l.cwd))throw new y({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(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const m=L(o);if(!C(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ie(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await z(async()=>{await N(t,{cwd:m}),await Ze(t)}),await $(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await w(t);const c=i.listen===void 0?void 0:ai(i.listen);if(i.scopes!==void 0){const o=_e(i.scopes),l=a.grantee==="app:terminal"?await ht(a):a.grant_id?await pt(a.grant_id):null;if(!o.every(p=>I(a.scopes,p)&&l!==null&&I(l.resolved,p)))throw new y({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")&&!I(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await N(t,{scopes:o})}if(i.situational_context!==void 0&&await Te(t,Pe(i.situational_context)),i.model!==void 0){const o=(await pe(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=$n(i.model,o),p=await yt(a.grant_id,i.model,l===void 0),m=p?{family:_t,strength:p.strength}:l,u=p?p.model:Cn(i.model,o);await W({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let R=!1;if(await _.isClaimed(t)&&await me(t,_.get(t)?.handle.exited)&&(R=await Pn(t,u,m).then(()=>!0,v=>{if(v instanceof Dn)return!1;throw v})),!R){if(await _.isClaimed(t)){const v=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",v,{error:"broker_not_ready",message:v,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Tn(t,u,m)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Ee(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;l==="orchestrator"&&!await In(t)&&(m=s(async()=>{const u=await Sn(t);await On(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await U(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await N(t,{name:i.name}),a.window&&An(a.window,zn(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await $(e,t,d,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await b(t)}}s(di,"handleConfig");async function Ae(e="app:terminal"){return(await pe(process.cwd(),Ce()||null,e)).kinds}s(Ae,"daemonKinds");async function Ee(e,n="app:terminal"){const t=Object.keys(await Ae(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s(Ee,"assertKindServer");async function si(){const e=await Ae();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}))}}}s(si,"handleListKinds");const Dr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:Nt},{method:"GET",pattern:"/v1/nodes",handler:Lt},{method:"GET",pattern:"/v1/kinds",handler:s(()=>si(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:ri},{method:"GET",pattern:"/v1/nodes/:id",handler:Mt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:jt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Gt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Bt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Kt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:xt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Vt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:zt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Ut},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Yt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ht},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Qt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Xt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Zt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:qt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:ei},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:ni},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:ii},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:di}];export{di as handleConfig,Nt as handleCreate,zt as handleFork,Lt as handleList,qt as handlePromote,ti as handleYield,Dr as nodeRoutes,jr as resolveCreateKind};
@@ -1,14 +1,14 @@
1
- var M=Object.defineProperty;var s=(t,e)=>M(t,"name",{value:e,configurable:!0});import{existsSync as P}from"node:fs";import{getNode as d}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as D}from"../../../core/canvas/executions.js";import{markStopSignal as B}from"../../../core/runtime/stop-signals.js";import{emitEvent as j}from"../../../core/events/emit.js";import{push as J,FinalizationError as k,StructuredRequestFinalizationError as z}from"../../../core/feed/feed.js";import{branchIsPushedAtCurrentTip as L,hasOpenManagedWorktree as W,missingWorktreeRecoveryHint as H}from"../../../core/worktree.js";import{autoDropCleanManagedWorktreeAsync as X}from"../../../core/worktree-mutation-async.js";import{withCanvasWrite as G,openDb as K}from"../../../core/canvas/db.js";import{getMany as U}from"../../../core/graph/bodies.js";import{heads as V}from"../../../core/graph/documents.js";import{listObjects as Y,nodeObject as Q}from"../../../core/graph/objects.js";import{readerFor as Z}from"../../../core/graph/reader.js";import{notFound as ee,usage as f}from"../../../core/errors.js";import{InputError as u}from"../../../core/io.js";import{toReportResultDTO as te}from"../map.js";import{validateStructuredResult as re}from"../../../core/runtime/structured-output.js";import{clearSchemaReprompts as ne}from"../../../core/runtime/output-result.js";import{getPendingStructuredRequestForNode as _,getStructuredRequest as S,settleStructuredRequestIn as ie}from"../../../core/canvas/structured-requests.js";import{ApiError as h}from"../../../api/errors.js";import{applySettlementEffects as R}from"../../structured-requests/effects.js";import{nodeEventStreams as x}from"./node-events.js";import{emitRunEvent as E}from"../../../core/runs/events.js";import{mapAsync as oe}from"../../../core/async-array.js";async function g(t){const e=await d(t);if(e===null)throw ee(`unknown node: ${t}`,{received:t});return e}s(g,"requireNode");function ae(t){if(typeof t!="object"||t===null)throw f("a push report requires a JSON body { tier, body }");const e=t.tier,r=t.delivery_tier,i=t.body;if(e!=="update"&&e!=="urgent"&&e!=="final")throw f(`invalid report tier: ${String(e)} (expected update|urgent|final)`);if(r!==void 0&&r!=="deferred"&&r!=="normal"&&r!=="urgent")throw f(`invalid delivery_tier: ${String(r)} (expected deferred|normal|urgent)`);if(e!=="update"&&r!==void 0)throw f("delivery_tier is only valid for update reports");if(typeof i!="string"||i.trim()==="")throw f("a push report requires a non-empty body");return{tier:e,...r===void 0?{}:{delivery_tier:r},body:i}}s(ae,"parsePushBody");async function se(t){const e=t.params.id;await g(e);const r=ae(t.body);if(r.tier==="final"&&await _(e)!==null)throw new u({error:"structured_result_pending",message:"This node owes a structured result \u2014 a plain `push final` would finish it without recording one.",next:'Submit the result with the `submit_result` tool instead (or `crtr push result`); it validates against the pending schema, records it, and pushes the final report for you. If the schema cannot be honestly satisfied, call `submit_result` with `decline` (or `crtr push result --decline "<reason>" --code <token>`) to record the decline and finish the node.'});const i=r.tier==="final"?(await d(e))?.status:void 0,n=r.tier==="final"?await O(e):void 0,o=await b(e,r);r.tier==="final"&&await A(e);const a=r.tier==="final"&&i!==void 0?{from:i,to:(await d(e))?.status??"done"}:void 0,c=te(o,a,n),m=(await q(e)).find(p=>p.id===o.reportId);if(m!==void 0){x.report(e,m);const p=(await d(e))?.run_id;p&&await E(p,e,"node.report.pushed",{body:m.body,kind:m.tier==="final"?"final":"update"})}return{status:200,body:c}}s(se,"handlePush");async function O(t){if(!W(await d(t)))return;const e=await X(t);if(e!==null)return e.worktree_path;if(!await L((await d(t)).managed_worktree))throw new u({error:"open_managed_worktree",message:"This node still owns an open managed worktree that is neither clean and locally landed nor clean with its exact tip on origin \u2014 `push final` cannot finish.",next:await(async()=>{const r=(await d(t))?.managed_worktree;return r!=null&&r.state==="open"&&!P(r.path)?H(r):"Make the recorded worktree clean, including untracked files: commit work to retain and remove or ignore only disposable generated files. With its recorded branch checked out and no rebase in progress, push its current tip to a branch on origin, then rerun `crtr push final`; or run `crtr node worktree close` to land the clean worktree into its recorded local base."})()})}s(O,"guardFinalWorktree");const $=2e3;function de(t){const e=JSON.stringify(t,null,2);return`Structured output submitted.
1
+ var B=Object.defineProperty;var s=(t,e)=>B(t,"name",{value:e,configurable:!0});import{existsSync as W}from"node:fs";import{getNode as d}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as j}from"../../../core/canvas/executions.js";import{markStopSignal as z}from"../../../core/runtime/stop-signals.js";import{emitEvent as J}from"../../../core/events/emit.js";import{push as L,FinalizationError as v,StructuredRequestFinalizationError as H}from"../../../core/feed/feed.js";import{branchIsPushedAtCurrentTip as X,hasOpenManagedWorktree as K,missingWorktreeRecoveryHint as S}from"../../../core/worktree.js";import{autoDropCleanManagedWorktreeAsync as G}from"../../../core/worktree-mutation-async.js";import{finalizeManagedWorktreeOnMachine as U,worktreeMachineOf as V}from"../../../core/worktree-machine.js";import{withCanvasWrite as Y,openDb as Q}from"../../../core/canvas/db.js";import{getMany as Z}from"../../../core/graph/bodies.js";import{heads as ee}from"../../../core/graph/documents.js";import{listObjects as te,nodeObject as re}from"../../../core/graph/objects.js";import{readerFor as ne}from"../../../core/graph/reader.js";import{notFound as ie,usage as f}from"../../../core/errors.js";import{InputError as u}from"../../../core/io.js";import{toReportResultDTO as oe}from"../map.js";import{validateStructuredResult as ae}from"../../../core/runtime/structured-output.js";import{clearSchemaReprompts as se}from"../../../core/runtime/output-result.js";import{getPendingStructuredRequestForNode as _,getStructuredRequest as R,settleStructuredRequestIn as de}from"../../../core/canvas/structured-requests.js";import{ApiError as h}from"../../../api/errors.js";import{applySettlementEffects as E}from"../../structured-requests/effects.js";import{nodeEventStreams as O}from"./node-events.js";import{emitRunEvent as x}from"../../../core/runs/events.js";import{mapAsync as ue}from"../../../core/async-array.js";async function g(t){const e=await d(t);if(e===null)throw ie(`unknown node: ${t}`,{received:t});return e}s(g,"requireNode");function ce(t){if(typeof t!="object"||t===null)throw f("a push report requires a JSON body { tier, body }");const e=t.tier,o=t.delivery_tier,i=t.body;if(e!=="update"&&e!=="urgent"&&e!=="final")throw f(`invalid report tier: ${String(e)} (expected update|urgent|final)`);if(o!==void 0&&o!=="deferred"&&o!=="normal"&&o!=="urgent")throw f(`invalid delivery_tier: ${String(o)} (expected deferred|normal|urgent)`);if(e!=="update"&&o!==void 0)throw f("delivery_tier is only valid for update reports");if(typeof i!="string"||i.trim()==="")throw f("a push report requires a non-empty body");return{tier:e,...o===void 0?{}:{delivery_tier:o},body:i}}s(ce,"parsePushBody");async function le(t){const e=t.params.id;await g(e);const o=ce(t.body);if(o.tier==="final"&&await _(e)!==null)throw new u({error:"structured_result_pending",message:"This node owes a structured result \u2014 a plain `push final` would finish it without recording one.",next:'Submit the result with the `submit_result` tool instead (or `crtr push result`); it validates against the pending schema, records it, and pushes the final report for you. If the schema cannot be honestly satisfied, call `submit_result` with `decline` (or `crtr push result --decline "<reason>" --code <token>`) to record the decline and finish the node.'});const i=o.tier==="final"?(await d(e))?.status:void 0,r=o.tier==="final"?await $(e):void 0,n=await b(e,o);o.tier==="final"&&await C(e);const a=o.tier==="final"&&i!==void 0?{from:i,to:(await d(e))?.status??"done"}:void 0,c=oe(n,a,r),m=(await q(e)).find(p=>p.id===n.reportId);if(m!==void 0){O.report(e,m);const p=(await d(e))?.run_id;p&&await x(p,e,"node.report.pushed",{body:m.body,kind:m.tier==="final"?"final":"update"})}return{status:200,body:c}}s(le,"handlePush");async function $(t){const e=await d(t);if(!K(e))return;const o=await V(e?.profile_id);if(o!==null){const n=await U(o,t);if(n.kind==="dropped")return n.dropped.worktree_path;if(n.kind==="pushed")return;throw T(n.missing?S(n.worktree):N)}const i=await G(t);if(i!==null)return i.worktree_path;if(await X((await d(t)).managed_worktree))return;const r=(await d(t))?.managed_worktree;throw T(r!=null&&r.state==="open"&&!W(r.path)?S(r):N)}s($,"guardFinalWorktree");const N="Make the recorded worktree clean, including untracked files: commit work to retain and remove or ignore only disposable generated files. With its recorded branch checked out and no rebase in progress, push its current tip to a branch on origin, then rerun `crtr push final`; or run `crtr node worktree close` to land the clean worktree into its recorded local base.";function T(t){return new u({error:"open_managed_worktree",message:"This node still owns an open managed worktree that is neither clean and locally landed nor clean with its exact tip on origin \u2014 `push final` cannot finish.",next:t})}s(T,"openManagedWorktreeError");const I=2e3;function fe(t){const e=JSON.stringify(t,null,2);return`Structured output submitted.
2
2
 
3
3
  \`\`\`json
4
- ${e.length>$?`${e.slice(0,$)}
4
+ ${e.length>I?`${e.slice(0,I)}
5
5
  \u2026 (truncated \u2014 the full result is on the structured request)`:e}
6
6
  \`\`\`
7
- `}s(de,"submitReportBody");function ue(t){return`Structured result declined.
7
+ `}s(fe,"submitReportBody");function me(t){return`Structured result declined.
8
8
 
9
9
  Reason: ${t.reason}
10
10
  Code: ${t.code}
11
11
  Retryable: ${t.retryable?"yes":"no"}
12
- `}s(ue,"declineReportBody");const I=1024,N=64;async function ce(t,e){if(typeof t!="object"||t===null)throw f("a result submission requires a JSON body { value } or { decline, code, retryable }");const r=t.request_id;if(typeof r!="string"||r.trim()===""){const o=await _(e);throw new u({error:"request_id_required",message:`a structured result requires request_id${o===null?"":` (pending request: ${o.request_id})`}`,next:"Pass `--request <request-id>` exactly as named in the structured-output instruction."})}const i=Object.hasOwn(t,"value"),n=Object.hasOwn(t,"decline");if(i&&n)throw f("a result submission carries either { value } or { decline, code, retryable }, not both");if(n){const{decline:o,code:a,retryable:c}=t;if(typeof o!="string"||o.trim()==="")throw new u({error:"missing_decline_reason",message:"A decline needs a reason.",next:'Rerun with `--decline "<one sentence on why the schema cannot be honestly satisfied>" --code <token>`.'});if(o.length>I)throw new u({error:"decline_reason_too_long",message:`A decline reason is at most ${I} characters (got ${o.length}).`,next:"Keep the reason to one plain sentence; put any detail in an artifact and name its path."});if(typeof a!="string"||a.trim()===""||/\s/.test(a.trim())||a.trim().length>N)throw new u({error:"invalid_decline_code",message:`A decline needs a code: one whitespace-free token of at most ${N} characters naming the decline class.`,next:"Rerun with `--code <token>` \u2014 the token your requester documented for this case."});if(typeof c!="boolean")throw f("a decline carries `retryable` as a boolean");return{requestId:r.trim(),declined:{reason:o.trim(),code:a.trim(),retryable:c}}}if(!i)throw f("a result submission requires a JSON body { value } or { decline, code, retryable }");return{requestId:r.trim(),value:t.value}}s(ce,"parseSubmitBody");const le=1024*1024;async function fe(t){const e=t.params.id,r=await g(e);await _(e)!==null&&await ne(e);const i=await ce(t.body,e),n=await S(i.requestId);if(n===null||n.node_id!==e)throw new h(404,"structured_request_not_found","the named structured request does not belong to this node");if(n.state!=="pending")throw new h(409,n.state==="expired"?"structured_request_expired":"structured_request_settled",`structured request ${n.request_id} is already ${n.state}`);let o;if("value"in i){if(Buffer.byteLength(JSON.stringify(i.value)??"")>le)throw new u({error:"result_too_large",message:"the submitted result is over 1 MiB serialized; nothing was recorded.",next:"Submit a smaller result \u2014 write bulky content to a file and put its path in the result."});try{o=await re(n.schema,i.value)}catch(l){throw new u({error:"result_schema_mismatch",message:`the submitted result does not match the requested schema: ${l.message}`,next:'Fix the listed fields and submit again; if the schema cannot be honestly satisfied, decline it (`submit_result` with `decline`, or `crtr push result --decline "<reason>" --code <token>`).'})}}const a="declined"in i?ue(i.declined):de(o);if(n.submission==="oneoff"){const l=await G(async C=>await ie(C,n.request_id,"declined"in i?{intended:"declined",declined:i.declined}:{intended:"completed",result:o}));if(!l.changed||l.row===null||l.row.state!=="completed"&&l.row.state!=="declined")throw new h(409,l.row?.state==="expired"?"structured_request_expired":"structured_request_settled",`structured request ${n.request_id} is already ${l.row?.state??"settled"}`);await R(l.row);const y=await b(e,{tier:"update",body:a},void 0,{requestMessageId:n.request_message_id});return await T(e,y.reportId),{status:200,body:{mode:n.submission,report:y.report,notified:[...y.deliveredTo],..."declined"in i?{declined:i.declined}:{}}}}const c=(await d(e))?.status,m=await O(e),p="declined"in i?{kind:"failure",reason:"declined",detailJson:JSON.stringify({schema:"crtr.node-outcome-detail/v1",message:i.declined.reason,declined:i.declined}),structured:{requestId:n.request_id,declined:i.declined,skipEffects:!0}}:{structured:{requestId:n.request_id,value:o,skipEffects:!0}},w=await b(e,{tier:"final",body:a},p);await A(e);const F=await S(n.request_id);await R(F),await T(e,w.reportId);const v=c===void 0?void 0:{from:c,to:(await d(e))?.status??"done"};return{status:200,body:{mode:n.submission,report:w.report,notified:[...w.deliveredTo],..."declined"in i?{declined:i.declined}:{},...v===void 0?{}:{transitioned:v},...m===void 0?{}:{worktree_auto_dropped:!0,worktree_auto_dropped_path:m}}}}s(fe,"handleSubmitResult");async function T(t,e){const r=(await q(t)).find(n=>n.id===e);if(r===void 0)return;x.report(t,r);const i=(await d(t))?.run_id;i&&await E(i,t,"node.report.pushed",{body:r.body,kind:r.tier==="final"?"final":"update"})}s(T,"emitReportEvents");async function A(t){try{const e=await D(t);e!==null&&B(t,"pushedFinal",e.executionId)}catch(e){try{j({event:"daemon.node.final-marker.failed",level:"error",node_id:t,error:e})||process.stderr.write(`final marker failed for ${t}: ${String(e)}
12
+ `}s(me,"declineReportBody");const M=1024,A=64;async function pe(t,e){if(typeof t!="object"||t===null)throw f("a result submission requires a JSON body { value } or { decline, code, retryable }");const o=t.request_id;if(typeof o!="string"||o.trim()===""){const n=await _(e);throw new u({error:"request_id_required",message:`a structured result requires request_id${n===null?"":` (pending request: ${n.request_id})`}`,next:"Pass `--request <request-id>` exactly as named in the structured-output instruction."})}const i=Object.hasOwn(t,"value"),r=Object.hasOwn(t,"decline");if(i&&r)throw f("a result submission carries either { value } or { decline, code, retryable }, not both");if(r){const{decline:n,code:a,retryable:c}=t;if(typeof n!="string"||n.trim()==="")throw new u({error:"missing_decline_reason",message:"A decline needs a reason.",next:'Rerun with `--decline "<one sentence on why the schema cannot be honestly satisfied>" --code <token>`.'});if(n.length>M)throw new u({error:"decline_reason_too_long",message:`A decline reason is at most ${M} characters (got ${n.length}).`,next:"Keep the reason to one plain sentence; put any detail in an artifact and name its path."});if(typeof a!="string"||a.trim()===""||/\s/.test(a.trim())||a.trim().length>A)throw new u({error:"invalid_decline_code",message:`A decline needs a code: one whitespace-free token of at most ${A} characters naming the decline class.`,next:"Rerun with `--code <token>` \u2014 the token your requester documented for this case."});if(typeof c!="boolean")throw f("a decline carries `retryable` as a boolean");return{requestId:o.trim(),declined:{reason:n.trim(),code:a.trim(),retryable:c}}}if(!i)throw f("a result submission requires a JSON body { value } or { decline, code, retryable }");return{requestId:o.trim(),value:t.value}}s(pe,"parseSubmitBody");const he=1024*1024;async function we(t){const e=t.params.id,o=await g(e);await _(e)!==null&&await se(e);const i=await pe(t.body,e),r=await R(i.requestId);if(r===null||r.node_id!==e)throw new h(404,"structured_request_not_found","the named structured request does not belong to this node");if(r.state!=="pending")throw new h(409,r.state==="expired"?"structured_request_expired":"structured_request_settled",`structured request ${r.request_id} is already ${r.state}`);let n;if("value"in i){if(Buffer.byteLength(JSON.stringify(i.value)??"")>he)throw new u({error:"result_too_large",message:"the submitted result is over 1 MiB serialized; nothing was recorded.",next:"Submit a smaller result \u2014 write bulky content to a file and put its path in the result."});try{n=await ae(r.schema,i.value)}catch(l){throw new u({error:"result_schema_mismatch",message:`the submitted result does not match the requested schema: ${l.message}`,next:'Fix the listed fields and submit again; if the schema cannot be honestly satisfied, decline it (`submit_result` with `decline`, or `crtr push result --decline "<reason>" --code <token>`).'})}}const a="declined"in i?me(i.declined):fe(n);if(r.submission==="oneoff"){const l=await Y(async D=>await de(D,r.request_id,"declined"in i?{intended:"declined",declined:i.declined}:{intended:"completed",result:n}));if(!l.changed||l.row===null||l.row.state!=="completed"&&l.row.state!=="declined")throw new h(409,l.row?.state==="expired"?"structured_request_expired":"structured_request_settled",`structured request ${r.request_id} is already ${l.row?.state??"settled"}`);await E(l.row);const y=await b(e,{tier:"update",body:a},void 0,{requestMessageId:r.request_message_id});return await F(e,y.reportId),{status:200,body:{mode:r.submission,report:y.report,notified:[...y.deliveredTo],..."declined"in i?{declined:i.declined}:{}}}}const c=(await d(e))?.status,m=await $(e),p="declined"in i?{kind:"failure",reason:"declined",detailJson:JSON.stringify({schema:"crtr.node-outcome-detail/v1",message:i.declined.reason,declined:i.declined}),structured:{requestId:r.request_id,declined:i.declined,skipEffects:!0}}:{structured:{requestId:r.request_id,value:n,skipEffects:!0}},w=await b(e,{tier:"final",body:a},p);await C(e);const P=await R(r.request_id);await E(P),await F(e,w.reportId);const k=c===void 0?void 0:{from:c,to:(await d(e))?.status??"done"};return{status:200,body:{mode:r.submission,report:w.report,notified:[...w.deliveredTo],..."declined"in i?{declined:i.declined}:{},...k===void 0?{}:{transitioned:k},...m===void 0?{}:{worktree_auto_dropped:!0,worktree_auto_dropped_path:m}}}}s(we,"handleSubmitResult");async function F(t,e){const o=(await q(t)).find(r=>r.id===e);if(o===void 0)return;O.report(t,o);const i=(await d(t))?.run_id;i&&await x(i,t,"node.report.pushed",{body:o.body,kind:o.tier==="final"?"final":"update"})}s(F,"emitReportEvents");async function C(t){try{const e=await j(t);e!==null&&z(t,"pushedFinal",e.executionId)}catch(e){try{J({event:"daemon.node.final-marker.failed",level:"error",node_id:t,error:e})||process.stderr.write(`final marker failed for ${t}: ${String(e)}
13
13
  `)}catch{process.stderr.write(`final marker failed for ${t}: ${String(e)}
14
- `)}}}s(A,"markCommittedFinal");async function b(t,e,r,i){try{return await J(t,{kind:e.tier,body:e.body,...e.delivery_tier===void 0?{}:{deliveryTier:e.delivery_tier},...r===void 0?{}:{outcome:r},...i===void 0?{}:{result:i}})}catch(n){throw n instanceof z?new h(409,n.message,n.message==="structured_request_expired"?"the named structured request expired before this submission committed":"the named structured request is already settled"):n instanceof k&&n.code==="already_finalized"?new u({error:"already_finalized",message:"This node already submitted its canonical final result.",next:"Push an update with the new information, then stop."}):n instanceof k&&n.code==="finalization_forbidden"?new u({error:"finalization_forbidden",message:"A canceled or dead node cannot submit a canonical final result.",next:"Do not push final from this node."}):n}}s(b,"pushOrRethrow");async function q(t){const e=await K(),r=await Y(e,await Z(e,{class:"person"},async()=>[]),{type:"document",kind:"report",owner:await Q(e,t)}),i=await oe(r,async o=>({doc:o,head:(await V(e,o))[0]})),n=await U(e,i.flatMap(o=>o.head===void 0?[]:[o.head.body_hash]));return i.map(({doc:o,head:a})=>{const c=o.name.match(/-(update|urgent|final)$/)?.[1]??"update";return{name:o.name,id:o.id,tier:c,body:a===void 0?"":n.get(a.body_hash).trim(),created:o.created_at}}).sort((o,a)=>o.created<a.created?1:o.created>a.created?-1:a.name.localeCompare(o.name))}s(q,"reportsForNode");async function me(t){const e=t.params.id;await g(e);const r=t.query.get("tier"),i=t.query.get("limit"),n=i!==null?Number(i):void 0;let o=await q(e);return r!==null&&(o=o.filter(a=>a.tier===r)),n!==void 0&&Number.isFinite(n)&&n>=0&&(o=o.slice(0,n)),{status:200,body:o}}s(me,"handleList");const Be=[{method:"POST",pattern:"/v1/nodes/:id/reports",ownerOnly:!0,handler:se},{method:"GET",pattern:"/v1/nodes/:id/reports",handler:me},{method:"POST",pattern:"/v1/nodes/:id/result",handler:fe}];export{Be as reportRoutes,q as reportsForNode};
14
+ `)}}}s(C,"markCommittedFinal");async function b(t,e,o,i){try{return await L(t,{kind:e.tier,body:e.body,...e.delivery_tier===void 0?{}:{deliveryTier:e.delivery_tier},...o===void 0?{}:{outcome:o},...i===void 0?{}:{result:i}})}catch(r){throw r instanceof H?new h(409,r.message,r.message==="structured_request_expired"?"the named structured request expired before this submission committed":"the named structured request is already settled"):r instanceof v&&r.code==="already_finalized"?new u({error:"already_finalized",message:"This node already submitted its canonical final result.",next:"Push an update with the new information, then stop."}):r instanceof v&&r.code==="finalization_forbidden"?new u({error:"finalization_forbidden",message:"A canceled or dead node cannot submit a canonical final result.",next:"Do not push final from this node."}):r}}s(b,"pushOrRethrow");async function q(t){const e=await Q(),o=await te(e,await ne(e,{class:"person"},async()=>[]),{type:"document",kind:"report",owner:await re(e,t)}),i=await ue(o,async n=>({doc:n,head:(await ee(e,n))[0]})),r=await Z(e,i.flatMap(n=>n.head===void 0?[]:[n.head.body_hash]));return i.map(({doc:n,head:a})=>{const c=n.name.match(/-(update|urgent|final)$/)?.[1]??"update";return{name:n.name,id:n.id,tier:c,body:a===void 0?"":r.get(a.body_hash).trim(),created:n.created_at}}).sort((n,a)=>n.created<a.created?1:n.created>a.created?-1:a.name.localeCompare(n.name))}s(q,"reportsForNode");async function ye(t){const e=t.params.id;await g(e);const o=t.query.get("tier"),i=t.query.get("limit"),r=i!==null?Number(i):void 0;let n=await q(e);return o!==null&&(n=n.filter(a=>a.tier===o)),r!==void 0&&Number.isFinite(r)&&r>=0&&(n=n.slice(0,r)),{status:200,body:n}}s(ye,"handleList");const Le=[{method:"POST",pattern:"/v1/nodes/:id/reports",ownerOnly:!0,handler:le},{method:"GET",pattern:"/v1/nodes/:id/reports",handler:ye},{method:"POST",pattern:"/v1/nodes/:id/result",handler:we}];export{Le as reportRoutes,q as reportsForNode};
@@ -1 +1 @@
1
- var i=Object.defineProperty;var a=(e,t)=>i(e,"name",{value:t,configurable:!0});import{closeManagedWorktreeAsync as d}from"../../../core/worktree-close.js";import{abandonManagedWorktreeAsync as p}from"../../../core/worktree-mutation-async.js";import{listQuarantinedManagedWorktrees as m}from"../../../core/worktree-quarantine.js";import{usage as c}from"../../../core/errors.js";import{ApiError as l}from"../../../api/errors.js";import{getNode as u}from"../../../core/canvas/canvas.js";import{runsOnBlaxel as y}from"../environment-of.js";import{directorySizeBytes as f}from"../../../core/disk-usage.js";import{appsRoot as n,userRoot as h}from"../../../core/layout.js";import{existsSync as w,readdirSync as b}from"node:fs";import{join as k}from"node:path";import{ownerOnly as g}from"../router.js";async function s(e){const t=await u(e);if(t!==null&&await y(t.profile_id??null))throw new l(409,"worktree_not_available",`${e} runs in a sandbox, whose clone is its worktree; push a branch from it instead`)}a(s,"refuseOnBlaxel");async function v(e){const t=e.params.id;return await s(t),{status:200,body:await d(t)}}a(v,"handleWorktreeClose");async function S(e){const t=e.body?.by,o=typeof t=="string"?t.trim():"";if(o==="")throw c("abandon requires a non-empty invoking identity",{received:e.body,next:"Pass the invoking node id or human identity."});return await s(e.params.id),{status:200,body:await p(e.params.id,o)}}a(S,"handleWorktreeAbandon");async function W(){return{status:200,body:await m()}}a(W,"handleQuarantinedWorktrees");async function O(){const e=w(n())?b(n(),{withFileTypes:!0}).filter(r=>r.isDirectory()).map(r=>r.name).sort():[],t=[{space:"user",path:h()},...e.map(r=>({space:`app:${r}`,path:k(n(),r)}))];return{status:200,body:{spaces:await Promise.all(t.map(async r=>({...r,size_bytes:await f(r.path)})))}}}a(O,"handleSpaces");const $=g([{method:"GET",pattern:"/v1/spaces",handler:O},{method:"POST",pattern:"/v1/nodes/:id/worktree/close",handler:v},{method:"POST",pattern:"/v1/nodes/:id/worktree/abandon",handler:S},{method:"GET",pattern:"/v1/worktrees/quarantined",handler:W}]);export{$ as worktreeRoutes};
1
+ var p=Object.defineProperty;var r=(e,t)=>p(e,"name",{value:t,configurable:!0});import{closeManagedWorktreeAsync as m}from"../../../core/worktree-close.js";import{abandonManagedWorktreeAsync as l}from"../../../core/worktree-mutation-async.js";import{abandonManagedWorktreeOnMachine as u,closeManagedWorktreeOnMachine as y,worktreeMachineOf as f}from"../../../core/worktree-machine.js";import{listQuarantinedManagedWorktrees as h}from"../../../core/worktree-quarantine.js";import{usage as w}from"../../../core/errors.js";import{ApiError as b}from"../../../api/errors.js";import{getNode as s}from"../../../core/canvas/canvas.js";import{runsOnBlaxel as k}from"../environment-of.js";import{directorySizeBytes as g}from"../../../core/disk-usage.js";import{appsRoot as o,userRoot as O}from"../../../core/layout.js";import{existsSync as v,readdirSync as M}from"node:fs";import{join as W}from"node:path";import{ownerOnly as S}from"../router.js";async function d(e){const t=await s(e);if(t!==null&&await k(t.profile_id??null))throw new b(409,"worktree_not_available",`${e} runs in a sandbox, whose clone is its worktree; push a branch from it instead`)}r(d,"refuseOnBlaxel");async function c(e){return f((await s(e))?.profile_id)}r(c,"machineOf");async function T(e){const t=e.params.id;await d(t);const n=await c(t);return{status:200,body:n!==null?await y(n,t):await m(t)}}r(T,"handleWorktreeClose");async function _(e){const t=e.body?.by,n=typeof t=="string"?t.trim():"";if(n==="")throw w("abandon requires a non-empty invoking identity",{received:e.body,next:"Pass the invoking node id or human identity."});const a=e.params.id;await d(a);const i=await c(a);return{status:200,body:i!==null?await u(i,a,n):await l(a,n)}}r(_,"handleWorktreeAbandon");async function x(){return{status:200,body:await h()}}r(x,"handleQuarantinedWorktrees");async function A(){const e=v(o())?M(o(),{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>a.name).sort():[],t=[{space:"user",path:O()},...e.map(a=>({space:`app:${a}`,path:W(o(),a)}))];return{status:200,body:{spaces:await Promise.all(t.map(async a=>({...a,size_bytes:await g(a.path)})))}}}r(A,"handleSpaces");const H=S([{method:"GET",pattern:"/v1/spaces",handler:A},{method:"POST",pattern:"/v1/nodes/:id/worktree/close",handler:T},{method:"POST",pattern:"/v1/nodes/:id/worktree/abandon",handler:_},{method:"GET",pattern:"/v1/worktrees/quarantined",handler:x}]);export{H as worktreeRoutes};
@@ -1 +1 @@
1
- var _=Object.defineProperty;var c=(e,n)=>_(e,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as T}from"node:path";import{apiSocketPath as E}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as f}from"../core/events/emit.js";import{createMachineExecutor as P,stopAllBrokers as x}from"../core/runtime/runner/machine/executor.js";import{readPersonCredential as C}from"../core/directory/person-credential.js";import{socketDir as F}from"../core/layout.js";import{isDaemonRunning as G,pidfilePath as u,readPidfile as b}from"./pidfile.js";import{cancelMachineCron as N,runMachineCron as D,stopOrphanedMachineCrons as O}from"./cron/machine-exec.js";import{startMachineLink as U}from"./machine-link/client.js";import{deleteMoveRecord as w,readMachineConfig as Y,readMachineCredential as y,readMoveRecord as A,writeMoveRecord as z}from"./machine-link/config.js";import{notifyMoveFinished as H}from"./machine-link/move-notify.js";function j(e,n){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:e,signed_in:n,startup_phase:e?"ready":"recovering"}}c(j,"machineHealth");async function se(){const e=Y();if(e===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const n=C()!==void 0;if(n&&y(),G())throw new Error("a crtrd is already running for this home");R(),n||(await x(),await O(),f({level:"info",event:"daemon.machine.signed_out",fields:{environment:e.environmentId}})),h(F(),{recursive:!0,mode:493});const a=E();S(a)&&g(a);let r;const t=k((s,d)=>{const p=(s.method??"GET")==="GET"&&(s.url??"/").split("?")[0]==="/healthz";d.writeHead(p?200:404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify(p?j(r?.connected()===!0,n):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((s,d)=>{t.once("error",d),t.listen(a,()=>{t.off("error",d),M(a,384),s()})}),h(T(u()),{recursive:!0}),I(u(),String(process.pid),"utf8");let i;await L(e.runId,n,()=>i!==void 0);const o=P({apiUrl:e.apiUrl,environmentId:e.environmentId});r=n?U({apiUrl:e.apiUrl,environmentId:e.environmentId,credential:y,handlers:{start:o.start,wake:o.wake,stop:o.stop,status:o.status,delete:o.delete,viewer:o.viewer,"cron.run":D,"cron.cancel":N}}):void 0,f({level:"info",event:"daemon.machine.started",fields:{environment:e.environmentId}});const l=c(()=>i??=(async()=>{r?.stop(),await new Promise(s=>{t.close(()=>s()),t.closeAllConnections()}),b()===process.pid&&(v(a,{force:!0}),v(u(),{force:!0})),process.off("SIGINT",m),process.off("SIGTERM",m)})(),"teardown"),m=c(()=>{l().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",m),process.on("SIGTERM",m),l}c(se,"runMachineDaemon");const B=5e3,J=3e5;async function L(e,n,a){let r;try{r=A()}catch(i){f({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(r===void 0||r.state==="running"||r.runId!==e)return;if(r.notified||r.notify===null){w();return}if(r.state==="committed"&&(r={...r,state:"activated"},z(r)),!n)return;const t=r;(async()=>{let i=B;for(;;){try{await H(t),w();return}catch(o){f({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:t.notify??"",error:o.message}})}if(await new Promise(o=>{setTimeout(o,i).unref()}),a())return;i=Math.min(i*2,J)}})()}c(L,"settleFinishedMove");export{j as machineHealth,se as runMachineDaemon};
1
+ var _=Object.defineProperty;var c=(e,n)=>_(e,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as T}from"node:path";import{apiSocketPath as E}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as f}from"../core/events/emit.js";import{createMachineExecutor as P,stopAllBrokers as x}from"../core/runtime/runner/machine/executor.js";import{machineWorktreeHandlers as C}from"../core/worktree-machine.js";import{readPersonCredential as F}from"../core/directory/person-credential.js";import{socketDir as G}from"../core/layout.js";import{isDaemonRunning as b,pidfilePath as u,readPidfile as N}from"./pidfile.js";import{cancelMachineCron as D,runMachineCron as O,stopOrphanedMachineCrons as U}from"./cron/machine-exec.js";import{startMachineLink as Y}from"./machine-link/client.js";import{deleteMoveRecord as w,readMachineConfig as A,readMachineCredential as y,readMoveRecord as H,writeMoveRecord as z}from"./machine-link/config.js";import{notifyMoveFinished as j}from"./machine-link/move-notify.js";function B(e,n){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:e,signed_in:n,startup_phase:e?"ready":"recovering"}}c(B,"machineHealth");async function de(){const e=A();if(e===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const n=F()!==void 0;if(n&&y(),b())throw new Error("a crtrd is already running for this home");R(),n||(await x(),await U(),f({level:"info",event:"daemon.machine.signed_out",fields:{environment:e.environmentId}})),h(G(),{recursive:!0,mode:493});const a=E();S(a)&&g(a);let r;const t=k((s,d)=>{const p=(s.method??"GET")==="GET"&&(s.url??"/").split("?")[0]==="/healthz";d.writeHead(p?200:404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify(p?B(r?.connected()===!0,n):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((s,d)=>{t.once("error",d),t.listen(a,()=>{t.off("error",d),M(a,384),s()})}),h(T(u()),{recursive:!0}),I(u(),String(process.pid),"utf8");let i;await W(e.runId,n,()=>i!==void 0);const o=P({apiUrl:e.apiUrl,environmentId:e.environmentId});r=n?Y({apiUrl:e.apiUrl,environmentId:e.environmentId,credential:y,handlers:{start:o.start,wake:o.wake,stop:o.stop,status:o.status,delete:o.delete,viewer:o.viewer,"cron.run":O,"cron.cancel":D,...C}}):void 0,f({level:"info",event:"daemon.machine.started",fields:{environment:e.environmentId}});const l=c(()=>i??=(async()=>{r?.stop(),await new Promise(s=>{t.close(()=>s()),t.closeAllConnections()}),N()===process.pid&&(v(a,{force:!0}),v(u(),{force:!0})),process.off("SIGINT",m),process.off("SIGTERM",m)})(),"teardown"),m=c(()=>{l().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",m),process.on("SIGTERM",m),l}c(de,"runMachineDaemon");const J=5e3,L=3e5;async function W(e,n,a){let r;try{r=H()}catch(i){f({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(r===void 0||r.state==="running"||r.runId!==e)return;if(r.notified||r.notify===null){w();return}if(r.state==="committed"&&(r={...r,state:"activated"},z(r)),!n)return;const t=r;(async()=>{let i=J;for(;;){try{await j(t),w();return}catch(o){f({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:t.notify??"",error:o.message}})}if(await new Promise(o=>{setTimeout(o,i).unref()}),a())return;i=Math.min(i*2,L)}})()}c(W,"settleFinishedMove");export{B as machineHealth,de as runMachineDaemon};
@@ -1,3 +1,3 @@
1
- var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as O}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as D,isPidAlive as f}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as G}from"./startup-policy.js";import{exclusiveLockOwnerPid as se}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ce}from"../core/canvas/paths.js";import{envNoDaemonAutostart as ue}from"../shared/env.js";import{awaitJoinLockRelease as le,joinInProgress as de,joinInProgressError as pe,joinLockHolder as fe}from"../core/directory/join-lock.js";import{waitForDaemonAvailability as me}from"../api/index.js";import{localClient as he}from"../api/node-transport.js";const we=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function M(){const e={...process.env};for(const t of we)delete e[t];return e}o(M,"sanitizedDaemonEnv");function _e(){for(let e=k(Z(import.meta.url));;e=k(e)){if(H(E(e,"bin","runtime-generation-manifest.mjs")))return e;if(k(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(_e,"generationRoot");async function A(){const e=_e(),t=I(E(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(E(r(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,E(e,"src","daemon","crtrd-cli.ts")]}const n=I(E(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),c=a("daemon");if(!c.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${c.error}`);return[c.runtime.entryPath]}o(A,"resolveDaemonLaunch");function Ee(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(Ee,"daemonCommandDeclaresCanvasHome");function De(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&Ee(a,t)&&n!==process.pid&&r.push(n);return r}o(De,"findDaemonPids");function xe(e){const t=De().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>f(n));)V("sleep",["0.1"]);for(const n of t)if(f(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(xe,"sweepStrayDaemons");async function Qe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=O(),r=await A();return e(t,[t,...r,"--canvas-home",g()],M())}o(Qe,"execDaemon");async function R(e){const t=await A(),r=B(O(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:M()});let n="",a="";r.stdout.setEncoding("utf8").on("data",u=>{n+=u}),r.stderr.setEncoding("utf8").on("data",u=>{a+=u});const c=await new Promise((u,m)=>{r.once("error",m),r.once("close",p=>u(p))});if(c!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${c}`);const s=n.trim().split(`
2
- `).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function Ze(){return R(["export-sqlite"])}o(Ze,"runDaemonExportSqlite");function et(e,t){return R(["import-dump",e,t])}o(et,"runDaemonImportDump");function tt(e){return R(["import-dump",e,"bodies"])}o(tt,"runDaemonBodiesDump");function rt(){return R(["import-dump","","install-id"])}o(rt,"runDaemonInstallId");const ye=3*6e4,z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return he({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function ge(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(ge,"probeErrorMessage");async function J(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=D()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(J,"probeDaemonServing");async function nt(){try{return await J(),!0}catch{return!1}}o(nt,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
- ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Se(e,t=G,r={},n="ready"){const a=r.readPidfile??D,c=r.isPidAlive??f,s=r.childExited,u=r.isDaemonServing,m=r.probeDaemonServing??(async w=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await J(w)}),p=r.probeDaemonHealth??L,x=r.sleepMs??$,y=r.now??Date.now;let i=null,l=null;return await me({windowMs:t,pollIntervalMs:N,now:y,sleep:x,retry:o(w=>w!==l,"retry"),probe:o(async w=>{const h=a();if(h===null||!c(h)){const d=s?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await m(w)}catch(d){throw d instanceof v&&(l=d),d}i=h;return}const _=await p(w);if(_.startup_phase==="prepared"){i=h;return}throw _.startup_phase==="blocked"?(l=new v(h,_.startup_blocked??"on-disk migration is blocked"),l):_.startup_phase==="ready"?(l=new F(h,_.startup_phase),l):new Error(`daemon ${h} is ${_.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),i===e?null:i}o(Se,"verifyDaemonStartup");async function Re(e,t=z,r={}){const n=r.readPidfile??D,a=r.isPidAlive??f,c=r.sleepMs??$,s=r.now??Date.now,u=s()+t;for(;s()<=u;){if(!a(e)&&n()!==e)return;await c(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(Re,"waitForDaemonExit");const ve=2e3,Te=5e3;async function X(e,t=z,r={}){const n=r.isPidAlive??f,a=r.sleepMs??$,c=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await Re(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const s=c()+ve;for(;c()<=s;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(X,"stopDaemonProcess");async function ot(){const e=D(),t=e!==null&&f(e),r=t&&await X(e)==="killed",n=xe(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(ot,"stopAllDaemons");function be(e,t,r=2048){let n;try{n=U(e,"r");const{size:a}=K(n),c=Math.max(t,a-r),s=a-c;if(s<=0)return"";const u=Buffer.alloc(s);return re(n,u,0,s,c),u.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{j(n)}catch{}}}o(be,"readLogTailFrom");async function ke(e={}){if(process.platform==="linux"&&H("/run/crtr/launcher.sock")&&!f(D()??-1))throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=D();if(r!==null&&f(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:ge(i)}}te(g(),{recursive:!0});const n=await A().catch(i=>{throw new Y(i)});e.waitForJoinLock===!0&&await le(ye);const a=fe();if(a!==null&&a!==process.pid&&e.ignoreJoinLock!==!0)throw pe(a);const c=E(g(),"crtrd.err"),s=U(c,"a"),u=(()=>{try{return K(s).size}catch{return 0}})();ae()===void 0&&oe();const m=B(O(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:M()});j(s);const p=m.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let x=null;m.once("exit",(i,l)=>{x={code:i,signal:l}}),m.unref();let y;try{y=await Se(p,G,{childExited:o(()=>x,"childExited"),childStderrTail:o(()=>be(c,u),"childStderrTail")},t)}catch(i){const l=se(ce())===p;if(x===null&&!l&&!(i instanceof v))try{await X(p,Te)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(ke,"spawnDaemon");function Ie(){return ue()||process.argv.includes("--no-autostart")}o(Ie,"autostartDisabled");const Oe=5e3,Me=6e4;let W=!1,S,T=0,b=0;function Ae(e){return Math.min(Oe*2**(e-1),Me)}o(Ae,"autostartBackoffMs");function Ne(){S=void 0,T=0,b=0}o(Ne,"resetDaemonAutostart");function at(){return S}o(at,"daemonAutostartStartupFailure");function it(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??ke,n=e.now??Date.now;if(!Ie()&&!de()&&!W&&!(n()<b)){if(t()){Ne();return}S=void 0,W=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof Y)&&(S=a.message),T+=1,b=n()+Ae(T)}).finally(()=>{W=!1})}}o(it,"ensureDaemon");export{we as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Ie as autostartDisabled,at as daemonAutostartStartupFailure,Ee as daemonCommandDeclaresCanvasHome,it as ensureDaemon,Qe as execDaemon,De as findDaemonPids,nt as isDaemonServing,L as probeDaemonHealth,J as probeDaemonServing,ge as probeErrorMessage,Ne as resetDaemonAutostart,tt as runDaemonBodiesDump,Ze as runDaemonExportSqlite,et as runDaemonImportDump,rt as runDaemonInstallId,M as sanitizedDaemonEnv,ke as spawnDaemon,ot as stopAllDaemons,X as stopDaemonProcess,xe as sweepStrayDaemons,Se as verifyDaemonStartup,Re as waitForDaemonExit};
1
+ var q=Object.defineProperty;var o=(e,t)=>q(e,"name",{value:t,configurable:!0});import{spawn as B,execFileSync as V}from"node:child_process";import{createRequire as Q}from"node:module";import{dirname as k,join as E}from"node:path";import{fileURLToPath as Z,pathToFileURL as I}from"node:url";import{existsSync as H,lstatSync as ee,mkdirSync as te,openSync as U,closeSync as j,fstatSync as K,readSync as re}from"node:fs";import{crtrHome as g}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as M}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as D,isPidAlive as f}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as G}from"./startup-policy.js";import{readMachineConfig as se}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ce}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as ue}from"../core/canvas/paths.js";import{envNoDaemonAutostart as le}from"../shared/env.js";import{awaitJoinLockRelease as de,joinInProgress as pe,joinInProgressError as fe,joinLockHolder as me}from"../core/directory/join-lock.js";import{waitForDaemonAvailability as he}from"../api/index.js";import{localClient as we}from"../api/node-transport.js";const _e=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function O(){const e={...process.env};for(const t of _e)delete e[t];return e}o(O,"sanitizedDaemonEnv");function Ee(){for(let e=k(Z(import.meta.url));;e=k(e)){if(H(E(e,"bin","runtime-generation-manifest.mjs")))return e;if(k(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Ee,"generationRoot");async function A(){const e=Ee(),t=I(E(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{ee(E(r(),"selected"))}catch(s){if(s.code!=="ENOENT")throw s;return["--conditions","crtr-src","--import",I(Q(import.meta.url).resolve("tsx/esm")).href,E(e,"src","daemon","crtrd-cli.ts")]}const n=I(E(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),c=a("daemon");if(!c.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${c.error}`);return[c.runtime.entryPath]}o(A,"resolveDaemonLaunch");function De(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(De,"daemonCommandDeclaresCanvasHome");function xe(){const e=ne();if(e===null)return[];const t=g(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&De(a,t)&&n!==process.pid&&r.push(n);return r}o(xe,"findDaemonPids");function ye(e){const t=xe().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>f(n));)V("sleep",["0.1"]);for(const n of t)if(f(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(ye,"sweepStrayDaemons");async function et(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=M(),r=await A();return e(t,[t,...r,"--canvas-home",g()],O())}o(et,"execDaemon");async function R(e){const t=await A(),r=B(M(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:O()});let n="",a="";r.stdout.setEncoding("utf8").on("data",u=>{n+=u}),r.stderr.setEncoding("utf8").on("data",u=>{a+=u});const c=await new Promise((u,m)=>{r.once("error",m),r.once("close",p=>u(p))});if(c!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${c}`);const s=n.trim().split(`
2
+ `).at(-1)??"";return JSON.parse(s)}o(R,"runDaemonEntry");function tt(){return R(["export-sqlite"])}o(tt,"runDaemonExportSqlite");function rt(e,t){return R(["import-dump",e,t])}o(rt,"runDaemonImportDump");function nt(e){return R(["import-dump",e,"bodies"])}o(nt,"runDaemonBodiesDump");function ot(){return R(["import-dump","","install-id"])}o(ot,"runDaemonInstallId");const ge=3*6e4,z=2e4,N=10,P=1e3;async function L(e=P){const t=Math.min(e,P);return we({autostart:!1,timeoutMs:t}).probeHealthz(t)}o(L,"probeDaemonHealth");function Se(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(Se,"probeErrorMessage");async function J(e=P){const t=await L(e);if(t.startup_phase==="blocked"){const r=D()??process.pid;throw new v(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(J,"probeDaemonServing");async function at(){try{return await J(),!0}catch{return!1}}o(at,"isDaemonServing");function $(e){return new Promise(t=>{setTimeout(t,e)})}o($,"sleepMs");class C extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
3
+ ${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class Y extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class v extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class F extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Re(e,t=G,r={},n="ready"){const a=r.readPidfile??D,c=r.isPidAlive??f,s=r.childExited,u=r.isDaemonServing,m=r.probeDaemonServing??(async w=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await J(w)}),p=r.probeDaemonHealth??L,x=r.sleepMs??$,y=r.now??Date.now;let i=null,l=null;return await he({windowMs:t,pollIntervalMs:N,now:y,sleep:x,retry:o(w=>w!==l,"retry"),probe:o(async w=>{const h=a();if(h===null||!c(h)){const d=s?.();throw d!=null&&(d.signal!==null?l=new C(`daemon ${e} exited before becoming ready (by ${d.signal})`,r.childStderrTail?.()??""):d.code!==0&&(l=new C(`daemon ${e} exited before becoming ready (with exit code ${d.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await m(w)}catch(d){throw d instanceof v&&(l=d),d}i=h;return}const _=await p(w);if(_.startup_phase==="prepared"){i=h;return}throw _.startup_phase==="blocked"?(l=new v(h,_.startup_blocked??"on-disk migration is blocked"),l):_.startup_phase==="ready"?(l=new F(h,_.startup_phase),l):new Error(`daemon ${h} is ${_.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),i===e?null:i}o(Re,"verifyDaemonStartup");async function ve(e,t=z,r={}){const n=r.readPidfile??D,a=r.isPidAlive??f,c=r.sleepMs??$,s=r.now??Date.now,u=s()+t;for(;s()<=u;){if(!a(e)&&n()!==e)return;await c(N)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(ve,"waitForDaemonExit");const Te=2e3,be=5e3;async function X(e,t=z,r={}){const n=r.isPidAlive??f,a=r.sleepMs??$,c=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await ve(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const s=c()+Te;for(;c()<=s;){if(!n(e))return"killed";await a(N)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(X,"stopDaemonProcess");async function it(){const e=D(),t=e!==null&&f(e),r=t&&await X(e)==="killed",n=ye(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(it,"stopAllDaemons");function ke(e,t,r=2048){let n;try{n=U(e,"r");const{size:a}=K(n),c=Math.max(t,a-r),s=a-c;if(s<=0)return"";const u=Buffer.alloc(s);return re(n,u,0,s,c),u.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{j(n)}catch{}}}o(ke,"readLogTailFrom");async function Ie(e={}){if(process.platform==="linux"&&H("/run/crtr/launcher.sock")&&!f(D()??-1)&&se()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=D();if(r!==null&&f(r))try{const i=await L();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new F(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof F)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:Se(i)}}te(g(),{recursive:!0});const n=await A().catch(i=>{throw new Y(i)});e.waitForJoinLock===!0&&await de(ge);const a=me();if(a!==null&&a!==process.pid&&e.ignoreJoinLock!==!0)throw fe(a);const c=E(g(),"crtrd.err"),s=U(c,"a"),u=(()=>{try{return K(s).size}catch{return 0}})();ae()===void 0&&oe();const m=B(M(),[...n,"--canvas-home",g(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:O()});j(s);const p=m.pid;if(p===void 0)throw new Error("daemon spawn did not return a pid");let x=null;m.once("exit",(i,l)=>{x={code:i,signal:l}}),m.unref();let y;try{y=await Re(p,G,{childExited:o(()=>x,"childExited"),childStderrTail:o(()=>ke(c,u),"childStderrTail")},t)}catch(i){const l=ce(ue())===p;if(x===null&&!l&&!(i instanceof v))try{await X(p,be)}catch{}throw i}return y!==null?{started:!1,existing_pid:y,startup_phase:t}:{started:!0,pid:p,startup_phase:t}}o(Ie,"spawnDaemon");function Me(){return le()||process.argv.includes("--no-autostart")}o(Me,"autostartDisabled");const Oe=5e3,Ae=6e4;let W=!1,S,T=0,b=0;function Ne(e){return Math.min(Oe*2**(e-1),Ae)}o(Ne,"autostartBackoffMs");function Pe(){S=void 0,T=0,b=0}o(Pe,"resetDaemonAutostart");function st(){return S}o(st,"daemonAutostartStartupFailure");function ct(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??Ie,n=e.now??Date.now;if(!Me()&&!pe()&&!W&&!(n()<b)){if(t()){Pe();return}S=void 0,W=!0,r().then(()=>{S=void 0,T=0,b=0},a=>{(a instanceof C||a instanceof Y)&&(S=a.message),T+=1,b=n()+Ne(T)}).finally(()=>{W=!1})}}o(ct,"ensureDaemon");export{_e as DAEMON_ENV_STRIP_KEYS,C as DaemonExitedBeforeReadyError,Y as DaemonLaunchError,F as DaemonNotPreparedError,v as DaemonStartupBlockedError,Me as autostartDisabled,st as daemonAutostartStartupFailure,De as daemonCommandDeclaresCanvasHome,ct as ensureDaemon,et as execDaemon,xe as findDaemonPids,at as isDaemonServing,L as probeDaemonHealth,J as probeDaemonServing,Se as probeErrorMessage,Pe as resetDaemonAutostart,nt as runDaemonBodiesDump,tt as runDaemonExportSqlite,rt as runDaemonImportDump,ot as runDaemonInstallId,O as sanitizedDaemonEnv,Ie as spawnDaemon,it as stopAllDaemons,X as stopDaemonProcess,ye as sweepStrayDaemons,Re as verifyDaemonStartup,ve as waitForDaemonExit};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.651",
3
+ "version": "0.3.653",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.651",
148
+ "@north-light/identity": "0.3.653",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.651",
3
+ "version": "0.3.653",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.651",
3
+ "version": "0.3.653",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.651",
9
+ "version": "0.3.653",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.651",
31
+ "@north-light/identity": "0.3.653",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.651",
11959
+ "version": "0.3.653",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.651",
11964
+ "version": "0.3.653",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.651",
11969
+ "version": "0.3.653",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.651",
11977
+ "version": "0.3.653",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.651",
11981
- "@north-light/identity": "0.3.651"
11980
+ "@north-light/api": "0.3.653",
11981
+ "@north-light/identity": "0.3.653"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.651",
11986
+ "version": "0.3.653",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.651",
11990
- "@north-light/identity": "0.3.651",
11991
- "@north-light/plugin": "0.3.651",
11989
+ "@north-light/api": "0.3.653",
11990
+ "@north-light/identity": "0.3.653",
11991
+ "@north-light/plugin": "0.3.653",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {
@@ -1,23 +0,0 @@
1
- export interface TicketClaim {
2
- token: string;
3
- host: string;
4
- pid: number;
5
- claimedAt: string;
6
- heartbeatAt: string;
7
- tmuxClient?: string;
8
- }
9
- export interface ClaimOptions {
10
- host?: string;
11
- pid?: number;
12
- tmuxClient?: string;
13
- now?: Date;
14
- }
15
- export declare function readTicketClaim(dir: string): TicketClaim | null;
16
- export declare function isStaleClaim(claim: TicketClaim, now?: number, localHost?: string): boolean;
17
- /** Exclude another live presenter; the daemon owns whether the request can settle. */
18
- export declare function claimTicket(ticketDir: string, opts?: ClaimOptions): TicketClaim | null;
19
- export declare function heartbeatClaim(ticketDir: string, token: string, now?: Date): boolean;
20
- export declare function releaseClaimLocked(ticketDir: string, token: string): boolean;
21
- export declare function releaseClaim(dir: string, token: string): boolean;
22
- export declare function claimExists(dir: string): boolean;
23
- export declare function withTicketLock<T>(dir: string, operation: () => T): T;
@@ -1,3 +0,0 @@
1
- var y=Object.defineProperty;var n=(e,t)=>y(e,"name",{value:t,configurable:!0});import{existsSync as h,mkdirSync as S,renameSync as b,unlinkSync as k,writeFileSync as x}from"node:fs";import{join as g}from"node:path";import{hostname as m}from"node:os";import{randomUUID as C}from"node:crypto";import{claimPath as l}from"./convention.js";import{readJsonOrNull as A}from"../fs-utils.js";import{withExclusiveDirectoryLock as u}from"../exclusive-lock.js";import{runtimeRoot as w}from"../layout.js";import{isBlobRequestPath as $}from"./request-files.js";function o(e){if(!$(e))return e;const t=g(w(),"ticket-claims",e);return S(t,{recursive:!0}),t}n(o,"claimDir");const D=3e4;function L(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.token!="string"||typeof t.host!="string"||!Number.isInteger(t.pid)||typeof t.claimedAt!="string"||typeof t.heartbeatAt!="string"?null:{token:t.token,host:t.host,pid:t.pid,claimedAt:t.claimedAt,heartbeatAt:t.heartbeatAt,...typeof t.tmuxClient=="string"?{tmuxClient:t.tmuxClient}:{}}}n(L,"parseClaim");function s(e){return L(A(l(o(e))))}n(s,"readTicketClaim");function O(e){try{return process.kill(e,0),!0}catch{return!1}}n(O,"isLiveLocalPid");function E(e,t=Date.now(),i=m()){if(e.host===i)return!O(e.pid);const r=Date.parse(e.heartbeatAt);return!Number.isFinite(r)||t-r>D}n(E,"isStaleClaim");function U(e,t={}){const i=o(e);return u(`${i}/.ticket-lock`,()=>{const r=l(i),c=s(i);if(c!==null&&!E(c,Date.now(),t.host??m()))return null;h(r)&&k(r);const a=t.host??m(),d=t.pid??process.pid,f=(t.now??new Date).toISOString(),p={token:C(),host:a,pid:d,claimedAt:f,heartbeatAt:f,...t.tmuxClient?{tmuxClient:t.tmuxClient}:{}};return x(r,`${JSON.stringify(p)}
2
- `,{flag:"wx",mode:384}),p})}n(U,"claimTicket");function q(e,t,i=new Date){const r=o(e);return u(`${r}/.ticket-lock`,()=>{const c=s(r);if(c===null||c.token!==t)return!1;const a=`${l(r)}.${t}.heartbeat`;return x(a,`${JSON.stringify({...c,heartbeatAt:i.toISOString()})}
3
- `,{flag:"wx",mode:384}),b(a,l(r)),!0})}n(q,"heartbeatClaim");function N(e,t){const i=s(e);return i===null||i.token!==t?!1:(k(l(o(e))),!0)}n(N,"releaseClaimLocked");function B(e,t){return u(`${o(e)}/.ticket-lock`,()=>N(e,t))}n(B,"releaseClaim");function z(e){return h(l(o(e)))}n(z,"claimExists");function G(e,t){return u(`${o(e)}/.ticket-lock`,t)}n(G,"withTicketLock");export{z as claimExists,U as claimTicket,q as heartbeatClaim,E as isStaleClaim,s as readTicketClaim,B as releaseClaim,N as releaseClaimLocked,G as withTicketLock};