@north-light/cli 0.3.505 → 0.3.507

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.
@@ -1 +1 @@
1
- var Re=Object.defineProperty;var a=(e,t)=>Re(e,"name",{value:t,configurable:!0});import{prepared as X}from"../../../core/sqlite-statements.js";import{envProfileId as Ie}from"../../../shared/env.js";import{pausedCanvasProfiles as Oe}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as Z,statSync as q}from"node:fs";import{isAbsolute as G,resolve as T}from"node:path";import{appendSituationalContext as Ae,formatSituationalProse as $e}from"../../../core/runtime/situational-context.js";import{closeNode as Ce}from"../../../core/runtime/close.js";import{reviveNode as Ne}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as x,forkNode as Te,resolveForkSource as Ee,spawnChildPrepared as Pe}from"../../../core/runtime/spawn.js";import{forkSourceNode as De,newNodeId as ee}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ne,childrenOf as Me,completeCreateRequest as te,findCreateRequest as Le,getNode as R,recordCreateRequestNode as je,reserveCreateRequest as oe,reserveCreateRequestNode as Fe,listNodes as re,recordRespawnAttempt as Ge,subscribersOf as Be,subscriptionsOf as ie,setMessageWait as xe,updateNode as C}from"../../../core/canvas/canvas.js";import{subtreeIds as Ke}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as We}from"../../../core/canvas/recovery.js";import{nodeObject as Ve}from"../../../core/graph/objects.js";import{recordActedOn as ze}from"../../../core/graph/edges.js";import{publish as Je}from"../../../core/graph/events.js";import{readerFor as Ue}from"../reader.js";import{relocateSessionCwd as Ye,unbindSession as He}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as Qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as Xe}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as W}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as Ze}from"../../cron/authority.js";import{cronBirthPlacement as qe}from"../../cron/armed-context.js";import{existsBeneath as en,isAbsentOrRefused as nn,isBeneathRefusal as tn,readdirBeneath as on}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as rn,readNodeSession as dn,readNodeSnapshot as sn,transcriptMarkdown as an}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as ln}from"../../../core/substrate/subject.js";import{reviveAll as cn}from"../../../core/runtime/revive-all.js";import{promoteAsync as fn,requestYieldAsync as un,reshapeNodeAsync as V}from"../../../core/runtime/promote.js";import{recycleNode as pn}from"../../../core/runtime/recycle.js";import{relaunchRoot as mn}from"../../../core/runtime/reset.js";import{assertReopenGate as hn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as wn,readGoal as yn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as _n,hasRoadmap as gn}from"../../../core/runtime/roadmap.js";import{renameWindow as bn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as vn,explicitModelIntent as kn,normalizeModel as Sn,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Rn}from"../../../core/model-routes.js";import{persistDormantModel as In,setModelLive as On}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ae}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as An}from"../../../core/runtime/broker-request.js";import{boundFleet as E}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as $n}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Cn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as le}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Nn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Tn}from"../../../core/human-actions.js";import{parseDurationMs as En}from"../../../core/wake.js";import{claimWarmNode as Pn,refillWarmPool as ce,resumeWarmClaim as Dn,warmPoolEnabled as Mn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Ln,resolveLaunchTarget as jn}from"../../../core/runtime/launch-target.js";import{fullName as Fn}from"../../../core/canvas/labels.js";import{reportsForNode as fe}from"./reports.js";import{requireUsableProfile as Gn}from"./profiles.js";import{assertProfileActive as Bn,loadExactProfileManifest as xn}from"../../../core/profiles/manifest.js";import{getCron as ue}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Kn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Wn}from"../../control.js";import{notFound as P,usage as h}from"../../../core/errors.js";import{assertScope as Vn,validateScopes as pe}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as zn,toNodeDetailDTO as J,toNodeSummaryDTO as Jn,toReviveResultDTO as Un}from"../map.js";import{ApiError as u}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Yn,brokerMayReach as U,canReadNode as me,resolvedScopes as Hn}from"../router.js";import{forwardVerb as Qn,queryWithoutMachine as Xn,relayError as Zn,unknownError as qn,withMachine as et}from"../../peer/forward.js";import{fileRoot as nt}from"../../../core/spaces/file-root.js";import{activeGrant as tt,terminalGrant as ot}from"../../../core/grants/mirror.js";import{appRungForGrant as rt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as it}from"../../../core/model-routes.js";import{readConfig as dt}from"../../../core/config.js";import{hasConfiguredProviderCredential as st,NO_PROVIDER_CREDENTIAL_MESSAGE as he}from"../../../core/runtime/provider-credential-gate.js";function w(e){const t=R(e);if(t===null)throw P(`unknown node: ${e}`,{received:e});return t}a(w,"requireMeta");function Y(e){return{subscribesTo:ie(e),subscribers:Be(e),children:Me(e)}}a(Y,"edgesFor");function g(e){const t=w(e);return J(t,Y(e))}a(g,"detailOf");function at(e){let t=fe(e).length;try{t+=on(W(e),de(e)).length}catch(n){if(!nn(n))throw n}return t}a(at,"countFiles");function lt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&pe(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new u(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(lt,"parseCreateBody");function ct(e){if(e===void 0)return;const t=En(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new u(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(ct,"parseDeadline");function ft(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new u(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Nn.test(e.action))throw new u(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>le)throw new u(413,"payload_too_large",`serialized payload exceeds ${le} bytes`)}return e}}a(ft,"parseOutcomeDelivery");function ut(e,t){const n=Tn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new u(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new u(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(ut,"resolveOutcomeDelivery");function pt(e,t,n){const r={kind:e.kind,cwd:n,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),t!==void 0&&(r.parent=t),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=T(e.pin_cwd??e.cwd??n)),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}a(pt,"buildRecipe");function mt(e,t,n){return!Mn()||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:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(mt,"warmRequestFor");import{resolveCreateKind as pr}from"../../../core/runtime/launch-target.js";function we(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Rn(e.model,t,e.modelExact===!0)}a(we,"requestFromLaunch");function ht(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!O(t,r));if(n.length===0)return e;throw new u(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(ht,"withinCeiling");async function ye(e,t,n){const r=(await vn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await x(we(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(ye,"assertNodeModelChangeRegistered");function _e(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=nt({app:n.app,resolved:Hn(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new u(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(_e,"assertCallerReaches");const H=new Map;async function wt(e,t={},n={}){const r=ht(lt(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=w(r.parent);if(i.grantee!==c.app)throw new u(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw P(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new u(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=De(Ee(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new u(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new u(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=Ze({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new u(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(i.effectiveScopes,p)||!O(c.scopes,p));if(l!==void 0)throw new u(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ee(),c.isolated&&(r.isolated=!0,r.cwd=W(r.node_id,c.app))}r.creator!==void 0&&Vn(w(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&Xe(r.node_id)&&R(r.node_id)!==null&&Le(o)?.nodeId!==r.node_id)return D(e,r,t,n);const s=H.get(o);if(s!==void 0)return s;const d=yt(e,r,o,t,n);H.set(o,d);try{return await d}finally{H.delete(o)}}a(wt,"handleCreate");async function yt(e,t,n,r,o){const s=oe(n);if(s.nodeId!==null&&R(s.nodeId)!==null){if(s.state!=="warm_claimed"){const d=R(s.nodeId);if(e.principal.class!=="person"&&!me(e.principal,d.grantee??"app:terminal",s.nodeId))throw new u(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(s.nodeId)}}return D(e,t,r,o,s)}try{return await D(e,t,r,o,s)}catch(d){const c=oe(n);throw(c.nodeId===null||R(c.nodeId)===null)&&ne(n,c.nodeId),d}}a(yt,"handleKeyedCreateRequest");async function D(e,t,n,r,o=void 0){const s=r.deadlineAt??ct(t.deadline),d=ft(t.outcome_delivery),c=e.principal.class==="cron"?qe({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:ue(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.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 Cn(l)}const{profileId:p,kind:m,cwd:f,launch:b}=await jn(t,{validateKind:Se});_e(e,f),t.worktree!==void 0&&_e(e,T(t.pin_cwd??t.cwd??f));const v={...t,kind:m},_=d===void 0?void 0:ut(d,f);if(await x(we(b),{cwd:f,profileId:p},n.modelRegistry),!await st(p))throw new u(412,"no_provider_credential",he,{error:"no_provider_credential",message:he,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let L=null;{const A=o===void 0||o.nodeId===null||o.state==="warm_claimed"?mt(v,f,p):null,j=l===null&&r.beforeBrokerLaunch===void 0?void 0:S=>{l!==null&&$n(S,"terminal",l),r.beforeBrokerLaunch?.(S)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const S=A===null?null:await Dn(A,o.nodeId,j);if(S===null)throw ne(o.requestKey,o.nodeId),new u(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return te(o.requestKey,S),{status:201,body:g(S)}}if(A!==null){const S=await Pn(A,{...s===void 0?{}:{deadlineAt:s},..._===void 0?{}:{outcomeDelivery:_},...o===void 0?{}:{requestKey:o.requestKey}},j);if(S!==null)return o!==void 0&&te(o.requestKey,S),ce(A),{status:201,body:g(S)};L=A}const F=o?.nodeId??t.node_id??(o===void 0?void 0:ee());o!==void 0&&o.nodeId===null&&Fe(o.requestKey,F);const I=pt(F===void 0?v:{...v,node_id:F},i,f);c!==null&&(c.rootLifecycle!==void 0&&(I.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&v.scopes===void 0&&(I.scopes=c.scopes),c.run!==void 0&&(I.run=c.run),c.withinCreate!==void 0&&(I.withinCreate=c.withinCreate)),s!==void 0&&(I.deadlineAt=s),_!==void 0&&(I.outcomeDelivery=_),I.readiness=t.root===!0?"await":"launch";const Q=await Pe(I,j,()=>{L!==null&&ce(L)});return o!==void 0&&je(o.requestKey,Q.node.node_id),{status:201,body:g(Q.node.node_id)}}}a(D,"handleCreateRequest");function k(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(k,"singleQueryValue");function ge(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(ge,"optionalBoolean");function M(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(M,"oneOf");function _t(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[b]of e.query)if(!t.has(b))throw h(`unknown nodes query parameter: ${b}`);const n=M(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=M(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=k(e,"kind"),s=M(k(e,"mode"),"mode",["base","orchestrator"]),d=k(e,"profile_id"),c=k(e,"profile_prefix"),i=k(e,"parent"),l=ge(k(e,"top_level"),"top_level"),p=k(e,"under"),m=ge(k(e,"hanging"),"hanging"),f=M(k(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...s!==void 0?{mode:s}:{},...d!==void 0?{profile_id:d}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{hanging:m}:{},...f!==void 0?{include:f}:{}}}a(_t,"parseListQuery");function gt(e){const t=_t(e);let n=t.status!==void 0?re({status:t.status}):re();if(e.principal.class!=="person"&&(n=n.filter(d=>me(e.principal,d.grantee??"app:terminal",d.node_id))),t.lifecycle!==void 0&&(n=n.filter(d=>d.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(d=>d.kind===t.kind)),t.mode!==void 0&&(n=n.filter(d=>d.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(d=>d.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(d=>d.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(d=>d.parent===t.parent)),t.top_level===!0&&(n=n.filter(d=>d.parent===null)),t.under!==void 0){const d=new Set(Ke(t.under));n=n.filter(c=>d.has(c.node_id))}t.hanging===!0&&(n=n.filter(d=>d.parent!==null&&R(d.parent)===null));const r=t.include==="activity"?Qe(n.map(d=>d.node_id)):null,o=n.length>0?Oe():new Set;return{status:200,body:n.map(d=>{const c=Jn(d,d.profile_id!==null&&o.has(d.profile_id));if(r!==null){const i=fe(d.node_id);c.activity={latest_report:i[0]??null,final_report:d.final_report===null?null:i.find(l=>l.name===d.final_report)??null,pending_human_count:r[d.node_id]??0}}return c})}}a(gt,"handleList");async function bt(e){const t=e.params.id,n=await Qn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:Xn(e)});if(n.kind==="unknown")throw qn(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw Zn(n.status,n.body);return{status:n.status,body:et(n.body,n.machine)}}return w(t),{status:200,body:g(t)}}a(bt,"handleDetail");async function vt(e){const t=e.params.id;w(t);const n=await sn(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:B()}}}a(vt,"handleSnapshot");async function kt(e){const t=e.params.id,n=ln(t);if(n===null)throw P(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(kt,"handleSubject");function St(e){for(const[s]of e.query)if(s!=="cursor"&&s!=="limit")throw h(`unknown messages query parameter: ${s}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(St,"parseMessagesQuery");async function Rt(e){const t=e.params.id,n=await rn(t,St(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:B()}}}a(Rt,"handleMessages");function It(e){const t=e.params.id;w(t);const n=dn(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}a(It,"handleSession");async function Ot(e){const t=e.params.id;return w(t),{status:200,body:{node_id:t,markdown:await an(t)}}}a(Ot,"handleTranscript");function At(e){const t=e.params.id;w(t);const n=a((o,s)=>({node_id:o,label:R(o)?.name??o,dir:de(o),self:s,files:at(o)}),"root"),r=[n(t,!0),...ie(t).map(o=>n(o.node_id,!1))].filter(o=>$t(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(At,"handleContext");function $t(e,t){try{return en(W(e),t)}catch(n){if(tn(n))return!1;throw n}}a($t,"hasDir");async function Ct(e){const t=w(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(s=>O(n,s)),...n.filter(s=>O(t.scopes,s))])],o=await Te(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Ct,"handleFork");const Nt=1e4;async function Tt(e){const t=e.params.id;w(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;hn(t,o);const s=!r&&n?.cron_id!==void 0?ue(n.cron_id):null,d=await Ne(t,{resume:r,capacity:"refuse",...s!==null?{wakeReason:Kn(s,"schedule_revive")}:{}});d.outcome!=="already-live"&&Ge(t,{failures:0,notBefore:null});const c=R(t)?.status??"active",i=(d.launch??E().get(t)?.handle)?.exited,l=d.outcome!=="frozen"&&await ae(t,i,Nt);return{status:200,body:Un(t,d,c,l)}}a(Tt,"handleRevive");async function Et(e){const t=e.params.id;return{status:200,body:{newNodeId:(await mn(t))?.newNodeId??null}}}a(Et,"handleRelaunchRoot");function Pt(e){const t=e.params.id;w(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Wn(),o=Ce(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:zn(o)}}a(Pt,"handleClose");function Dt(e){if(!Yn(e.principal))throw new u(403,"permission_error","only the person marks a conversation read");const t=e.params.id;return w(t),We(t),{status:204}}a(Dt,"handleMarkRead");async function Mt(e){const t=e.params.id;w(t);const n=await pn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(Mt,"handleRecycle");async function Lt(e){const t=e.params.id;return w(t),await V(t,{lifecycle:"terminal"}),$(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Lt,"handleDemote");async function jt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await ye(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const s=await fn(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});$(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const d=J(s.meta,Y(n));return d.roadmap_written=s.roadmapWritten,d.roadmap_ref=s.roadmapRef,d.goal_path=s.goalPath,{status:200,body:d}}a(jt,"handlePromote");async function Ft(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await ye(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const s=o.note??"Refresh: continue against your roadmap or goal.";wn(n,s);const d=await un(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:J(d.meta,Y(n))}}a(Ft,"handleYield");function Gt(e){const t=e.params.id;w(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=R(n.controller);if(r===null)throw P(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new u(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return xe(t,n.controller),{status:200,body:g(t)}}a(Gt,"handleWait");async function Bt(e){const t=e.principal,n=await cn(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(Bt,"handleReviveAll");const xt=new Set(["interrupt","steer","after-turn","next-turn"]);function Kt(e){if(e===null)return null;const t=a(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 t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!xt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(Kt,"listenJson");function $(e,t,n,r){n.length===0&&r===void 0||K(o=>{if(r?.(o),n.length===0)return;const s=Ve(o,t),d=Ue(o,e),c=d.class==="person"?d.person:d.class==="app"?d.app:d.node;ze(o,c,s),Je(o,{event:"configured",object:s,actor:c,attrs:{changed:n.join(",")}})})}a($,"recordConfigured");function be(e){const t=E().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(be,"restartLiveBroker");function ve(e,t){try{return Z(e)===Z(t)}catch{return!1}}a(ve,"sameDirectory");async function Wt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=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(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(m=>m!=="profile"&&m!=="restart"&&o[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 i=w(n),l=Gn(e,o.profile);Bn(l.profileId);const p=xn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(Ln(i.kind)?(await z(i.kind,i.cwd,l.profileId),await V(n,{profileId:l.profileId})):C(n,{profile_id:l.profileId}),$(e,n,["profile"])),o.restart===!0&&be(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=w(n),p=N(l.cwd);if(o.keep_session===!0||p&&G(i)&&N(i)&&ve(l.cwd,i)){if(!G(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let b=!1;try{b=q(f).isDirectory()}catch{}if(!b)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ve(l.cwd,f))throw new y({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,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:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const v=l.cwd;return v!==f&&(K(_=>{C(n,{cwd:f}),X(_,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,v),Ye(n,v,f)}),$(e,n,["cwd"])),o.restart===!0&&be(n),{status:200,body:g(n)}}if(E().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new u(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,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:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,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:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,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:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!G(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const m=T(i);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!q(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof y?f:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return K(()=>{C(n,{cwd:m}),He(n)}),$(e,n,["cwd"]),{status:200,body:g(n)}}let s=w(n);const d=o.listen===void 0?void 0:Kt(o.listen);if(o.scopes!==void 0){const i=pe(o.scopes),l=s.grantee==="app:terminal"?ot():s.grant_id?tt(s.grant_id):null,p=s.grantee==="app:terminal"&&!dt("user").runtime?.issuer;if(!i.every(m=>O(s.scopes,m)&&(l?O(l.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!O(i,"crtr:llm"))throw new u(400,"invalid_scope","crtr:act requires crtr:llm");s=C(n,{scopes:i})}if(o.situational_context!==void 0&&Ae(n,$e(o.situational_context)),o.model!==void 0){const i=(await se(s.cwd,s.profile_id??null)).modelLadders,l=kn(o.model,i),p=rt(s.grant_id,o.model,l===void 0),m=p?{family:it,strength:p.strength}:l,f=p?p.model:Sn(o.model,i);await x({kind:"concrete",spec:f},{cwd:s.cwd,profileId:s.profile_id??null},t.modelRegistry);const b=E();let v=!1;if(b.isClaimed(n)&&await ae(n,b.get(n)?.handle.exited)&&(v=await On(n,f,m).then(()=>!0,_=>{if(_ instanceof An)return!1;throw _})),!v){if(b.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new u(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!f.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);In(n,f,m)}s=w(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await Se(o.kind);const i=o.kind??s.kind,l=o.mode??s.mode,p=o.lifecycle??s.lifecycle;let m;l==="orchestrator"&&!gn(n)&&(m=a(()=>{const f=yn(n);_n(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),s=await V(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},m)}o.name!==void 0&&(s=C(n,{name:o.name}),s.window&&bn(s.window,Fn(s)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return $(e,n,c,d===void 0?void 0:i=>{X(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(d,n)}),{status:200,body:g(n)}}a(Wt,"handleConfig");async function ke(){return(await se(process.cwd(),Ie()||null)).kinds}a(ke,"daemonKinds");async function Se(e){const t=Object.keys(await ke());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(Se,"assertKindServer");async function Vt(){const e=await ke();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Vt,"handleListKinds");const cr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:wt},{method:"GET",pattern:"/v1/nodes",handler:gt},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Vt(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Bt},{method:"GET",pattern:"/v1/nodes/:id",handler:bt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:vt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:kt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:It},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ot},{method:"GET",pattern:"/v1/nodes/:id/context",handler:At},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Ct},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Pt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Dt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Gt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Wt}];export{Wt as handleConfig,wt as handleCreate,Ct as handleFork,gt as handleList,jt as handlePromote,Ft as handleYield,cr as nodeRoutes,pr as resolveCreateKind};
1
+ var Oe=Object.defineProperty;var a=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{prepared as Z}from"../../../core/sqlite-statements.js";import{envProfileId as Ie}from"../../../shared/env.js";import{pausedCanvasProfiles as Ae}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as q,statSync as ee}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as $e,formatSituationalProse as Ce}from"../../../core/runtime/situational-context.js";import{closeNode as Ne}from"../../../core/runtime/close.js";import{reviveNode as Te}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{appPaidLaunch as Ee,assertLaunchModelRegistered as K,forkNode as Pe,resolveForkSource as De,spawnChildPrepared as Le}from"../../../core/runtime/spawn.js";import{forkSourceNode as Me,newNodeId as ne}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as te,childrenOf as je,completeCreateRequest as oe,findCreateRequest as Ge,getNode as R,recordCreateRequestNode as Fe,reserveCreateRequest as re,reserveCreateRequestNode as Be,listNodes as ie,recordRespawnAttempt as Ke,subscribersOf as We,subscriptionsOf as de,setMessageWait as xe,updateNode as C}from"../../../core/canvas/canvas.js";import{subtreeIds as Ve}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as W}from"../../../core/canvas/db.js";import{markNodeRead as ze}from"../../../core/canvas/recovery.js";import{nodeObject as Je}from"../../../core/graph/objects.js";import{recordActedOn as Ue}from"../../../core/graph/edges.js";import{publish as Ye}from"../../../core/graph/events.js";import{readerFor as He}from"../reader.js";import{relocateSessionCwd as Qe,unbindSession as Xe}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as Ze}from"../../../core/canvas/attention.js";import{isSafeNodeId as qe}from"../../../core/canvas/paths.js";import{contextDir as se,nodeAgentDir as x}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as en}from"../../cron/authority.js";import{cronBirthPlacement as nn}from"../../cron/armed-context.js";import{existsBeneath as tn,isAbsentOrRefused as on,isBeneathRefusal as rn,readdirBeneath as dn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as sn,readNodeSession as an,readNodeSnapshot as ln,transcriptMarkdown as cn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as fn}from"../../../core/substrate/subject.js";import{reviveAll as un}from"../../../core/runtime/revive-all.js";import{promoteAsync as pn,requestYieldAsync as mn,reshapeNodeAsync as V}from"../../../core/runtime/promote.js";import{recycleNode as hn}from"../../../core/runtime/recycle.js";import{relaunchRoot as wn}from"../../../core/runtime/reset.js";import{assertReopenGate as yn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as _n,readGoal as gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as bn,hasRoadmap as vn}from"../../../core/runtime/roadmap.js";import{renameWindow as kn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Sn,explicitModelIntent as Rn,normalizeModel as On,readMergedLaunchConfigAsync as ae}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as In}from"../../../core/model-routes.js";import{persistDormantModel as An,setModelLive as $n}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as le}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Cn}from"../../../core/runtime/broker-request.js";import{boundFleet as E}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Nn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Tn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ce}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as En}from"../../../core/human/action-binding.js";import{resolveHumanAction as Pn}from"../../../core/human-actions.js";import{parseDurationMs as Dn}from"../../../core/wake.js";import{claimWarmNode as Ln,refillWarmPool as fe,resumeWarmClaim as Mn,warmPoolEnabled as jn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Gn,resolveLaunchTarget as Fn}from"../../../core/runtime/launch-target.js";import{fullName as Bn}from"../../../core/canvas/labels.js";import{reportsForNode as ue}from"./reports.js";import{requireUsableProfile as Kn}from"./profiles.js";import{assertProfileActive as Wn,loadExactProfileManifest as xn}from"../../../core/profiles/manifest.js";import{getCron as pe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Vn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as zn}from"../../control.js";import{notFound as P,usage as h}from"../../../core/errors.js";import{assertScope as Jn,validateScopes as me}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Un,toNodeDetailDTO as J,toNodeSummaryDTO as Yn,toReviveResultDTO as Hn}from"../map.js";import{ApiError as u}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Qn,brokerMayReach as U,canReadNode as he,resolvedScopes as Xn}from"../router.js";import{forwardVerb as Zn,queryWithoutMachine as qn,relayError as et,unknownError as nt,withMachine as tt}from"../../peer/forward.js";import{fileRoot as ot}from"../../../core/spaces/file-root.js";import{activeGrant as rt,payerOfGrant as it,terminalGrant as dt}from"../../../core/grants/mirror.js";import{appRungForGrant as st}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as at}from"../../../core/model-routes.js";import{readConfig as lt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ct,NO_PROVIDER_CREDENTIAL_MESSAGE as we}from"../../../core/runtime/provider-credential-gate.js";function w(e){const t=R(e);if(t===null)throw P(`unknown node: ${e}`,{received:e});return t}a(w,"requireMeta");function Y(e){return{subscribesTo:de(e),subscribers:We(e),children:je(e)}}a(Y,"edgesFor");function g(e){const t=w(e);return J(t,Y(e))}a(g,"detailOf");function ft(e){let t=ue(e).length;try{t+=dn(x(e),se(e)).length}catch(n){if(!on(n))throw n}return t}a(ft,"countFiles");function ut(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&me(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new u(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(ut,"parseCreateBody");function pt(e){if(e===void 0)return;const t=Dn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new u(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(pt,"parseDeadline");function mt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new u(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!En.test(e.action))throw new u(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ce)throw new u(413,"payload_too_large",`serialized payload exceeds ${ce} bytes`)}return e}}a(mt,"parseOutcomeDelivery");function ht(e,t){const n=Pn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new u(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new u(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(ht,"resolveOutcomeDelivery");function wt(e,t,n){const r={kind:e.kind,cwd:n,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),t!==void 0&&(r.parent=t),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=T(e.pin_cwd??e.cwd??n)),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}a(wt,"buildRecipe");function yt(e,t,n){return!jn()||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:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(yt,"warmRequestFor");import{resolveCreateKind as wr}from"../../../core/runtime/launch-target.js";function ye(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return In(e.model,t,e.modelExact===!0)}a(ye,"requestFromLaunch");function _t(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!I(t,r));if(n.length===0)return e;throw new u(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(_t,"withinCeiling");async function _e(e,t,n){const r=(await Sn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await K(ye(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(_e,"assertNodeModelChangeRegistered");function ge(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=ot({app:n.app,resolved:Xn(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new u(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(ge,"assertCallerReaches");const H=new Map;async function gt(e,t={},n={}){const r=_t(ut(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=w(r.parent);if(i.grantee!==c.app)throw new u(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw P(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new u(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=Me(De(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new u(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new u(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=en({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new u(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!I(i.effectiveScopes,p)||!I(c.scopes,p));if(l!==void 0)throw new u(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ne(),c.isolated&&(r.isolated=!0,r.cwd=x(r.node_id,c.app))}r.creator!==void 0&&Jn(w(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&qe(r.node_id)&&R(r.node_id)!==null&&Ge(o)?.nodeId!==r.node_id)return D(e,r,t,n);const s=H.get(o);if(s!==void 0)return s;const d=bt(e,r,o,t,n);H.set(o,d);try{return await d}finally{H.delete(o)}}a(gt,"handleCreate");async function bt(e,t,n,r,o){const s=re(n);if(s.nodeId!==null&&R(s.nodeId)!==null){if(s.state!=="warm_claimed"){const d=R(s.nodeId);if(e.principal.class!=="person"&&!he(e.principal,d.grantee??"app:terminal",s.nodeId))throw new u(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(s.nodeId)}}return D(e,t,r,o,s)}try{return await D(e,t,r,o,s)}catch(d){const c=re(n);throw(c.nodeId===null||R(c.nodeId)===null)&&te(n,c.nodeId),d}}a(bt,"handleKeyedCreateRequest");async function D(e,t,n,r,o=void 0){const s=r.deadlineAt??pt(t.deadline),d=mt(t.outcome_delivery),c=e.principal.class==="cron"?nn({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:pe(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.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 Tn(l)}const{profileId:p,kind:m,cwd:f,launch:b}=await Fn(t,{validateKind:Re});ge(e,f),t.worktree!==void 0&&ge(e,T(t.pin_cwd??t.cwd??f));const v={...t,kind:m},_=d===void 0?void 0:ht(d,f),Q=("grant"in e.principal?e.principal.grant:null)??(i==null?null:R(i)?.grant_id??null);if(await K(ye(Ee(b,Q,t.model)),{cwd:f,profileId:p},n.modelRegistry),it(Q)!=="app"&&!await ct(p))throw new u(412,"no_provider_credential",we,{error:"no_provider_credential",message:we,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let M=null;{const A=o===void 0||o.nodeId===null||o.state==="warm_claimed"?yt(v,f,p):null,j=l===null&&r.beforeBrokerLaunch===void 0?void 0:S=>{l!==null&&Nn(S,"terminal",l),r.beforeBrokerLaunch?.(S)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const S=A===null?null:await Mn(A,o.nodeId,j);if(S===null)throw te(o.requestKey,o.nodeId),new u(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return oe(o.requestKey,S),{status:201,body:g(S)}}if(A!==null){const S=await Ln(A,{...s===void 0?{}:{deadlineAt:s},..._===void 0?{}:{outcomeDelivery:_},...o===void 0?{}:{requestKey:o.requestKey}},j);if(S!==null)return o!==void 0&&oe(o.requestKey,S),fe(A),{status:201,body:g(S)};M=A}const G=o?.nodeId??t.node_id??(o===void 0?void 0:ne());o!==void 0&&o.nodeId===null&&Be(o.requestKey,G);const O=wt(G===void 0?v:{...v,node_id:G},i,f);c!==null&&(c.rootLifecycle!==void 0&&(O.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&v.scopes===void 0&&(O.scopes=c.scopes),c.run!==void 0&&(O.run=c.run),c.withinCreate!==void 0&&(O.withinCreate=c.withinCreate)),s!==void 0&&(O.deadlineAt=s),_!==void 0&&(O.outcomeDelivery=_),O.readiness=t.root===!0?"await":"launch";const X=await Le(O,j,()=>{M!==null&&fe(M)});return o!==void 0&&Fe(o.requestKey,X.node.node_id),{status:201,body:g(X.node.node_id)}}}a(D,"handleCreateRequest");function k(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(k,"singleQueryValue");function be(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(be,"optionalBoolean");function L(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(L,"oneOf");function vt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[b]of e.query)if(!t.has(b))throw h(`unknown nodes query parameter: ${b}`);const n=L(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=L(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=k(e,"kind"),s=L(k(e,"mode"),"mode",["base","orchestrator"]),d=k(e,"profile_id"),c=k(e,"profile_prefix"),i=k(e,"parent"),l=be(k(e,"top_level"),"top_level"),p=k(e,"under"),m=be(k(e,"hanging"),"hanging"),f=L(k(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...s!==void 0?{mode:s}:{},...d!==void 0?{profile_id:d}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{hanging:m}:{},...f!==void 0?{include:f}:{}}}a(vt,"parseListQuery");function kt(e){const t=vt(e);let n=t.status!==void 0?ie({status:t.status}):ie();if(e.principal.class!=="person"&&(n=n.filter(d=>he(e.principal,d.grantee??"app:terminal",d.node_id))),t.lifecycle!==void 0&&(n=n.filter(d=>d.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(d=>d.kind===t.kind)),t.mode!==void 0&&(n=n.filter(d=>d.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(d=>d.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(d=>d.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(d=>d.parent===t.parent)),t.top_level===!0&&(n=n.filter(d=>d.parent===null)),t.under!==void 0){const d=new Set(Ve(t.under));n=n.filter(c=>d.has(c.node_id))}t.hanging===!0&&(n=n.filter(d=>d.parent!==null&&R(d.parent)===null));const r=t.include==="activity"?Ze(n.map(d=>d.node_id)):null,o=n.length>0?Ae():new Set;return{status:200,body:n.map(d=>{const c=Yn(d,d.profile_id!==null&&o.has(d.profile_id));if(r!==null){const i=ue(d.node_id);c.activity={latest_report:i[0]??null,final_report:d.final_report===null?null:i.find(l=>l.name===d.final_report)??null,pending_human_count:r[d.node_id]??0}}return c})}}a(kt,"handleList");async function St(e){const t=e.params.id,n=await Zn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:qn(e)});if(n.kind==="unknown")throw nt(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw et(n.status,n.body);return{status:n.status,body:tt(n.body,n.machine)}}return w(t),{status:200,body:g(t)}}a(St,"handleDetail");async function Rt(e){const t=e.params.id;w(t);const n=await ln(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:B()}}}a(Rt,"handleSnapshot");async function Ot(e){const t=e.params.id,n=fn(t);if(n===null)throw P(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(Ot,"handleSubject");function It(e){for(const[s]of e.query)if(s!=="cursor"&&s!=="limit")throw h(`unknown messages query parameter: ${s}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(It,"parseMessagesQuery");async function At(e){const t=e.params.id,n=await sn(t,It(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:B()}}}a(At,"handleMessages");function $t(e){const t=e.params.id;w(t);const n=an(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}a($t,"handleSession");async function Ct(e){const t=e.params.id;return w(t),{status:200,body:{node_id:t,markdown:await cn(t)}}}a(Ct,"handleTranscript");function Nt(e){const t=e.params.id;w(t);const n=a((o,s)=>({node_id:o,label:R(o)?.name??o,dir:se(o),self:s,files:ft(o)}),"root"),r=[n(t,!0),...de(t).map(o=>n(o.node_id,!1))].filter(o=>Tt(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(Nt,"handleContext");function Tt(e,t){try{return tn(x(e),t)}catch(n){if(rn(n))return!1;throw n}}a(Tt,"hasDir");async function Et(e){const t=w(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(s=>I(n,s)),...n.filter(s=>I(t.scopes,s))])],o=await Pe(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Et,"handleFork");const Pt=1e4;async function Dt(e){const t=e.params.id;w(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;yn(t,o);const s=!r&&n?.cron_id!==void 0?pe(n.cron_id):null,d=await Te(t,{resume:r,capacity:"refuse",...s!==null?{wakeReason:Vn(s,"schedule_revive")}:{}});d.outcome!=="already-live"&&Ke(t,{failures:0,notBefore:null});const c=R(t)?.status??"active",i=(d.launch??E().get(t)?.handle)?.exited,l=d.outcome!=="frozen"&&await le(t,i,Pt);return{status:200,body:Hn(t,d,c,l)}}a(Dt,"handleRevive");async function Lt(e){const t=e.params.id;return{status:200,body:{newNodeId:(await wn(t))?.newNodeId??null}}}a(Lt,"handleRelaunchRoot");function Mt(e){const t=e.params.id;w(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=zn(),o=Ne(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Un(o)}}a(Mt,"handleClose");function jt(e){if(!Qn(e.principal))throw new u(403,"permission_error","only the person marks a conversation read");const t=e.params.id;return w(t),ze(t),{status:204}}a(jt,"handleMarkRead");async function Gt(e){const t=e.params.id;w(t);const n=await hn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(Gt,"handleRecycle");async function Ft(e){const t=e.params.id;return w(t),await V(t,{lifecycle:"terminal"}),$(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Ft,"handleDemote");async function Bt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await _e(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const s=await pn(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});$(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const d=J(s.meta,Y(n));return d.roadmap_written=s.roadmapWritten,d.roadmap_ref=s.roadmapRef,d.goal_path=s.goalPath,{status:200,body:d}}a(Bt,"handlePromote");async function Kt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await _e(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const s=o.note??"Refresh: continue against your roadmap or goal.";_n(n,s);const d=await mn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:J(d.meta,Y(n))}}a(Kt,"handleYield");function Wt(e){const t=e.params.id;w(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=R(n.controller);if(r===null)throw P(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new u(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return xe(t,n.controller),{status:200,body:g(t)}}a(Wt,"handleWait");async function xt(e){const t=e.principal,n=await un(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(xt,"handleReviveAll");const Vt=new Set(["interrupt","steer","after-turn","next-turn"]);function zt(e){if(e===null)return null;const t=a(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 t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!Vt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(zt,"listenJson");function $(e,t,n,r){n.length===0&&r===void 0||W(o=>{if(r?.(o),n.length===0)return;const s=Je(o,t),d=He(o,e),c=d.class==="person"?d.person:d.class==="app"?d.app:d.node;Ue(o,c,s),Ye(o,{event:"configured",object:s,actor:c,attrs:{changed:n.join(",")}})})}a($,"recordConfigured");function ve(e){const t=E().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(ve,"restartLiveBroker");function ke(e,t){try{return q(e)===q(t)}catch{return!1}}a(ke,"sameDirectory");async function Jt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=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(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(m=>m!=="profile"&&m!=="restart"&&o[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 i=w(n),l=Kn(e,o.profile);Wn(l.profileId);const p=xn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(Gn(i.kind)?(await z(i.kind,i.cwd,l.profileId),await V(n,{profileId:l.profileId})):C(n,{profile_id:l.profileId}),$(e,n,["profile"])),o.restart===!0&&ve(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=w(n),p=N(l.cwd);if(o.keep_session===!0||p&&F(i)&&N(i)&&ke(l.cwd,i)){if(!F(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let b=!1;try{b=ee(f).isDirectory()}catch{}if(!b)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ke(l.cwd,f))throw new y({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,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:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const v=l.cwd;return v!==f&&(W(_=>{C(n,{cwd:f}),Z(_,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,v),Qe(n,v,f)}),$(e,n,["cwd"])),o.restart===!0&&ve(n),{status:200,body:g(n)}}if(E().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new u(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,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:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,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:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,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:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const m=T(i);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ee(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof y?f:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return W(()=>{C(n,{cwd:m}),Xe(n)}),$(e,n,["cwd"]),{status:200,body:g(n)}}let s=w(n);const d=o.listen===void 0?void 0:zt(o.listen);if(o.scopes!==void 0){const i=me(o.scopes),l=s.grantee==="app:terminal"?dt():s.grant_id?rt(s.grant_id):null,p=s.grantee==="app:terminal"&&!lt("user").runtime?.issuer;if(!i.every(m=>I(s.scopes,m)&&(l?I(l.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!I(i,"crtr:llm"))throw new u(400,"invalid_scope","crtr:act requires crtr:llm");s=C(n,{scopes:i})}if(o.situational_context!==void 0&&$e(n,Ce(o.situational_context)),o.model!==void 0){const i=(await ae(s.cwd,s.profile_id??null)).modelLadders,l=Rn(o.model,i),p=st(s.grant_id,o.model,l===void 0),m=p?{family:at,strength:p.strength}:l,f=p?p.model:On(o.model,i);await K({kind:"concrete",spec:f},{cwd:s.cwd,profileId:s.profile_id??null},t.modelRegistry);const b=E();let v=!1;if(b.isClaimed(n)&&await le(n,b.get(n)?.handle.exited)&&(v=await $n(n,f,m).then(()=>!0,_=>{if(_ instanceof Cn)return!1;throw _})),!v){if(b.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new u(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!f.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);An(n,f,m)}s=w(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await Re(o.kind);const i=o.kind??s.kind,l=o.mode??s.mode,p=o.lifecycle??s.lifecycle;let m;l==="orchestrator"&&!vn(n)&&(m=a(()=>{const f=gn(n);bn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),s=await V(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},m)}o.name!==void 0&&(s=C(n,{name:o.name}),s.window&&kn(s.window,Bn(s)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return $(e,n,c,d===void 0?void 0:i=>{Z(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(d,n)}),{status:200,body:g(n)}}a(Jt,"handleConfig");async function Se(){return(await ae(process.cwd(),Ie()||null)).kinds}a(Se,"daemonKinds");async function Re(e){const t=Object.keys(await Se());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(Re,"assertKindServer");async function Ut(){const e=await Se();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Ut,"handleListKinds");const pr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:gt},{method:"GET",pattern:"/v1/nodes",handler:kt},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Ut(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:xt},{method:"GET",pattern:"/v1/nodes/:id",handler:St},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Ot},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:At},{method:"GET",pattern:"/v1/nodes/:id/session",handler:$t},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ct},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Dt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Kt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Wt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Jt}];export{Jt as handleConfig,gt as handleCreate,Et as handleFork,kt as handleList,Bt as handlePromote,Kt as handleYield,pr as nodeRoutes,wr as resolveCreateKind};
@@ -1,3 +1,3 @@
1
- var Re=Object.defineProperty;var l=(e,t)=>Re(e,"name",{value:t,configurable:!0});import{prepared as $e}from"../../../core/sqlite-statements.js";import{ApiError as y}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as Ie}from"../../../api/dto/objects.js";import{openDb as T,withCanvasWrite as _}from"../../../core/canvas/db.js";import{actorOf as ee}from"../../../core/graph/documents.js";import{readerForObject as D,readerFor as Se}from"../../../core/graph/reader.js";import{resolveName as Ae}from"../../../core/graph/names.js";import{canRead as te,customReachable as Ne,holdsObjectsScope as Fe,mayActAs as ne}from"../../../core/graph/access.js";import{customObjectRef as re,authorizeCustom as oe,fenceArgv as M}from"./custom-objects.js";import{edgesOf as Le}from"../../../core/graph/edges.js";import{publish as G}from"../../../core/graph/events.js";import{objectDTO as g}from"../../../core/graph/kinds/dto.js";import{isKind as We,kindNames as Pe,kindOf as z}from"../../../core/graph/kinds/registry.js";import{listObjects as Ce,searchObjects as ie}from"../../../core/graph/objects.js";import{checkoutsForCwd as De}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as W,unwatch as Me,watchersOf as Ge,watchesOf as ze}from"../../../core/graph/watches.js";import{readerFor as v,resolveRef as H}from"../reader.js";import{readDelegationFor as se,runReadLeaf as He}from"../../plugin-objects/read-leaf.js";import{invalidRequest as P,isRecord as R}from"./validate.js";import{callerNode as ue,callerStub as U,forwardVerb as ae,originates as ce,queryWithoutMachine as V,relayError as C,remoteStub as Ue,unknownError as le,forwarding as F,withMachine as B}from"../../peer/forward.js";import{getById as L,getByRowid as fe}from"../../../core/graph/objects.js";import{ensureNodeStub as Ve,isStub as K,stubOf as Be,withKindDecl as $}from"../../../core/peer/stubs.js";import{isUnreachable as Ke}from"../../../core/peer/client.js";import{normalizeMachineId as I}from"../../../core/peer/directory.js";const S=l(e=>t=>De(e,t),"reposFnFor");function de(e,t){return{...g(e,t),...z(e,t.type).listItem?.(e,t)}}l(de,"listItem");function Ze(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}l(Ze,"remoteMessage");function me(e,t,r){try{return q(e,t,r)}catch(n){if(n instanceof y&&n.code==="not_found"&&!n.details?.deleted)return null;throw n}}l(me,"ownerFilter");function q(e,t,r){const n=H(e,t,r);if("remote"in n)throw new y(404,"not_found",Ze(n.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in n)throw new y(404,"not_found",`${n.deleted.name} is deleted`,{id:n.deleted.id,deleted:!0});return n}l(q,"liveRef");const k=l(e=>decodeURIComponent(e.params.ref),"refParam"),he=l(e=>{const t=e.trim().replace(/^\[\[(.*)\]\]$/,"$1").trim(),r=t.indexOf("/");return r>0?t.slice(0,r):t},"idOf");function pe(e){const t=L(T(),he(e));return t!==null&&K(T(),t)?t.id:null}l(pe,"stubIdOf");function Je(e,t){const r=pe(e);return r!==null?{stub:r,hit:!0}:_(n=>{try{const o=H(n,v(n,t),e);if("remote"in o)return{stub:null,hit:!1};const i="deleted"in o?o.deleted:o;return{stub:K(n,i)?i.id:null,hit:!0}}catch{return{stub:null,hit:!1}}})}l(Je,"resolvedLocally");async function Z(e,t,r){const n=Je(t,e);return n.stub!==null?ae(e,n.stub,r):n.hit||!ce(e.principal)?{kind:"local"}:ae(e,he(t),r)}l(Z,"forwardRef");const J=l(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");function we(e,t,r,n,o){const i=t?.object;!i?.id||!i.type||_(s=>{const u=ue(s,e);if(u===null)return;const c=Ue(s,i.id,i.type,r,{kind:i.kind??null,name:i.name??i.id,...i.preview===void 0?{}:{preview:i.preview},owner:i.owner??null,...i.kind_decl===void 0?{}:{kind_decl:i.kind_decl},...i.privacy===void 0?{}:{privacy:i.privacy}});W(s,u,c,n,o===void 0?{}:{patterns:o})})}l(we,"watchRemote");async function Qe(e){const t=k(e),r=["1","true"].includes(e.query.get("fields")??""),n=await Z(e,t,{method:"GET",path:J(t),query:V(e)});if(n.kind==="unknown")return{state:"unknown",ref:t,unreachable:n.unreachable};if(n.kind==="remote"){if(n.status>=400)throw C(n.status,n.body);return we(e,n.body,n.machine.id,"read"),B(n.body,n.machine)}const o=l(u=>{const c=U(u,e);return c===null?v(u,e):D(u,c,S(u))},"readerOf"),i=_(u=>{const c=o(u),a=H(u,c,t);if("remote"in a)return{state:"remote",remote:a.remote};if("deleted"in a)return{state:"deleted",deleted:g(u,a.deleted)};const f=se(u,a);if(f!==null)return{delegate:f,hitId:a.id};const{data:p,text:b}=z(u,a.type).read(u,c,a,{fields:r,reposFn:S(u)});return{state:"object",type:a.type,object:$(u,a,g(u,a)),text:b,data:p}});if(!("delegate"in i))return i;const s=await He(i.delegate,e.principal);return _(u=>{const c=o(u),a=L(u,i.hitId);if(a===null)throw new y(404,"not_found","object not found");if(a.deleted_at!==null)return{state:"deleted",deleted:g(u,a)};if(!te(u,c,a))throw new y(404,"not_found","object not found");const{data:f,text:p}=z(u,a.type).read(u,c,a,{fields:r,reposFn:S(u)});return se(u,a)===null?{state:"object",type:a.type,object:$(u,a,g(u,a)),text:p,data:f}:{state:"object",type:a.type,object:$(u,a,g(u,a)),text:"markdown"in s?s.markdown:`${p}
2
- content unavailable: ${s.unavailable}`,data:{...f,content:"markdown"in s?"live":"unavailable"}}})}l(Qe,"read");function Q(e,t,r,n){if(e!=null){if(!r.includes(e)){n.push({field:t,problem:`must be one of ${r.join(", ")}`,received:e});return}return e}}l(Q,"oneOf");function ye(e,t,r){if(t!=null){if(typeof t!="string"||!We(e,t)){r.push({field:"type",problem:`must be a kind: one of ${Pe(e).join(", ")}`,received:t});return}return t}}l(ye,"kindName");function ge(e,t,r,n){if(e==null)return n;const o=Number(e);return!Number.isInteger(o)||o<1||o>100?(r.push({field:t,problem:"must be an integer from 1 to 100",received:e}),n):o}l(ge,"limitOf");function be(e){const t=e.query,r=[],n=ye(T(),t.get("type"),r),o=Q(t.get("privacy"),"privacy",Ie,r),i=ge(t.get("limit"),"limit",r,50),s=t.get("cursor");s!==null&&!/^\d+$/.test(s)&&r.push({field:"cursor",problem:"is not a cursor from a previous page",received:s});const u=t.get("deleted");return u!==null&&!["0","1","true","false"].includes(u)&&r.push({field:"deleted",problem:"must be true or false",received:u}),r.length>0&&P("object list request",r),_(c=>{const a=v(c,e),f={...n?{type:n}:{},...o?{privacy:o}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...u==="1"||u==="true"?{deleted:!0}:{}},p=t.get("owner");if(p!==null){const m=me(c,a,p);if(m===null)return{items:[],next_cursor:null};f.owner=m}const b=t.get("name"),j=[];let h=s===null?0:Number(s),w=!0;for(;j.length<i&&w;){const m=Ce(c,a,f,{limit:100,after_rowid:h});w=m.length===100;for(const E of m)if(h=E.rowid,(b===null||E.name.startsWith(b))&&j.push(E),j.length===i)break}const d=j.at(-1);return{items:j.map(m=>de(c,m)),next_cursor:j.length===i&&d?String(d.rowid):null}})}l(be,"listLocal");const Ye={ms:3e4},Xe="self",Y=l((e,t)=>e.map(r=>({...r,machine:t})),"labelItems");async function je(e,t,r,n){const o=F.current;try{const i=await o.call(t.id,{method:"GET",path:"/v1/objects",query:r},o.envelope(e.principal),n);if(Ke(i))return{state:"unreachable",items:[],next:null};if(i.status===426)return{state:"too_old",items:[],next:null};const s=i.body;return i.status!==200||!Array.isArray(s?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:Y(s.items,t),next:s.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(je,"remotePage");async function xe(e){const t=new Promise(r=>e.addEventListener("abort",()=>r(null),{once:!0}));return Promise.race([F.current.machines().catch(()=>null),t])}l(xe,"machinesWithin");async function et(e){const t=e.query.get("machine");if(!ce(e.principal)||!F.current.joined()||t===Xe)return be(_e(e));const n=F.current.self(),o=t!==null&&I(t)!==n,i=o?null:be(_e(e)),s=new AbortController,u=setTimeout(()=>s.abort(),Ye.ms);u.unref?.();try{const c=await xe(s.signal);if(c===null){if(o)throw new y(503,"runtime_unreachable",`The directory did not answer, so ${I(t)} cannot be listed.`,{machine:I(t)});return i}const a=l(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),f=a(n),p=c.filter(d=>d.machine_id!==n&&d.kind!=="device"),b=V(e);if(t!==null){if(!o)return{items:Y(i.items,f),next_cursor:i.next_cursor,machines:[{machine_id:n,name:f.name,state:"ok",more:i.next_cursor!==null}]};const d=I(t);if(!p.some(E=>E.machine_id===d))throw new y(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await je(e,a(d),b,s.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:a(d).name,state:m.state,more:m.next!==null}]}}const{cursor:j,...h}=b,w=await Promise.all(p.map(d=>je(e,a(d.machine_id),h,s.signal)));return{items:[...Y(i.items,f),...w.flatMap(d=>d.items)],next_cursor:i.next_cursor,machines:[{machine_id:n,name:f.name,state:"ok",more:i.next_cursor!==null},...p.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:w[m].state,more:w[m].next!==null}))]}}finally{clearTimeout(u)}}l(et,"list");function _e(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(_e,"withoutMachine");function tt(e){const t=[],r=R(e.body)?e.body:{};R(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const n=r.text;(typeof n!="string"||n.trim()==="")&&t.push({field:"text",problem:"is required",received:n});const o=r.grep;if(o!==void 0)if(typeof o!="string")t.push({field:"grep",problem:"must be a regular expression string",received:o});else try{new RegExp(o)}catch(u){t.push({field:"grep",problem:`is not a valid regular expression: ${u.message}`,received:o})}r.body!==void 0&&typeof r.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:r.body});const i=ye(T(),r.type,t);r.kind!==void 0&&typeof r.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:r.kind}),r.owner!==void 0&&typeof r.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:r.owner});const s=ge(r.limit,"limit",t,50);return t.length>0&&P("object search request",t),_(u=>{const c=v(u,e),a=typeof r.owner=="string"?me(u,c,r.owner):null;if(typeof r.owner=="string"&&a===null)return{items:[]};const f=ie(u,c,{text:n,body:r.body===!0||typeof o=="string"}),p=new Set(f.map(h=>h.object.rowid));return{items:(typeof o=="string"?ie(u,c,{text:o,grep:!0}).filter(h=>p.has(h.object.rowid)):f).filter(h=>(!i||h.object.type===i)&&(r.kind===void 0||h.object.kind===r.kind)&&(!a||h.object.owner===a.rowid)).slice(0,s).map(h=>({object:de(u,h.object),...h.line!==void 0?{matches:[{line:h.line,text:h.text??""}]}:{}}))}})}l(tt,"search");const ke=["interrupt","steer","after-turn","next-turn"],nt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function rt(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||!nt.test(r)||r.includes(">")&&!r.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(rt,"patternsOf");function ot(e,t){if(e===void 0)return;if(!R(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const r=[];for(const[n,o]of Object.entries(e)){const i=Number(n);!Number.isInteger(i)||i<1||i>10?t.push({field:`config.${n}`,problem:"level must be an integer from 1 to 10"}):ke.includes(o)?r.push({threshold:i,delivery:o}):t.push({field:`config.${n}`,problem:`delivery must be one of ${ke.join(", ")}`,received:o})}return r.sort((n,o)=>o.threshold-n.threshold)}l(ot,"configOf");function ve(e){const t=pe(e);if(t!==null)throw new y(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(ve,"refuseStubWatch");function X(e,t){const r=L(e,t)??(()=>{const n=Ae(e,Se(e,{class:"person"},()=>[]),t);return"object"in n?n.object:null})();return r===null||r.deleted_at!==null||!(r.type.includes(".")||r.type==="node")?null:r}l(X,"findWatcher");const O=l(()=>{throw new y(404,"not_found","watcher not found")},"watcherNotFound");async function Oe(e,t,r){if(typeof t!="string"||r===void 0||r===null)return null;if(typeof r!="string")throw new y(400,"invalid_request","invalid watcher_machine");if(X(e,t)!==null)return null;const n=F.current;let o;try{o=await n.machines()}catch{throw new y(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const i=I(r);return(i===n.self()||!o.some(s=>I(s.machine_id)===i))&&O(),i}l(Oe,"remoteWatcherMachine");function Ee(e,t,r,n){if(t.publishToken||t.principal.class==="anonymous")return O();const o=v(e,t);if(o.class==="person")return O();let i;try{i=q(e,o,n)}catch{return O()}const s=i.owner===null?null:fe(e,i.owner);return s===null||!ne(e,o,s)||!Fe(e,o,"link",r)?O():(M(e,t,r),{actor:o.app,object:i})}l(Ee,"linkWatcher");function qe(e,t,r){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!r.type.includes("."))return!1;const n=v(e,t),o=r.owner===null?null:fe(e,r.owner);return o!==null&&ne(e,n,o)&&Ne(e,n,r)}l(qe,"ownsWatcher");async function it(e){const t=k(e),r=R(e.body)?e.body:{};if(typeof r.watcher=="string"&&ve(t),typeof r.watcher!="string"){const o=await Z(e,t,{method:"POST",path:`${J(t)}/watch`,body:e.body});if(o.kind==="unknown")throw le(t,o.unreachable);if(o.kind==="remote"){if(o.status>=400)throw C(o.status,o.body);const i=o.body.patterns;return we(e,o.body,o.machine.id,"ask",i),B(o.body,o.machine)}}const n=await Oe(T(),r.watcher,r.watcher_machine);return st(e,n)}l(it,"watch");function st(e,t=null){const r=[],n=e.body===void 0?{}:R(e.body)?e.body:(r.push({field:"body",problem:"must be an object"}),{}),o=rt(n.patterns,r),i=ot(n.config,r);return n.filter!==void 0&&!R(n.filter)&&r.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&r.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),n.watcher_machine!==void 0&&typeof n.watcher_machine!="string"&&r.push({field:"watcher_machine",problem:"must be a machine id",received:n.watcher_machine}),r.length>0&&P("watch request",r),_(s=>{const u=typeof n.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!u)throw new y(404,"not_found","watcher not found");const c=o??[">"],a={patterns:c,...i?{config:i}:{},...n.filter!==void 0?{filter:n.filter}:{}};if(u){const j=n.watcher,h=t===null?null:ut(s,e,j,t),w=h??(e.publishToken?re(s,j):X(s,j));if(w===null)return O();if(h===null&&qe(s,e,w)){const E=oe(s,e,w);M(s,e,w);const x=D(s,w),N=q(s,x,k(e));if(!te(s,x,N))throw new y(404,"not_found","object not found");return W(s,w,N,"act",a),G(s,{event:"watched",object:N,actor:E,attrs:{}},S(s)),{object:$(s,N,g(s,N)),patterns:c}}const{actor:d,object:m}=Ee(s,e,w,k(e));return W(s,w,m,"act",{...a,linkApp:d}),G(s,{event:"watched",object:m,actor:d,attrs:{}},S(s)),{object:$(s,m,g(s,m)),patterns:c}}const f=v(s,e),p=U(s,e)??ee(f),b=q(s,f,k(e));return W(s,p,b,"ask",a),G(s,{event:"watched",object:b,actor:p,attrs:{}},S(s)),{object:$(s,b,g(s,b)),patterns:c}})}l(st,"watchLocal");function ut(e,t,r,n){return t.publishToken||t.principal.class==="anonymous"?O():Ve(e,r,n)}l(ut,"ensureNodeStubFor");function Te(e,t,r,n){const o=l(()=>$e(e,`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.rowid = s.watch
3
- WHERE w.watcher = ? AND w.object = ?`).get(t.rowid,r.rowid).n,"count"),i=o();return Me(e,t,r,n??void 0),{object:g(e,r),removed:i-o()}}l(Te,"dropWatch");async function at(e){const t=k(e);if(e.query.get("watcher")&&ve(t),!e.query.get("watcher")){const n=await Z(e,t,{method:"DELETE",path:`${J(t)}/watch`,query:V(e)});if(n.kind==="unknown")throw le(t,n.unreachable);if(n.kind==="remote"){const o=n.status===404?n.body.error?.details:void 0,i=o?.deleted===!0?o.id:void 0;if(n.status>=400&&i===void 0)throw C(n.status,n.body);const s=i??n.body.object?.id,u=_(c=>{const a=ue(c,e),f=s===void 0?null:L(c,s);return a===null||f===null||!K(c,f)?null:Te(c,a,f,e.query.get("pattern"))});if(i!==void 0){if(u===null)throw C(n.status,n.body);return{...u,machine:n.machine}}return B(n.body,n.machine)}}const r=await Oe(T(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return ct(e,r)}l(at,"unwatchRoute");function ct(e,t=null){const r=e.query.get("pattern"),n=e.query.get("watcher");return _(o=>{if((e.publishToken||e.principal.class==="anonymous")&&!n)throw new y(404,"not_found","watcher not found");const i=l((c,a)=>Te(o,c,a,r),"drop");if(n){const c=t===null?null:(()=>{const f=L(o,n);return f!==null&&Be(o,f)!==null?f:null})();if(t!==null&&c===null)return O();const a=c??(e.publishToken?re(o,n):X(o,n));return a===null?O():c===null&&qe(o,e,a)?(oe(o,e,a),M(o,e,a),i(a,q(o,D(o,a),k(e)))):i(a,Ee(o,e,a,k(e)).object)}const s=v(o,e),u=U(o,e)??ee(s);return i(u,q(o,s,k(e)))})}l(ct,"unwatchLocal");function lt(e){const t=[],r=Q(e.query.get("type"),"type",["acted-on","links-to","watches"],t),n=Q(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&P("edges request",t),_(o=>{const i=v(o,e),s=q(o,i,k(e)),u=[];if(r!=="watches")for(const c of Le(o,i,s,{...r?{type:r}:{},direction:n??"both"}))u.push({type:c.type,src:g(o,c.src),dst:g(o,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(r===void 0||r==="watches"){const c=[...n!=="in"?ze(o,i,s):[],...n!=="out"?Ge(o,i,s):[]];for(const a of c)u.push({type:"watches",src:g(o,a.watcher),dst:g(o,a.object)})}return{items:u}})}l(lt,"edges");const A=l(e=>async t=>({status:200,body:await e(t)}),"ok"),Wt=[{method:"POST",pattern:"/v1/objects/search",handler:A(tt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:A(lt)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:A(it)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:A(at)},{method:"GET",pattern:"/v1/objects/:ref",handler:A(Qe)},{method:"GET",pattern:"/v1/objects",handler:A(et)}];export{Ye as listBudget,Wt as objectRoutes};
1
+ var Te=Object.defineProperty;var l=(e,t)=>Te(e,"name",{value:t,configurable:!0});import{prepared as $e}from"../../../core/sqlite-statements.js";import{ApiError as p}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as Ie}from"../../../api/dto/objects.js";import{openDb as R,withCanvasWrite as _}from"../../../core/canvas/db.js";import{actorOf as ee}from"../../../core/graph/documents.js";import{readerForObject as D,readerFor as Se}from"../../../core/graph/reader.js";import{resolveName as Ne,stubsNamed as Ae}from"../../../core/graph/names.js";import{canRead as te,customReachable as Fe,holdsObjectsScope as Le,mayActAs as ne}from"../../../core/graph/access.js";import{customObjectRef as re,authorizeCustom as oe,fenceArgv as M}from"./custom-objects.js";import{edgesOf as We}from"../../../core/graph/edges.js";import{publish as G}from"../../../core/graph/events.js";import{objectDTO as b}from"../../../core/graph/kinds/dto.js";import{isKind as Pe,kindNames as Ce,kindOf as z}from"../../../core/graph/kinds/registry.js";import{listObjects as De,searchObjects as ie}from"../../../core/graph/objects.js";import{checkoutsForCwd as Me}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as W,unwatch as Ge,watchersOf as ze,watchesOf as He}from"../../../core/graph/watches.js";import{readerFor as v,resolveRef as H}from"../reader.js";import{readDelegationFor as se,runReadLeaf as Ue}from"../../plugin-objects/read-leaf.js";import{invalidRequest as P,isRecord as T}from"./validate.js";import{callerNode as ue,callerStub as U,forwardVerb as ae,originates as ce,queryWithoutMachine as V,relayError as C,remoteStub as Ve,unknownError as le,forwarding as F,withMachine as B}from"../../peer/forward.js";import{getById as L,getByRowid as fe}from"../../../core/graph/objects.js";import{ensureNodeStub as Be,isStub as K,stubOf as Ke,withKindDecl as $}from"../../../core/peer/stubs.js";import{isUnreachable as Ze}from"../../../core/peer/client.js";import{normalizeMachineId as I}from"../../../core/peer/directory.js";const S=l(e=>t=>Me(e,t),"reposFnFor");function de(e,t){return{...b(e,t),...z(e,t.type).listItem?.(e,t)}}l(de,"listItem");function Je(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}l(Je,"remoteMessage");function me(e,t,r){try{return q(e,t,r)}catch(n){if(n instanceof p&&n.code==="not_found"&&!n.details?.deleted)return null;throw n}}l(me,"ownerFilter");function q(e,t,r){const n=H(e,t,r);if("remote"in n)throw new p(404,"not_found",Je(n.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in n)throw new p(404,"not_found",`${n.deleted.name} is deleted`,{id:n.deleted.id,deleted:!0});return n}l(q,"liveRef");const k=l(e=>decodeURIComponent(e.params.ref),"refParam"),he=l(e=>{const t=e.trim().replace(/^\[\[(.*)\]\]$/,"$1").trim(),r=t.indexOf("/");return r>0?t.slice(0,r):t},"idOf");function pe(e){const t=L(R(),he(e));return t!==null&&K(R(),t)?t.id:null}l(pe,"stubIdOf");function Qe(e,t){const r=pe(e);return r!==null?{stub:r,hit:!0}:_(n=>{try{const o=v(n,t),i=l(()=>{const u=Ae(n,o,e);if(u.length>1)throw new p(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:u.map(c=>c.id),next:"Read one by its object id."});return{stub:u[0]?.id??null,hit:!1}},"named");let s;try{s=H(n,o,e)}catch(u){if(u instanceof p&&u.code==="not_found")return i();throw u}if("remote"in s)return i();if("deleted"in s){const u=i();return u.stub===null?{stub:null,hit:!0}:u}return{stub:K(n,s)?s.id:null,hit:!0}}catch(o){if(o instanceof p&&o.code==="ambiguous_name")throw o;return{stub:null,hit:!1}}})}l(Qe,"resolvedLocally");async function Z(e,t,r){const n=Qe(t,e);return n.stub!==null?ae(e,n.stub,r):n.hit||!ce(e.principal)?{kind:"local"}:ae(e,he(t),r)}l(Z,"forwardRef");const J=l(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");function we(e,t,r,n,o){const i=t?.object;!i?.id||!i.type||_(s=>{const u=ue(s,e);if(u===null)return;const c=Ve(s,i.id,i.type,r,{kind:i.kind??null,name:i.name??i.id,...i.preview===void 0?{}:{preview:i.preview},owner:i.owner??null,...i.kind_decl===void 0?{}:{kind_decl:i.kind_decl},...i.privacy===void 0?{}:{privacy:i.privacy}});W(s,u,c,n,o===void 0?{}:{patterns:o})})}l(we,"watchRemote");async function Ye(e){const t=k(e),r=["1","true"].includes(e.query.get("fields")??""),n=await Z(e,t,{method:"GET",path:J(t),query:V(e)});if(n.kind==="unknown")return{state:"unknown",ref:t,unreachable:n.unreachable};if(n.kind==="remote"){if(n.status>=400)throw C(n.status,n.body);return we(e,n.body,n.machine.id,"read"),B(n.body,n.machine)}const o=l(u=>{const c=U(u,e);return c===null?v(u,e):D(u,c,S(u))},"readerOf"),i=_(u=>{const c=o(u),a=H(u,c,t);if("remote"in a)return{state:"remote",remote:a.remote};if("deleted"in a)return{state:"deleted",deleted:b(u,a.deleted)};const f=se(u,a);if(f!==null)return{delegate:f,hitId:a.id};const{data:w,text:g}=z(u,a.type).read(u,c,a,{fields:r,reposFn:S(u)});return{state:"object",type:a.type,object:$(u,a,b(u,a)),text:g,data:w}});if(!("delegate"in i))return i;const s=await Ue(i.delegate,e.principal);return _(u=>{const c=o(u),a=L(u,i.hitId);if(a===null)throw new p(404,"not_found","object not found");if(a.deleted_at!==null)return{state:"deleted",deleted:b(u,a)};if(!te(u,c,a))throw new p(404,"not_found","object not found");const{data:f,text:w}=z(u,a.type).read(u,c,a,{fields:r,reposFn:S(u)});return se(u,a)===null?{state:"object",type:a.type,object:$(u,a,b(u,a)),text:w,data:f}:{state:"object",type:a.type,object:$(u,a,b(u,a)),text:"markdown"in s?s.markdown:`${w}
2
+ content unavailable: ${s.unavailable}`,data:{...f,content:"markdown"in s?"live":"unavailable"}}})}l(Ye,"read");function Q(e,t,r,n){if(e!=null){if(!r.includes(e)){n.push({field:t,problem:`must be one of ${r.join(", ")}`,received:e});return}return e}}l(Q,"oneOf");function ye(e,t,r){if(t!=null){if(typeof t!="string"||!Pe(e,t)){r.push({field:"type",problem:`must be a kind: one of ${Ce(e).join(", ")}`,received:t});return}return t}}l(ye,"kindName");function be(e,t,r,n){if(e==null)return n;const o=Number(e);return!Number.isInteger(o)||o<1||o>100?(r.push({field:t,problem:"must be an integer from 1 to 100",received:e}),n):o}l(be,"limitOf");function ge(e){const t=e.query,r=[],n=ye(R(),t.get("type"),r),o=Q(t.get("privacy"),"privacy",Ie,r),i=be(t.get("limit"),"limit",r,50),s=t.get("cursor");s!==null&&!/^\d+$/.test(s)&&r.push({field:"cursor",problem:"is not a cursor from a previous page",received:s});const u=t.get("deleted");return u!==null&&!["0","1","true","false"].includes(u)&&r.push({field:"deleted",problem:"must be true or false",received:u}),r.length>0&&P("object list request",r),_(c=>{const a=v(c,e),f={...n?{type:n}:{},...o?{privacy:o}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...u==="1"||u==="true"?{deleted:!0}:{}},w=t.get("owner");if(w!==null){const m=me(c,a,w);if(m===null)return{items:[],next_cursor:null};f.owner=m}const g=t.get("name"),j=[];let h=s===null?0:Number(s),y=!0;for(;j.length<i&&y;){const m=De(c,a,f,{limit:100,after_rowid:h});y=m.length===100;for(const E of m)if(h=E.rowid,(g===null||E.name.startsWith(g))&&j.push(E),j.length===i)break}const d=j.at(-1);return{items:j.map(m=>de(c,m)),next_cursor:j.length===i&&d?String(d.rowid):null}})}l(ge,"listLocal");const Xe={ms:3e4},xe="self",Y=l((e,t)=>e.map(r=>({...r,machine:t})),"labelItems");async function je(e,t,r,n){const o=F.current;try{const i=await o.call(t.id,{method:"GET",path:"/v1/objects",query:r},o.envelope(e.principal),n);if(Ze(i))return{state:"unreachable",items:[],next:null};if(i.status===426)return{state:"too_old",items:[],next:null};const s=i.body;return i.status!==200||!Array.isArray(s?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:Y(s.items,t),next:s.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(je,"remotePage");async function et(e){const t=new Promise(r=>e.addEventListener("abort",()=>r(null),{once:!0}));return Promise.race([F.current.machines().catch(()=>null),t])}l(et,"machinesWithin");async function tt(e){const t=e.query.get("machine");if(!ce(e.principal)||!F.current.joined()||t===xe)return ge(_e(e));const n=F.current.self(),o=t!==null&&I(t)!==n,i=o?null:ge(_e(e)),s=new AbortController,u=setTimeout(()=>s.abort(),Xe.ms);u.unref?.();try{const c=await et(s.signal);if(c===null){if(o)throw new p(503,"runtime_unreachable",`The directory did not answer, so ${I(t)} cannot be listed.`,{machine:I(t)});return i}const a=l(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),f=a(n),w=c.filter(d=>d.machine_id!==n&&d.kind!=="device"),g=V(e);if(t!==null){if(!o)return{items:Y(i.items,f),next_cursor:i.next_cursor,machines:[{machine_id:n,name:f.name,state:"ok",more:i.next_cursor!==null}]};const d=I(t);if(!w.some(E=>E.machine_id===d))throw new p(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await je(e,a(d),g,s.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:a(d).name,state:m.state,more:m.next!==null}]}}const{cursor:j,...h}=g,y=await Promise.all(w.map(d=>je(e,a(d.machine_id),h,s.signal)));return{items:[...Y(i.items,f),...y.flatMap(d=>d.items)],next_cursor:i.next_cursor,machines:[{machine_id:n,name:f.name,state:"ok",more:i.next_cursor!==null},...w.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:y[m].state,more:y[m].next!==null}))]}}finally{clearTimeout(u)}}l(tt,"list");function _e(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(_e,"withoutMachine");function nt(e){const t=[],r=T(e.body)?e.body:{};T(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const n=r.text;(typeof n!="string"||n.trim()==="")&&t.push({field:"text",problem:"is required",received:n});const o=r.grep;if(o!==void 0)if(typeof o!="string")t.push({field:"grep",problem:"must be a regular expression string",received:o});else try{new RegExp(o)}catch(u){t.push({field:"grep",problem:`is not a valid regular expression: ${u.message}`,received:o})}r.body!==void 0&&typeof r.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:r.body});const i=ye(R(),r.type,t);r.kind!==void 0&&typeof r.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:r.kind}),r.owner!==void 0&&typeof r.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:r.owner});const s=be(r.limit,"limit",t,50);return t.length>0&&P("object search request",t),_(u=>{const c=v(u,e),a=typeof r.owner=="string"?me(u,c,r.owner):null;if(typeof r.owner=="string"&&a===null)return{items:[]};const f=ie(u,c,{text:n,body:r.body===!0||typeof o=="string"}),w=new Set(f.map(h=>h.object.rowid));return{items:(typeof o=="string"?ie(u,c,{text:o,grep:!0}).filter(h=>w.has(h.object.rowid)):f).filter(h=>(!i||h.object.type===i)&&(r.kind===void 0||h.object.kind===r.kind)&&(!a||h.object.owner===a.rowid)).slice(0,s).map(h=>({object:de(u,h.object),...h.line!==void 0?{matches:[{line:h.line,text:h.text??""}]}:{}}))}})}l(nt,"search");const ke=["interrupt","steer","after-turn","next-turn"],rt=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function ot(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(r=>typeof r!="string"||!rt.test(r)||r.includes(">")&&!r.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(ot,"patternsOf");function it(e,t){if(e===void 0)return;if(!T(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const r=[];for(const[n,o]of Object.entries(e)){const i=Number(n);!Number.isInteger(i)||i<1||i>10?t.push({field:`config.${n}`,problem:"level must be an integer from 1 to 10"}):ke.includes(o)?r.push({threshold:i,delivery:o}):t.push({field:`config.${n}`,problem:`delivery must be one of ${ke.join(", ")}`,received:o})}return r.sort((n,o)=>o.threshold-n.threshold)}l(it,"configOf");function ve(e){const t=pe(e);if(t!==null)throw new p(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(ve,"refuseStubWatch");function X(e,t){const r=L(e,t)??(()=>{const n=Ne(e,Se(e,{class:"person"},()=>[]),t);return"object"in n?n.object:null})();return r===null||r.deleted_at!==null||!(r.type.includes(".")||r.type==="node")?null:r}l(X,"findWatcher");const O=l(()=>{throw new p(404,"not_found","watcher not found")},"watcherNotFound");async function Oe(e,t,r){if(typeof t!="string"||r===void 0||r===null)return null;if(typeof r!="string")throw new p(400,"invalid_request","invalid watcher_machine");if(X(e,t)!==null)return null;const n=F.current;let o;try{o=await n.machines()}catch{throw new p(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const i=I(r);return(i===n.self()||!o.some(s=>I(s.machine_id)===i))&&O(),i}l(Oe,"remoteWatcherMachine");function Ee(e,t,r,n){if(t.publishToken||t.principal.class==="anonymous")return O();const o=v(e,t);if(o.class==="person")return O();let i;try{i=q(e,o,n)}catch{return O()}const s=i.owner===null?null:fe(e,i.owner);return s===null||!ne(e,o,s)||!Le(e,o,"link",r)?O():(M(e,t,r),{actor:o.app,object:i})}l(Ee,"linkWatcher");function qe(e,t,r){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!r.type.includes("."))return!1;const n=v(e,t),o=r.owner===null?null:fe(e,r.owner);return o!==null&&ne(e,n,o)&&Fe(e,n,r)}l(qe,"ownsWatcher");async function st(e){const t=k(e),r=T(e.body)?e.body:{};if(typeof r.watcher=="string"&&ve(t),typeof r.watcher!="string"){const o=await Z(e,t,{method:"POST",path:`${J(t)}/watch`,body:e.body});if(o.kind==="unknown")throw le(t,o.unreachable);if(o.kind==="remote"){if(o.status>=400)throw C(o.status,o.body);const i=o.body.patterns;return we(e,o.body,o.machine.id,"ask",i),B(o.body,o.machine)}}const n=await Oe(R(),r.watcher,r.watcher_machine);return ut(e,n)}l(st,"watch");function ut(e,t=null){const r=[],n=e.body===void 0?{}:T(e.body)?e.body:(r.push({field:"body",problem:"must be an object"}),{}),o=ot(n.patterns,r),i=it(n.config,r);return n.filter!==void 0&&!T(n.filter)&&r.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&r.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),n.watcher_machine!==void 0&&typeof n.watcher_machine!="string"&&r.push({field:"watcher_machine",problem:"must be a machine id",received:n.watcher_machine}),r.length>0&&P("watch request",r),_(s=>{const u=typeof n.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!u)throw new p(404,"not_found","watcher not found");const c=o??[">"],a={patterns:c,...i?{config:i}:{},...n.filter!==void 0?{filter:n.filter}:{}};if(u){const j=n.watcher,h=t===null?null:at(s,e,j,t),y=h??(e.publishToken?re(s,j):X(s,j));if(y===null)return O();if(h===null&&qe(s,e,y)){const E=oe(s,e,y);M(s,e,y);const x=D(s,y),A=q(s,x,k(e));if(!te(s,x,A))throw new p(404,"not_found","object not found");return W(s,y,A,"act",a),G(s,{event:"watched",object:A,actor:E,attrs:{}},S(s)),{object:$(s,A,b(s,A)),patterns:c}}const{actor:d,object:m}=Ee(s,e,y,k(e));return W(s,y,m,"act",{...a,linkApp:d}),G(s,{event:"watched",object:m,actor:d,attrs:{}},S(s)),{object:$(s,m,b(s,m)),patterns:c}}const f=v(s,e),w=U(s,e)??ee(f),g=q(s,f,k(e));return W(s,w,g,"ask",a),G(s,{event:"watched",object:g,actor:w,attrs:{}},S(s)),{object:$(s,g,b(s,g)),patterns:c}})}l(ut,"watchLocal");function at(e,t,r,n){return t.publishToken||t.principal.class==="anonymous"?O():Be(e,r,n)}l(at,"ensureNodeStubFor");function Re(e,t,r,n){const o=l(()=>$e(e,`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.rowid = s.watch
3
+ WHERE w.watcher = ? AND w.object = ?`).get(t.rowid,r.rowid).n,"count"),i=o();return Ge(e,t,r,n??void 0),{object:b(e,r),removed:i-o()}}l(Re,"dropWatch");async function ct(e){const t=k(e);if(e.query.get("watcher")&&ve(t),!e.query.get("watcher")){const n=await Z(e,t,{method:"DELETE",path:`${J(t)}/watch`,query:V(e)});if(n.kind==="unknown")throw le(t,n.unreachable);if(n.kind==="remote"){const o=n.status===404?n.body.error?.details:void 0,i=o?.deleted===!0?o.id:void 0;if(n.status>=400&&i===void 0)throw C(n.status,n.body);const s=i??n.body.object?.id,u=_(c=>{const a=ue(c,e),f=s===void 0?null:L(c,s);return a===null||f===null||!K(c,f)?null:Re(c,a,f,e.query.get("pattern"))});if(i!==void 0){if(u===null)throw C(n.status,n.body);return{...u,machine:n.machine}}return B(n.body,n.machine)}}const r=await Oe(R(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return lt(e,r)}l(ct,"unwatchRoute");function lt(e,t=null){const r=e.query.get("pattern"),n=e.query.get("watcher");return _(o=>{if((e.publishToken||e.principal.class==="anonymous")&&!n)throw new p(404,"not_found","watcher not found");const i=l((c,a)=>Re(o,c,a,r),"drop");if(n){const c=t===null?null:(()=>{const f=L(o,n);return f!==null&&Ke(o,f)!==null?f:null})();if(t!==null&&c===null)return O();const a=c??(e.publishToken?re(o,n):X(o,n));return a===null?O():c===null&&qe(o,e,a)?(oe(o,e,a),M(o,e,a),i(a,q(o,D(o,a),k(e)))):i(a,Ee(o,e,a,k(e)).object)}const s=v(o,e),u=U(o,e)??ee(s);return i(u,q(o,s,k(e)))})}l(lt,"unwatchLocal");function ft(e){const t=[],r=Q(e.query.get("type"),"type",["acted-on","links-to","watches"],t),n=Q(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&P("edges request",t),_(o=>{const i=v(o,e),s=q(o,i,k(e)),u=[];if(r!=="watches")for(const c of We(o,i,s,{...r?{type:r}:{},direction:n??"both"}))u.push({type:c.type,src:b(o,c.src),dst:b(o,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(r===void 0||r==="watches"){const c=[...n!=="in"?He(o,i,s):[],...n!=="out"?ze(o,i,s):[]];for(const a of c)u.push({type:"watches",src:b(o,a.watcher),dst:b(o,a.object)})}return{items:u}})}l(ft,"edges");const N=l(e=>async t=>({status:200,body:await e(t)}),"ok"),Pt=[{method:"POST",pattern:"/v1/objects/search",handler:N(nt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:N(ft)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:N(st)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:N(ct)},{method:"GET",pattern:"/v1/objects/:ref",handler:N(Ye)},{method:"GET",pattern:"/v1/objects",handler:N(tt)}];export{Xe as listBudget,Pt as objectRoutes};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.505",
3
+ "version": "0.3.507",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -138,7 +138,7 @@
138
138
  },
139
139
  "license": "UNLICENSED",
140
140
  "dependencies": {
141
- "@north-light/identity": "0.3.505",
141
+ "@north-light/identity": "0.3.507",
142
142
  "@earendil-works/pi-agent-core": "1.1.0",
143
143
  "@earendil-works/pi-ai": "1.1.0",
144
144
  "@earendil-works/pi-coding-agent": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.505",
3
+ "version": "0.3.507",
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.505",
3
+ "version": "0.3.507",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.505",
9
+ "version": "0.3.507",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -18,7 +18,7 @@
18
18
  "@earendil-works/pi-ai": "1.1.0",
19
19
  "@earendil-works/pi-coding-agent": "1.1.0",
20
20
  "@earendil-works/pi-tui": "1.1.0",
21
- "@north-light/identity": "0.3.505",
21
+ "@north-light/identity": "0.3.507",
22
22
  "cron-parser": "^5.6.0",
23
23
  "esbuild": "^0.27.7",
24
24
  "jose": "^6.2.12",
@@ -12116,17 +12116,17 @@
12116
12116
  },
12117
12117
  "packages/crouter-api": {
12118
12118
  "name": "@north-light/api",
12119
- "version": "0.3.505",
12119
+ "version": "0.3.507",
12120
12120
  "license": "UNLICENSED"
12121
12121
  },
12122
12122
  "packages/crouter-env-docker": {
12123
12123
  "name": "@north-light/env-docker",
12124
- "version": "0.3.505",
12124
+ "version": "0.3.507",
12125
12125
  "license": "UNLICENSED"
12126
12126
  },
12127
12127
  "packages/crouter-identity": {
12128
12128
  "name": "@north-light/identity",
12129
- "version": "0.3.505",
12129
+ "version": "0.3.507",
12130
12130
  "license": "UNLICENSED",
12131
12131
  "dependencies": {
12132
12132
  "jose": "^6.2.1"
@@ -12134,20 +12134,20 @@
12134
12134
  },
12135
12135
  "packages/crouter-plugin": {
12136
12136
  "name": "@north-light/plugin",
12137
- "version": "0.3.505",
12137
+ "version": "0.3.507",
12138
12138
  "license": "UNLICENSED",
12139
12139
  "dependencies": {
12140
- "@north-light/api": "0.3.505",
12141
- "@north-light/identity": "0.3.505"
12140
+ "@north-light/api": "0.3.507",
12141
+ "@north-light/identity": "0.3.507"
12142
12142
  }
12143
12143
  },
12144
12144
  "packages/crouter-sdk": {
12145
12145
  "name": "@north-light/sdk",
12146
- "version": "0.3.505",
12146
+ "version": "0.3.507",
12147
12147
  "license": "UNLICENSED",
12148
12148
  "dependencies": {
12149
- "@north-light/api": "0.3.505",
12150
- "@north-light/identity": "0.3.505",
12149
+ "@north-light/api": "0.3.507",
12150
+ "@north-light/identity": "0.3.507",
12151
12151
  "jose": "^6.2.1"
12152
12152
  },
12153
12153
  "bin": {