@north-light/cli 0.3.534 → 0.3.536
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -0
- package/dist/api/client.js +3 -3
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/api/dto/recovery.d.ts +2 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +1 -1
- package/dist/clients/attach/viewer.js +406 -406
- package/dist/commands/api-client.d.ts +1 -0
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/node/inspect.js +9 -9
- package/dist/core/bash-jobs.d.ts +4 -0
- package/dist/core/bash-jobs.js +8 -8
- package/dist/core/canvas/canvas.d.ts +26 -2
- package/dist/core/canvas/canvas.js +19 -19
- package/dist/core/canvas/crons.d.ts +4 -2
- package/dist/core/canvas/crons.js +1 -1
- package/dist/core/canvas/paths.d.ts +5 -0
- package/dist/core/canvas/paths.js +1 -1
- package/dist/core/canvas/recovery.d.ts +7 -0
- package/dist/core/canvas/recovery.js +2 -2
- package/dist/core/canvas/remote-canvas-source.d.ts +1 -0
- package/dist/core/canvas/remote-canvas-source.js +1 -1
- package/dist/core/canvas/source.d.ts +4 -0
- package/dist/core/canvas/source.js +1 -1
- package/dist/core/canvas/tree.d.ts +2 -0
- package/dist/core/canvas/tree.js +12 -5
- package/dist/core/feed/feed.js +3 -3
- package/dist/core/feed/messages.d.ts +6 -0
- package/dist/core/feed/messages.js +5 -5
- package/dist/core/graph/kinds/node.js +5 -5
- package/dist/core/graph/watches.d.ts +0 -2
- package/dist/core/graph/watches.js +7 -12
- package/dist/core/providers/mint.d.ts +2 -0
- package/dist/core/providers/mint.js +1 -1
- package/dist/core/runtime/broker/cli-relay.js +1 -1
- package/dist/core/runtime/broker/fault-retry.d.ts +18 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/run-turn-end.d.ts +3 -2
- package/dist/core/runtime/broker/run-turn-end.js +1 -1
- package/dist/core/runtime/launch.js +2 -2
- package/dist/core/runtime/lifecycle.d.ts +4 -0
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/revive.d.ts +1 -1
- package/dist/core/runtime/revive.js +1 -1
- package/dist/core/worktree-mutation-async.d.ts +10 -0
- package/dist/core/worktree-mutation-async.js +5 -5
- package/dist/core/worktree-sweep.js +6 -6
- package/dist/core/worktree.d.ts +1 -0
- package/dist/core/worktree.js +1 -1
- package/dist/daemon/api/handlers/broker-recovery.js +1 -1
- package/dist/daemon/api/handlers/messages.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/messaging/node-message.js +1 -1
- package/dist/daemon/peer/forward.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.d.ts +6 -0
- package/dist/daemon/reconcilers/bash-deadline.js +3 -2
- package/dist/daemon/runs/observer.d.ts +2 -0
- package/dist/daemon/runs/observer.js +2 -2
- package/docs/sdk/release-notes.md +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +12 -12
- package/dist/core/canvas/nav-model.d.ts +0 -44
- package/dist/core/canvas/nav-model.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var q=Object.defineProperty;var
|
|
2
|
-
`))if(e.startsWith("worktree "))return e.slice(9).trim();return null}
|
|
3
|
-
`))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&s===`branch refs/heads/${r}`&&
|
|
4
|
-
${
|
|
5
|
-
`).map(p=>p.trim()).filter(p=>p!==""),
|
|
6
|
-
${k}`}}
|
|
1
|
+
var q=Object.defineProperty;var c=(t,e)=>q(t,"name",{value:e,configurable:!0});import{createHash as z}from"node:crypto";import{existsSync as w,realpathSync as Q}from"node:fs";import{isAbsolute as V,relative as j,resolve as v,sep as G}from"node:path";import{completeCleanup as J,getNode as E,recordSweepAttempt as X,resumableNodeCwds as Y}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as Z}from"./exclusive-lock.js";import{gitAsync as d}from"./git.js";import{proveBranchContained as D,upstreamTip as I}from"./worktree-containment.js";import{parseStatusPorcelain as tt,planLandIntoCheckout as et,refDeleteTransactionStdin as at}from"./worktree-landing.js";import{shellQuote as rt}from"../shared/shell-quote.js";import{deleteTrashAsync as st,removeWorktreeCheckoutAsync as B}from"./worktree-remove.js";import{WORKTREE_LOCK_WAIT_MS as nt,canonicalPath as L,checkoutPathForBranchInList as M,samePath as C,worktreeLockPathForCommonDir as it}from"./worktree.js";const A=[2,5,15,30,60],ot=A.length;function S(t){return t==null||t.state==="abandoned"?!1:t.state==="open"||t.cleanup!=="complete"}c(S,"isReconcilable");function Ht(t,e){const r=t.sweep?.next_attempt;if(r===void 0)return!0;const a=Date.parse(r);return Number.isNaN(a)||a<=e}c(Ht,"isDueForSweep");async function m(t,e){const r=await d(["rev-parse","--verify","--quiet",e],t);return r.status===0?r.stdout.trim():null}c(m,"revParseRef");function h(t){return(t.stderr.trim()||t.stdout.trim()).trim()}c(h,"detailOf");async function F(t){const e=await d(["rev-parse","--git-common-dir"],t);if(e.status!==0)return null;try{return Q(v(t,e.stdout.trim()))}catch{return null}}c(F,"commonGitDirAsync");async function lt(t){for(const e of["rebase-merge","rebase-apply"]){const r=await d(["rev-parse","--git-path",e],t);if(r.status!==0)return null;if(w(v(t,r.stdout.trim())))return!0}return!1}c(lt,"isRebaseInProgressAsync");function ut(t){for(const e of t.split(`
|
|
2
|
+
`))if(e.startsWith("worktree "))return e.slice(9).trim();return null}c(ut,"mainWorktreePath");function ct(t,e,r){let a=null;for(const s of t.split(`
|
|
3
|
+
`))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&s===`branch refs/heads/${r}`&&C(a,e))return a;return null}c(ct,"registeredCheckoutPath");async function dt(t){const e=w(t.path),r=e?t.path:t.repo_root,a=await m(r,`refs/heads/${t.base_ref}`),s=await I(r,t.base_ref),n=await m(r,`refs/heads/${t.branch}`);if(!e)return{base:a,upstream:s?.sha??null,branch:n,checkout:"absent"};const i=await d(["rev-parse","HEAD"],t.path),o=await d(["status","--porcelain"],t.path),l=i.status!==0||o.status!==0?null:z("sha256").update(`${i.stdout.trim()}
|
|
4
|
+
${o.stdout}`).digest("hex");return{base:a,upstream:s?.sha??null,branch:n,checkout:l}}c(dt,"observe");function ft(t,e){return t.checkout===null||e.checkout===null?!1:t.base===e.base&&t.upstream===e.upstream&&t.branch===e.branch&&t.checkout===e.checkout}c(ft,"sameObservation");async function ht(t,e,r,a,s,n){if(r.status!=="refused"&&r.status!=="failed"||!await n.stillEligible())return;const i=(e.sweep?.attempts??0)+1,o=A[Math.min(i,A.length)-1]??A[0],l=(await E(t))?.managed_worktree;l==null||!S(l)||await X(t,{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>=ot})}c(ht,"recordUnfinished");async function pt(t,e,r,a,s){const n=await d(["status","--porcelain"],t);if(n.status!==0)return{ok:!1,detail:h(n)};const i=await d(["diff","--name-only",r,a],t);if(i.status!==0)return{ok:!1,detail:h(i)};const o=i.stdout.split(`
|
|
5
|
+
`).map(p=>p.trim()).filter(p=>p!==""),l=et(tt(n.stdout),o);if(l.kind==="refuse")return{ok:!1,detail:`untracked files in ${t} would be overwritten by the incoming commits: ${l.collisions.join(", ")}`};if(!await s.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=c(async()=>{const p=await d(["merge","--ff-only",a],t);return p.status===0?{ok:!0}:{ok:!1,detail:h(p)}},"merge");if(l.kind==="direct")return u();const b=await m(t,"refs/stash"),g=await d(["stash","push","--message",`crtr landing ${e}`],t);if(g.status!==0)return{ok:!1,detail:h(g)};const f=await m(t,"refs/stash");if(f===null||f===b)return u();const k=`local changes from ${t} are retained in stash ${f}; recover them with \`git -C ${rt(t)} stash apply ${f}\` and resolve any conflict.`,_=await u();return _.ok?(await d(["stash","apply",f],t)).status===0?(await U(t,f),{ok:!0}):(await d(["reset","--hard",a],t),{ok:!0,stash:`the shared base checkout was reset to landed commit ${a} because local changes conflicted with it. ${k}`}):(await d(["stash","apply",f],t)).status===0?(await U(t,f),_):{ok:!1,detail:`${_.detail}
|
|
6
|
+
${k}`}}c(pt,"landIntoBaseCheckoutAsync");async function U(t,e){await m(t,"refs/stash")===e&&await d(["stash","drop"],t)}c(U,"dropStashIfStillTip");async function mt(t,e,r){const a=await m(t.path,`refs/heads/${t.base_ref}`);if(a===null)return{ok:!1,detail:`local base branch '${t.base_ref}' does not resolve`};if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const s=await d(["rebase",a],t.path);if(s.status!==0)return await d(["rebase","--abort"],t.path),{ok:!1,detail:h(s)};const n=await m(t.path,"HEAD");if(n===null)return{ok:!1,detail:"could not read the rebased worktree tip"};if((await d(["merge-base","--is-ancestor",a,n],t.path)).status!==0)return{ok:!1,detail:`the rebased branch is not a fast-forward of '${t.base_ref}'`};const i=M(e,t.base_ref);if(i===null){if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=await d(["update-ref",`refs/heads/${t.base_ref}`,n,a],t.path);return u.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:h(u)}}const o=await d(["rev-parse","HEAD"],i);if(o.status!==0||o.stdout.trim()!==a)return{ok:!1,detail:`base checkout ${i} is not at ${a}`};const l=await pt(i,t.branch,a,n,r);return l.ok?{ok:!0,landedSha:n,...l.stash===void 0?{}:{stash:l.stash}}:l}c(mt,"finishBlockedLand");const $={status:"skipped",reason:"node_no_longer_terminal"},x={status:"skipped",reason:"checkout_in_use"};function bt(t,e){const r=j(t,e);return r===""||r!==".."&&!r.startsWith(`..${G}`)&&!V(r)}c(bt,"isWithinDirectory");async function P(t,e){const r=[v(e),L(e)];return(await Y(t)).some(({cwd:a})=>{const s=[v(a),L(a)];return r.some(n=>s.some(i=>bt(n,i)))})}c(P,"checkoutHasDependents");async function Nt(t,e,r=Date.now()){const a=(await E(t))?.managed_worktree;if(!S(a)||a==null)return{status:"skipped",reason:"already_reconciled"};if(w(a.path)&&await P(t,a.path))return x;const s=w(a.path)?a.path:a.repo_root;if(!w(s))return await T(t,a,{status:"refused",reason:"repo_unavailable",detail:`neither the recorded checkout nor repository root exists, so ${a.branch} cannot be proved absent`},{base:null,upstream:null,branch:null,checkout:null},r,e);const n=await F(s);if(n===null)return await T(t,a,{status:"failed",reason:"git_dir_unreadable",detail:`could not resolve the git common dir from ${s}`},{base:null,upstream:null,branch:null,checkout:null},r,e);let i={base:null,upstream:null,branch:null,checkout:null},o;const l=[];try{o=await Z(it(n),async()=>{if(!await e.stillEligible())return $;const u=(await E(t))?.managed_worktree;return!S(u)||u==null?{status:"skipped",reason:"already_reconciled"}:(i=await dt(u),u.sweep!==void 0&&ft(u.sweep.observed,i)?{status:"refused",reason:u.sweep.reason,...u.sweep.detail===void 0?{}:{detail:u.sweep.detail},unchanged:!0}:w(u.path)?await _t(t,u,e,l):await kt(t,u,i,e))},{timeoutMs:nt,timeoutError:c(()=>new Error(`timed out waiting for the managed-worktree lock on ${n}`),"timeoutError")})}catch(u){o={status:"failed",reason:"lock_unavailable",detail:u instanceof Error?u.message:String(u)}}return await st(a.path,l[0]),await T(t,a,o,i,r,e)}c(Nt,"reconcileManagedWorktree");async function T(t,e,r,a,s,n){return await ht(t,e,r,a,s,n),r}c(T,"finish");async function H(t,e,r){if(!await r.stillEligible())return $;const a=(await E(t))?.managed_worktree;return a==null||a.path!==e.path||a.branch!==e.branch?{status:"skipped",reason:"record_changed"}:(await J(t),{status:"complete"})}c(H,"persistComplete");async function kt(t,e,r,a){const s=e.repo_root;if(r.branch===null){const l=await d(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],s);return l.status!==1?{status:"failed",reason:"branch_inspection_failed",detail:h(l)}:await H(t,e,a)}const n=await d(["worktree","list","--porcelain"],s);if(n.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:h(n)};const i=M(n.stdout,e.branch);if(i!==null)return{status:"refused",reason:"branch_checked_out_elsewhere",detail:`${e.branch} is checked out at ${i}`};const o=await D(s,e,r.branch);return o===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`}:K(t,e,s,r.branch,o,a)}c(kt,"concludeAbsentCheckout");async function _t(t,e,r,a){const s=await d(["worktree","list","--porcelain"],e.path);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:h(s)};const n=e.disposal,i=n?.observed_branch??e.branch,o=ct(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 l=ut(s.stdout);if(l===null||C(l,o)||!w(l))return{status:"refused",reason:"repo_unavailable",detail:`the repository's main checkout is unavailable, so ${e.path} cannot be removed from outside itself`};const u=await lt(e.path);if(u===null)return{status:"failed",reason:"git_path_failed",detail:`could not inspect in-progress operations in ${e.path}`};if(u)return{status:"refused",reason:"rebase_in_progress",detail:`${e.path} is mid-rebase`};const b=await d(["rev-parse","--abbrev-ref","HEAD"],e.path);if(b.status!==0)return{status:"failed",reason:"branch_check_failed",detail:h(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 g=await d(["status","--porcelain"],e.path);if(g.status!==0)return{status:"failed",reason:"status_failed",detail:h(g)};if(g.stdout.trim()!=="")return{status:"refused",reason:"dirty_worktree",detail:`${e.path} has uncommitted changes`};let f=await m(e.path,"HEAD");if(f===null)return{status:"failed",reason:"head_unreadable",detail:`could not read HEAD in ${e.path}`};if(n!==void 0){if(await F(e.path)!==n.common_dir||f!==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 r.stillEligible())return $;if(await P(t,o))return x;const{result:W,trash:R}=await B(l,o);return R!==void 0&&a.push(R),W.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:h(W)}:await H(t,e,r)}let k=await D(e.path,e,f),_;if(k===null&&e.land_intent!==void 0){const y=await mt(e,s.stdout,r);if(!y.ok)return y.ineligible===!0?$:{status:"refused",reason:"land_blocked",detail:y.detail};f=y.landedSha,_=y.stash,k=await D(e.path,e,f)}if(k===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 r.stillEligible())return $;if(await P(t,o))return x;const{result:p,trash:N}=await B(l,o);if(N!==void 0&&a.push(N),p.status!==0)return{status:"refused",reason:"worktree_remove_failed",detail:h(p)};const O=await K(t,e,l,f,k,r);return O.status==="complete"&&_!==void 0?{status:"complete",stash:_}:O}c(_t,"reconcilePresentCheckout");async function K(t,e,r,a,s,n){if(!await n.stillEligible())return $;const i=at(e.branch,a,s.containingRef,s.containingSha),o=await d(["update-ref","--stdin"],r,i);return o.status!==0?{status:"refused",reason:"branch_delete_failed",detail:h(o)}:await H(t,e,n)}c(K,"deleteBranchAndComplete");export{Ht as isDueForSweep,S as isReconcilable,Nt as reconcileManagedWorktree};
|
package/dist/core/worktree.d.ts
CHANGED
|
@@ -30,6 +30,7 @@ export declare function checkoutPathForBranchInList(porcelain: string, branch: s
|
|
|
30
30
|
* failures fall back to `resolve`, which is the pre-canonical comparison — no
|
|
31
31
|
* worse than the string compare it replaces. */
|
|
32
32
|
export declare function samePath(a: string, b: string): boolean;
|
|
33
|
+
export declare function canonicalPath(path: string): string;
|
|
33
34
|
export declare const WORKTREE_LOCK_WAIT_MS = 30000;
|
|
34
35
|
/** The lock directory naming one repository's common Git dir. Every process
|
|
35
36
|
* that mutates a managed worktree — the synchronous commands here and the
|
package/dist/core/worktree.js
CHANGED
|
@@ -15,4 +15,4 @@ stderr: ${a}${s}`)}return _(e,["rev-parse","--verify",t],"base_branch_resolve_fa
|
|
|
15
15
|
`;re(r,t+u)}catch{}}o(We,"seedManagedWorktreeExclude");function Qe(e,r,t="main"){const n=we(e);if(ye(n))throw new f("managed_worktree_base",`cwd ${n} is a managed worktree and cannot be used as a managed worktree base`,"Pass `--cwd` pointing at the repository\u2019s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.");return B(n,()=>{const a=R(n,t),s=ge(r),u=`crtr/${r}`;if(k(s))throw new f("worktree_path_exists",`managed worktree path already exists: ${s}`,"Remove the stale path or choose a fresh node id.");if(i(["show-ref","--verify","--quiet",`refs/heads/${u}`],n).status===0)throw new f("worktree_branch_exists",`managed worktree branch already exists: ${u}`,"Remove the stale branch or choose a fresh node id.");const h={state:"open",path:s,branch:u,repo_root:n,base_ref:t,base_sha:a,created:new Date().toISOString()};_(n,["branch",u,a],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");try{return _(n,["worktree","add",s,u],"worktree_add_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree."),We(n),h}catch(m){throw K(h,!0),m}})}o(Qe,"createManagedWorktree");function Ae(e){return _(e,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")}o(Ae,"statusPorcelain");function U(e){return _(e,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")}o(U,"currentBranch");function X(e,r){return _(e,["rev-parse","--git-path",r],"git_path_failed","Inspect the worktree manually, then retry.")}o(X,"gitPath");function M(e){return k(X(e,"rebase-merge"))||k(X(e,"rebase-apply"))}o(M,"isRebaseInProgress");async function $(e,r,t="pending"){const n=await v(e);await ue(e,{cwd:r.repo_root,cleanup:t,closedAt:new Date().toISOString(),unbindSession:n?.pi_session_id!=null||n?.pi_session_file!=null})}o($,"persistClosedWorktreeState");async function Re(e,r){const t=(await v(e))?.managed_worktree;t==null||t.state!=="open"||await le(e,{at:new Date().toISOString(),blocked:r})}o(Re,"recordBlockedLandIntent");function Me(e,r,t,n){const a=i(["status","--porcelain"],e);if(a.status!==0)return{ok:!1,detail:(a.stderr.trim()||a.stdout.trim()).trim()};const s=i(["diff","--name-only",t,n],e);if(s.status!==0)return{ok:!1,detail:(s.stderr.trim()||s.stdout.trim()).trim()};const u=s.stdout.split(`
|
|
16
16
|
`).map(g=>g.trim()).filter(g=>g!==""),h=ke(be(a.stdout),u);if(h.kind==="refuse")return{ok:!1,detail:`untracked files in ${e} would be overwritten by the incoming commits: ${h.collisions.join(", ")}`};const m=o(()=>{const g=i(["merge","--ff-only",n],e);return g.status===0?{ok:!0}:{ok:!1,detail:(g.stderr.trim()||g.stdout.trim()).trim()}},"merge");if(h.kind==="direct")return m();const d=i(["rev-parse","--verify","--quiet","refs/stash"],e),l=d.status===0?d.stdout.trim():null,b=i(["stash","push","--message",`crtr landing ${r}`],e);if(b.status!==0)return{ok:!1,detail:(b.stderr.trim()||b.stdout.trim()).trim()};const c=i(["rev-parse","--verify","--quiet","refs/stash"],e),p=c.status===0?c.stdout.trim():null;if(p===null||p===l)return m();const y=`local changes from ${e} are retained in stash ${p}; recover them with \`git -C ${w(e)} stash apply ${p}\` and resolve any conflict.`,W=m();return W.ok?i(["stash","apply",p],e).status===0?(z(e,p),{ok:!0}):(i(["reset","--hard",n],e),{ok:!0,stash:`the shared base checkout was reset to landed commit ${n} because local changes conflicted with it. ${y}`}):i(["stash","apply",p],e).status===0?(z(e,p),W):{ok:!1,detail:`${W.detail}
|
|
17
17
|
${y}`}}o(Me,"landIntoBaseCheckout");function z(e,r){const t=i(["rev-parse","--verify","--quiet","refs/stash"],e);t.status===0&&t.stdout.trim()===r&&i(["stash","drop"],e)}o(z,"dropStashIfStillTip");function L(e){const r=`git -C ${w(e.repo_root)} worktree remove ${w(e.path)}`;return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${e.path} remains intact. After its node exits, run \`${r}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${e.branch} remains checked out at ${e.path}; delete it only after that checkout is removed and its landed commit is still contained in ${e.base_ref}.`}}o(L,"deferredCleanupResult");async function Le(e,r,t){if(D(r.repo_root,r.path,t)!==!0)throw new f("wrong_branch",`managed worktree's recorded branch ${r.branch} no longer exists, and its checkout at ${r.path} is not registered to ${t} either`,`Inspect ${r.path} and its git worktree registration, then ask the user with \`crtr human send\` if you are unsure how to proceed.`);const n=_(r.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.");if(Ee(r.path,r.base_ref,n)===null)throw new f("branch_moved_unlanded",`managed worktree's recorded branch ${r.branch} no longer exists; its checkout is now on ${t} at ${n}, which carries content local base branch '${r.base_ref}' does not yet contain`,`Land or push ${t} through its own workflow (merge its PR, or fast-forward '${r.base_ref}' to include it) before closing, or ask the user with \`crtr human send\` if you are unsure how ${t} should be delivered.`);const s=S(r.repo_root),u=D(r.repo_root,r.path,t)===!0,h=U(r.path)===t,m=_(r.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")===n;if(!u||!h||!m)throw new f("wrong_branch",`managed worktree at ${r.path} changed while closing`,`Inspect ${r.path}, then rerun \`crtr node worktree close\`.`);const d={observed_branch:t,observed_sha:n,common_dir:s,authorized:new Date().toISOString()};await $(e,{...r,disposal:d},"pending");const l=`git -C ${w(r.repo_root)} worktree remove ${w(r.path)}`;return{node_id:e,branch:t,worktree_path:r.path,landed_sha:n,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${r.path} remains intact. After its node exits, run \`${l}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`${t} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}o(Le,"closeBranchMovedWorktree");async function Te(e,r){const t=(await v(e))?.managed_worktree;if(t==null)return{message:`node ${e} has no managed worktree`,next:`Nothing to ${r} for this node.`};if(t.state==="abandoned"){const n=t.abandoned?.branch??t.branch;return{message:`node ${e}'s managed worktree was already abandoned`,next:`Nothing to ${r} for this node; its work was retained on branch ${n}.`}}return t.state==="closed"?t.cleanup==="complete"?{message:`node ${e}'s managed worktree is already closed and its cleanup is complete`,next:`Nothing to ${r} for this node.`}:{message:`node ${e}'s managed worktree is already closed; this is not lost ownership \u2014 its checkout at ${t.path} is scheduled for automatic cleanup once that is safe`,next:`Nothing to ${r} for this node. The daemon sweep finishes removing ${t.path} on its own; inspect it directly only if it still needs manual attention.`}:{message:`node ${e} has no open managed worktree`,next:`Nothing to ${r} for this node.`}}o(Te,"noManagedWorktreeMessage");async function Q(e){if(await v(e)===null)throw new f("unknown_node",`unknown node: ${e}`,"Run this from a live node, or pass a real node id once that command supports it.");const t=await x(e);if(t===null){const{message:c,next:p}=await Te(e,"close");throw new f("no_managed_worktree",c,p)}if(!k(t.path)){const c=T(t);if(c===null)throw new f("worktree_missing",`managed worktree path is missing: ${t.path}`,J(t));if(await V(e,t,c)===null)throw new f("worktree_missing",`managed worktree path is missing: ${t.path}`,J(t));return{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:c.branchSha??t.base_sha,worktree_removed:!0,branch_deleted:!0}}if(M(t.path))throw new f("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${t.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(Ae(t.path)!=="")throw new f("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${t.path} (or ask the user with \`crtr human send\` if you do not know whether to keep it), then rerun \`crtr node worktree close\`.`);const a=U(t.path);if(a!==t.branch){const c=a==="HEAD"?"detached HEAD":a,p=$e(t.path,t.branch);if(p||a==="HEAD")throw new f("wrong_branch",`managed worktree is not on its recorded branch (expected ${t.branch}, found ${c})`,p?`Check out ${t.branch} in ${t.path} before closing, or ask the user with \`crtr human send\` if you are unsure why it changed, then rerun \`crtr node worktree close\`.`:`The recorded branch ${t.branch} no longer exists, and ${t.path} is in detached HEAD, so there is no branch to preserve. Check out or create a branch there before closing, or ask the user with \`crtr human send\` if you are unsure how to proceed.`);return await Le(e,t,a)}let s;try{s=R(t.path,t.base_ref)}catch(c){const p=_(t.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(!(c instanceof f)||c.code!=="missing_base_branch"||p!==t.base_sha)throw c;return await $(e,t,"pending"),{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:t.base_sha,...L(t)}}const u=i(["rebase",s],t.path);if(u.status!==0){const c=(u.stderr.trim()||u.stdout.trim()).trim();throw new f("rebase_failed",`rebase onto local base branch '${t.base_ref}' did not complete`,`Resolve conflicts in ${t.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`. If the blocker is not mechanical, ask the user with \`crtr human send\`.`,c)}const h=_(t.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),m=o(async(c,p,y)=>(await Re(e,c),new f("land_base_failed",c,p,y)),"blocked"),d=i(["merge-base","--is-ancestor",s,h],t.path);if(d.status!==0)throw await m(`rebased worktree is not a fast-forward of local base branch '${t.base_ref}'`,"Ask the user with `crtr human send` how to land this managed worktree.",(d.stderr.trim()||d.stdout.trim()).trim());const l=ve(t.path,t.base_ref);if(l!==null){const c=i(["rev-parse","HEAD"],l),p=c.stdout.trim();if(c.status!==0||p!==s){const y=c.status!==0?(c.stderr.trim()||p).trim():`expected ${s}, found ${p}`;throw await m(`local base branch '${t.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${l}, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`,y)}}let b;if(l!==null){const c=Me(l,t.branch,s,h);if(!c.ok)throw await m(`could not fast-forward local base branch '${t.base_ref}' to this worktree`,`Local base branch '${t.base_ref}' is checked out at ${l} in a state that blocks a fast-forward. Reconcile it there, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`,c.detail);b=c.stash}else{const c=i(["update-ref",`refs/heads/${t.base_ref}`,h,s],t.path);if(c.status!==0)throw await m(`could not fast-forward local base branch '${t.base_ref}' to this worktree`,"Ask the user with `crtr human send` how to land this managed worktree.",(c.stderr.trim()||c.stdout.trim()).trim())}return await $(e,t,"pending"),{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:h,...L(t),...b===void 0?{}:{base_checkout_stash:b}}}o(Q,"closeManagedWorktreeLocked");async function Je(e){const r=await x(e);return r===null?await Q(e):await j(k(r.path)?r.path:r.repo_root,async()=>await Q(e))}o(Je,"closeManagedWorktree");function Pe(e,r,t,n){const a=_e(e.branch,r,t,n),s=i(["update-ref","--stdin"],e.repo_root,a),u=s.status===0;if(u)return{branchDeleted:u};const h=(s.stderr.trim()||s.stdout.trim()).trim();return{branchDeleted:u,branchDeleteError:`local branch ${e.branch} could not be deleted automatically (${h}); run \`git -C ${w(e.repo_root)} branch -D ${w(e.branch)}\` after confirming it is merged.`}}o(Pe,"bestEffortDeleteBranchWithContainmentProof");function T(e){if(e.state!=="open"||k(e.path))return null;const r=`refs/heads/${e.branch}`,t=i(["show-ref","--verify","--quiet",r],e.repo_root);if(t.status===1)return{branchSha:null};if(t.status!==0)return null;const n=i(["rev-parse","--verify",r],e.repo_root);if(n.status!==0)return null;const a=n.stdout.trim(),s=i(["worktree","list","--porcelain"],e.repo_root);if(s.status!==0||I(s.stdout,e.branch)!==null)return null;const u=[],h=`refs/heads/${e.base_ref}`,m=i(["show-ref","--verify","--quiet",h],e.repo_root);if(m.status===0){const l=i(["rev-parse","--verify",h],e.repo_root);if(l.status!==0)return null;u.push({ref:h,sha:l.stdout.trim()})}else if(m.status!==1)return null;const d=i(["rev-parse","--symbolic-full-name","--verify",`${e.base_ref}@{upstream}`],e.repo_root);if(d.status===0){const l=d.stdout.trim(),b=i(["rev-parse","--verify",l],e.repo_root);l.startsWith("refs/")&&b.status===0&&u.push({ref:l,sha:b.stdout.trim()})}else{const l=`refs/remotes/origin/${e.base_ref}`,b=i(["show-ref","--verify","--quiet",l],e.repo_root);if(b.status===0){const c=i(["rev-parse","--verify",l],e.repo_root);c.status===0&&u.push({ref:l,sha:c.stdout.trim()})}else if(b.status!==1)return null}for(const l of u)if(i(["merge-base","--is-ancestor",a,l.sha],e.repo_root).status===0)return{branchSha:a,containingRef:l.ref,containingSha:l.sha};return null}o(T,"proveAbsentPathManagedWorktree");function J(e){return`The recorded checkout path is gone, but crtr cannot prove ${e.branch} is already delivered. Push or land ${e.branch}, then rerun \`crtr push final\`; if you cannot establish what happened to the branch, ask the user with \`crtr human send\`.`}o(J,"missingWorktreeRecoveryHint");function P(e){if(e.state!=="open"||!k(e.path)||M(e.path))return null;const r=i(["rev-parse","--abbrev-ref","HEAD"],e.path);if(r.status!==0||r.stdout.trim()!==e.branch)return null;const t=i(["status","--porcelain"],e.path);if(t.status!==0||t.stdout.trim()!=="")return null;const n=i(["rev-parse","HEAD"],e.path);if(n.status!==0)return null;const a=n.stdout.trim();let s;try{s=R(e.path,e.base_ref)}catch(h){if(h instanceof f&&h.code==="missing_base_branch"&&a===e.base_sha)return{branchSha:a,baseSha:e.base_sha};throw h}return i(["merge-base","--is-ancestor",a,s],e.path).status!==0?null:{branchSha:a,baseSha:s}}o(P,"proveCleanEmptyManagedWorktree");async function V(e,r,t){if(k(r.path))return null;if(t.branchSha===null)return await $(e,r,"complete"),{node_id:e,branch:r.branch,worktree_path:r.path,worktree_removed:!0,branch_deleted:!0};if(t.containingRef===void 0||t.containingSha===void 0)return null;const{branchDeleted:n}=Pe(r,t.branchSha,t.containingRef,t.containingSha);return n?(await $(e,r,"complete"),{node_id:e,branch:r.branch,worktree_path:r.path,worktree_removed:!0,branch_deleted:!0}):null}o(V,"autoDropAbsentPathManagedWorktreeLocked");async function He(e,r,t){const n=P(r);return n===null||n.branchSha!==t.branchSha?null:(await $(e,r,"pending"),{node_id:e,branch:r.branch,worktree_path:r.path,...L(r)})}o(He,"autoDropCleanManagedWorktreeLocked");function Y(e){if(e.state!=="open"||!k(e.path)||M(e.path))return null;const r=i(["status","--porcelain"],e.path);if(r.status!==0||r.stdout.trim()!=="")return null;const t=i(["rev-parse","HEAD"],e.path);return t.status===0?t.stdout.trim():null}o(Y,"cleanCurrentCheckoutTip");async function Ve(e){const r=Y(e);if(r===null)return!1;const t=process.env.GIT_SSH_COMMAND??process.env.GIT_SSH??"ssh",n=await he(["ls-remote","--exit-code","--heads","origin"],e.path,void 0,{timeoutMs:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:`${t} -o BatchMode=yes`}});return n.status!==0||!n.stdout.split(`
|
|
18
|
-
`).some(s=>{const[u,h]=s.split(" ",2);return u===r&&h?.startsWith("refs/heads/")===!0})?!1:Y(e)===r}o(Ve,"branchIsPushedAtCurrentTip");async function Ye(e){const r=await x(e);if(r===null)return null;const t=!k(r.path);return(t?T(r)===null:P(r)===null)?null:await j(t?r.repo_root:r.path,async()=>{const n=await x(e);if(n===null)return null;if(!k(n.path)){const s=T(n);return s===null?null:await V(e,n,s)}const a=P(n);return a===null?null:await He(e,n,a)})}o(Ye,"autoDropCleanManagedWorktree");export{q as WORKTREE_LOCK_WAIT_MS,f as WorktreeError,Ye as autoDropCleanManagedWorktree,He as autoDropCleanManagedWorktreeLocked,Ve as branchIsPushedAtCurrentTip,I as checkoutPathForBranchInList,Je as closeManagedWorktree,Qe as createManagedWorktree,Xe as hasOpenManagedWorktree,ye as isManagedWorktreeBase,M as isRebaseInProgress,ge as managedWorktreePath,F as managedWorktreesRoot,J as missingWorktreeRecoveryHint,x as openManagedWorktreeForNode,$ as persistClosedWorktreeState,P as proveCleanEmptyManagedWorktree,ze as rollbackManagedWorktree,xe as samePath,G as worktreeLockPathForCommonDir};
|
|
18
|
+
`).some(s=>{const[u,h]=s.split(" ",2);return u===r&&h?.startsWith("refs/heads/")===!0})?!1:Y(e)===r}o(Ve,"branchIsPushedAtCurrentTip");async function Ye(e){const r=await x(e);if(r===null)return null;const t=!k(r.path);return(t?T(r)===null:P(r)===null)?null:await j(t?r.repo_root:r.path,async()=>{const n=await x(e);if(n===null)return null;if(!k(n.path)){const s=T(n);return s===null?null:await V(e,n,s)}const a=P(n);return a===null?null:await He(e,n,a)})}o(Ye,"autoDropCleanManagedWorktree");export{q as WORKTREE_LOCK_WAIT_MS,f as WorktreeError,Ye as autoDropCleanManagedWorktree,He as autoDropCleanManagedWorktreeLocked,Ve as branchIsPushedAtCurrentTip,E as canonicalPath,I as checkoutPathForBranchInList,Je as closeManagedWorktree,Qe as createManagedWorktree,Xe as hasOpenManagedWorktree,ye as isManagedWorktreeBase,M as isRebaseInProgress,ge as managedWorktreePath,F as managedWorktreesRoot,J as missingWorktreeRecoveryHint,x as openManagedWorktreeForNode,$ as persistClosedWorktreeState,P as proveCleanEmptyManagedWorktree,ze as rollbackManagedWorktree,xe as samePath,G as worktreeLockPathForCommonDir};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var k=Object.defineProperty;var o=(
|
|
1
|
+
var k=Object.defineProperty;var o=(t,e)=>k(t,"name",{value:e,configurable:!0});import{ApiError as E}from"../../../api/errors.js";import{getNode as I}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as S}from"../../../core/canvas/executions.js";import{admitEpisode as T,clearEpisode as q,clearFault as m,closeTurn as R,invalidateEpisode as P,openTurn as h,parseProviderError as F,readEpisode as A,readFault as _,recordFault as v,recordPendingEpisode as N,recordTransportPoisonVerdict as j,recordTurnProgress as O,reopenEpisode as L,settleRejectedEpisode as D}from"../../../core/canvas/recovery.js";import{notFound as B,usage as n}from"../../../core/errors.js";import{hasPresentedViewer as $}from"../viewer-presence.js";import{ownerOnly as b}from"../router.js";const y=new Set(["pi\u2192provider","viewer\u2194broker","relay\u2194broker","viewer\u2194crtrd","daemon\u2192node","crtr\u2192pi"]),C=new Set(["rate-limit","overloaded","connection","auth","protocol","context-overflow","other","wedged","model-not-found"]),K=new Set(["auto","manual","fatal"]),U=new Set(["sdk","daemon","client"]);function d(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw n(`${e} requires a JSON object`);return t}o(d,"objectBody");async function a(t){if(await I(t)===null)throw B(`unknown node: ${t}`,{received:t})}o(a,"requireNode");async function u(t,e){if(typeof e!="string"||e==="")throw n("expected_execution_id must be a non-empty string");const r=await S(t);if(r===null||r.executionId!==e)throw new E(409,"stale_execution","broker execution is no longer current")}o(u,"requireCurrentExecution");function g(t){if(typeof t!="object"||t===null||Array.isArray(t))throw n("retry must be an object");const e=t;if(!K.has(e.disposition))throw n("retry.disposition must be auto, manual, or fatal");if(e.by!==void 0&&!U.has(e.by))throw n("retry.by must be sdk, daemon, or client");for(const r of["attempt","max"])if(e[r]!==void 0&&(!Number.isSafeInteger(e[r])||e[r]<0))throw n(`retry.${r} must be a non-negative safe integer`);if(e.nextAt!==void 0&&typeof e.nextAt!="string")throw n("retry.nextAt must be a string");return e}o(g,"parseRetry");function c(t){const e=d(t,"fault input");if(!y.has(e.link))throw n("fault link is invalid");if(typeof e.op!="string"||e.op==="")throw n("fault op must be a non-empty string");if(!C.has(e.kind))throw n("fault kind is invalid");if(typeof e.message!="string")throw n("fault message must be a string");if(e.operation_id!==void 0&&(typeof e.operation_id!="string"||e.operation_id===""))throw n("operation_id must be a non-empty string");if(e.since!==void 0&&typeof e.since!="string")throw n("since must be a string");if(e.anchor_entry_id!==void 0&&(typeof e.anchor_entry_id!="string"||e.anchor_entry_id===""))throw n("anchor_entry_id must be a non-empty string");const r=e.provider_error===void 0?void 0:F(e.provider_error);if(e.provider_error!==void 0&&r===void 0)throw n("provider_error is invalid");return{...e,...r===void 0?{}:{provider_error:r},retry:g(e.retry)}}o(c,"parseFaultInput");function p(t){return{link:t.link,op:t.op,kind:t.kind,retry:t.retry,message:t.message,...t.operation_id===void 0?{}:{operation_id:t.operation_id},...t.since===void 0?{}:{since:t.since},...t.anchor_entry_id===void 0?{}:{anchorEntryId:t.anchor_entry_id},...t.provider_error===void 0?{}:{providerError:t.provider_error}}}o(p,"faultInput");function l(t){return{fault_id:t.faultId,link:t.link,op:t.op,kind:t.kind,retry:t.retry,message:t.message,since:t.since,operation_id:t.operation_id,...t.anchorEntryId===void 0?{}:{anchor_entry_id:t.anchorEntryId},...t.providerError===void 0?{}:{provider_error:t.providerError}}}o(l,"faultDto");async function x(t){const e=await _(t),r=await A(t);return{fault:e===null?null:l(e),episode:r===null?null:{state:r.state,session_id:r.sessionId,fault:l(r.fault)}}}o(x,"recoveryState");function V(t){const e=d(t,"broker turn"),r=e.event;if(r!=="started"&&r!=="progress"&&r!=="closed"&&r!=="interrupted"&&r!=="exit-diagnostic")throw n("event is invalid");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw n("expected_execution_id must be a non-empty string");if(r==="closed"){if(e.end_reason!=="settled"&&e.end_reason!=="teardown-aborted")throw n("closed turn requires end_reason settled or teardown-aborted")}else if(e.end_reason!==void 0)throw n("end_reason is valid only for closed turns");if(r==="exit-diagnostic"){const i=d(e.exit_diagnostic,"exit_diagnostic"),s=d(i.transport_poison,"exit_diagnostic.transport_poison");if(i.schema!=="crtr.execution-exit-diagnostic/v1"||!Number.isSafeInteger(s.consecutive_passes)||s.consecutive_passes<1||!Array.isArray(s.routes)||s.routes.length===0||!s.routes.every(f=>typeof f=="string"&&f!==""))throw n("exit_diagnostic is invalid")}else if(e.exit_diagnostic!==void 0)throw n("exit_diagnostic is valid only for exit-diagnostic turns");return e}o(V,"parseTurn");async function Y(t){const e=t.params.id;await a(e);const r=V(t.body);await u(e,r.expected_execution_id);let i;switch(r.event){case"started":i=await h(r.expected_execution_id,{reason:"agent-start"});break;case"interrupted":i=await h(r.expected_execution_id,{reason:"prompt-unsettled"});break;case"progress":i=await O(r.expected_execution_id);break;case"closed":i=await R(r.expected_execution_id,{endReason:r.end_reason,viewerPresent:$(e)});break;case"exit-diagnostic":{const w=r.exit_diagnostic.transport_poison;i=await j(r.expected_execution_id,{consecutivePasses:w.consecutive_passes,routes:w.routes});break}}const s=(await _(e))?.link;return{status:200,body:{applied:i,fault_link:s==="daemon\u2192node"||s==="pi\u2192provider"?s:null}}}o(Y,"handleTurn");function G(t){const e=d(t,"provider retry");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw n("expected_execution_id must be a non-empty string");if(!["record-pending","admit","reopen","invalidate","clear","settle-rejected"].includes(e.op))throw n("provider retry op is invalid");if(typeof e.session_id!="string"||e.session_id==="")throw n("session_id must be a non-empty string");if(e.op==="record-pending"&&(e.input=c(e.input)),e.op==="settle-rejected"){if(typeof e.fault_id!="string"||e.fault_id==="")throw n("settle-rejected requires fault_id");if(typeof e.reopen!="boolean")throw n("settle-rejected requires reopen");e.input=c(e.input)}if(e.op==="admit"){if(typeof e.fault_id!="string"||e.fault_id==="")throw n("admit requires fault_id");e.retry=g(e.retry)}return e}o(G,"parseProviderRetry");async function J(t){const e=t.params.id;await a(e);const r=G(t.body);await u(e,r.expected_execution_id);let i;switch(r.op){case"record-pending":i=await N(e,{sessionId:r.session_id,input:p(r.input)})!==null;break;case"admit":i=await T(e,{sessionId:r.session_id,faultId:r.fault_id,retry:r.retry});break;case"settle-rejected":i=await D(e,{sessionId:r.session_id,faultId:r.fault_id,fault:p(r.input),reopen:r.reopen});break;case"reopen":i=await L(e,{sessionId:r.session_id});break;case"invalidate":i=await P(e,{sessionId:r.session_id});break;case"clear":i=await q(e,{sessionId:r.session_id});break}return{status:200,body:{applied:i,episode:(await x(e)).episode}}}o(J,"handleProviderRetry");function W(t){const e=d(t,"broker fault");if(typeof e.expected_execution_id!="string"||e.expected_execution_id==="")throw n("expected_execution_id must be a non-empty string");if(e.op!=="record"&&e.op!=="clear")throw n("fault op must be record or clear");if(e.op==="record"&&(e.input=c(e.input)),e.op==="clear"&&e.link!==void 0&&!y.has(e.link))throw n("fault link is invalid");if(e.preserve_episode!==void 0&&typeof e.preserve_episode!="boolean")throw n("preserve_episode must be boolean");return e}o(W,"parseBrokerFault");async function z(t){const e=t.params.id;await a(e);const r=W(t.body);await u(e,r.expected_execution_id);const i=r.op==="record"?await v(e,p(r.input)):(await m(e,{...r.link===void 0?{}:{link:r.link},...r.preserve_episode===void 0?{}:{preserveEpisode:r.preserve_episode}}),await _(e));return{status:200,body:{fault:i===null?null:l(i)}}}o(z,"handleBrokerFault");async function H(t){const e=t.params.id;return await a(e),await u(e,t.query.get("expected_execution_id")),{status:200,body:await x(e)}}o(H,"handleRecovery");async function M(t){const e=t.params.id;await a(e);const r=await v(e,p(c(t.body)));return{status:200,body:{fault:r===null?null:l(r)}}}o(M,"handleNodeFaultRecord");async function Q(t){const e=t.params.id;await a(e);const r=t.query.get("link");if(r!==null&&!y.has(r))throw n("fault link is invalid");const i=t.query.get("preserve_episode");if(i!==null&&i!=="true"&&i!=="false")throw n("preserve_episode must be true or false");return{status:200,body:{cleared:await m(e,{...r===null?{}:{link:r},...i===null?{}:{preserveEpisode:i==="true"}})}}}o(Q,"handleNodeFaultClear");const se=b([{method:"POST",pattern:"/v1/broker/:id/turn",handler:Y},{method:"POST",pattern:"/v1/broker/:id/provider-retry",handler:J},{method:"POST",pattern:"/v1/broker/:id/fault",handler:z},{method:"GET",pattern:"/v1/broker/:id/recovery",handler:H}]),de=b([{method:"POST",pattern:"/v1/nodes/:id/fault",handler:M},{method:"DELETE",pattern:"/v1/nodes/:id/fault",handler:Q}]);export{se as brokerRecoveryRoutes,de as nodeFaultRoutes,u as requireCurrentExecution};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ce=Object.defineProperty;var u=(t,e)=>ce(t,"name",{value:e,configurable:!0});import{randomBytes as ue}from"node:crypto";import{claimNodeMail as le,acknowledgeNodeMail as fe}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as me}from"../../../core/feed/inbox.js";import{enqueueNodeMail as
|
|
2
|
-
`)[0].slice(0,120)}u(
|
|
1
|
+
var ce=Object.defineProperty;var u=(t,e)=>ce(t,"name",{value:e,configurable:!0});import{randomBytes as ue}from"node:crypto";import{claimNodeMail as le,acknowledgeNodeMail as fe}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as me}from"../../../core/feed/inbox.js";import{enqueueNodeMail as D,cancelPendingNodeMail as pe}from"../../../core/feed/messages.js";import{reviveNode as L}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as U}from"../../../core/runtime/broker-request.js";import{isBrokerLive as R}from"../../../core/runtime/model-swap.js";import{deliverLive as ye,interruptLive as he}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as we}from"../../../core/profiles/manifest.js";import{getNode as O,withFreshTerminalGuard as be}from"../../../core/canvas/canvas.js";import{getById as G,nodeObject as F,ownerForGrantee as ge}from"../../../core/graph/objects.js";import{recordActedOn as ve}from"../../../core/graph/edges.js";import{recordWatch as H}from"../../../core/graph/watches.js";import{publish as V}from"../../../core/graph/events.js";import{readerFor as K}from"../reader.js";import{canRead as _e}from"../../../core/graph/access.js";import{withCanvasWrite as k}from"../../../core/canvas/db.js";import{getPendingStructuredRequestForNode as Q}from"../../../core/canvas/structured-requests.js";import{consumeDeadlineOnWake as X}from"../../../core/feed/messages.js";import{assertNotFinalized as M,assertFinalizedForReopen as ke,commitReopenResident as P}from"../../../core/runtime/reopen.js";import{admitLegacyStructuredOutput as Se}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as $e}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as E,formatSituationalProse as Ne}from"../../../core/runtime/situational-context.js";import{formatDataCard as Y}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as je}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as Ae}from"../../park-pending.js";import{wantsExecution as qe}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as Oe}from"../../../core/runtime/revive.js";import{CrtrError as Ce,notFound as C,usage as c}from"../../../core/errors.js";import{emitEvent as xe}from"../../../core/events/emit.js";import{assertScope as Re}from"../../../core/scopes.js";import{InputError as I}from"../../../core/io.js";import{ApiError as Fe}from"../../../api/index.js";import{describeObject as Me,stubOf as Pe}from"../../../core/peer/stubs.js";import{machineNameOf as Z}from"../../../core/peer/names.js";import{callerNode as Ee,callerStub as Ie,forwardVerb as ee,relayError as te,remoteStub as Te,unknownError as re,withMachine as ne}from"../../peer/forward.js";import{ownerOnly as Be}from"../router.js";const ze=["critical","urgent","normal","deferred"];function oe(t,e){if(typeof t!="object"||t===null||Array.isArray(t))throw c(`${e} must be an object { kind, facts?, body? }`);const a=t,n=a.kind;if(typeof n!="string"||n.trim()==="")throw c(`${e}.kind is required`);if(!n.includes(":"))throw c(`${e}.kind must be namespaced (contain ':'): ${n}`);const r={kind:n},o=a.facts;if(o!==void 0){if(typeof o!="object"||o===null||Array.isArray(o))throw c(`${e}.facts must be an object of string or number values`);const d={};for(const[l,m]of Object.entries(o)){if(typeof m!="string"&&typeof m!="number")throw c(`${e}.facts.${l} must be a string or number`);d[l]=m}r.facts=d}const s=a.body;if(s!==void 0){if(typeof s!="string")throw c(`${e}.body must be a string`);r.body=s}return r}u(oe,"parseCardRequest");function ae(t,e){try{return Y(t.kind,t.facts??{},t.body??"")}catch(a){throw c(`${e}: ${a instanceof Error?a.message:String(a)}`)}}u(ae,"renderCard");function We(t){if(typeof t!="object"||t===null)throw c("a message requires a JSON body { body, tier?, fresh? }");const e=t,a=e.body,n=e.fresh===!0,r=e.tier,o=e.situational_context,s=e.output_schema,d=typeof a=="string"&&a.trim()!=="",l=typeof o=="string"&&o.trim()!=="",m=typeof s=="string"&&s.trim()!=="",v=e.situational_card,S=e.context_cards,b=v===void 0?void 0:oe(v,"situational_card");if(S!==void 0&&!Array.isArray(S))throw c("context_cards must be an array of { kind, facts?, body? }");const p=S?.map((N,$)=>oe(N,`context_cards[${$}]`));if(b!==void 0&&typeof o=="string"&&o!=="")throw c("situational_card and situational_context are mutually exclusive");const w=b!==void 0||p!==void 0&&p.length>0;if(!n&&!d&&!l&&!m&&!w)throw c("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(n&&p!==void 0&&p.length>0)throw c("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(r!==void 0&&!ze.includes(r))throw c(`invalid tier: ${String(r)} (expected critical|urgent|normal|deferred)`);const f={body:typeof a=="string"?a:""};r!==void 0&&(f.tier=r),n&&(f.fresh=!0),e.reopen===!0&&(f.reopen=!0),typeof o=="string"&&(f.situational_context=o),b!==void 0&&(f.situational_card=b),p!==void 0&&(f.context_cards=p),typeof s=="string"&&(f.output_schema=s),typeof e.from=="string"&&(f.from=e.from);const y=e.delivery;if(y!==void 0&&y!=="interactive")throw c(`invalid delivery: ${String(y)} (expected interactive)`);if(y==="interactive"){if(n||f.situational_context!==void 0||f.output_schema!==void 0)throw c("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!d)throw c("interactive delivery requires a non-empty body");if(f.tier==="deferred")throw c("interactive delivery cannot be deferred");f.delivery="interactive"}return f}u(We,"parseSendBody");function Je(t){let e;try{e=JSON.parse(t)}catch{throw c("output_schema must be a JSON schema string")}if(typeof e!="object"||e===null||Array.isArray(e))throw c("output_schema must be a JSON schema object");return e}u(Je,"parseSchema");function De(t){return t.split(`
|
|
2
|
+
`)[0].slice(0,120)}u(De,"label");function ie(t,e){return e===null?"":Y("reopen-final-report",{report:`${t}/${e}`},"This node previously completed work. Read this final report before acting on the new instruction.")}u(ie,"previousFinalReportCard");async function Le(t,e,a){if(a!==null&&a!=="human"&&(await G(t,a))?.type==="node"){const o=await F(t,a);return{actor:o,senderNode:o}}if(a==="human")return{actor:await ge(t,"user:local"),senderNode:null};const n=await K(t,e);return{actor:n.class==="person"?n.person:n.class==="app"?n.app:n.node,senderNode:n.class==="node"?n.node:null}}u(Le,"messageActor");async function se(t,e,a,n,r,o){const s=await F(t,a),{actor:d,senderNode:l}=await Le(t,e,n),m=r===null?{}:{pointer:r};await ve(t,d,s),l!==null&&l.id!==s.id&&await H(t,l,s,"message",{endsOn:o&&r!==null?`result:${r}`:"final"}),await V(t,{event:"messaged",object:s,actor:d,attrs:{},...m}),l!==null&&await V(t,{event:"sent",object:l,actor:l,attrs:{to:s.id},...m})}u(se,"recordMessage");function Ue(t,e){return new I({error:"deferred_no_natural_cycle",message:`${t} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}u(Ue,"deferredNoNaturalCycle");async function Ge(t){if(!await Oe(t))throw new Fe(422,"unprocessable",`node ${t} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}u(Ge,"assertRecoverableForFresh");function He(t,e){return t instanceof I?{error:t.payload.error,message:t.payload.message,next:t.payload.next,message_id:e}:t instanceof Ce?{error:t.code,message:t.message,message_id:e}:{error:"wake_failed",message:"the target could not be woken; see the daemon log",message_id:e}}u(He,"wakeFailure");async function Ve(t,e){const a=typeof t.body=="object"&&t.body!==null&&!Array.isArray(t.body)?{...t.body}:t.body;typeof a=="object"&&a!==null&&delete a.from;const n=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/messages`,body:a});if(n.kind==="local")return null;if(n.kind==="unknown")throw re(e,n.unreachable);if(n.status>=400)throw te(n.status,n.body);return await k(async r=>{const o=await Ee(r,t);if(o===null)return;const s=n.body?.object,d=await Te(r,e,"node",n.machine.id,s);await H(r,o,d,"message",{endsOn:"final"})}),{status:n.status,body:ne(n.body,n.machine)}}u(Ve,"forwardMessage");async function Ke(t){const e=await Qe(t);if(t.principal.class!=="forwarded"||typeof e.body!="object"||e.body===null)return e;const a=await k(async n=>{const r=await F(n,t.params.id);return await _e(n,await K(n,t),r)?await Me(n,r):{id:r.id,type:r.type,kind:null,name:r.id,owner:null}});return{...e,body:{...e.body,object:a}}}u(Ke,"handleMessage");async function Qe(t){const e=t.params.id,a=await Ve(t,e);if(a!==null)return a;const n=await O(e);if(n===null)throw C(`unknown node: ${e}`,{received:e});const r=We(t.body),o=r.tier??"normal",s=we(n.profile_id),d=t.principal.class==="forwarded"?await k(async i=>(await Ie(i,t))?.id??null):r.from??null;if(d!==null){const i=await O(d);i!==null&&Re(i,"crtr:act")}const l=d===null?null:await k(async i=>{const h=await G(i,d);return h===null?null:(await Pe(i,h))?.home_machine??null}),m=l===null?void 0:`${d} on ${Z(l)}`,v=t.principal.class==="broker"?t.principal.node:null,S=l===null?{}:{from_machine:Z(l)},b=r.body.trim()!=="",p=r.situational_card!==void 0?ae(r.situational_card,"situational_card"):r.situational_context!==void 0?Ne(r.situational_context.trim()):"",w=p!=="",f=(r.context_cards??[]).map((i,h)=>ae(i,`context_cards[${h}]`)),y=r.output_schema!==void 0&&r.output_schema.trim()!==""?Je(r.output_schema):null;y!==null&&await $e(y);let N=!1;const $=u(async i=>{if(!(y===null||N)){if(await Q(e)!==null)throw new I({error:"structured_request_conflict",message:`node ${e} already has a pending structured request`,next:"Wait for the current request to settle before requesting another structured result."});await Se(e,"oneoff",y,i),N=!0}},"ensureSchema");if(r.fresh){const i=r.reopen?await ke(e):null;r.reopen||await M(e),await Ge(e),await $(),w&&E(e,p),r.reopen&&await P(e,i,v);const h=await L(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:h.launch!==void 0}}}r.delivery==="interactive"&&!r.reopen&&await M(e);let T=!1,_="";if(r.delivery==="interactive"&&r.reopen&&(_=ie(e,await P(e,void 0,v)),T=!0),r.delivery==="interactive"&&await $(),r.delivery==="interactive"&&!s&&!n.run_id&&R(n))try{return w&&E(e,p),await ye(e,r.body,{cards:[..._===""?[]:[_],...w?[p]:[],...f],origin:d==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...d===null?{}:{from:d},...m===void 0?{}:{fromName:m},kind:"message",tier:o}]}}),await k(async h=>await se(h,t,e,d,null,!1)),await X(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(i){if(!(i instanceof U))throw i}const B=u(async()=>{r.reopen||await M(e);const i=ue(16).toString("hex"),h=u(async q=>await se(q,t,e,d,i,y!==null),"withinEnqueue");await $(i),w&&E(e,p),r.reopen&&!T&&(_=ie(e,await P(e,void 0,v)));const x=[..._===""?[]:[_],...f],J=x.length>0?{cards:x}:{};if(b||y!==null){const q=b?r.body:`A one-off structured-output request has been granted. Submit a result matching the requested schema with the \`submit_result\` tool (\`request_id: "${(await Q(e))?.request_id??"<request-id>"}"\`) before you stop; after it is accepted, continue normally.`;return await D(e,{senderNodeId:d,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:i,withinEnqueue:h,label:De(q),bodyJson:{body:q,...S,...w?{situational:!0}:{},...J}})}return await D(e,{senderNodeId:d,...m===void 0?{}:{senderName:m},urgency:o,wake:1,kind:"message",messageId:i,withinEnqueue:h,label:w?"(ambient context updated)":"(context delivered)",bodyJson:{...w?{situational:!0}:{},situationalOnly:!0,...J}})},"deliverImmediate"),g=await u(async()=>{if(o==="deferred"){const i=await be(e,je,B);if(i.kind==="missing")throw C(`unknown node: ${e}`,{received:e});if(i.kind==="terminal")throw Ue(e,i.status);return i.result}return await B()},"deliver")();g.urgency!=="deferred"&&await k(async()=>Ae(e));const j=await O(e);if(j===null)throw C(`unknown node: ${e}`,{received:e});n.frozen_at!==null&&await X(e);let z=!1,W=!1,A;if((r.reopen||j.lifecycle==="terminal"||!await qe(j))&&g.urgency!=="deferred"&&!s&&!R(j))try{const i=await L(e,{resume:!0,capacity:"freeze"});z=i.launch!==void 0,W=i.outcome==="frozen"}catch(i){A=He(i,g.messageId),xe({level:"error",event:"message.wake_failed",node_id:e,error:i,fields:{message_id:g.messageId,error_code:A.error}})}return{status:201,body:{node_id:e,delivered:!0,revived:z,...W?{not_revived_reason:"capacity_frozen"}:{},...A===void 0?{}:{wake_failed:A},delivered_at:g.createdAt,...g.urgency===o?{}:{delivered_tier:g.urgency},...r.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}u(Qe,"handleMessageHere");async function Xe(t){const e=t.params.id,a=await ee(t,e,{method:"POST",path:`/v1/nodes/${encodeURIComponent(e)}/interrupt`,body:t.body});if(a.kind==="unknown")throw re(e,a.unreachable);if(a.kind==="remote"){if(a.status>=400)throw te(a.status,a.body);return{status:a.status,body:ne(a.body,a.machine)}}const n=await O(e);if(n===null)throw C(`unknown node: ${e}`,{received:e});const r=await pe(e,{senderNodeId:"human",kind:"message"});let o=!1;if(R(n))try{o=await he(e)!=="idle"}catch(d){if(!(d instanceof U))throw d}return{status:200,body:{node_id:e,outcome:o?"aborted_turn":r.length>0?"canceled_pending":"idle",aborted_turn:o,canceled_pending:r.length}}}u(Xe,"handleInterrupt");function de(t){if(typeof t.body!="object"||t.body===null||Array.isArray(t.body))throw c("mail requires an object body");const e=t.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw c("execution_id is required");return e}u(de,"mailBody");async function Ye(t){const e=de(t),a=e.channel;if(a!=="wake"&&a!=="passive"&&a!=="deferred_run")throw c("channel must be wake, passive, or deferred_run");const n=await le(t.params.id,e.execution_id,a);return{status:200,body:{action:n.action,deliveries:n.deliveries.map(o=>({delivery_id:o.deliveryId,attempts:o.attempts,handoff:o.handoff,entry:{...me(o),seq:o.message.seq}}))}}}u(Ye,"handleMailClaim");async function Ze(t){const e=de(t);if(!Array.isArray(e.deliveries))throw c("deliveries must be an array");const a=e.deliveries.map(o=>{if(typeof o!="object"||o===null||Array.isArray(o))throw c("each delivery must be an object");const s=o;if(typeof s.delivery_id!="string"||s.delivery_id==="")throw c("delivery_id is required");if(!Number.isSafeInteger(s.attempts)||s.attempts<1)throw c("attempts must be a positive integer");if(s.disposition!=="acknowledged"&&s.disposition!=="released")throw c("disposition must be acknowledged or released");return{delivery_id:s.delivery_id,attempts:s.attempts,disposition:s.disposition}}),n=await fe(t.params.id,e.execution_id,a.map(o=>({deliveryId:o.delivery_id,attempts:o.attempts,disposition:o.disposition})));return{status:200,body:{action:n.action,results:n.results.map(o=>({delivery_id:o.deliveryId,outcome:o.outcome}))}}}u(Ze,"handleMailAcknowledge");const Wt=Be([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:Ye},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:Ze}]),Jt=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:Ke},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:Xe}];export{Wt as brokerMailRoutes,Ke as handleMessage,Jt as messageRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ie=Object.defineProperty;var s=(e,t)=>Ie(e,"name",{value:t,configurable:!0});import{envProfileId as Ae}from"../../../shared/env.js";import{pausedCanvasProfiles as $e}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as q,statSync as ee}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as Ce,formatSituationalProse as Ne}from"../../../core/runtime/situational-context.js";import{closeNode as Te}from"../../../core/runtime/close.js";import{reviveNode as Pe}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{appPaidLaunch as Ee,assertLaunchModelRegistered as K,forkNode as De,resolveForkSource as Le,spawnChildPrepared as Me}from"../../../core/runtime/spawn.js";import{forkSourceNode as je,newNodeId as ne}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as te,childrenOf as Ge,completeCreateRequest as ie,findCreateRequest as Fe,getNode as R,recordCreateRequestNode as Be,reserveCreateRequest as oe,reserveCreateRequestNode as Ke,listNodes as re,recordRespawnAttempt as We,subscribersOf as Ve,subscriptionsOf as ae,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as xe}from"../../../core/canvas/waits.js";import{subtreeIds as ze}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as W}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as V}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn}from"../../cron/authority.js";import{cronBirthPlacement as tn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as rn,isBeneathRefusal as an,readdirBeneath as dn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as sn,readNodeSession as ln,readNodeSnapshot as cn,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as un}from"../../../core/substrate/subject.js";import{reviveAll as pn}from"../../../core/runtime/revive-all.js";import{promoteAsync as mn,requestYieldAsync as wn,reshapeNodeAsync as x}from"../../../core/runtime/promote.js";import{recycleNode as hn}from"../../../core/runtime/recycle.js";import{relaunchRoot as yn}from"../../../core/runtime/reset.js";import{assertReopenGate as _n}from"../../../core/runtime/reopen.js";import{writeYieldMessage as gn,readGoal as bn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as vn,hasRoadmap as kn}from"../../../core/runtime/roadmap.js";import{renameWindow as Sn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Rn,explicitModelIntent as On,normalizeModel as In,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as An}from"../../../core/model-routes.js";import{persistDormantModel as $n,setModelLive as Cn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as le}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Nn}from"../../../core/runtime/broker-request.js";import{boundFleet as P}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Tn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Pn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ce}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as En}from"../../../core/human/action-binding.js";import{resolveHumanAction as Dn}from"../../../core/human-actions.js";import{parseDurationMs as Ln}from"../../../core/wake.js";import{claimWarmNode as Mn,refillWarmPool as fe,resumeWarmClaim as jn,warmPoolEnabled as Gn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Fn,resolveLaunchTarget as Bn}from"../../../core/runtime/launch-target.js";import{fullName as Kn}from"../../../core/canvas/labels.js";import{reportsForNode as ue}from"./reports.js";import{requireUsableProfile as Wn}from"./profiles.js";import{assertProfileActive as Vn,loadExactProfileManifest as xn}from"../../../core/profiles/manifest.js";import{getCron as pe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as zn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Jn}from"../../control.js";import{notFound as E,usage as w}from"../../../core/errors.js";import{assertScope as Un,validateScopes as me}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Yn,toNodeDetailDTO as J,toNodeSummaryDTO as Hn,toReviveResultDTO as Qn}from"../map.js";import{ApiError as u}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Xn,brokerMayReach as U,canReadNode as we,resolvedScopes as Zn}from"../router.js";import{forwardVerb as qn,queryWithoutMachine as et,relayError as nt,unknownError as tt,withMachine as it}from"../../peer/forward.js";import{fileRoot as ot}from"../../../core/spaces/file-root.js";import{activeGrant as rt,payerOfGrant as at,terminalGrant as dt}from"../../../core/grants/mirror.js";import{appRungForGrant as st}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as lt}from"../../../core/model-routes.js";import{readConfig as ct}from"../../../core/config.js";import{hasConfiguredProviderCredential as ft,NO_PROVIDER_CREDENTIAL_MESSAGE as he}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Y,mapAsync as ye}from"../../../core/async-array.js";async function h(e){const t=await R(e);if(t===null)throw E(`unknown node: ${e}`,{received:e});return t}s(h,"requireMeta");async function H(e){return{subscribesTo:await ae(e),subscribers:await Ve(e),children:await Ge(e)}}s(H,"edgesFor");async function g(e){const t=await h(e);return await J(t,await H(e))}s(g,"detailOf");async function ut(e){let t=(await ue(e)).length;try{t+=dn(await V(e),await de(e)).length}catch(n){if(!rn(n))throw n}return t}s(ut,"countFiles");function pt(e){if(typeof e!="object"||e===null)throw w("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw w("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw w("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw w("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&me(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new u(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw w("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw w("request_key must be a non-empty string of at most 128 characters when provided");return t}s(pt,"parseCreateBody");function mt(e){if(e===void 0)return;const t=Ln(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new u(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}s(mt,"parseDeadline");function wt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new u(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!En.test(e.action))throw new u(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ce)throw new u(413,"payload_too_large",`serialized payload exceeds ${ce} bytes`)}return e}}s(wt,"parseOutcomeDelivery");function ht(e,t){const n=Dn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new u(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new u(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}s(ht,"resolveOutcomeDelivery");function yt(e,t,n){const o={kind:e.kind,cwd:n,prompt:e.prompt??""};return e.mode!==void 0&&(o.mode=e.mode),e.name!==void 0&&(o.name=e.name),e.description!==void 0&&(o.description=e.description),t!==void 0&&(o.parent=t),e.creator!==void 0&&(o.creator=e.creator),e.scopes!==void 0&&(o.scopes=e.scopes),e.isolated!==void 0&&(o.isolated=e.isolated),e.root===!0&&(o.root=!0),e.root_lifecycle!==void 0&&(o.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(o.worktree=!0),typeof e.worktree=="string"&&(o.worktreeBase=e.worktree),e.worktree!==void 0&&(o.worktreeCwd=T(e.pin_cwd??e.cwd??n)),e.fork_from!==void 0&&(o.forkFrom=e.fork_from),e.model!==void 0&&(o.model=e.model),e.profile!==void 0&&(o.profile=e.profile),e.situational_context!==void 0&&(o.situationalContext=e.situational_context),e.node_id!==void 0&&(o.nodeId=e.node_id),o}s(yt,"buildRecipe");function _t(e,t,n){return!Gn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(_t,"warmRequestFor");import{resolveCreateKind as _o}from"../../../core/runtime/launch-target.js";function _e(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return An(e.model,t,e.modelExact===!0)}s(_e,"requestFromLaunch");function gt(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(o=>!I(t,o));if(n.length===0)return e;throw new u(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}s(gt,"withinCeiling");async function ge(e,t,n){const o=(await Rn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await K(_e(o),{cwd:e.cwd,profileId:e.profile_id??null},n)}s(ge,"assertNodeModelChangeRegistered");async function be(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const o=ot({app:n.app,resolved:await Zn(n),launched:n.scopes},t,"read");if("root"in o)return;const i="missing"in o?o.missing:null;throw new u(403,"scope_missing",i?`the child's directory ${t} needs missing scope ${i}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,i?{scope:i}:void 0)}s(be,"assertCallerReaches");const Q=new Map;async function bt(e,t={},n={}){const o=gt(pt(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(o.prefer_warm===!0&&c.app!=="app:terminal"&&(o.prefer_warm=!1),o.parent!=null){const r=await h(o.parent);if(r.grantee!==c.app)throw new u(403,"other_app_run","cannot create a child under another app's node");if(!await U(c,o.parent,r.grantee??"app:terminal"))throw E(`unknown node: ${o.parent}`,{received:o.parent})}if(o.creator!==void 0&&o.creator!==c.node)throw new u(403,"other_app_run","cannot create for another node");if(o.fork_from!==void 0){let r=null;try{r=await je(await Le(o.fork_from))}catch{}if(r?.grantee!==c.app||!await U(c,r.node_id,r.grantee))throw new u(403,"other_app_run","cannot fork another app's conversation")}o.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(o[l]!=null)throw new u(403,"permission_error",`a cron cannot set ${l} on a node it starts`);o.prefer_warm=!1;const r=await nn({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!r.allowed)throw new u(r.reason==="scope_missing"?403:401,r.reason==="scope_missing"?"scope_missing":"grant_revoked",r.message);if(o.scopes!==void 0){const l=o.scopes.find(p=>!I(r.effectiveScopes,p)||!I(c.scopes,p));if(l!==void 0)throw new u(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(o.scopes=[...c.scopes]);o.node_id=await ne(),c.isolated&&(o.isolated=!0,o.cwd=await V(o.node_id,c.app))}o.creator!==void 0&&Un(await h(o.creator),"crtr:act");const i=o.request_key?.trim();if(i===void 0||o.node_id!==void 0&&en(o.node_id)&&await R(o.node_id)!==null&&(await Fe(i))?.nodeId!==o.node_id)return D(e,o,t,n);const d=Q.get(i);if(d!==void 0)return d;const a=vt(e,o,i,t,n);Q.set(i,a);try{return await a}finally{Q.delete(i)}}s(bt,"handleCreate");async function vt(e,t,n,o,i){const d=await oe(n);if(d.nodeId!==null&&await R(d.nodeId)!==null){if(d.state!=="warm_claimed"){const a=await R(d.nodeId);if(e.principal.class!=="person"&&!await we(e.principal,a.grantee??"app:terminal",d.nodeId))throw new u(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await g(d.nodeId)}}return D(e,t,o,i,d)}try{return await D(e,t,o,i,d)}catch(a){const c=await oe(n);throw(c.nodeId===null||await R(c.nodeId)===null)&&await te(n,c.nodeId),a}}s(vt,"handleKeyedCreateRequest");async function D(e,t,n,o,i=void 0){const d=o.deadlineAt??mt(t.deadline),a=wt(t.outcome_delivery),c=e.principal.class==="cron"?await tn({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:(await pe(e.principal.cron))?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const r=c?.parent??t.parent??void 0;if(r==null&&t.root!==!0)throw w("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.output_schema)}catch{throw w("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw w("output_schema must be a JSON schema object");await Pn(l)}const{profileId:p,kind:m,cwd:f,launch:b}=await Bn(t,{validateKind:Oe});await be(e,f),t.worktree!==void 0&&await be(e,T(t.pin_cwd??t.cwd??f));const v={...t,kind:m},_=a===void 0?void 0:ht(a,f),X=("grant"in e.principal?e.principal.grant:null)??(r==null?null:(await R(r))?.grant_id??null);if(await K(_e(await Ee(b,X,t.model)),{cwd:f,profileId:p},n.modelRegistry),await at(X)!=="app"&&!await ft(p))throw new u(412,"no_provider_credential",he,{error:"no_provider_credential",message:he,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let M=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?_t(v,f,p):null,j=l===null&&o.beforeBrokerLaunch===void 0?void 0:async S=>{l!==null&&await Tn(S,"terminal",l),o.beforeBrokerLaunch?.(S)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const S=A===null?null:await jn(A,i.nodeId,j);if(S===null)throw await te(i.requestKey,i.nodeId),new u(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ie(i.requestKey,S),{status:201,body:await g(S)}}if(A!==null){const S=await Mn(A,{...d===void 0?{}:{deadlineAt:d},..._===void 0?{}:{outcomeDelivery:_},...i===void 0?{}:{requestKey:i.requestKey}},j);if(S!==null)return i!==void 0&&await ie(i.requestKey,S),fe(A),{status:201,body:await g(S)};M=A}const G=i?.nodeId??t.node_id??(i===void 0?void 0:await ne());i!==void 0&&i.nodeId===null&&await Ke(i.requestKey,G);const O=yt(G===void 0?v:{...v,node_id:G},r,f);c!==null&&(c.rootLifecycle!==void 0&&(O.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&v.scopes===void 0&&(O.scopes=c.scopes),c.run!==void 0&&(O.run=c.run),c.withinCreate!==void 0&&(O.withinCreate=c.withinCreate)),d!==void 0&&(O.deadlineAt=d),_!==void 0&&(O.outcomeDelivery=_),O.readiness=t.root===!0?"await":"launch";const Z=await Me(O,j,()=>{M!==null&&fe(M)});return i!==void 0&&await Be(i.requestKey,Z.node.node_id),{status:201,body:await g(Z.node.node_id)}}}s(D,"handleCreateRequest");function k(e,t){const n=e.query.getAll(t);if(n.length>1)throw w(`${t} must appear at most once`);return n[0]}s(k,"singleQueryValue");function ve(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w(`${t} must be true or false`)}}s(ve,"optionalBoolean");function L(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw w(`${t} must be one of: ${n.join(", ")}`)}}s(L,"oneOf");function kt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[b]of e.query)if(!t.has(b))throw w(`unknown nodes query parameter: ${b}`);const n=L(k(e,"status"),"status",["active","idle","done","dead","canceled"]),o=L(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=k(e,"kind"),d=L(k(e,"mode"),"mode",["base","orchestrator"]),a=k(e,"profile_id"),c=k(e,"profile_prefix"),r=k(e,"parent"),l=ve(k(e,"top_level"),"top_level"),p=k(e,"under"),m=ve(k(e,"hanging"),"hanging"),f=L(k(e,"include"),"include",["activity"]);if(r!==void 0&&l===!0)throw w("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...o!==void 0?{lifecycle:o}:{},...i!==void 0?{kind:i}:{},...d!==void 0?{mode:d}:{},...a!==void 0?{profile_id:a}:{},...c!==void 0?{profile_prefix:c}:{},...r!==void 0?{parent:r}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{hanging:m}:{},...f!==void 0?{include:f}:{}}}s(kt,"parseListQuery");async function St(e){const t=kt(e);let n=t.status!==void 0?await re({status:t.status}):await re();if(e.principal.class!=="person"&&(n=await Y(n,async a=>await we(e.principal,a.grantee??"app:terminal",a.node_id))),t.lifecycle!==void 0&&(n=n.filter(a=>a.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(a=>a.kind===t.kind)),t.mode!==void 0&&(n=n.filter(a=>a.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(a=>a.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(a=>a.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(a=>a.parent===t.parent)),t.top_level===!0&&(n=n.filter(a=>a.parent===null)),t.under!==void 0){const a=new Set(await ze(t.under));n=n.filter(c=>a.has(c.node_id))}t.hanging===!0&&(n=await Y(n,async a=>a.parent!==null&&await R(a.parent)===null));const o=t.include==="activity"?await qe(n.map(a=>a.node_id)):null,i=n.length>0?$e():new Set;return{status:200,body:await ye(n,async a=>{const c=await Hn(a,a.profile_id!==null&&i.has(a.profile_id));if(o!==null){const r=await ue(a.node_id);c.activity={latest_report:r[0]??null,final_report:a.final_report===null?null:r.find(l=>l.name===a.final_report)??null,pending_human_count:o[a.node_id]??0}}return c})}}s(St,"handleList");async function Rt(e){const t=e.params.id,n=await qn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:et(e)});if(n.kind==="unknown")throw tt(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw nt(n.status,n.body);return{status:n.status,body:it(n.body,n.machine)}}return await h(t),{status:200,body:await g(t)}}s(Rt,"handleDetail");async function Ot(e){const t=e.params.id;await h(t);const n=await cn(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:B()}}}s(Ot,"handleSnapshot");async function It(e){const t=e.params.id,n=await un(t);if(n===null)throw E(`unknown node: ${t}`,{received:t});return{status:200,body:n}}s(It,"handleSubject");function At(e){for(const[d]of e.query)if(d!=="cursor"&&d!=="limit")throw w(`unknown messages query parameter: ${d}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw w("cursor must appear at most once");if(n.length>1)throw w("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const o=n[0],i=Number(o);if(!Number.isSafeInteger(i)||o==="")throw w("limit must be an integer from 1 through 500");return t.length===0?{limit:i}:{cursor:t[0],limit:i}}s(At,"parseMessagesQuery");async function $t(e){const t=e.params.id,n=await sn(t,At(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:B()}}}s($t,"handleMessages");async function Ct(e){const t=e.params.id;await h(t);const n=await ln(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}s(Ct,"handleSession");async function Nt(e){const t=e.params.id;return await h(t),{status:200,body:{node_id:t,markdown:await fn(t)}}}s(Nt,"handleTranscript");async function Tt(e){const t=e.params.id;await h(t);const n=s(async(i,d)=>({node_id:i,label:(await R(i))?.name??i,dir:await de(i),self:d,files:await ut(i)}),"root"),o=await Y([await n(t,!0),...await ye(await ae(t),async i=>await n(i.node_id,!1))],async i=>await Pt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:t,roots:o}}}s(Tt,"handleContext");async function Pt(e,t){try{return on(await V(e),t)}catch(n){if(an(n))return!1;throw n}}s(Pt,"hasDir");async function Et(e){const t=await h(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,o=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(d=>I(n,d)),...n.filter(d=>I(t.scopes,d))])],i=await De(t.node_id,o,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await g(i.node.node_id)}}s(Et,"handleFork");const Dt=1e4;async function Lt(e){const t=e.params.id;await h(t);const n=e.body,o=n?.resume??!0,i=n?.reopen??!1;await _n(t,i,e.principal.class==="broker"?e.principal.node:null);const d=!o&&n?.cron_id!==void 0?await pe(n.cron_id):null,a=await Pe(t,{resume:o,capacity:"refuse",...d!==null?{wakeReason:await zn(d,"schedule_revive")}:{}});a.outcome!=="already-live"&&await We(t,{failures:0,notBefore:null});const c=(await R(t))?.status??"active",r=(a.launch??P().get(t)?.handle)?.exited,l=a.outcome!=="frozen"&&await le(t,r,Dt);return{status:200,body:Qn(t,a,c,l)}}s(Lt,"handleRevive");async function Mt(e){const t=e.params.id;return{status:200,body:{newNodeId:(await yn(t))?.newNodeId??null}}}s(Mt,"handleRelaunchRoot");async function jt(e){const t=e.params.id;await h(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw w("caller_pid must be a positive integer when provided");const o=Jn(),i=new Promise(a=>{e.res.once("close",()=>a())}),d=await Te(t,{teardownAfter:i,rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...o===null?{}:{registerDetached:o.registerDetached}});return{status:200,body:Yn(d)}}s(jt,"handleClose");async function Gt(e){if(!Xn(e.principal))throw new u(403,"permission_error","only the person marks a conversation read");const t=e.params.id;return await h(t),await Je(t),{status:204}}s(Gt,"handleMarkRead");async function Ft(e){const t=e.params.id;await h(t);const n=await hn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}s(Ft,"handleRecycle");async function Bt(e){const t=e.params.id;return await h(t),await x(t,{lifecycle:"terminal"}),await $(e,t,["lifecycle"]),{status:200,body:await g(t)}}s(Bt,"handleDemote");async function Kt(e,t={}){const n=e.params.id,o=await h(n),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":o.lifecycle,model:i.model},t.modelRegistry);const d=await mn(n,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await $(e,n,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const a=await J(d.meta,await H(n));return a.roadmap_written=d.roadmapWritten,a.roadmap_ref=d.roadmapRef,a.goal_path=d.goalPath,{status:200,body:a}}s(Kt,"handlePromote");async function Wt(e,t={}){const n=e.params.id,o=await h(n),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:i.promote===!0?"orchestrator":o.mode,lifecycle:o.lifecycle,model:i.model},t.modelRegistry);const d=i.note??"Refresh: continue against your roadmap or goal.";await gn(n,d);const a=await wn(n,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await J(a.meta,await H(n))}}s(Wt,"handleYield");async function Vt(e){const t=e.params.id;await h(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw w("a wait requires a controller node id");const o=await R(n.controller);if(o===null)throw E(`unknown controller: ${n.controller}`,{received:n.controller});if(o.status!=="active"&&o.status!=="idle")throw new u(422,"unprocessable",`controller ${n.controller} is ${o.status}`);return await xe(t,n.controller),{status:200,body:await g(t)}}s(Vt,"handleWait");async function xt(e){const t=e.principal,n=await pn(t.class==="broker"?async i=>i.grantee===t.app&&await U(t,i.node_id,i.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}s(xt,"handleReviveAll");const zt=new Set(["interrupt","steer","after-turn","next-turn"]);function Jt(e){if(e===null)return null;const t=s(o=>{throw new y({error:"invalid_listen",message:o,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[o,i]of n)/^(?:[1-9]|10)$/.test(o)||t(`listen level must be 1..10: ${o}`),(typeof i!="string"||!zt.has(i))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(n))}s(Jt,"listenJson");async function $(e,t,n,o){n.length===0&&o===void 0||await W(async i=>{if(o?.(i),n.length===0)return;const d=await Ue(i,t),a=await Qe(i,e),c=a.class==="person"?a.person:a.class==="app"?a.app:a.node;await Ye(i,c,d),await He(i,{event:"configured",object:d,actor:c,attrs:{changed:n.join(",")}})})}s($,"recordConfigured");function ke(e){const t=P().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}s(ke,"restartLiveBroker");function Se(e,t){try{return q(e)===q(t)}catch{return!1}}s(Se,"sameDirectory");async function Ut(e,t={}){const n=e.params.id,o=e.body;let i;if(o===void 0)i={};else if(typeof o=="object"&&o!==null&&!Array.isArray(o))i=o;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:o,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const r=await h(n),l=await Wn(e,i.profile);Vn(l.profileId);const p=xn(l.profileId).manifest.grantee??"app:terminal";if(p!==(r.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${r.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(r.profile_id??null)!==l.profileId&&(Fn(r.kind)?(await z(r.kind,r.cwd,l.profileId),await x(n,{profileId:l.profileId})):await C(n,{profile_id:l.profileId}),await $(e,n,["profile"])),i.restart===!0&&ke(n),{status:200,body:await g(n)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const r=i.cwd;if(typeof r!="string"||r==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:r,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&i[f]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(n),p=N(l.cwd);if(i.keep_session===!0||p&&F(r)&&N(r)&&Se(l.cwd,r)){if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const f=T(r);let b=!1;try{b=ee(f).isDirectory()}catch{}if(!b)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:r,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Se(l.cwd,f))throw new y({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:r,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot relocate its cwd`,received:r,field:"cwd",next:"Reconcile the managed worktree first."});const v=l.cwd;return v!==f&&(await W(async _=>{await C(n,{cwd:f}),await _.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,v),await Xe(n,v,f)}),await $(e,n,["cwd"])),i.restart===!0&&ke(n),{status:200,body:await g(n)}}if(P().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new u(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:r,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:r,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot repair its cwd`,received:r,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(l.cwd))throw new y({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:r,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const m=T(r);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ee(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:r,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof y?f:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await W(async()=>{await C(n,{cwd:m}),await Ze(n)}),await $(e,n,["cwd"]),{status:200,body:await g(n)}}let d=await h(n);const a=i.listen===void 0?void 0:Jt(i.listen);if(i.scopes!==void 0){const r=me(i.scopes),l=d.grantee==="app:terminal"?await dt():d.grant_id?await rt(d.grant_id):null,p=d.grantee==="app:terminal"&&!ct("user").runtime?.issuer;if(!r.every(m=>I(d.scopes,m)&&(l?I(l.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:r,field:"scopes",next:"Send only scopes the node currently holds."});if(r.includes("crtr:act")&&!I(r,"crtr:llm"))throw new u(400,"invalid_scope","crtr:act requires crtr:llm");d=await C(n,{scopes:r})}if(i.situational_context!==void 0&&Ce(n,Ne(i.situational_context)),i.model!==void 0){const r=(await se(d.cwd,d.profile_id??null)).modelLadders,l=On(i.model,r),p=await st(d.grant_id,i.model,l===void 0),m=p?{family:lt,strength:p.strength}:l,f=p?p.model:In(i.model,r);await K({kind:"concrete",spec:f},{cwd:d.cwd,profileId:d.profile_id??null},t.modelRegistry);const b=P();let v=!1;if(b.isClaimed(n)&&await le(n,b.get(n)?.handle.exited)&&(v=await Cn(n,f,m).then(()=>!0,_=>{if(_ instanceof Nn)return!1;throw _})),!v){if(b.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new u(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!f.includes("/"))throw w(`model must resolve to a provider/id spec: ${i.model}`);await $n(n,f,m)}d=await h(n)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Oe(i.kind);const r=i.kind??d.kind,l=i.mode??d.mode,p=i.lifecycle??d.lifecycle;let m;l==="orchestrator"&&!await kn(n)&&(m=s(async()=>{const f=await bn(n);await vn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),d=await x(n,{...i.kind!==void 0?{kind:r}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(d=await C(n,{name:i.name}),d.window&&Sn(d.window,Kn(d)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(r=>i[r]!==void 0);return await $(e,n,c,a===void 0?void 0:async r=>{await r.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(a,n)}),{status:200,body:await g(n)}}s(Ut,"handleConfig");async function Re(){return(await se(process.cwd(),Ae()||null)).kinds}s(Re,"daemonKinds");async function Oe(e){const t=Object.keys(await Re());if(!t.includes(e))throw w(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s(Oe,"assertKindServer");async function Yt(){const e=await Re();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}s(Yt,"handleListKinds");const wo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:bt},{method:"GET",pattern:"/v1/nodes",handler:St},{method:"GET",pattern:"/v1/kinds",handler:s(()=>Yt(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:xt},{method:"GET",pattern:"/v1/nodes/:id",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Ot},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:It},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:$t},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Ct},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Nt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Kt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Wt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Vt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Ut}];export{Ut as handleConfig,bt as handleCreate,Et as handleFork,St as handleList,Kt as handlePromote,Wt as handleYield,wo as nodeRoutes,_o as resolveCreateKind};
|
|
1
|
+
var Ie=Object.defineProperty;var d=(e,n)=>Ie(e,"name",{value:n,configurable:!0});import{envProfileId as Oe}from"../../../shared/env.js";import{pausedCanvasProfiles as Ae}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as q,statSync as ee}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as $e,formatSituationalProse as Ce}from"../../../core/runtime/situational-context.js";import{closeNode as Ne}from"../../../core/runtime/close.js";import{reviveNode as Te}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{appPaidLaunch as Pe,assertLaunchModelRegistered as K,forkNode as Ee,resolveForkSource as De,spawnChildPrepared as Le}from"../../../core/runtime/spawn.js";import{forkSourceNode as Me,newNodeId as ne}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as te,childrenOf as je,completeCreateRequest as ie,findCreateRequest as Ge,getNode as R,recordCreateRequestNode as Fe,reserveCreateRequest as oe,reserveCreateRequestNode as Be,listNodes as Ke,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as re,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as xe}from"../../../core/canvas/waits.js";import{withCanvasWrite as V}from"../../../core/canvas/db.js";import{markNodeRead as ze}from"../../../core/canvas/recovery.js";import{nodeObject as Je}from"../../../core/graph/objects.js";import{recordActedOn as Ue}from"../../../core/graph/edges.js";import{publish as Ye}from"../../../core/graph/events.js";import{readerFor as He}from"../reader.js";import{relocateSessionCwd as Qe,unbindSession as Xe}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as Ze}from"../../../core/canvas/attention.js";import{isSafeNodeId as qe}from"../../../core/canvas/paths.js";import{contextDir as ae,nodeAgentDir as W}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as en}from"../../cron/authority.js";import{cronBirthPlacement as nn}from"../../cron/armed-context.js";import{existsBeneath as tn,isAbsentOrRefused as on,isBeneathRefusal as rn,readdirBeneath as an}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as dn,readNodeSession as sn,readNodeSnapshot as ln,transcriptMarkdown as cn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as un}from"../../../core/substrate/subject.js";import{reviveAll as fn}from"../../../core/runtime/revive-all.js";import{promoteAsync as pn,requestYieldAsync as mn,reshapeNodeAsync as x}from"../../../core/runtime/promote.js";import{recycleNode as wn}from"../../../core/runtime/recycle.js";import{relaunchRoot as hn}from"../../../core/runtime/reset.js";import{assertReopenGate as yn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as _n,readGoal as gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as bn,hasRoadmap as vn}from"../../../core/runtime/roadmap.js";import{renameWindow as kn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Sn,explicitModelIntent as Rn,normalizeModel as In,readMergedLaunchConfigAsync as de}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as On}from"../../../core/model-routes.js";import{persistDormantModel as An,setModelLive as $n}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as se}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Cn}from"../../../core/runtime/broker-request.js";import{boundFleet as P}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Nn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Tn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as le}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Pn}from"../../../core/human/action-binding.js";import{resolveHumanAction as En}from"../../../core/human-actions.js";import{parseDurationMs as Dn}from"../../../core/wake.js";import{claimWarmNode as Ln,refillWarmPool as ce,resumeWarmClaim as Mn,warmPoolEnabled as jn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Gn,resolveLaunchTarget as Fn}from"../../../core/runtime/launch-target.js";import{fullName as Bn}from"../../../core/canvas/labels.js";import{reportsForNode as ue}from"./reports.js";import{requireUsableProfile as Kn}from"./profiles.js";import{assertProfileActive as Vn,loadExactProfileManifest as Wn}from"../../../core/profiles/manifest.js";import{getCron as fe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as xn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as zn}from"../../control.js";import{notFound as E,usage as w}from"../../../core/errors.js";import{assertScope as Jn,validateScopes as pe}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Un,toNodeDetailDTO as J,toNodeSummaryDTO as Yn,toReviveResultDTO as Hn}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Qn,brokerMayReach as U,canReadNode as me,resolvedScopes as Xn}from"../router.js";import{forwardVerb as Zn,queryWithoutMachine as qn,relayError as et,unknownError as nt,withMachine as tt}from"../../peer/forward.js";import{fileRoot as it}from"../../../core/spaces/file-root.js";import{activeGrant as ot,payerOfGrant as rt,terminalGrant as at}from"../../../core/grants/mirror.js";import{appRungForGrant as dt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as st}from"../../../core/model-routes.js";import{readConfig as lt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ct,NO_PROVIDER_CREDENTIAL_MESSAGE as we}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as he,mapAsync as ye}from"../../../core/async-array.js";async function h(e){const n=await R(e);if(n===null)throw E(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Y(e){return{subscribesTo:await re(e),subscribers:await We(e),children:await je(e)}}d(Y,"edgesFor");async function b(e){const n=await h(e);return await J(n,await Y(e))}d(b,"detailOf");async function ut(e){let n=(await ue(e)).length;try{n+=an(await W(e),await ae(e)).length}catch(t){if(!on(t))throw t}return n}d(ut,"countFiles");function ft(e){if(typeof e!="object"||e===null)throw w("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw w("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw w("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw w("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&pe(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw w("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 w("request_key must be a non-empty string of at most 128 characters when provided");return n}d(ft,"parseCreateBody");function pt(e){if(e===void 0)return;const n=Dn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(pt,"parseDeadline");function mt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Pn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>le)throw new f(413,"payload_too_large",`serialized payload exceeds ${le} bytes`)}return e}}d(mt,"parseOutcomeDelivery");function wt(e,n){const t=En(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(wt,"resolveOutcomeDelivery");function ht(e,n,t){const o={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(o.mode=e.mode),e.name!==void 0&&(o.name=e.name),e.description!==void 0&&(o.description=e.description),n!==void 0&&(o.parent=n),e.creator!==void 0&&(o.creator=e.creator),e.scopes!==void 0&&(o.scopes=e.scopes),e.isolated!==void 0&&(o.isolated=e.isolated),e.root===!0&&(o.root=!0),e.root_lifecycle!==void 0&&(o.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(o.worktree=!0),typeof e.worktree=="string"&&(o.worktreeBase=e.worktree),e.worktree!==void 0&&(o.worktreeCwd=T(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(o.forkFrom=e.fork_from),e.model!==void 0&&(o.model=e.model),e.profile!==void 0&&(o.profile=e.profile),e.situational_context!==void 0&&(o.situationalContext=e.situational_context),e.node_id!==void 0&&(o.nodeId=e.node_id),o}d(ht,"buildRecipe");function yt(e,n,t){return!jn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(yt,"warmRequestFor");import{resolveCreateKind as ho}from"../../../core/runtime/launch-target.js";function _e(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return On(e.model,n,e.modelExact===!0)}d(_e,"requestFromLaunch");function _t(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(o=>!O(n,o));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(_t,"withinCeiling");async function ge(e,n,t){const o=(await Sn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await K(_e(o),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(ge,"assertNodeModelChangeRegistered");async function be(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron")return;const o=it({app:t.app,resolved:await Xn(t),launched:t.scopes},n,"read");if("root"in o)return;const i="missing"in o?o.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(be,"assertCallerReaches");const H=new Map;async function gt(e,n={},t={}){const o=_t(ft(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(o.prefer_warm===!0&&c.app!=="app:terminal"&&(o.prefer_warm=!1),o.parent!=null){const r=await h(o.parent);if(r.grantee!==c.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await U(c,o.parent,r.grantee??"app:terminal"))throw E(`unknown node: ${o.parent}`,{received:o.parent})}if(o.creator!==void 0&&o.creator!==c.node)throw new f(403,"other_app_run","cannot create for another node");if(o.fork_from!==void 0){let r=null;try{r=await Me(await De(o.fork_from))}catch{}if(r?.grantee!==c.app||!await U(c,r.node_id,r.grantee))throw new f(403,"other_app_run","cannot fork another app's conversation")}o.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const s of["parent","creator","fork_from","node_id"])if(o[s]!=null)throw new f(403,"permission_error",`a cron cannot set ${s} on a node it starts`);o.prefer_warm=!1;const r=await en({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!r.allowed)throw new f(r.reason==="scope_missing"?403:401,r.reason==="scope_missing"?"scope_missing":"grant_revoked",r.message);if(o.scopes!==void 0){const s=o.scopes.find(p=>!O(r.effectiveScopes,p)||!O(c.scopes,p));if(s!==void 0)throw new f(403,"scope_missing",`scope ${s} is not held by this cron`,void 0,void 0,{scope:s})}else c.scopes!==null&&(o.scopes=[...c.scopes]);o.node_id=await ne(),c.isolated&&(o.isolated=!0,o.cwd=await W(o.node_id,c.app))}o.creator!==void 0&&Jn(await h(o.creator),"crtr:act");const i=o.request_key?.trim();if(i===void 0||o.node_id!==void 0&&qe(o.node_id)&&await R(o.node_id)!==null&&(await Ge(i))?.nodeId!==o.node_id)return D(e,o,n,t);const a=H.get(i);if(a!==void 0)return a;const l=bt(e,o,i,n,t);H.set(i,l);try{return await l}finally{H.delete(i)}}d(gt,"handleCreate");async function bt(e,n,t,o,i){const a=await oe(t);if(a.nodeId!==null&&await R(a.nodeId)!==null){if(a.state!=="warm_claimed"){const l=await R(a.nodeId);if(e.principal.class!=="person"&&!await me(e.principal,l.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return D(e,n,o,i,a)}try{return await D(e,n,o,i,a)}catch(l){const c=await oe(t);throw(c.nodeId===null||await R(c.nodeId)===null)&&await te(t,c.nodeId),l}}d(bt,"handleKeyedCreateRequest");async function D(e,n,t,o,i=void 0){const a=o.deadlineAt??pt(n.deadline),l=mt(n.outcome_delivery),c=e.principal.class==="cron"?await nn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:(await fe(e.principal.cron))?.created_by??null},n.node_id):null;c!==null&&(n.root=c.root===!0);const r=c?.parent??n.parent??void 0;if(r==null&&n.root!==!0)throw w("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 w("output_schema must be a JSON schema string")}if(s===null||typeof s!="object"||Array.isArray(s))throw w("output_schema must be a JSON schema object");await Tn(s)}const{profileId:p,kind:m,cwd:u,launch:k}=await Fn(n,{validateKind:Re});await be(e,u),n.worktree!==void 0&&await be(e,T(n.pin_cwd??n.cwd??u));const _={...n,kind:m},g=l===void 0?void 0:wt(l,u),X=("grant"in e.principal?e.principal.grant:null)??(r==null?null:(await R(r))?.grant_id??null);if(await K(_e(await Pe(k,X,n.model)),{cwd:u,profileId:p},t.modelRegistry),await rt(X)!=="app"&&!await ct(p))throw new f(412,"no_provider_credential",we,{error:"no_provider_credential",message:we,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let M=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?yt(_,u,p):null,j=s===null&&o.beforeBrokerLaunch===void 0?void 0:async S=>{s!==null&&await Nn(S,"terminal",s),o.beforeBrokerLaunch?.(S)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const S=A===null?null:await Mn(A,i.nodeId,j);if(S===null)throw await te(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ie(i.requestKey,S),{status:201,body:await b(S)}}if(A!==null){const S=await Ln(A,{...a===void 0?{}:{deadlineAt:a},...g===void 0?{}:{outcomeDelivery:g},...i===void 0?{}:{requestKey:i.requestKey}},j);if(S!==null)return i!==void 0&&await ie(i.requestKey,S),ce(A),{status:201,body:await b(S)};M=A}const G=i?.nodeId??n.node_id??(i===void 0?void 0:await ne());i!==void 0&&i.nodeId===null&&await Be(i.requestKey,G);const I=ht(G===void 0?_:{..._,node_id:G},r,u);c!==null&&(c.rootLifecycle!==void 0&&(I.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&_.scopes===void 0&&(I.scopes=c.scopes),c.run!==void 0&&(I.run=c.run),c.withinCreate!==void 0&&(I.withinCreate=c.withinCreate)),a!==void 0&&(I.deadlineAt=a),g!==void 0&&(I.outcomeDelivery=g),I.readiness=n.root===!0?"await":"launch";const Z=await Le(I,j,()=>{M!==null&&ce(M)});return i!==void 0&&await Fe(i.requestKey,Z.node.node_id),{status:201,body:await b(Z.node.node_id)}}}d(D,"handleCreateRequest");function v(e,n){const t=e.query.getAll(n);if(t.length>1)throw w(`${n} must appear at most once`);return t[0]}d(v,"singleQueryValue");function Q(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w(`${n} must be true or false`)}}d(Q,"optionalBoolean");function L(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw w(`${n} must be one of: ${t.join(", ")}`)}}d(L,"oneOf");function vt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[_]of e.query)if(!n.has(_))throw w(`unknown nodes query parameter: ${_}`);const t=L(v(e,"status"),"status",["active","idle","done","dead","canceled"]),o=L(v(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=v(e,"kind"),a=L(v(e,"mode"),"mode",["base","orchestrator"]),l=v(e,"profile_id"),c=v(e,"profile_prefix"),r=v(e,"parent"),s=Q(v(e,"top_level"),"top_level"),p=v(e,"under"),m=Q(v(e,"under_inclusive"),"under_inclusive"),u=Q(v(e,"hanging"),"hanging"),k=L(v(e,"include"),"include",["activity"]);if(r!==void 0&&s===!0)throw w("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...o!==void 0?{lifecycle:o}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...l!==void 0?{profile_id:l}:{},...c!==void 0?{profile_prefix:c}:{},...r!==void 0?{parent:r}:{},...s!==void 0?{top_level:s}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},...k!==void 0?{include:k}:{}}}d(vt,"parseListQuery");async function kt(e){const n=vt(e);let t=await Ke({...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}:{}});e.principal.class!=="person"&&(t=await he(t,async l=>await me(e.principal,l.grantee??"app:terminal",l.node_id)));const o=n.include==="activity"?await Ze(t.map(l=>l.node_id)):null,i=t.length>0?Ae():new Set;return{status:200,body:await ye(t,async l=>{const c=await Yn(l,l.profile_id!==null&&i.has(l.profile_id));if(o!==null){const r=await ue(l.node_id);c.activity={latest_report:r[0]??null,final_report:l.final_report===null?null:r.find(s=>s.name===l.final_report)??null,pending_human_count:o[l.node_id]??0}}return c})}}d(kt,"handleList");async function St(e){const n=e.params.id,t=await Zn(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:qn(e)});if(t.kind==="unknown")throw nt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw et(t.status,t.body);return{status:t.status,body:tt(t.body,t.machine)}}return await h(n),{status:200,body:await b(n)}}d(St,"handleDetail");async function Rt(e){const n=e.params.id;await h(n);const t=await ln(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:B()}}}d(Rt,"handleSnapshot");async function It(e){const n=e.params.id,t=await un(n);if(t===null)throw E(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(It,"handleSubject");function Ot(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw w(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw w("cursor must appear at most once");if(t.length>1)throw w("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const o=t[0],i=Number(o);if(!Number.isSafeInteger(i)||o==="")throw w("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(Ot,"parseMessagesQuery");async function At(e){const n=e.params.id,t=await dn(n,Ot(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:B()}}}d(At,"handleMessages");async function $t(e){const n=e.params.id;await h(n);const t=await sn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:B()}}}d($t,"handleSession");async function Ct(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await cn(n)}}}d(Ct,"handleTranscript");async function Nt(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await R(i))?.name??i,dir:await ae(i),self:a,files:await ut(i)}),"root"),o=await he([await t(n,!0),...await ye(await re(n),async i=>await t(i.node_id,!1))],async i=>await Tt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:o}}}d(Nt,"handleContext");async function Tt(e,n){try{return tn(await W(e),n)}catch(t){if(rn(t))return!1;throw t}}d(Tt,"hasDir");async function Pt(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,o=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await Ee(n.node_id,o,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}d(Pt,"handleFork");const Et=1e4;async function Dt(e){const n=e.params.id;await h(n);const t=e.body,o=t?.resume??!0,i=t?.reopen??!1;await yn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!o&&t?.cron_id!==void 0?await fe(t.cron_id):null,l=await Te(n,{resume:o,capacity:"refuse",...a!==null?{wakeReason:await xn(a,"schedule_revive")}:{}});l.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const c=(await R(n))?.status??"active",r=(l.launch??P().get(n)?.handle)?.exited,s=l.outcome!=="frozen"&&await se(n,r,Et);return{status:200,body:Hn(n,l,c,s)}}d(Dt,"handleRevive");async function Lt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await hn(n))?.newNodeId??null}}}d(Lt,"handleRelaunchRoot");async function Mt(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 w("caller_pid must be a positive integer when provided");const o=zn(),i=new Promise(l=>{e.res.once("close",()=>l())}),a=await Ne(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...o===null?{}:{registerDetached:o.registerDetached}});return{status:200,body:Un(a)}}d(Mt,"handleClose");async function jt(e){if(!Qn(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await ze(n),{status:204}}d(jt,"handleMarkRead");async function Gt(e){const n=e.params.id;await h(n);const t=await wn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Gt,"handleRecycle");async function Ft(e){const n=e.params.id;return await h(n),await x(n,{lifecycle:"terminal"}),await $(e,n,["lifecycle"]),{status:200,body:await b(n)}}d(Ft,"handleDemote");async function Bt(e,n={}){const t=e.params.id,o=await h(t),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":o.lifecycle,model:i.model},n.modelRegistry);const a=await pn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await $(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const l=await J(a.meta,await Y(t));return l.roadmap_written=a.roadmapWritten,l.roadmap_ref=a.roadmapRef,l.goal_path=a.goalPath,{status:200,body:l}}d(Bt,"handlePromote");async function Kt(e,n={}){const t=e.params.id,o=await h(t),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:i.promote===!0?"orchestrator":o.mode,lifecycle:o.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await _n(t,a);const l=await mn(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 J(l.meta,await Y(t))}}d(Kt,"handleYield");async function Vt(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 w("a wait requires a controller node id");const o=await R(t.controller);if(o===null)throw E(`unknown controller: ${t.controller}`,{received:t.controller});if(o.status!=="active"&&o.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${o.status}`);return await xe(n,t.controller),{status:200,body:await b(n)}}d(Vt,"handleWait");async function Wt(e){const n=e.principal,t=await fn(n.class==="broker"?async i=>i.grantee===n.app&&await U(n,i.node_id,i.grantee):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Wt,"handleReviveAll");const xt=new Set(["interrupt","steer","after-turn","next-turn"]);function zt(e){if(e===null)return null;const n=d(o=>{throw new y({error:"invalid_listen",message:o,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[o,i]of t)/^(?:[1-9]|10)$/.test(o)||n(`listen level must be 1..10: ${o}`),(typeof i!="string"||!xt.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(zt,"listenJson");async function $(e,n,t,o){t.length===0&&o===void 0||await V(async i=>{if(o?.(i),t.length===0)return;const a=await Je(i,n),l=await He(i,e),c=l.class==="person"?l.person:l.class==="app"?l.app:l.node;await Ue(i,c,a),await Ye(i,{event:"configured",object:a,actor:c,attrs:{changed:t.join(",")}})})}d($,"recordConfigured");function ve(e){const n=P().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(ve,"restartLiveBroker");function ke(e,n){try{return q(e)===q(n)}catch{return!1}}d(ke,"sameDirectory");async function Jt(e,n={}){const t=e.params.id,o=e.body;let i;if(o===void 0)i={};else if(typeof o=="object"&&o!==null&&!Array.isArray(o))i=o;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:o,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const r=await h(t),s=await Kn(e,i.profile);Vn(s.profileId);const p=Wn(s.profileId).manifest.grantee??"app:terminal";if(p!==(r.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${s.profileId} belongs to ${p}, node ${t} to ${r.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(r.profile_id??null)!==s.profileId&&(Gn(r.kind)?(await z(r.kind,r.cwd,s.profileId),await x(t,{profileId:s.profileId})):await C(t,{profile_id:s.profileId}),await $(e,t,["profile"])),i.restart===!0&&ve(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const r=i.cwd;if(typeof r!="string"||r==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:r,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const s=await h(t),p=N(s.cwd);if(i.keep_session===!0||p&&F(r)&&N(r)&&ke(s.cwd,r)){if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const u=T(r);let k=!1;try{k=ee(u).isDirectory()}catch{}if(!k)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:r,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ke(s.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${s.cwd}; --keep-session only relocates an alias`,received:r,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 y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:r,field:"cwd",next:"Reconcile the managed worktree first."});const _=s.cwd;return _!==u&&(await V(async g=>{await C(t,{cwd:u}),await g.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,_),await Qe(t,_,u)}),await $(e,t,["cwd"])),i.restart===!0&&ve(t),{status:200,body:await b(t)}}if(P().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:r,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(s.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${s.cwd}`,received:r,field:"cwd",next:`Restore ${s.cwd}, then revive the fork normally.`});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:r,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(s.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${s.cwd}; cwd repair is not a relocation command`,received:r,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const m=T(r);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ee(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:r,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await V(async()=>{await C(t,{cwd:m}),await Xe(t)}),await $(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await h(t);const l=i.listen===void 0?void 0:zt(i.listen);if(i.scopes!==void 0){const r=pe(i.scopes),s=a.grantee==="app:terminal"?await at():a.grant_id?await ot(a.grant_id):null,p=a.grantee==="app:terminal"&&!lt("user").runtime?.issuer;if(!r.every(m=>O(a.scopes,m)&&(s?O(s.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:r,field:"scopes",next:"Send only scopes the node currently holds."});if(r.includes("crtr:act")&&!O(r,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await C(t,{scopes:r})}if(i.situational_context!==void 0&&$e(t,Ce(i.situational_context)),i.model!==void 0){const r=(await de(a.cwd,a.profile_id??null)).modelLadders,s=Rn(i.model,r),p=await dt(a.grant_id,i.model,s===void 0),m=p?{family:st,strength:p.strength}:s,u=p?p.model:In(i.model,r);await K({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const k=P();let _=!1;if(k.isClaimed(t)&&await se(t,k.get(t)?.handle.exited)&&(_=await $n(t,u,m).then(()=>!0,g=>{if(g instanceof Cn)return!1;throw g})),!_){if(k.isClaimed(t)){const g=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",g,{error:"broker_not_ready",message:g,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw w(`model must resolve to a provider/id spec: ${i.model}`);await An(t,u,m)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Re(i.kind);const r=i.kind??a.kind,s=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;s==="orchestrator"&&!await vn(t)&&(m=d(async()=>{const u=await gn(t);await bn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await x(t,{...i.kind!==void 0?{kind:r}:{},...i.mode!==void 0?{mode:s}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await C(t,{name:i.name}),a.window&&kn(a.window,Bn(a)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(r=>i[r]!==void 0);return await $(e,t,c,l===void 0?void 0:async r=>{await r.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(l,t)}),{status:200,body:await b(t)}}d(Jt,"handleConfig");async function Se(){return(await de(process.cwd(),Oe()||null)).kinds}d(Se,"daemonKinds");async function Re(e){const n=Object.keys(await Se());if(!n.includes(e))throw w(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${n.sort().join(", ")}.`})}d(Re,"assertKindServer");async function Ut(){const e=await Se();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(Ut,"handleListKinds");const po=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:gt},{method:"GET",pattern:"/v1/nodes",handler:kt},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Ut(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Wt},{method:"GET",pattern:"/v1/nodes/:id",handler:St},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:It},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:At},{method:"GET",pattern:"/v1/nodes/:id/session",handler:$t},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ct},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Pt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Dt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Kt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Vt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Jt}];export{Jt as handleConfig,gt as handleCreate,Pt as handleFork,kt as handleList,Bt as handlePromote,Kt as handleYield,po as nodeRoutes,ho as resolveCreateKind};
|