@north-light/cli 0.3.709 → 0.3.710
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/session/layout-record.d.ts +13 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/teardown.d.ts +2 -0
- package/dist/clients/attach/session/teardown.js +3 -3
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +2 -0
- package/dist/clients/attach/viewer.js +504 -501
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +3 -3
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +1 -0
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +111 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +9 -1
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`))if(
|
|
3
|
-
`))if(s.startsWith("worktree "))
|
|
4
|
-
${o.stdout}`).digest("hex");return{base:
|
|
1
|
+
var F=Object.defineProperty;var l=(e,t)=>F(e,"name",{value:t,configurable:!0});import{createHash as L}from"node:crypto";import{existsSync as h,realpathSync as U}from"node:fs";import{isAbsolute as K,relative as q,resolve as w,sep as z}from"node:path";import{completeCleanup as I,getNode as E,recordSweepAttempt as V,resumableNodeCwds as O}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as G}from"./exclusive-lock.js";import{gitAsync as c}from"./git.js";import{proveBranchContained as $,upstreamTip as Q}from"./worktree-containment.js";import{refDeleteTransactionStdin as j}from"./worktree-landing.js";import{deleteTrashAsync as J,removeWorktreeCheckoutAsync as P}from"./worktree-remove.js";import{WORKTREE_LOCK_WAIT_MS as X,canonicalPath as T,checkoutPathForBranchInList as N,samePath as W,worktreeLockPathForCommonDir as Y}from"./worktree.js";const v=[2,5,15,30,60],Z=v.length;function R(e){return e==null||e.state==="abandoned"?!1:e.state==="open"||e.cleanup!=="complete"}l(R,"isReconcilable");function Ee(e,t){const r=e.sweep?.next_attempt;if(r===void 0)return!0;const a=Date.parse(r);return Number.isNaN(a)||a<=t}l(Ee,"isDueForSweep");async function _(e,t){const r=await c(["rev-parse","--verify","--quiet",t],e);return r.status===0?r.stdout.trim():null}l(_,"revParseRef");function d(e){return(e.stderr.trim()||e.stdout.trim()).trim()}l(d,"detailOf");async function M(e){const t=await c(["rev-parse","--git-common-dir"],e);if(t.status!==0)return null;try{return U(w(e,t.stdout.trim()))}catch{return null}}l(M,"commonGitDirAsync");async function ee(e){for(const t of["rebase-merge","rebase-apply"]){const r=await c(["rev-parse","--git-path",t],e);if(r.status!==0)return null;if(h(w(e,r.stdout.trim())))return!0}return!1}l(ee,"isRebaseInProgressAsync");function te(e){for(const t of e.split(`
|
|
2
|
+
`))if(t.startsWith("worktree "))return t.slice(9).trim();return null}l(te,"mainWorktreePath");function ae(e,t,r){let a=null;for(const s of e.split(`
|
|
3
|
+
`))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&s===`branch refs/heads/${r}`&&W(a,t))return a;return null}l(ae,"registeredCheckoutPath");async function re(e){const t=h(e.path),r=t?e.path:e.repo_root,a=await _(r,`refs/heads/${e.base_ref}`),s=await Q(r,e.base_ref),n=await _(r,`refs/heads/${e.branch}`);if(!t)return{base:a,upstream:s?.sha??null,branch:n,checkout:"absent"};const i=await c(["rev-parse","HEAD"],e.path),o=await c(["status","--porcelain"],e.path),u=i.status!==0||o.status!==0?null:L("sha256").update(`${i.stdout.trim()}
|
|
4
|
+
${o.stdout}`).digest("hex");return{base:a,upstream:s?.sha??null,branch:n,checkout:u}}l(re,"observe");function se(e,t){return e.checkout===null||t.checkout===null?!1:e.base===t.base&&e.upstream===t.upstream&&e.branch===t.branch&&e.checkout===t.checkout}l(se,"sameObservation");async function ne(e,t,r,a,s,n){if(r.status!=="refused"&&r.status!=="failed"||!await n.stillEligible())return;const i=(t.sweep?.attempts??0)+1,o=v[Math.min(i,v.length)-1]??v[0],u=(await E(e))?.managed_worktree;u==null||!R(u)||await V(e,{reason:r.reason,...r.detail===void 0?{}:{detail:r.detail},observed:a,attempts:i,lastAttemptAt:new Date(s).toISOString(),nextAttemptAt:new Date(s+o*6e4).toISOString(),quarantined:i>=Z})}l(ne,"recordUnfinished");async function ie(e,t,r){const a=await _(e.path,`refs/heads/${e.base_ref}`);if(a===null)return{ok:!1,detail:`local base branch '${e.base_ref}' does not resolve`};if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const s=await c(["rebase",a],e.path);if(s.status!==0)return await c(["rebase","--abort"],e.path),{ok:!1,detail:d(s)};const n=await _(e.path,"HEAD");if(n===null)return{ok:!1,detail:"could not read the rebased worktree tip"};if((await c(["merge-base","--is-ancestor",a,n],e.path)).status!==0)return{ok:!1,detail:`the rebased branch is not a fast-forward of '${e.base_ref}'`};const i=N(t,e.base_ref);if(i===null){if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const f=await c(["update-ref",`refs/heads/${e.base_ref}`,n,a],e.path);return f.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:d(f)}}const o=await c(["rev-parse","HEAD"],i);if(o.status!==0||o.stdout.trim()!==a)return{ok:!1,detail:`base checkout ${i} is not at ${a}`};if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=await c(["merge","--ff-only",n],i);return u.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:d(u)}}l(ie,"finishBlockedLand");const m={status:"skipped",reason:"node_no_longer_terminal"},A={status:"skipped",reason:"checkout_in_use"};function oe(e,t){const r=q(e,t);return r===""||r!==".."&&!r.startsWith(`..${z}`)&&!K(r)}l(oe,"isWithinDirectory");async function D(e,t){const r=[w(t),T(t)];return(await e()).some(a=>{const s=[w(a),T(a)];return r.some(n=>s.some(i=>oe(n,i)))})}l(D,"checkoutHasDependents");async function $e(e,t,r=Date.now(),a){const s=(await E(e))?.managed_worktree;if(!R(s)||s==null)return{status:"skipped",reason:"already_reconciled"};const{outcome:n,observed:i,trash:o}=a===void 0?await ue(s,t,async()=>(await O(e)).map(({cwd:u})=>u)):await a(s,(await O(e)).map(({cwd:u})=>u));return a===void 0&&await J(s.path,o),n.status==="complete"?await le(e,s,t):(await ne(e,s,n,i,r,t),n)}l($e,"reconcileManagedWorktree");async function ue(e,t,r){const a={base:null,upstream:null,branch:null,checkout:null};if(h(e.path)&&await D(r,e.path))return{outcome:A,observed:a};const s=h(e.path)?e.path:e.repo_root;if(!h(s))return{outcome:{status:"refused",reason:"repo_unavailable",detail:`neither the recorded checkout nor repository root exists, so ${e.branch} cannot be proved absent`},observed:a};const n=await M(s);if(n===null)return{outcome:{status:"failed",reason:"git_dir_unreadable",detail:`could not resolve the git common dir from ${s}`},observed:a};let i=a,o;const u=[];try{o=await G(Y(n),async()=>await t.stillEligible()?(i=await re(e),e.sweep!==void 0&&se(e.sweep.observed,i)?{status:"refused",reason:e.sweep.reason,...e.sweep.detail===void 0?{}:{detail:e.sweep.detail},unchanged:!0}:h(e.path)?await de(e,t,r,u):await ce(e,i,t)):m,{timeoutMs:X,timeoutError:l(()=>new Error(`timed out waiting for the managed-worktree lock on ${n}`),"timeoutError")})}catch(f){o={status:"failed",reason:"lock_unavailable",detail:f instanceof Error?f.message:String(f)}}return{outcome:o,observed:i,...u[0]===void 0?{}:{trash:u[0]}}}l(ue,"sweepManagedWorktreeOnHost");async function le(e,t,r){if(!await r.stillEligible())return m;const a=(await E(e))?.managed_worktree;return a==null||a.path!==t.path||a.branch!==t.branch?{status:"skipped",reason:"record_changed"}:(await I(e),{status:"complete"})}l(le,"persistComplete");async function ce(e,t,r){const a=e.repo_root;if(t.branch===null){const o=await c(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],a);return o.status!==1?{status:"failed",reason:"branch_inspection_failed",detail:d(o)}:{status:"complete"}}const s=await c(["worktree","list","--porcelain"],a);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:d(s)};const n=N(s.stdout,e.branch);if(n!==null)return{status:"refused",reason:"branch_checked_out_elsewhere",detail:`${e.branch} is checked out at ${n}`};const i=await $(a,e,t.branch);return i===null?{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries content no base or upstream ref contains; its checkout is already gone, so the branch is the only copy`}:B(e,a,t.branch,i,r)}l(ce,"concludeAbsentCheckout");async function de(e,t,r,a){const s=await c(["worktree","list","--porcelain"],e.path);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:d(s)};const n=e.disposal,i=n?.observed_branch??e.branch,o=ae(s.stdout,e.path,i);if(o===null)return{status:"refused",reason:"not_registered",detail:`${e.path} is not registered to refs/heads/${i}; crtr will not act on a path it cannot prove it owns`};const u=te(s.stdout);if(u===null||W(u,o)||!h(u))return{status:"refused",reason:"repo_unavailable",detail:`the repository's main checkout is unavailable, so ${e.path} cannot be removed from outside itself`};const f=await ee(e.path);if(f===null)return{status:"failed",reason:"git_path_failed",detail:`could not inspect in-progress operations in ${e.path}`};if(f)return{status:"refused",reason:"rebase_in_progress",detail:`${e.path} is mid-rebase`};const b=await c(["rev-parse","--abbrev-ref","HEAD"],e.path);if(b.status!==0)return{status:"failed",reason:"branch_check_failed",detail:d(b)};if(b.stdout.trim()!==i)return{status:"refused",reason:"wrong_branch",detail:`expected ${i}, found ${b.stdout.trim()==="HEAD"?"detached HEAD":b.stdout.trim()}`};const y=await c(["status","--porcelain"],e.path);if(y.status!==0)return{status:"failed",reason:"status_failed",detail:d(y)};if(y.stdout.trim()!=="")return{status:"refused",reason:"dirty_worktree",detail:`${e.path} has uncommitted changes`};let p=await _(e.path,"HEAD");if(p===null)return{status:"failed",reason:"head_unreadable",detail:`could not read HEAD in ${e.path}`};if(n!==void 0){if(await M(e.path)!==n.common_dir||p!==n.observed_sha)return{status:"refused",reason:"disposal_authorization_stale",detail:`${e.path} changed since \`close\` authorized its disposal; rerun \`crtr node worktree close\` from that node to re-authorize, or ask the user with \`crtr human send\``};if(!await t.stillEligible())return m;if(await D(r,o))return A;const{result:C,trash:H}=await P(u,o);return H!==void 0&&a.push(H),C.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:d(C)}:{status:"complete"}}let g=await $(e.path,e,p);if(g===null&&e.land_intent!==void 0){const k=await ie(e,s.stdout,t);if(!k.ok)return k.ineligible===!0?m:{status:"refused",reason:"land_blocked",detail:k.detail};p=k.landedSha,g=await $(e.path,e,p)}if(g===null)return{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries commits its base does not contain, and this node never asked to land them`};if(!await t.stillEligible())return m;if(await D(r,o))return A;const{result:S,trash:x}=await P(u,o);return x!==void 0&&a.push(x),S.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:d(S)}:await B(e,u,p,g,t)}l(de,"reconcilePresentCheckout");async function B(e,t,r,a,s){if(!await s.stillEligible())return m;const n=j(e.branch,r,a.containingRef,a.containingSha),i=await c(["update-ref","--stdin"],t,n);return i.status!==0?{status:"refused",reason:"branch_delete_failed",detail:d(i)}:{status:"complete"}}l(B,"deleteBranchAndComplete");export{Ee as isDueForSweep,R as isReconcilable,$e as reconcileManagedWorktree,ue as sweepManagedWorktreeOnHost};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}from"../../../core/profiles/manifest.js";import{existsSync as T,realpathSync as oe,statSync as ae}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ve,assertLaunchModelRegistered as V,forkNode as Ke,resolveForkSource as se,spawnChildPrepared as ze}from"../../../core/runtime/spawn.js";import{forkSourceNode as le,newNodeId as ce}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ue,CREATE_LEASE_RENEW_MS as Je,claimCreateLease as fe,createLeaseLive as He,renewCreateLease as Ye,childrenOf as Qe,completeCreateRequest as pe,findCreateRequest as me,getNode as b,recordCreateRequestNode as Xe,reserveCreateRequest as we,reserveCreateRequestNode as Ze,listNodes as qe,recordRespawnAttempt as en,subscribersOf as nn,subscriptionsOf as he,updateNode as $}from"../../../core/canvas/canvas.js";import{armControllerWait as tn,liveControllerWaits as rn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as on}from"../../../core/canvas/recovery.js";import{nodeObject as an}from"../../../core/graph/objects.js";import{recordActedOn as dn}from"../../../core/graph/edges.js";import{publish as sn}from"../../../core/graph/events.js";import{readerFor as ln}from"../reader.js";import{relocateSessionCwd as cn,unbindSession as un}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as fn}from"../../../core/canvas/attention.js";import{isSafeNodeId as pn}from"../../../core/canvas/paths.js";import{contextDir as ye,nodeAgentDir as z}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as mn,cronRefusalError as wn}from"../../cron/authority.js";import{cronBirthPlacement as hn}from"../../cron/armed-context.js";import{existsBeneath as yn,isAbsentOrRefused as _n,isBeneathRefusal as gn,readdirBeneath as bn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as vn,readNodeSession as kn,readNodeSnapshot as Sn,transcriptMarkdown as In}from"../../../core/runtime/node-read.js";import{SNAPSHOT_TAIL as J,toolCallIds as Rn,withoutImages as En}from"../../../core/runtime/broker-protocol.js";import{assembleNodeSubject as On}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as Cn,requestYieldAsync as Tn,reshapeNodeAsync as H}from"../../../core/runtime/promote.js";import{recycleNode as $n}from"../../../core/runtime/recycle.js";import{relaunchRoot as Nn}from"../../../core/runtime/reset.js";import{assertReopenGate as Pn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Dn}from"./broker-recovery.js";import{readOutputRequest as Ln}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Mn,readGoal as jn,captureGoalIfAbsent as Fn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Gn,hasRoadmap as xn}from"../../../core/runtime/roadmap.js";import{renameWindow as Bn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Wn,explicitModelIntent as Un,normalizeModel as Vn,readMergedLaunchConfigAsync as _e}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Kn}from"../../../core/model-routes.js";import{persistDormantModel as zn,setModelLive as Jn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as ge}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Hn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Yn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Qn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as be}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Xn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Zn}from"../../../core/human-actions.js";import{parseDurationMs as qn}from"../../../core/wake.js";import{claimWarmNode as et,refillWarmPool as ve,resumeWarmClaim as nt,warmPoolEnabled as tt}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as it,resolveLaunchTarget as rt}from"../../../core/runtime/launch-target.js";import{fullName as ot}from"../../../core/canvas/labels.js";import{reportsForNode as ke}from"./reports.js";import{requireUsableProfile as at}from"./profiles.js";import{assertProfileActive as dt,isProfilePaused as st,loadExactProfileManifest as lt}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ct}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as ut}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Q}from"../../../core/canvas/crons.js";import{cronWakeOrigin as ft}from"../../../core/runtime/bearings.js";import{boundDaemonControl as pt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as mt,validateScopes as Se}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as wt,toNodeDetailDTO as X,toNodeSummaryDTO as ht,toReviveResultDTO as yt}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as _t,liveExecutionForNode as Ie,requestExecutionStop as gt}from"../../../core/canvas/executions.js";import{runnerForExecution as bt}from"../../../core/runtime/runner/index.js";import{wakeResident as vt}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as kt}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as St}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as It}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as Rt,readableNodeIds as Et,resolvedScopes as Ot}from"../router.js";import{forwardVerb as At,queryWithoutMachine as Ct,relayError as Tt,unknownError as $t,withMachine as Nt}from"../../peer/forward.js";import{fileRoot as Pt}from"../../../core/spaces/file-root.js";import{activeGrant as Dt,payerOfGrant as Lt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as Mt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as jt}from"../../../core/grants/terminal.js";import{appRungForGrant as Ft}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as Gt}from"../../../core/model-routes.js";import{listProfileEnvNames as xt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Bt,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Wt,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Ut,collectStepTimings as Vt,serverTimingHeader as Kt,sinceCollectionStart as zt,timedStep as Jt}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Z(e){return{subscribesTo:await he(e),subscribers:await nn(e),children:await Qe(e)}}d(Z,"edgesFor");async function v(e){const n=await h(e);return await X(n,await Z(e))}d(v,"detailOf");async function Ht(e){let n=(await ke(e)).length;try{n+=bn(await z(e),await ye(e)).length}catch(t){if(!_n(t))throw t}return n}d(Ht,"countFiles");function Yt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Se(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Yt,"parseCreateBody");function Qt(e){if(e===void 0)return;const n=qn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Qt,"parseDeadline");function Xt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Xn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>be)throw new p(413,"payload_too_large",`serialized payload exceeds ${be} bytes`)}return e}}d(Xt,"parseOutcomeDelivery");function Zt(e,n){const t=Zn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(Zt,"resolveOutcomeDelivery");function qt(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(qt,"buildRecipe");function ei(e,n,t){return!tt()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ei,"warmRequestFor");import{resolveCreateKind as vo}from"../../../core/runtime/launch-target.js";function Ae(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Kn(e.model,n,e.modelExact===!0)}d(Ae,"requestFromLaunch");function ni(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ni,"withinCeiling");async function Ce(e,n,t){const r=(await Wn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ae(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Ce,"assertNodeModelChangeRegistered");async function ti(e){if(!It()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Q(e.cron))?.profile??null;return n!==null&&await St(n)!==null}d(ti,"callerRunsOnMachine");async function Te(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ti(t))return;const r=Pt({app:t.app,resolved:await Ot(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(Te,"assertCallerReaches");const q=new Map;async function ii(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Vt(()=>ri(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":Kt(a)}}}d(ii,"handleCreate");async function ri(e,n,t){const r=ni(Yt(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 o=await h(r.parent);if(o.grantee!==c.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await A(c,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await le(await se(r.fork_from))}catch{}if(o?.grantee!==c.app||!await A(c,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const c=r.fork_from===void 0?null:await le(await se(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,c?.node_id])if(o!=null&&await b(o)!==null&&!await Rt(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const c=e.principal;for(const s of["parent","creator","fork_from","node_id"])if(r[s]!=null)throw new p(403,"permission_error",`a cron cannot set ${s} on a node it starts`);r.prefer_warm=!1,r.node_id=await ce(),c.isolated&&(r.isolated=!0,r.cwd=await z(r.node_id,c.app));const o=await mn({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes,from_exec:c.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw wn(o);if(r.scopes!==void 0){const s=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(c.scopes,m));if(s!==void 0)throw new p(403,"scope_missing",`scope ${s} is not held by this cron`,void 0,void 0,{scope:s})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&mt(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&pn(r.node_id)&&await b(r.node_id)!==null&&(await me(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=q.get(i);if(a!==void 0)return a;const l=oi(e,r,i,n,t);q.set(i,l);try{return await l}finally{q.delete(i)}}d(ri,"createWithinTimings");const $e=`${process.pid}:${Fe()}`,ee="create_request_in_progress";async function Ne(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await He(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await me(n))?.nodeId!==t)break;await new Promise(l=>setTimeout(l,100))}throw new p(409,ee,"another create with this request_key is in progress; retry it")}d(Ne,"awaitForeignCreate");async function oi(e,n,t,r,i){const a=await we(t),l=$e;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await fe(t,a.nodeId,l))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ee||!await fe(t,a.nodeId,l))throw o}const c=setInterval(()=>{Ye(t,l).catch(()=>{})},Je);try{return await ai(e,n,t,r,i,a)}finally{clearInterval(c)}}d(oi,"handleKeyedCreateRequest");async function ai(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const l=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,l.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(l){if(l instanceof p&&l.code===ee)throw l;const c=await we(t);throw(c.nodeId===null||await b(c.nodeId)===null)&&await ue(t,c.nodeId),l}}d(ai,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Qt(n.deadline),l=Xt(n.outcome_delivery),c=e.principal.class==="cron"?await hn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Q(e.principal.cron))?.created_by??null},n.node_id):null;c!==null&&(n.root=c.root===!0);const o=c?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let s=null;if(n.output_schema!==void 0){try{s=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(s===null||typeof s!="object"||Array.isArray(s))throw y("output_schema must be a JSON schema object");await Qn(s)}const m=await rt(n,{validateKind:Me,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!T(_)&&await Re(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Te(e,_),n.worktree!==void 0&&await Te(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=l===void 0?void 0:Zt(l,_),te=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ae(await Ve(I,te,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Lt(te)!=="app"&&!await Bt(f===null?[]:await xt(f))&&!await Mt(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const ie=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ei(k,_,f):null,O=ie!==null&&!(n.start===!0&&await Re(f)!==null)?ie:null,B=s===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{s!==null&&await Yn(g,"terminal",s),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await nt(O,i.nodeId,B);if(g===null)throw await ue(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await pe(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await et(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await pe(i.requestKey,g),ve(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ce());if(i!==void 0&&i.nodeId===null){const g=await Ze(i.requestKey,D,$e);if(g!==D)return await Ne(e,i.requestKey,g)}const R=qt(D===void 0?k:{...k,node_id:D},o,_);c!==null&&(c.rootLifecycle!==void 0&&(R.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&k.scopes===void 0&&(R.scopes=c.scopes),c.run!==void 0&&(R.run=c.run),c.withinCreate!==void 0&&(R.withinCreate=c.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Ut("handler_checks",zt());const re=await ze(R,B,()=>{x!==null&&ve(x)});return i!==void 0&&await Xe(i.requestKey,re.node.node_id),{status:201,body:await Jt("response_detail",()=>v(re.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function ne(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(ne,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function di(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),l=S(e,"profile_id"),c=S(e,"profile_prefix"),o=S(e,"parent"),s=ne(S(e,"top_level"),"top_level"),m=S(e,"under"),f=ne(S(e,"under_inclusive"),"under_inclusive"),u=ne(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&s===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...l!==void 0?{profile_id:l}:{},...c!==void 0?{profile_prefix:c}:{},...o!==void 0?{parent:o}:{},...s!==void 0?{top_level:s}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(di,"parseListQuery");async function si(e){const n=di(e);let t=await qe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Et(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await fn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,l=new Map((await rn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const s=await ht(o,o.profile_id!==null&&a.has(o.profile_id),l.get(o.node_id)??null);if(i!==null){const m=await ke(o.node_id);s.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return s})}}d(si,"handleList");async function li(e){const n=e.params.id,t=await At(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:Ct(e)});if(t.kind==="unknown")throw $t(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw Tt(t.status,t.body);return{status:t.status,body:Nt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(li,"handleDetail");async function ci(e){const n=e.params.id;await h(n);const t=await Sn(n),r=t.snapshot.messages.slice(-J).map(l=>En(l,n)),i=Rn(r);return{status:200,body:{node_id:n,snapshot:{messages:r,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(-J)},messageVisibility:t.snapshot.messageVisibility.slice(-J),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([l])=>i.has(l)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(l=>({name:l.name,description:l.description,source:l.source})),captured_at:U()}}}d(ci,"handleSnapshot");async function ui(e){const n=e.params.id,t=await On(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(ui,"handleSubject");function fi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(fi,"parseMessagesQuery");async function pi(e){const n=e.params.id,t=await vn(n,fi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(pi,"handleMessages");async function mi(e){const n=e.params.id;await h(n);const t=await kn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(mi,"handleSession");async function wi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await In(n)}}}d(wi,"handleTranscript");async function hi(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await ye(i),self:a,files:await Ht(i)}),"root"),r=await Wt([await t(n,!0),...await Oe(await he(n),async i=>await t(i.node_id,!1))],async i=>await yi(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(hi,"handleContext");async function yi(e,n){try{return yn(await z(e),n)}catch(t){if(gn(t))return!1;throw t}}d(yi,"hasDir");async function _i(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Ke(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(_i,"handleFork");const gi=1e4;async function bi(e){const n=e.params.id,t=await h(n),r=await Ie(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!kt(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await gt(n,{afterTurn:!1,reason:"revive_now"});const i=await bt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await _t(r.executionId,{reason:"revive_now"}),await de(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(bi,"handleKick");async function vi(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;await Pn(n,a,e.principal.class==="broker"?e.principal.node:null);const l=!i&&r?.cron_id!==void 0?await Q(r.cron_id):null,c=await Ie(n);if(i&&c!==null&&c.runner!=="process"&&c.state==="running"&&!st(t.profile_id))try{await ut({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>vt(c))}catch(u){if(!(u instanceof ct))throw u}const o=await de(n,{resume:i,capacity:"refuse",...l!==null?{wakeReason:await ft(l,"schedule_revive")}:{}});o.outcome!=="already-live"&&await en(n,{failures:0,notBefore:null});const s=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await ge(n,m,gi);return{status:200,body:yt(n,o,s,f)}}d(vi,"handleRevive");async function ki(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Nn(n))?.newNodeId??null}}}d(ki,"handleRelaunchRoot");async function Si(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=pt(),i=new Promise(l=>{e.res.once("close",()=>l())}),a=await Ue(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:wt(a)}}d(Si,"handleClose");async function Ii(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await on(n),{status:204}}d(Ii,"handleMarkRead");async function Ri(e){const n=e.params.id;await h(n);const t=await $n(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Ri,"handleRecycle");async function Ei(e){const n=e.params.id;return await h(n),await H(n,{lifecycle:"terminal"}),await C(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Ei,"handleDemote");async function Oi(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ce(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await Cn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await C(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const l=await X(a.meta,await Z(t));return l.roadmap_written=a.roadmapWritten,l.roadmap_ref=a.roadmapRef,l.goal_path=a.goalPath,{status:200,body:l}}d(Oi,"handlePromote");async function Ai(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Ln(n)}}}d(Ai,"handleBrokerStructuredRequest");async function Ci(e){const n=e.params.id,t=e.body??{};if(await Dn(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Fn(n,t.text)}}}d(Ci,"handleBrokerGoal");async function Ti(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Ce(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Mn(t,a);const l=await Tn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await X(l.meta,await Z(t))}}d(Ti,"handleYield");async function $i(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await tn(n,t.controller),{status:200,body:await v(n)}}d($i,"handleWait");async function Ni(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Ni,"handleReviveAll");const Pi=new Set(["interrupt","steer","after-turn","next-turn"]);function Di(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Pi.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Di,"listenJson");async function C(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await an(i,n),l=await ln(i,e),c=l.class==="person"?l.person:l.class==="app"?l.app:l.node;await dn(i,c,a),await sn(i,{event:"configured",object:a,actor:c,attrs:{changed:t.join(",")}})})}d(C,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return oe(e)===oe(n)}catch{return!1}}d(De,"sameDirectory");async function Li(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),s=await at(e,i.profile);dt(s.profileId);const m=lt(s.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${s.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==s.profileId&&(it(o.kind)?(await Y(o.kind,o.cwd,s.profileId),await H(t,{profileId:s.profileId})):await $(t,{profile_id:s.profileId}),await C(e,t,["profile"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const s=await h(t),m=T(s.cwd);if(i.keep_session===!0||m&&W(o)&&T(o)&&De(s.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ae(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!De(s.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${s.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(s.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=s.cwd;return I!==u&&(await K(async k=>{await $(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await cn(t,I,u)}),await C(e,t,["cwd"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(s.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${s.cwd}`,received:o,field:"cwd",next:`Restore ${s.cwd}, then revive the fork normally.`});if(s.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(T(s.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${s.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!T(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ae(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await $(t,{cwd:f}),await un(t)}),await C(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const l=i.listen===void 0?void 0:Di(i.listen);if(i.scopes!==void 0){const o=Se(i.scopes),s=a.grantee==="app:terminal"?await jt(a):a.grant_id?await Dt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&s!==null&&E(s.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await $(t,{scopes:o})}if(i.situational_context!==void 0&&await Be(t,We(i.situational_context)),i.model!==void 0){const o=(await _e(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,s=Un(i.model,o),m=await Ft(a.grant_id,i.model,s===void 0),f=m?{family:Gt,strength:m.strength}:s,u=m?m.model:Vn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&await ge(t,_.get(t)?.handle.exited)&&(I=await Jn(t,u,f).then(()=>!0,k=>{if(k instanceof Hn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await zn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Me(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,s=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;s==="orchestrator"&&!await xn(t)&&(f=d(async()=>{const u=await jn(t);await Gn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await H(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:s}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await $(t,{name:i.name}),a.window&&Bn(a.window,ot(a)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await C(e,t,c,l===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(l,t)}),{status:200,body:await v(t)}}d(Li,"handleConfig");async function Le(e="app:terminal"){return(await _e(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function Mi(){const e=await Le();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(Mi,"handleListKinds");const _o=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ii},{method:"GET",pattern:"/v1/nodes",handler:si},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Mi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Ni},{method:"GET",pattern:"/v1/nodes/:id",handler:li},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:ci},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:pi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:mi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:hi},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:_i},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:vi},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:bi},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:$i},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Li}];export{Li as handleConfig,ii as handleCreate,_i as handleFork,si as handleList,Oi as handlePromote,Ti as handleYield,_o as nodeRoutes,vo as resolveCreateKind};
|
|
1
|
+
var je=Object.defineProperty;var d=(e,n)=>je(e,"name",{value:n,configurable:!0});import{randomUUID as Fe}from"node:crypto";import{envProfileId as Ge}from"../../../shared/env.js";import{pausedCanvasProfiles as xe}from"../../../core/profiles/manifest.js";import{existsSync as C,realpathSync as ae,statSync as de}from"node:fs";import{isAbsolute as W,resolve as L}from"node:path";import{appendSituationalContext as Be,formatSituationalProse as We}from"../../../core/runtime/situational-context.js";import{closeNode as Ue}from"../../../core/runtime/close.js";import{reviveNode as se}from"../../../core/runtime/revive.js";import{nowIso as U}from"../../../core/fs-utils.js";import{appPaidLaunch as Ve,assertLaunchModelRegistered as V,forkNode as Ke,resolveForkSource as le,spawnChildPrepared as ze}from"../../../core/runtime/spawn.js";import{forkSourceNode as ce,newNodeId as ue}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as fe,CREATE_LEASE_RENEW_MS as Je,claimCreateLease as pe,createLeaseLive as He,renewCreateLease as Ye,childrenOf as Qe,completeCreateRequest as me,findCreateRequest as we,getNode as b,recordCreateRequestNode as Xe,reserveCreateRequest as he,reserveCreateRequestNode as Ze,listNodes as qe,recordRespawnAttempt as en,subscribersOf as nn,subscriptionsOf as ye,updateNode as $}from"../../../core/canvas/canvas.js";import{armControllerWait as tn,liveControllerWaits as rn}from"../../../core/canvas/waits.js";import{withCanvasWrite as K}from"../../../core/canvas/db.js";import{markNodeRead as on}from"../../../core/canvas/recovery.js";import{nodeObject as an}from"../../../core/graph/objects.js";import{recordActedOn as dn}from"../../../core/graph/edges.js";import{publish as sn}from"../../../core/graph/events.js";import{readerFor as ln}from"../reader.js";import{relocateSessionCwd as cn,unbindSession as un}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as fn}from"../../../core/canvas/attention.js";import{isSafeNodeId as pn}from"../../../core/canvas/paths.js";import{contextDir as _e,nodeAgentDir as z}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as mn,cronRefusalError as wn}from"../../cron/authority.js";import{cronBirthPlacement as hn}from"../../cron/armed-context.js";import{existsBeneath as yn,isAbsentOrRefused as _n,isBeneathRefusal as gn,readdirBeneath as bn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as vn,readNodeSession as kn,readNodeSnapshot as Sn,transcriptMarkdown as In}from"../../../core/runtime/node-read.js";import{SNAPSHOT_TAIL as J,toolCallIds as Rn,withoutImages as En}from"../../../core/runtime/broker-protocol.js";import{assembleNodeSubject as On}from"../../../core/substrate/subject.js";import{reviveAll as An}from"../../../core/runtime/revive-all.js";import{promoteAsync as Tn,requestYieldAsync as Cn,reshapeNodeAsync as H}from"../../../core/runtime/promote.js";import{recycleNode as $n}from"../../../core/runtime/recycle.js";import{relaunchRoot as Nn}from"../../../core/runtime/reset.js";import{assertReopenGate as Pn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as Dn}from"./broker-recovery.js";import{readOutputRequest as Ln}from"../../../core/runtime/output-result.js";import{writeYieldMessage as Mn,readGoal as jn,captureGoalIfAbsent as Fn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Gn,hasRoadmap as xn}from"../../../core/runtime/roadmap.js";import{renameWindow as Bn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Wn,explicitModelIntent as Un,normalizeModel as Vn,readMergedLaunchConfigAsync as ge}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Kn}from"../../../core/model-routes.js";import{persistDormantModel as zn,setModelLive as Jn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as be}from"../../../core/runtime/view-socket.js";import{viewTransport as Hn}from"../../runs/observer.js";import{BrokerUnreachableError as Yn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Qn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Xn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ve}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Zn}from"../../../core/human/action-binding.js";import{resolveHumanAction as qn}from"../../../core/human-actions.js";import{parseDurationMs as et}from"../../../core/wake.js";import{claimWarmNode as nt,refillWarmPool as ke,resumeWarmClaim as tt,warmPoolEnabled as it}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as rt,resolveLaunchTarget as ot}from"../../../core/runtime/launch-target.js";import{fullName as at}from"../../../core/canvas/labels.js";import{reportsForNode as Se}from"./reports.js";import{requireUsableProfile as dt}from"./profiles.js";import{assertProfileActive as st,isProfilePaused as lt,loadExactProfileManifest as ct}from"../../../core/profiles/manifest.js";import{MachineOfflineError as ut}from"../../../core/runtime/runner/machine/ops.js";import{asNodePerson as ft}from"../../reconcilers/node-lifecycle/node-person.js";import{getCron as Q}from"../../../core/canvas/crons.js";import{cronWakeOrigin as pt}from"../../../core/runtime/bearings.js";import{boundDaemonControl as mt}from"../../control.js";import{notFound as N,usage as y}from"../../../core/errors.js";import{assertScope as wt,validateScopes as Ie}from"../../../core/scopes.js";import{scopeAllowed as E}from"../../../shared/env.js";import{toCloseResultDTO as ht,toNodeDetailDTO as X,toNodeSummaryDTO as yt,toReviveResultDTO as _t}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as w}from"../../../core/io.js";import{endExecution as gt,liveExecutionForNode as Z,requestExecutionStop as bt}from"../../../core/canvas/executions.js";import{runnerForExecution as vt}from"../../../core/runtime/runner/index.js";import{wakeResident as kt}from"../../reconcilers/node-lifecycle/remote-wake.js";import{isNowEligibleFault as St}from"../../../core/canvas/status-glyph.js";import{remoteEnvironmentOf as Re}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as It}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as Rt}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as A,mayOnNode as Et,readableNodeIds as Ot,resolvedScopes as At}from"../router.js";import{forwardVerb as Tt,queryWithoutMachine as Ct,relayError as $t,unknownError as Nt,withMachine as Pt}from"../../peer/forward.js";import{fileRoot as Dt}from"../../../core/spaces/file-root.js";import{activeGrant as Lt,payerOfGrant as Mt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as jt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as Ft}from"../../../core/grants/terminal.js";import{appRungForGrant as Gt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as xt}from"../../../core/model-routes.js";import{listProfileEnvNames as Bt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as Wt,NO_PROVIDER_CREDENTIAL_MESSAGE as Ee}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Ut,mapAsync as Oe}from"../../../core/async-array.js";import{addStepTiming as Vt,collectStepTimings as Kt,serverTimingHeader as zt,sinceCollectionStart as Jt,timedStep as Ht}from"../../../core/step-timings.js";async function h(e){const n=await b(e);if(n===null)throw N(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function q(e){return{subscribesTo:await ye(e),subscribers:await nn(e),children:await Qe(e)}}d(q,"edgesFor");async function v(e){const n=await h(e);return await X(n,await q(e))}d(v,"detailOf");async function Yt(e){let n=(await Se(e)).length;try{n+=bn(await z(e),await _e(e)).length}catch(t){if(!_n(t))throw t}return n}d(Yt,"countFiles");function Qt(e){if(typeof e!="object"||e===null)throw y("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw y("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw y("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw y("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&Ie(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});if(n.start!==void 0&&typeof n.start!="boolean")throw new p(400,"invalid_request","start must be a boolean",{param:"start"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw y("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw y("request_key must be a non-empty string of at most 128 characters when provided");return n}d(Qt,"parseCreateBody");function Xt(e){if(e===void 0)return;const n=et(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(Xt,"parseDeadline");function Zt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Zn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>ve)throw new p(413,"payload_too_large",`serialized payload exceeds ${ve} bytes`)}return e}}d(Zt,"parseOutcomeDelivery");function qt(e,n){const t=qn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(qt,"resolveOutcomeDelivery");function ei(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.start===!0&&(r.start=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}d(ei,"buildRecipe");function ni(e,n,t){return!it()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(ni,"warmRequestFor");import{resolveCreateKind as So}from"../../../core/runtime/launch-target.js";function Ae(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Kn(e.model,n,e.modelExact===!0)}d(Ae,"requestFromLaunch");function ti(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!E(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(ti,"withinCeiling");async function Te(e,n,t){const r=(await Wn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(Ae(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(Te,"assertNodeModelChangeRegistered");async function ii(e){if(!Rt()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await b(e.node))?.profile_id??null:e.cron===null?null:(await Q(e.cron))?.profile??null;return n!==null&&await It(n)!==null}d(ii,"callerRunsOnMachine");async function Ce(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await ii(t))return;const r=Dt({app:t.app,resolved:await At(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(Ce,"assertCallerReaches");const ee=new Map;async function ri(e,n={},t={}){const r=performance.now(),{value:i,steps:a}=await Kt(()=>oi(e,n,t));return a.push(["total",performance.now()-r]),{...i,headers:{...i.headers??{},"server-timing":zt(a)}}}d(ri,"handleCreate");async function oi(e,n,t){const r=ti(Qt(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 o=await h(r.parent);if(o.grantee!==c.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await A(c,o.grantee??"app:terminal",r.parent))throw N(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await ce(await le(r.fork_from))}catch{}if(o?.grantee!==c.app||!await A(c,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const c=r.fork_from===void 0?null:await ce(await le(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,c?.node_id])if(o!=null&&await b(o)!==null&&!await Et(e.principal,"edit",o))throw N(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const c=e.principal;for(const s of["parent","creator","fork_from","node_id"])if(r[s]!=null)throw new p(403,"permission_error",`a cron cannot set ${s} on a node it starts`);r.prefer_warm=!1,r.node_id=await ue(),c.isolated&&(r.isolated=!0,r.cwd=await z(r.node_id,c.app));const o=await mn({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes,from_exec:c.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw wn(o);if(r.scopes!==void 0){const s=r.scopes.find(m=>!E(o.effectiveScopes,m)||!E(c.scopes,m));if(s!==void 0)throw new p(403,"scope_missing",`scope ${s} is not held by this cron`,void 0,void 0,{scope:s})}else o.scopes!==null&&(r.scopes=o.scopes)}r.creator!==void 0&&wt(await h(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&pn(r.node_id)&&await b(r.node_id)!==null&&(await we(i))?.nodeId!==r.node_id)return F(e,r,n,t);const a=ee.get(i);if(a!==void 0)return a;const l=ai(e,r,i,n,t);ee.set(i,l);try{return await l}finally{ee.delete(i)}}d(oi,"createWithinTimings");const $e=`${process.pid}:${Fe()}`,ne="create_request_in_progress";async function Ne(e,n,t){const r=Date.now()+9e4;let i=Date.now()+1e4;for(;t!==null;){const a=await b(t);if(a!==null){if(!j(e.principal)&&!await A(e.principal,a.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(t)}}if(await He(n)&&(i=Math.min(r,Date.now()+1e3)),Date.now()>=i||(await we(n))?.nodeId!==t)break;await new Promise(l=>setTimeout(l,100))}throw new p(409,ne,"another create with this request_key is in progress; retry it")}d(Ne,"awaitForeignCreate");async function ai(e,n,t,r,i){const a=await he(t),l=$e;if(a.nodeId!==null&&a.state==="reserved"&&await b(a.nodeId)===null&&!await pe(t,a.nodeId,l))try{return await Ne(e,t,a.nodeId)}catch(o){if(!(o instanceof p)||o.code!==ne||!await pe(t,a.nodeId,l))throw o}const c=setInterval(()=>{Ye(t,l).catch(()=>{})},Je);try{return await di(e,n,t,r,i,a)}finally{clearInterval(c)}}d(ai,"handleKeyedCreateRequest");async function di(e,n,t,r,i,a){if(a.nodeId!==null&&await b(a.nodeId)!==null){if(a.state!=="warm_claimed"){const l=await b(a.nodeId);if(!j(e.principal)&&!await A(e.principal,l.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await v(a.nodeId)}}return F(e,n,r,i,a)}try{return await F(e,n,r,i,a)}catch(l){if(l instanceof p&&l.code===ne)throw l;const c=await he(t);throw(c.nodeId===null||await b(c.nodeId)===null)&&await fe(t,c.nodeId),l}}d(di,"keyedCreateOwned");async function F(e,n,t,r,i=void 0){const a=r.deadlineAt??Xt(n.deadline),l=Zt(n.outcome_delivery),c=e.principal.class==="cron"?await hn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await Q(e.principal.cron))?.created_by??null},n.node_id):null;c!==null&&(n.root=c.root===!0);const o=c?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw y("a node create requires a parent (or root: true for an independent root)");let s=null;if(n.output_schema!==void 0){try{s=JSON.parse(n.output_schema)}catch{throw y("output_schema must be a JSON schema string")}if(s===null||typeof s!="object"||Array.isArray(s))throw y("output_schema must be a JSON schema object");await Xn(s)}const m=await ot(n,{validateKind:Me,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:f,kind:u,cwd:_,launch:I}=m;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!C(_)&&await Re(f)===null)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Ce(e,_),n.worktree!==void 0&&await Ce(e,L(n.pin_cwd??n.cwd??_));const k={...n,kind:u},P=l===void 0?void 0:qt(l,_),ie=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await b(o))?.grant_id??null);if(await V(Ae(await Ve(I,ie,n.model)),{cwd:_,profileId:f},t.modelRegistry),await Mt(ie)!=="app"&&!await Wt(f===null?[]:await Bt(f))&&!await jt(m))throw new p(412,"no_provider_credential",Ee,{error:"no_provider_credential",message:Ee,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let x=null;{const re=i===void 0||i.nodeId===null||i.state==="warm_claimed"?ni(k,_,f):null,O=re!==null&&!(n.start===!0&&await Re(f)!==null)?re:null,B=s===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{s!==null&&await Qn(g,"terminal",s),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=O===null?null:await tt(O,i.nodeId,B);if(g===null)throw await fe(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await me(i.requestKey,g),{status:201,body:await v(g)}}if(O!==null){const g=await nt(O,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await me(i.requestKey,g),ke(O),{status:201,body:await v(g)};x=O}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ue());if(i!==void 0&&i.nodeId===null){const g=await Ze(i.requestKey,D,$e);if(g!==D)return await Ne(e,i.requestKey,g)}const R=ei(D===void 0?k:{...k,node_id:D},o,_);c!==null&&(c.rootLifecycle!==void 0&&(R.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&k.scopes===void 0&&(R.scopes=c.scopes),c.run!==void 0&&(R.run=c.run),c.withinCreate!==void 0&&(R.withinCreate=c.withinCreate)),a!==void 0&&(R.deadlineAt=a),P!==void 0&&(R.outcomeDelivery=P),R.readiness=n.root===!0?"await":"launch",Vt("handler_checks",Jt());const oe=await ze(R,B,()=>{x!==null&&ke(x)});return i!==void 0&&await Xe(i.requestKey,oe.node.node_id),{status:201,body:await Ht("response_detail",()=>v(oe.node.node_id))}}}d(F,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw y(`${n} must appear at most once`);return t[0]}d(S,"singleQueryValue");function te(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw y(`${n} must be true or false`)}}d(te,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw y(`${n} must be one of: ${t.join(", ")}`)}}d(G,"oneOf");function si(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[I]of e.query)if(!n.has(I))throw y(`unknown nodes query parameter: ${I}`);const t=G(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=G(S(e,"mode"),"mode",["base","orchestrator"]),l=S(e,"profile_id"),c=S(e,"profile_prefix"),o=S(e,"parent"),s=te(S(e,"top_level"),"top_level"),m=S(e,"under"),f=te(S(e,"under_inclusive"),"under_inclusive"),u=te(S(e,"hanging"),"hanging"),_=G(S(e,"include"),"include",["activity"]);if(o!==void 0&&s===!0)throw y("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...l!==void 0?{profile_id:l}:{},...c!==void 0?{profile_prefix:c}:{},...o!==void 0?{parent:o}:{},...s!==void 0?{top_level:s}:{},...m!==void 0?{under:m}:{},...f!==void 0?{under_inclusive:f}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}d(si,"parseListQuery");async function li(e){const n=si(e);let t=await qe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await Ot(e.principal);r!==null&&(t=t.filter(o=>r.has(o.node_id)));const i=n.include==="activity"?await fn(t.map(o=>o.node_id)):null,a=t.length>0?xe():new Set,l=new Map((await rn()).map(o=>[o.nodeId,o.controllerId]));return{status:200,body:await Oe(t,async o=>{const s=await yt(o,o.profile_id!==null&&a.has(o.profile_id),l.get(o.node_id)??null);if(i!==null){const m=await Se(o.node_id);s.activity={latest_report:m[0]??null,final_report:o.final_report===null?null:m.find(f=>f.name===o.final_report)??null,pending_human_count:i[o.node_id]??0}}return s})}}d(li,"handleList");async function ci(e){const n=e.params.id,t=await Tt(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:Ct(e)});if(t.kind==="unknown")throw Nt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw $t(t.status,t.body);return{status:t.status,body:Pt(t.body,t.machine)}}return await h(n),{status:200,body:await v(n)}}d(ci,"handleDetail");async function ui(e){const n=e.params.id;await h(n);const t=await Sn(n),r=t.snapshot.messages.slice(-J).map(l=>En(l,n)),i=Rn(r);return{status:200,body:{node_id:n,snapshot:{messages:r,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds.slice(-J)},messageVisibility:t.snapshot.messageVisibility.slice(-J),turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:Object.fromEntries(Object.entries(t.snapshot.toolGroupSummaries).filter(([l])=>i.has(l)))},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(l=>({name:l.name,description:l.description,source:l.source})),captured_at:U()}}}d(ui,"handleSnapshot");async function fi(e){const n=e.params.id,t=await On(n);if(t===null)throw N(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(fi,"handleSubject");function pi(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw y(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw y("cursor must appear at most once");if(t.length>1)throw y("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw y("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(pi,"parseMessagesQuery");async function mi(e){const n=e.params.id,t=await vn(n,pi(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:U()}}}d(mi,"handleMessages");async function wi(e){const n=e.params.id;await h(n);const t=await kn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:U()}}}d(wi,"handleSession");async function hi(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await In(n)}}}d(hi,"handleTranscript");async function yi(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await b(i))?.name??i,dir:await _e(i),self:a,files:await Yt(i)}),"root"),r=await Ut([await t(n,!0),...await Oe(await ye(n),async i=>await t(i.node_id,!1))],async i=>await _i(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}d(yi,"handleContext");async function _i(e,n){try{return yn(await z(e),n)}catch(t){if(gn(t))return!1;throw t}}d(_i,"hasDir");async function gi(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>E(t,a)),...t.filter(a=>E(n.scopes,a))])],i=await Ke(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await v(i.node.node_id)}}d(gi,"handleFork");const bi=1e4;async function vi(e){const n=e.params.id,t=await h(n),r=await Z(n);if(r===null||r.runner!=="machine")throw new w({error:"not_hanging",message:`${n} has no live broker on a Mac \u2014 nothing to kick here.`,next:`Use \`crtr node lifecycle revive ${n} --now\` from the CLI, which kicks a local broker directly.`});if(!St(t.fault??null))throw new w({error:"not_hanging",message:`${n} is live but has no pi\u2192provider fault eligible for --now.`,next:"Use --now only on a node the canvas shows as hanging (\u26A0) with a `pi\u2192provider` fault."});if(t.streaming===!0)throw new w({error:"busy",message:`${n} is mid-turn right now (busy) \u2014 refusing to stop a working engine.`,next:"Re-check the canvas \u2014 if it is no longer marked hanging (\u26A0), nothing to do."});await bt(n,{afterTurn:!1,reason:"revive_now"});const i=await vt("machine").stop(r,{reason:"revive_now"});if(!i.confirmed)throw i.error??new Error(`stop of ${n} on its Mac was not confirmed`);return await gt(r.executionId,{reason:"revive_now"}),await se(n,{resume:!0,capacity:"refuse"}),{status:200,body:{kicked:!0}}}d(vi,"handleKick");async function ki(e){const n=e.params.id,t=await h(n),r=e.body,i=r?.resume??!0,a=r?.reopen??!1;await Pn(n,a,e.principal.class==="broker"?e.principal.node:null);const l=!i&&r?.cron_id!==void 0?await Q(r.cron_id):null,c=await Z(n);if(i&&c!==null&&c.runner!=="process"&&c.state==="running"&&!lt(t.profile_id))try{await ft({node_id:n,sub:t.sub??null,profile_id:t.profile_id??null},()=>kt(c))}catch(u){if(!(u instanceof ut))throw u}const o=await se(n,{resume:i,capacity:"refuse",...l!==null?{wakeReason:await pt(l,"schedule_revive")}:{}});o.outcome!=="already-live"&&await en(n,{failures:0,notBefore:null});const s=(await b(n))?.status??"active",m=(o.launch??M().get(n)?.handle)?.exited,f=o.outcome!=="frozen"&&await be(n,m,bi);return{status:200,body:_t(n,o,s,f)}}d(ki,"handleRevive");async function Si(e){const n=e.params.id;return{status:200,body:{newNodeId:(await Nn(n))?.newNodeId??null}}}d(Si,"handleRelaunchRoot");async function Ii(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw y("caller_pid must be a positive integer when provided");const r=mt(),i=new Promise(l=>{e.res.once("close",()=>l())}),a=await Ue(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:ht(a)}}d(Ii,"handleClose");async function Ri(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await on(n),{status:204}}d(Ri,"handleMarkRead");async function Ei(e){const n=e.params.id;await h(n);const t=await $n(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Ei,"handleRecycle");async function Oi(e){const n=e.params.id;return await h(n),await H(n,{lifecycle:"terminal"}),await T(e,n,["lifecycle"]),{status:200,body:await v(n)}}d(Oi,"handleDemote");async function Ai(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Te(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await Tn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await T(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const l=await X(a.meta,await q(t));return l.roadmap_written=a.roadmapWritten,l.roadmap_ref=a.roadmapRef,l.goal_path=a.goalPath,{status:200,body:l}}d(Ai,"handlePromote");async function Ti(e){const n=e.params.id;return await h(n),{status:200,body:{request:await Ln(n)}}}d(Ti,"handleBrokerStructuredRequest");async function Ci(e){const n=e.params.id,t=e.body??{};if(await Dn(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await h(n),{status:200,body:{captured:await Fn(n,t.text)}}}d(Ci,"handleBrokerGoal");async function $i(e,n={}){const t=e.params.id,r=await h(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await Te(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await Mn(t,a);const l=await Cn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await X(l.meta,await q(t))}}d($i,"handleYield");async function Ni(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw y("a wait requires a controller node id");const r=await b(t.controller);if(r===null)throw N(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await tn(n,t.controller),{status:200,body:await v(n)}}d(Ni,"handleWait");async function Pi(e){const n=e.principal,t=await An(n.class==="broker"?async i=>i.grantee===n.app&&await A(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await A(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Pi,"handleReviveAll");const Di=new Set(["interrupt","steer","after-turn","next-turn"]);function Li(e){if(e===null)return null;const n=d(r=>{throw new w({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!Di.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(Li,"listenJson");async function T(e,n,t,r){t.length===0&&r===void 0||await K(async i=>{if(r?.(i),t.length===0)return;const a=await an(i,n),l=await ln(i,e),c=l.class==="person"?l.person:l.class==="app"?l.app:l.node;await dn(i,c,a),await sn(i,{event:"configured",object:a,actor:c,attrs:{changed:t.join(",")}})})}d(T,"recordConfigured");function Pe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(Pe,"restartLiveBroker");function De(e,n){try{return ae(e)===ae(n)}catch{return!1}}d(De,"sameDirectory");async function Mi(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new w({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new w({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(f=>f!=="profile"&&f!=="restart"&&i[f]!==void 0))throw new w({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await h(t),s=await dt(e,i.profile);st(s.profileId);const m=ct(s.profileId).manifest.grantee??"app:terminal";if(m!==(o.grantee??"app:terminal"))throw new w({error:"profile_grantee_mismatch",message:`profile ${s.profileId} belongs to ${m}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==s.profileId&&(rt(o.kind)?(await Y(o.kind,o.cwd,s.profileId),await H(t,{profileId:s.profileId})):await $(t,{profile_id:s.profileId}),await T(e,t,["profile"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new w({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new w({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const s=await h(t),m=C(s.cwd);if(i.keep_session===!0||m&&W(o)&&C(o)&&De(s.cwd,o)){if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=de(u).isDirectory()}catch{}if(!_)throw new w({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(m&&!De(s.cwd,u))throw new w({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${s.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(s.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const I=s.cwd;return I!==u&&(await K(async k=>{await $(t,{cwd:u}),await k.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,I),await cn(t,I,u)}),await T(e,t,["cwd"])),i.restart===!0&&Pe(t),{status:200,body:await v(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(s.fork_from!=null)throw new w({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${s.cwd}`,received:o,field:"cwd",next:`Restore ${s.cwd}, then revive the fork normally.`});if(s.managed_worktree?.state==="open")throw new w({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(C(s.cwd))throw new w({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${s.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!W(o))throw new w({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const f=L(o);if(!C(f))throw new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!de(f).isDirectory())throw new w({error:"cwd_not_a_directory",message:`cwd is not a directory: ${f}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof w?u:new w({error:"cwd_missing",message:`cwd does not exist: ${f}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await K(async()=>{await $(t,{cwd:f}),await un(t)}),await T(e,t,["cwd"]),{status:200,body:await v(t)}}let a=await h(t);const l=i.listen===void 0?void 0:Li(i.listen);if(i.scopes!==void 0){const o=Ie(i.scopes),s=a.grantee==="app:terminal"?await Ft(a):a.grant_id?await Lt(a.grant_id):null;if(!o.every(m=>E(a.scopes,m)&&s!==null&&E(s.resolved,m)))throw new w({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!E(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await $(t,{scopes:o})}if(i.situational_context!==void 0&&await Be(t,We(i.situational_context)),i.model!==void 0){const o=(await ge(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,s=Un(i.model,o),m=await Gt(a.grant_id,i.model,s===void 0),f=m?{family:xt,strength:m.strength}:s,u=m?m.model:Vn(i.model,o);await V({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let I=!1;if(await _.isClaimed(t)&&((await Z(t))?.runner==="machine"||await be(t,_.get(t)?.handle.exited))&&(I=await Jn(t,u,f,await Hn(t)).then(()=>!0,k=>{if(k instanceof Yn)return!1;throw k})),!I){if(await _.isClaimed(t)){const k=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",k,{error:"broker_not_ready",message:k,received:i.model,field:"model",next:"Check the node with `crtr node inspect show`, then retry the model change."})}if(!u.includes("/"))throw y(`model must resolve to a provider/id spec: ${i.model}`);await zn(t,u,f)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Me(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,s=i.mode??a.mode,m=i.lifecycle??a.lifecycle;let f;s==="orchestrator"&&!await xn(t)&&(f=d(async()=>{const u=await jn(t);await Gn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await H(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:s}:{},...i.lifecycle!==void 0?{lifecycle:m}:{}},f)}i.name!==void 0&&(a=await $(t,{name:i.name}),a.window&&Bn(a.window,at(a)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await T(e,t,c,l===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(l,t)}),{status:200,body:await v(t)}}d(Mi,"handleConfig");async function Le(e="app:terminal"){return(await ge(process.cwd(),Ge()||null,e)).kinds}d(Le,"daemonKinds");async function Me(e,n="app:terminal"){const t=Object.keys(await Le(n));if(!t.includes(e))throw y(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(Me,"assertKindServer");async function ji(){const e=await Le();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(ji,"handleListKinds");const bo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:ri},{method:"GET",pattern:"/v1/nodes",handler:li},{method:"GET",pattern:"/v1/kinds",handler:d(()=>ji(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Pi},{method:"GET",pattern:"/v1/nodes/:id",handler:ci},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:ui},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:fi},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:mi},{method:"GET",pattern:"/v1/nodes/:id/session",handler:wi},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:hi},{method:"GET",pattern:"/v1/nodes/:id/context",handler:yi},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:gi},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:ki},{method:"POST",pattern:"/v1/nodes/:id/kick",scope:"crtr:act",handler:vi},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Si},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ii},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ri},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ei},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Oi},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Ai},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:$i},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ti},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Ci},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Ni},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Mi}];export{Mi as handleConfig,ri as handleCreate,gi as handleFork,li as handleList,Ai as handlePromote,$i as handleYield,bo as nodeRoutes,So as resolveCreateKind};
|
package/dist/daemon/fleet.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ export type DeadNodeRow = Pick<NodeMeta, 'status' | 'intent' | 'pi_session_id' |
|
|
|
36
36
|
* `pendingWake` is the one non-row input (`hasPendingWake`): whether anything
|
|
37
37
|
* would drive a turn if the engine came back. It selects row 4b and defaults
|
|
38
38
|
* to `true`, so an uninformed caller keeps the conservative respawn. */
|
|
39
|
-
export declare function classifyDeadNode(row: DeadNodeRow | null, busy: boolean, pendingWake?: boolean): DeadNodeAction;
|
|
39
|
+
export declare function classifyDeadNode(row: DeadNodeRow | null, busy: boolean, pendingWake?: boolean, admittedTurn?: boolean): DeadNodeAction;
|
|
40
40
|
export interface DaemonFleetOpts {
|
|
41
41
|
/** This daemon's epoch id (randomBytes(8).toString('hex'), minted by
|
|
42
42
|
* runDaemon after the ownership claim). */
|
package/dist/daemon/fleet.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R}from"../core/canvas/index.js";import{revokeExitedNodeToken as T}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as N,endExecution as y,hasLaunchingExecution as S,hasProfilePauseStop as F,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as C,markProfilePauseStop as k,recordExecutionExit as O,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as
|
|
1
|
+
var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R}from"../core/canvas/index.js";import{revokeExitedNodeToken as T}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as N,endExecution as y,hasLaunchingExecution as S,hasProfilePauseStop as F,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as C,markProfilePauseStop as k,recordExecutionExit as O,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as A}from"../core/profiles/manifest.js";import{fullName as p}from"../core/canvas/labels.js";import{isSafeNodeId as o}from"../core/canvas/paths.js";import{hasIdleReleaseIntent as z,transition as v}from"../core/runtime/lifecycle.js";import{publishNotice as L}from"../core/runtime/close.js";import{hasAdmittedTurn as B,readFault as D,readInterruptedTurn as W,readTransportPoisonVerdict as q}from"../core/canvas/recovery.js";import{hasPendingWake as G}from"./reconcilers/live-obligation.js";import{clearRespawnPolicy as h,deferRespawnWhileOffline as H,MAX_RESPAWN_ATTEMPTS as Y,OFFLINE_RESPAWN_RETRY_MS as U,recordRespawnPolicy as V,respawnBackoffMs as j}from"./reconcilers/node-lifecycle/respawn-policy.js";import{probeOnline as K}from"../core/runtime/connectivity.js";import{runnerForExecution as X}from"../core/runtime/runner/index.js";import{reviveNode as J}from"../core/runtime/revive.js";import{isStartRefusal as Q}from"../core/runtime/start-check.js";import{MachineOfflineError as Z}from"../core/runtime/runner/machine/ops.js";import{pushUrgent as m}from"../core/feed/feed.js";import{emitEvent as u}from"../core/events/emit.js";import{brokerThresholdsForDaemon as I}from"../core/runtime/fleet.js";import{isRecoveryHeld as ee}from"../core/runtime/recovery-hold.js";async function E(i,e){const r=await D(i.node_id),t=r===null?"":`The broker reported a ${r.kind} fault on ${r.link} (${r.op}) before it exited: ${r.message}
|
|
2
2
|
|
|
3
3
|
`,s=e===void 0?"The daemon did not observe an exit status.":`The observed exit status was code ${e.code??"null"}, signal ${e.signal??"null"}.`;return`\u26A0 Spawn failed \u2014 \`${i.name}\` (${i.kind}) never started.
|
|
4
4
|
|
|
@@ -8,14 +8,14 @@ Its pi vehicle exited before the session came up (no pi_session_id was ever reco
|
|
|
8
8
|
|
|
9
9
|
If the work still needs doing, re-spawn it.`}l(E,"bootFailureBody");async function $(i,e){await m(i.node_id,await E(i,e),{from:i.node_id})}l($,"surfaceBootFailure");function x(i){return`\u26A0 Out of memory \u2014 \`${i.name}\` (${i.kind}) was killed because its app's processes together passed the app's memory limit.
|
|
10
10
|
|
|
11
|
-
Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function
|
|
11
|
+
Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function te(i){const e=await q(i.node_id),r=e===null?"":`
|
|
12
12
|
|
|
13
13
|
Provider rotation observed ${e.consecutivePasses} consecutive route-queue passes with no HTTP response (tried ${e.routes.join(", ")}). Check network and provider transport before reviving.`,t=`\u26A0 Crash loop \u2014 \`${i.name}\` (${i.kind}) kept dying without settling a turn.
|
|
14
14
|
|
|
15
15
|
Its session started successfully, but six consecutive relaunches made no progress, so the daemon stopped retrying.`+r+`
|
|
16
16
|
|
|
17
|
-
Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(
|
|
17
|
+
Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(te,"surfaceCrashLoop");async function re(i,e){const r=e instanceof Error?e.message:String(e),t=`\u26A0 Recovery failed \u2014 \`${i.name}\` (${i.kind}) could not be relaunched.
|
|
18
18
|
|
|
19
19
|
The daemon refused this recovery before starting a broker: ${r}
|
|
20
20
|
|
|
21
|
-
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(
|
|
21
|
+
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(re,"surfaceRecoveryFailure");function ie(i){return i?.cycle_pending!==!0}l(ie,"retryResumeMode");function se(i,e,r=!0,t=!1){return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?"forget":i.intent==="refresh"?"respawn-fresh":z(i)?"dormant":i.lifecycle==="resident"&&!e&&!r&&(i.pi_session_id!=null||t)?"release-idle":i.pi_session_id!=null?ie(i)?"respawn-resume":"respawn-cycle":e||t||i.fork_from!=null?"respawn-fresh":"boot-failure"}l(se,"classifyDeadNode");const ae=3e4;class Re{static{l(this,"DaemonFleet")}#a;#n;#r;#o;#e=new Map;#t=new Set;#l=Number.NEGATIVE_INFINITY;constructor(e){this.#a=e.epoch,this.#n=e.enqueue,this.#r=e.now??Date.now,this.#o=e.probeOnline??(()=>K())}epoch(){return this.#a}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}async has(e){return this.#e.has(e)||await b(e)}async isClaimed(e){return this.#e.has(e)||this.#t.has(e)||await b(e)||await S(e,this.#a)}get(e){return this.#e.get(e)}size(){return this.#e.size}async#c(){const e=await C();for(const r of this.#e.keys())e.add(r);for(const r of this.#t)e.add(r);return e}async occupancy(){return(await this.#c()).size}async reserveSlot(e){if(this.#t.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=I(),t=await this.#c();if(this.#t.has(e)||this.#e.has(e))return!0;if(t.delete(e),t.size<r)return this.#t.has(e)||this.#t.add(e),!0;const s=this.#r();return s-this.#l>=ae&&(this.#l=s,u({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:t.size,hard_cap:r}})),!1}releaseReservation(e){this.#t.delete(e)}entries(){return this.#e.entries()}async interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r===void 0){const t=await g(e);if(t===null||t.runner==="process"||t.state!=="running")return;await k(e),(await X(t.runner).stop(t,{reason:_})).confirmed&&await y(t.executionId,{reason:_});return}await k(e);try{process.kill(r,"SIGTERM")}catch{}}async hasProfilePauseInterruption(e){return await F(e)}forget(e){this.#e.delete(e),this.#t.delete(e)}#i=new Set;async exitsSettled(){for(;this.#i.size>0;)await Promise.allSettled([...this.#i])}async onChildExit(e,r,t){const s=this.#u(e,r,t);this.#i.add(s);try{await s}finally{this.#i.delete(s)}}async#u(e,r,t){const s=t??(await g(e))?.executionId;t&&await T(t),this.#e.delete(e),s!==void 0&&(await O(s,r),await y(s,{reason:"exited"})),this.#n(async()=>{const a=await w(e),n=a?.launched_at==null?Number.NaN:Date.parse(a.launched_at),d=Number.isFinite(n)?Math.max(0,this.#r()-n):null,f=a?.respawn_failures??0;this.#f(e,r,d,f)})}async deliverExit(e,r){await this.onChildExit(e,r)}async applyDeadRowPolicy(e){await this.#h(e,await M(e))}async terminalizeIfStillNonTerminal(e,r,t,s,a){const n=await w(e);return n===null||n.status==="done"||n.status==="canceled"||n.status==="dead"?!1:(await this.#s(e,n,{event:r,reason:s,detail:a,wake:`Child crashed \u2014 ${p(n)} (${e}) could not be relaunched and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>re(n,t),"surface")}),!0)}dispose(){}#f(e,r,t,s){u({level:"info",event:"broker.exit.observed",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},code:r.code,signal:r.signal,uptime_ms:t,consecutive_failures:s}})}async#h(e,r){return this.#d(e,r)}async#d(e,r){const t=await w(e);if(t!==null&&A(t.profile_id))return await h(e),"forget";if(await N(e))return await h(e),"forget";if(await ee(e))return"dormant";const s=(await W(e))?.interrupted===!0;if(r?.oomKilled===!0&&t!==null&&t.status!=="done"&&t.status!=="canceled"&&t.status!=="dead")return await h(e),await this.#s(e,t,{event:"broker.out_of_memory",reason:"out_of_memory",detail:{schema:"crtr.node-outcome-detail/v1",message:x(t)},wake:`Child out of memory \u2014 ${p(t)} (${e}) used more memory than its app is allowed and is now dead. It is not restarted automatically. Revive it with \`crtr node lifecycle revive ${e}\` once the work needs less memory or the cap is raised (\`crtr sys limits set\`).`,surface:l(async()=>{await m(e,x(t),{from:e})},"surface")}),"forget";const a=se(t,s,await G(e),await B(e));switch(a){case"forget":await h(e);break;case"dormant":await h(e);break;case"release-idle":await h(e),await v(e,"release"),u({level:"info",event:"broker.recovery.released",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e}}});break;case"boot-failure":await this.#s(e,t,{event:"broker.boot.failed",reason:"boot_failed",detail:{schema:"crtr.node-outcome-detail/v1",message:await E(t,r)},wake:`Child crashed \u2014 ${p(t)} (${e}) exited before its session ever came up and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>$(t,r),"surface")});break;case"respawn-fresh":case"respawn-cycle":case"respawn-resume":await this.#p(e,t,a,s);break}return a}async#p(e,r,t,s){const a=await R(e);if(a===null)return;const n=a.respawn_failures??0;if(!await this.#o()){await H(e,n,this.#r()),u({level:"info",event:"broker.respawn.offline_deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,retry_in_ms:U,consecutive_failures:n}});return}const d=a.respawn_not_before==null,f=d?await V(a,this.#r()):{failures:n,notBefore:a.respawn_not_before,exhausted:n>=Y};if(f.exhausted){const c=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${f.failures} consecutive launches) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await this.#s(e,r,{event:"broker.respawn.exhausted",reason:"crash_looped",detail:{schema:"crtr.node-outcome-detail/v1",message:c,respawn_failures:f.failures},wake:c,...r.pi_session_id!=null?{surface:l(()=>te(r),"surface")}:{}});return}if(d&&f.notBefore!==null){u({level:"info",event:"broker.respawn.deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,backoff_ms:j(f.failures),consecutive_failures:f.failures}});return}u({level:"info",event:"broker.respawn.started",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,consecutive_failures:f.failures}});try{await J(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&s?"runtime-restart-abort":void 0,recovery:!0})}catch(c){if(Q(c)||c instanceof Z){await h(e),await v(e,"release"),u({level:"warn",event:"node.start.refused",node_id:e,error:c,fields:{enact:"respawn"}});return}u({level:"error",event:"broker.respawn.failed",...o(e)?{node_id:e}:{},error:c,fields:{...o(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",c,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:c instanceof Error?c.message:String(c)})}}async#s(e,r,t){u({level:"error",event:t.event,...o(e)?{node_id:e}:{fields:{affected_node_id:e}}}),await v(e,"crash",{reason:t.reason,outcome:{detail:t.detail}});try{await(t.surface??(()=>$(r)))()}catch(s){u({level:"error",event:"broker.boot_failure_surface.failed",...o(e)?{node_id:e}:{fields:{affected_node_id:e}},error:s})}await L(e,"notice.crash",t.wake,{reason:"child-crashed",child:e})}}export{Re as DaemonFleet,se as classifyDeadNode,ie as retryResumeMode,$ as surfaceBootFailure};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var k=Object.defineProperty;var o=(e,t)=>k(e,"name",{value:t,configurable:!0});import{getNode as _,getRow as h}from"../../core/canvas/index.js";import{managedWorktreeSweepCandidates as y}from"../../core/canvas/managed-worktree-sweep-candidates.js";import{isSafeNodeId as w}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as S,recordedPidLiveness as v}from"../../core/canvas/pid.js";import{emitEvent as u}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{reconcileManagedWorktree as R}from"../../core/worktree-sweep.js";import{sweepOnMachine as T,worktreeMachineOf as W}from"../../core/worktree-machine.js";import{runThrottledLane as I}from"./throttled-lane.js";const M=60*1e3,O=300*1e3,L=3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)}o(g,"isTerminal");function E(e,t){return t?.state==="closed"||t?.state==="open"&&e.status==="done"&&e.final_report!==null}o(E,"hasSweepDisposition");async function b(e,t,r,s){return await t.isClaimed(e.node_id)||e.frozen_at!==null||!g(e)||!E(e,(await _(e.node_id))?.managed_worktree)?!1:s||v(e.pi_pid,e.pi_pid_identity,r)==="dead"}o(b,"engineIsGone");function A(e,t){const r=e.node_id,s=e.pi_pid,i=e.pi_pid_identity;return{stillEligible:o(async()=>{if(await t.isClaimed(r))return!1;const n=await h(r);return n===null||!g(n)||n.frozen_at!==null||!E(n,(await _(r))?.managed_worktree)?!1:n.pi_pid===s&&n.pi_pid_identity===i},"stillEligible")}}o(A,"eligibilityGuard");class j{static{o(this,"ManagedWorktreeSweepReconciler")}run(t,r){if(!r.lifecycle.acceptsDetachedWork())return;const s=I("managed-worktree-sweep","",t,M,O,i=>this.sweep(t,r.fleet,i)).then(()=>{}).catch(i=>{p.fresh(()=>u({level:"error",event:"worktree.sweep.failed",error:i}))});r.lifecycle.registerDetached(s)}async candidates(t){try{return await y(t)}catch(r){return p.fresh(()=>{u({level:"error",event:"worktree.sweep.scan_failed",error:r})}),null}}async sweep(t,r,s){const i=await this.candidates(t);if(i===null||i.length===0)return;let n=Number(s.state??0);(!Number.isInteger(n)||n>=i.length)&&(n=0);const d=Math.min(L,i.length),l=[];for(let c=0;c<d;c+=1)l.push(i[(n+c)%i.length]);if(!await s.save(String((n+d)%i.length)))return;const a=await S();if(a!==null)for(const c of l){const f=await h(c),m=f===null?null:await W(f.profile_id);if(!(f===null||!await b(f,r,a,m!==null))){if(!await s.holds())return;await this.reconcileOne(f,t,r,m)}}}async reconcileOne(t,r,s,i){const n=t.node_id,d=w(n)?{node_id:n}:{},l=w(n)?{}:{affected_node_id:n};try{const a=await R(n,A(t,s),r,i===null?void 0:T(i,n));p.fresh(()=>{if(a.status==="complete"){u({level:"info",event:"worktree.sweep.reconciled",outcome:"succeeded",...d,fields:l});return}a.status!=="skipped"&&(a.status==="refused"&&a.unchanged===!0||u({level:a.status==="failed"?"error":"warn",event:a.status==="failed"?"worktree.sweep.failed":"worktree.sweep.refused",outcome:a.status==="failed"?"failed":"skipped",...d,fields:{...l,reason:a.reason,...a.detail===void 0?{}:{detail:a.detail}}}))})}catch(a){p.fresh(()=>{u({level:"error",event:"worktree.sweep.failed",...d,error:a,fields:l})})}}}export{j as ManagedWorktreeSweepReconciler,L as WORKTREE_SWEEP_BUDGET,M as WORKTREE_SWEEP_INTERVAL_MS};
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import type { Transport } from '../../core/broker-client/transport.js';
|
|
2
|
+
/** The transport to the node's live broker, from where its runner says viewers connect: this machine's `view.sock`, or
|
|
3
|
+
* the `/view` WebSocket behind a sandbox's preview. */
|
|
4
|
+
export declare function viewTransport(nodeId: string): Promise<Transport>;
|
|
1
5
|
/** What the model is streaming now in a node's open assistant message. */
|
|
2
6
|
export type OpenAssistantBlock = {
|
|
3
7
|
kind: 'thinking' | 'text';
|
|
@@ -3,4 +3,4 @@ var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});i
|
|
|
3
3
|
FROM node_rows n
|
|
4
4
|
LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
|
|
5
5
|
AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
|
|
6
|
-
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers};
|
|
6
|
+
WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,$ as viewTransport};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var J=Object.defineProperty;var l=(r,t)=>J(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as $,envNodeId as G,envProfileId as X,envWatcherDebounceMs as j,envWatcherTickMs as z,envWatcherBackstopMs as L}from"../shared/env.js";import{coalesceBrokerInbox as V,entryCards as Q}from"../core/runtime/broker/inbox.js";import{acknowledgeBrokerMail as Y,claimBrokerMail as K,brokerExtensionState as O,recordConversationWriteFault as Z}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as ee}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as P}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as te,startupClaimsHeld as ie}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as ne}from"../core/runtime/broker/extension-abort.js";import{isDaemonTransportApiError as A,isTokenRevokedApiError as se}from"../api/errors.js";import{announceMessageOrigin as re,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as ae,generateAndCommitInitialName as de}from"./broker-local.js";import{emitEvent as D}from"../core/events/emit.js";import{errorClassFromError as oe}from"../core/events/errors.js";import{operationIdContext as g}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as x}from"../shared/generated-context.js";import{isProfilePaused as fe}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as le,brokerRunTurnBusy as he,brokerRunSteer as _,HELD_DEFERRED_INBOX_PROMPT_JOIN as ue}from"../core/runtime/broker/held-deferred-inbox.js";const E=64,U=16;let v,ce=0;class q extends Error{static{l(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function me(){return{tickMs:z(),debounceMs:j()}}l(me,"resolveCadence");function T(){const r=G();return r===void 0||r.trim()===""?void 0:r}l(T,"currentNodeId");function B(){const r=X();return r!==void 0&&r!==""&&fe(r)}l(B,"profilePaused");function S(r){try{return oe(r)}catch{return{class:"unknown"}}}l(S,"safeErrorClass");function w(r){try{D(r)}catch{}}l(w,"emitBestEffort");function I(r){try{g.fresh(t=>{w({...r,operation_id:t})})}catch{}}l(I,"emitFreshBestEffort");function F(r,t){try{g.run(r,()=>{w({...t,operation_id:r})})}catch{}}l(F,"emitStoredBestEffort");function pe(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}l(pe,"deliveryOrigin");function k(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-U;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,U),...i>0?{sourceOperationIdsOmitted:i}:{}}}l(k,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}l(b,"deliveryFields");function ye(r){F(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}l(ye,"emitDeliveryCompleted");function M(r,t,e,i){F(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:e,...b(t)}})}l(M,"emitDeliveryFailure");function R(r,t){F(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}l(R,"emitDeliveryAbandoned");function ge(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
-
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return String(s?.message).startsWith("conversation_write_failed")&&(D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"conversation_write_failed"}}),await Z(t,s),H()?.("conversation_write_failed",1)),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|
|
2
|
+
`):""}l(ge,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}l(W,"isSessionShutdownReason");function be(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}l(be,"disposalReasonForShutdown");function ve(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}l(ve,"boundedRuntimeReason");class we{static{l(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;polledOk=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=$();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=l((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(d=>d.awaitingDequeue!==void 0))return;const n=C(ge(i.content)),s=this.pendingHandoffs.find(d=>d.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=T();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?be(i):"reload";W(i)||I({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ve(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=P();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=T();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const d of this.signalUnsubscribers.splice(0))d();const s=n;{const d=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of d)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=P().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),L()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&he())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),I({level:"error",event:t,outcome:"failed",error:i,error_class:S(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ie()){this.waitingForStartup||(this.waitingForStartup=!0,te(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}const e=this.tick().then(()=>{this.retryNeeded=!1,this.polledOk=!0}).catch(i=>{if(this.canMutate()){if(A(i)){this.retryNeeded=!0,I({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:S(i),fields:{stage:"poll"}});return}if(this.polledOk&&se(i)){this.clearTimer(),I({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await K(t,"wake",this.reportBodies)}catch(a){throw A(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let d=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ee(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?g.fresh(o=>{this.pendingHandoffs.push({...k([a.entry],"visible"),operationId:o,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),d=!0))}return d&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=T();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||B()||this.pendingHandoffs.length>=E||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&_()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=_()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&_()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(u=>u.entry_id)),s=new Set(i.map(u=>u.entry_id)),d=t.filter(u=>n.has(u.entry_id)||s.has(u.entry_id)),a=this.isIdle()&&d.length>0&&d.every(u=>u.tier==="deferred"),f=this.visibleRoute(i)==="critical",o=!a&&!f&&e.length>0,m=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(o)+Number(m)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await O(t)).situational_card}catch(d){this.raiseSituationalFatal(n,d)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return V(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=E&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let d;try{d=k(e,t)}catch(o){this.raiseReadFatal(n,o)}let a;try{g.fresh(o=>{a=o,w({level:"info",event:"inbox.delivery.started",operation_id:o,fields:b(d)}),i()})}catch(o){return a===void 0&&this.raiseReadFatal(n,o),M(a,d,"send",o),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...d,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,d){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(o=>o.entry_id)}),i.forEach((o,m)=>{const u=s&&m===i.length-1;this.pi.sendMessage({customType:x,content:o,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:u?{deliverAs:"followUp",triggerTurn:!0}:{})})},d,f)}sendVisible(t,e,i,n,s,d){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:x,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(re(i,n),s==="idle"){const a=le();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},d,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(d=>e.has(d.entry_id)),n=new Set(i.map(d=>d.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const o of e.visibleEntries)n.add(o.entry_id);for(const o of e.hiddenEntries)n.add(o.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id))};if(this.runNode&&s==="steer"){let o=-1;e.visibleEntries.forEach((h,y)=>{this.isRunSteer(h)&&(o=y)});const m=e.visibleEntries.slice(0,o+1);if(e.hiddenEntries.length>0||m.some(h=>h.kind!=="message"||h.tier==="deferred"||(h.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};const u=this.digest(m,i),c=u.map(h=>({text:h.text,messageIds:h.entries.map(y=>y.entry_id),cards:h.cards}));if(_()?.accept(c)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(h=>h.entry_id))};for(const h of u){const y=k(h.entries,"visible");g.fresh(N=>{w({level:"info",event:"inbox.delivery.started",operation_id:N,fields:b(y)}),this.pendingHandoffs.push({...y,operationId:N,settlesThroughBridge:!0})})}const p=new Set(m.map(h=>h.entry_id));for(const h of e.visibleEntries)p.has(h.entry_id)||n.add(h.entry_id);for(const h of e.hiddenEntries)n.add(h.entry_id);return{inactive:!1,requeueEntryIds:n}}const d=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=d;for(const o of f)for(const m of o.entries)n.add(m.entry_id);if(e.hiddenEntries.length>0){const o=await this.contextCards(t,e.hiddenEntries),m=this.sendContext(t,e.hiddenEntries,o,s,a===void 0,i);if(m==="inactive")return{inactive:!0,requeueEntryIds:n};if(m==="failed")for(const u of e.hiddenEntries)n.add(u.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const o=this.sendVisible(a.entries,a.cards,a.text,pe(a),s,i);if(o==="inactive")return{inactive:!0,requeueEntryIds:n};if(o==="failed")for(const m of a.entries)n.add(m.entry_id);else a.kind==="human"&&(await ae(t,a.text).catch(()=>{}),de(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>E)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||B())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>E)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const d of i)await this.sendPromptJoinDelivery(t,"visible",d.entries,[...d.cards,d.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=k(i,e)}catch(f){this.raiseReadFatal("poll",f)}let d;try{await g.fresh(async f=>{d=f,w({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const o of n)await t.sendCustomMessage({customType:x,content:o,display:!0})})}catch(f){throw d===void 0&&this.raiseReadFatal("poll",f),M(d,s,"send",f),f}d===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:d,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Y(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const d of e.receipts){const a=s.results.find(f=>f.delivery_id===d.delivery_id);if(a?.outcome!==d.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(d=>d.outcome==="acknowledged")}catch(s){if(this.pendingCommit===e)for(const d of e.handoffs)M(d.operationId,d,"receipt_commit",s);return D({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await Z(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>!s.has(d.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(d=>!this.claims.has(d)));for(const s of n)i&&ye(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ne(),d=!s&&this.pendingHandoffs.some(c=>c.awaitingDequeue!==void 0)&&await this.nodeRefreshing(t);if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const a=new Set(this.buffer.map(c=>c.entry_id)),f=new Set(d?this.pendingHandoffs.filter(c=>c.awaitingDequeue!==void 0).flatMap(c=>[...c.entryIds]):[]),o=this.pendingHandoffs.filter(c=>(n||c.settleAtAgentSettled!==!0)&&c.entryIds.every(p=>!f.has(p))),m=new Set(o.flatMap(c=>[...c.entryIds])),u=[...this.claims.keys()].filter(c=>s||m.has(c)&&!a.has(c));return u.length===0?"settled":(this.pendingCommit={handoffs:o,entryIds:u,receipts:u.map(c=>{const p=this.claims.get(c);return{delivery_id:p.delivery_id,attempts:p.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}async nodeRefreshing(t){try{return(await O(t)).node.intent==="refresh"}catch{return!0}}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function _e(r,t){v?.dispose("reload",!1);const e=new we(r,t,++ce);v=e;const i=l(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ue]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}l(_e,"installWatcher");function Ee(r){const t=_e(r,me());return()=>t.dispose("shutdown",!1)}l(Ee,"registerCanvasInboxWatcher");var Be=Ee;export{Be as default,Ee as registerCanvasInboxWatcher};
|