@north-light/cli 0.3.652 → 0.3.654
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/build-root.js +1 -1
- package/dist/builtin-memory/crouter-sdk/client.md +1 -1
- package/dist/builtin-memory/internal/INDEX.md +2 -2
- package/dist/builtin-memory/internal/memory-loading.md +1 -1
- package/dist/builtin-memory/internal/nodes-and-canvas.md +13 -2
- package/dist/builtin-memory/internal/storage-tiers.md +43 -23
- package/dist/builtin-memory/northlight-apps/concepts/connections.md +2 -2
- package/dist/builtin-memory/northlight-apps/errors.md +1 -1
- package/dist/builtin-memory/northlight-apps/how-it-fits.md +2 -2
- package/dist/clients/attach/viewer.js +502 -502
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +1 -1
- package/dist/core/canvas/paths.d.ts +7 -9
- package/dist/core/canvas/schema-pg/017-machine-worktree-ops.sql +7 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/command-plugins/compose.d.ts +5 -1
- package/dist/core/command-plugins/compose.js +1 -1
- package/dist/core/runtime/runner/machine/call.d.ts +2 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/executor.d.ts +1 -1
- package/dist/core/runtime/runner/machine/ops.d.ts +59 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/worktree-close.d.ts +27 -0
- package/dist/core/worktree-close.js +6 -6
- package/dist/core/worktree-machine.d.ts +27 -0
- package/dist/core/worktree-machine.js +1 -0
- package/dist/core/worktree-mutation-async.d.ts +31 -0
- package/dist/core/worktree-mutation-async.js +7 -7
- package/dist/daemon/api/handlers/human-requests.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/reports.js +5 -5
- package/dist/daemon/api/handlers/worktree.js +1 -1
- package/dist/daemon/machine-daemon.js +1 -1
- package/docs/apps/concepts/connections.md +2 -2
- package/docs/apps/errors.md +1 -1
- package/docs/apps/how-it-fits.md +2 -2
- package/docs/cli/join-northlight.md +3 -2
- package/docs/sdk/client.md +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
var
|
|
2
|
-
stderr: ${
|
|
3
|
-
`).map(
|
|
1
|
+
var N=Object.defineProperty;var o=(t,e)=>N(t,"name",{value:e,configurable:!0});import{existsSync as d,mkdirSync as j,readFileSync as G,realpathSync as K,rmSync as z,writeFileSync as J}from"node:fs";import{basename as Q,dirname as U,isAbsolute as V,join as D,relative as X,resolve as Y,sep as S}from"node:path";import{abandonWorktreeAndRepoint as Z,getNode as b,readWorktree as ee}from"./canvas/index.js";import{isPidAlive as te}from"./canvas/pid.js";import{InputError as ae}from"./io.js";import{CONFIG_FILE as re,CRTR_DIR_NAME as M,STATE_FILE as ne}from"../types.js";import{withExclusiveDirectoryLockAsync as C}from"./exclusive-lock.js";import{gitAsync as s}from"./git.js";import{WORKTREE_LOCK_WAIT_MS as oe,canonicalPath as L,checkoutPathForBranchInList as ie,isManagedWorktreeBase as se,managedWorktreesRoot as ce,managedWorktreePath as he,persistClosedWorktreeState as y,worktreeLockPathForCommonDir as P,WorktreeError as c,branchIsPushedAtCurrentTip as le}from"./worktree.js";import{proveBranchContained as de}from"./worktree-containment.js";import{refDeleteTransactionStdin as ue}from"./worktree-landing.js";import{deleteTrashAsync as H,removeWorktreeCheckoutAsync as pe}from"./worktree-remove.js";const O=o(()=>Math.min(oe,25e3),"lockWaitMs");function g(t){return(t.stderr.trim()||t.stdout.trim()).trim()}o(g,"detailOf");async function h(t,e,a,r){const n=await s(e,t);if(n.status!==0)throw new c(a,`git ${e.join(" ")} failed`,r,g(n));return n.stdout.trim()}o(h,"runGit");async function R(t){return K(Y(t,await h(t,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.")))}o(R,"commonGitDir");async function m(t,e){const a=await R(t);return C(P(a),e,{timeoutMs:O(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting for the managed-worktree lock in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(m,"withRepositoryLock");function fe(t,e){const a=L(ce()),r=X(a,L(t));if(r===""||r===".."||r.startsWith(`..${S}`)||V(r))return null;const n=r.split(S)[0];return n===e?null:D(a,n)}o(fe,"foreignManagedCheckout");async function Oe(t,e,a){const r=fe(t,e);if(r===null)return a();const n=await ee(Q(r));return n===null?a():m(n.repo_root,async()=>{if(!d(t))throw new ae({error:"cwd_missing",message:`cwd is not an existing directory: ${t}`,received:t,field:"cwd",next:"Pass an existing directory; the managed checkout it was in has been cleaned up."});return a()})}o(Oe,"admitIntoManagedCheckout");async function v(t,e){const a=`refs/heads/${e}`,r=await s(["show-ref","--verify","--quiet",a],t);if(r.status===1&&r.executionFailed!==!0)throw new c("missing_base_branch",`managed worktree base '${e}' does not name an existing local branch`,"The base must be a local branch that landing can fast-forward \u2014 freshen your local branch from origin first (rebase-not-merge), then base on it.");if(r.status!==0)throw new c("base_branch_inspection_failed",`could not inspect local base branch '${e}' (git show-ref exited with status ${r.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${r.status}
|
|
2
|
+
stderr: ${r.stderr.trim()||"<empty>"}`);return h(t,["rev-parse","--verify",a],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(v,"resolveLandableBase");function me(t,e){try{const a=D(e,"info","exclude");j(U(a),{recursive:!0});let r="";try{r=G(a,"utf8")}catch{}const n=[`/${M}/${re}`,`/${M}/${ne}`];if(n.every(i=>r.split(`
|
|
3
|
+
`).map(u=>u.trim()).includes(i)))return;J(a,`${r}${r!==""&&!r.endsWith(`
|
|
4
4
|
`)?`
|
|
5
5
|
`:""}# crtr: exclude crtr's own untracked project-scope bookkeeping (auto-added at managed-worktree creation)
|
|
6
|
-
${
|
|
7
|
-
`).map(
|
|
6
|
+
${n.filter(i=>!r.split(`
|
|
7
|
+
`).map(u=>u.trim()).includes(i)).join(`
|
|
8
8
|
`)}
|
|
9
|
-
`)}catch{}}o(
|
|
10
|
-
`).some(n=>n.trim()===`branch refs/heads/${e.branch}`)){if((await i(["worktree","remove","--force",e.path],e.repo_root)).status!==0)return}else if(p(e.path))try{N(e.path,{recursive:!0,force:!0})}catch{return}await i(["update-ref","-d",`refs/heads/${e.branch}`,e.base_sha],e.repo_root)}})}o(Ce,"rollbackManagedWorktreeAsync");async function Le(e,a,r="main"){const n=await h(e,["rev-parse","--show-toplevel"],"not_git_repo","Pass --cwd <real repo> pointing inside a git repository.");if(ae(n))throw new c("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.");const t=await L(n);return W(M(t),async()=>{const s=await $(n,r),l=oe(a),u=`crtr/${a}`;if(p(l))throw new c("worktree_path_exists",`managed worktree path already exists: ${l}`,"Remove the stale path or choose a fresh node id.");if((await i(["show-ref","--verify","--quiet",`refs/heads/${u}`],n)).status===0)throw new c("worktree_branch_exists",`managed worktree branch already exists: ${u}`,"Remove the stale branch or choose a fresh node id.");const b={state:"open",path:l,branch:u,repo_root:n,base_ref:r,base_sha:s,created:new Date().toISOString()};await h(n,["branch",u,s],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");const f=await i(["worktree","add",l,u],n);if(f.status!==0)throw await i(["update-ref","-d",`refs/heads/${u}`,s],n),new c("worktree_add_failed","git worktree add failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.",v(f));return le(n,t),b},{timeoutMs:C(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${t}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(Le,"createManagedWorktreeAsync");async function P(e){if(e.state!=="open"||!p(e.path))return null;const a=await i(["rev-parse","--abbrev-ref","HEAD"],e.path),r=await i(["status","--porcelain"],e.path),n=await i(["rev-parse","HEAD"],e.path);if(a.status!==0||a.stdout.trim()!==e.branch||r.status!==0||r.stdout.trim()!==""||n.status!==0)return null;const t=await i(["rev-parse","--git-path","rebase-merge"],e.path);return t.status!==0||p(t.stdout.trim())?null:n.stdout.trim()}o(P,"cleanTip");async function F(e,a){try{const r=await $(e.path,e.base_ref);return(await i(["merge-base","--is-ancestor",a,r],e.path)).status===0}catch(r){if(r instanceof c&&r.code==="missing_base_branch")return a===e.base_sha;throw r}}o(F,"containedInLocalBase");function de(e){return{node_id:"",branch:e.branch,worktree_path:e.path,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${e.path} remains intact.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${e.branch} remains checked out at ${e.path}.`}}o(de,"deferred");async function R(e){if(e.state!=="open"||p(e.path))return null;const a=`refs/heads/${e.branch}`,r=await i(["show-ref","--verify","--quiet",a],e.repo_root);if(r.status===1&&r.executionFailed!==!0)return{branchSha:null};if(r.status!==0)return null;const n=await i(["rev-parse","--verify",a],e.repo_root);if(n.status!==0)return null;const t=n.stdout.trim(),s=await i(["worktree","list","--porcelain"],e.repo_root);if(s.status!==0||re(s.stdout,e.branch)!==null)return null;const l=await ie(e.repo_root,e,t);return l===null?null:{branchSha:t,containment:l}}o(R,"proveAbsentPathManagedWorktree");async function pe(e,a,r){return p(a.path)?null:r.branchSha===null?(await k(e,a,"complete"),{node_id:e,branch:a.branch,worktree_path:a.path,worktree_removed:!0,branch_deleted:!0}):r.containment===void 0?null:(await k(e,a,"complete"),{node_id:e,branch:a.branch,worktree_path:a.path,worktree_removed:!0,branch_deleted:!1,branch_delete_error:`local branch ${a.branch} is delivered but retained because its checkout status can change outside crtr's repository lock.`})}o(pe,"autoDropAbsentPathManagedWorktreeLocked");async function fe(e){const a=(await m(e))?.managed_worktree;return a==null||a.state!=="open"||p(a.path)||await R(a)===null?null:_(a.repo_root,async()=>{const r=(await m(e))?.managed_worktree;if(r==null||r.state!=="open")return null;const n=await R(r);if(n===null)return null;const t=await pe(e,r,n);return t===null?null:{dropped:t,landedSha:n.branchSha??r.base_sha}})}o(fe,"concludeAbsentManagedWorktreeAsync");async function Pe(e){const a=(await m(e))?.managed_worktree;if(a==null||a.state!=="open")return null;if(!p(a.path))return(await fe(e))?.dropped??null;const r=await P(a);return r===null||!await F(a,r)?null:_(a.path,async()=>{const n=(await m(e))?.managed_worktree;if(n==null||n.state!=="open")return null;const t=await P(n);return t===null||t!==r||!await F(n,t)?null:(await k(e,n,"pending"),{...de(n),node_id:e})})}o(Pe,"autoDropCleanManagedWorktreeAsync");async function T(e){for(const a of["rebase-merge","rebase-apply"]){const r=await i(["rev-parse","--git-path",a],e);if(r.status!==0||p(r.stdout.trim()))return!0}return!1}o(T,"rebaseInProgress");async function y(e,a,r,n,t,s=a.branch){await U(e,{cwd:a.repo_root,abandoned:{branch:s,tip_sha:r,at:n,by:t}})}o(y,"persistAbandoned");async function Fe(e,a){const r=(await m(e))?.managed_worktree;if(r==null||r.state!=="open")throw new c("no_managed_worktree",`node ${e} has no open managed worktree`,"Nothing to abandon for this node.");const n=[];try{return await _(r.path,()=>we(e,a,n))}finally{await ce(r.path,n[0])}}o(Fe,"abandonManagedWorktreeAsync");async function g(e,a){const{result:r,trash:n}=await he(e.repo_root,e.path);if(n!==void 0&&a.push(n),r.status!==0)throw new c("worktree_remove_failed",`git worktree remove ${e.path} failed`,"Inspect the worktree manually, then retry.",v(r))}o(g,"removeCheckout");async function we(e,a,r){const n=await m(e),t=n?.managed_worktree;if(n===null||t===void 0||t===null||t.state!=="open")throw new c("no_managed_worktree",`node ${e} has no open managed worktree`,"Nothing to abandon for this node.");if(n.status==="active"||n.status==="idle"||X(n.pi_pid))throw new c("node_running",`node ${e} is still running`,"Abandon requires a stopped node with no live broker process. From the running owner, use `crtr node worktree close` to land locally, or make the checkout clean, push its current tip to origin, and rerun `crtr push final`.");if(!p(t.path))throw new c("worktree_missing",`managed worktree path is missing: ${t.path}`,"Inspect the branch and worktree registration, then retry.");const s=await h(t.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),l=await i(["show-ref","--verify","--quiet",`refs/heads/${t.branch}`],t.path);if(s!==t.branch){if(l.status===0||s==="HEAD")throw new c("wrong_branch",`managed worktree is not on its recorded branch (expected ${t.branch}, found ${s==="HEAD"?"detached HEAD":s})`,`Inspect ${t.path}, then rerun \`crtr node worktree abandon\`.`);if(await T(t.path)||await h(t.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new c("dirty_worktree","managed worktree has uncommitted changes",`Commit or stash them in ${t.path}, then rerun \`crtr node worktree abandon\`.`);const d=await h(t.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the worktree manually, then retry.");await g(t,r);const w=new Date().toISOString();return await y(e,t,d,w,a,s),{node_id:e,branch:s,tip_sha:d,worktree_path:t.path,branch_deleted:!1}}const u=await h(t.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");let b=null;try{const d=await $(t.path,t.base_ref);(await i(["merge-base","--is-ancestor",u,d],t.path)).status===0&&(b=d)}catch(d){if(!(d instanceof c)||d.code!=="missing_base_branch")throw d}const f=new Date().toISOString(),H=await h(t.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.");if(b!==null&&u===t.base_sha){const d=await h(t.repo_root,["rev-parse",`${u}^{tree}`],"abandon_tree_failed","Inspect the branch manually, then retry."),w=await h(t.repo_root,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit-tree",d,"-p",u,"-m","crtr-abandon","-m",`Crtr-Abandon: ${e} ${f}`],"abandon_commit_failed","Inspect the branch manually, then retry.");return await h(t.repo_root,["update-ref",`refs/heads/${t.branch}`,w,u],"abandon_marker_failed","The branch changed while abandon was starting; inspect the worktree, then retry."),await g(t,r),(await i(["update-ref","--stdin"],t.repo_root,se(t.branch,w,`refs/heads/${t.base_ref}`,b))).status===0?(await k(e,t,"complete"),{node_id:e,branch:t.branch,tip_sha:w,worktree_path:t.path,branch_deleted:!0}):(await y(e,t,w,f,a),{node_id:e,branch:t.branch,tip_sha:w,worktree_path:t.path,branch_deleted:!1})}if(!await T(t.path)&&H==="")return await g(t,r),await y(e,t,u,f,a),{node_id:e,branch:t.branch,tip_sha:u,worktree_path:t.path,branch_deleted:!1};await h(t.path,["add","--all"],"abandon_stage_failed","Inspect the worktree manually, then retry."),await h(t.path,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit","--allow-empty","-m","crtr-abandon","-m",`Crtr-Abandon: ${e} ${f}`],"abandon_commit_failed","Inspect the worktree manually, then retry.");const A=await h(t.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");return await g(t,r),await y(e,t,A,f,a),{node_id:e,branch:t.branch,tip_sha:A,worktree_path:t.path,branch_deleted:!1}}o(we,"abandonLocked");export{Fe as abandonManagedWorktreeAsync,Me as admitIntoManagedCheckout,Pe as autoDropCleanManagedWorktreeAsync,fe as concludeAbsentManagedWorktreeAsync,Le as createManagedWorktreeAsync,Ce as rollbackManagedWorktreeAsync};
|
|
9
|
+
`)}catch{}}o(me,"seedExclude");async function Re(t){await m(t.repo_root,async()=>{const e=await s(["rev-parse","--verify",`refs/heads/${t.branch}`],t.repo_root);if(e.status!==0||e.stdout.trim()!==t.base_sha)return;const a=await s(["worktree","list","--porcelain"],t.repo_root);if(a.status===0){if(a.stdout.split(`
|
|
10
|
+
`).some(r=>r.trim()===`branch refs/heads/${t.branch}`)){if((await s(["worktree","remove","--force",t.path],t.repo_root)).status!==0)return}else if(d(t.path))try{z(t.path,{recursive:!0,force:!0})}catch{return}await s(["update-ref","-d",`refs/heads/${t.branch}`,t.base_sha],t.repo_root)}})}o(Re,"rollbackManagedWorktreeAsync");async function Te(t,e,a="main"){const r=await h(t,["rev-parse","--show-toplevel"],"not_git_repo","Pass --cwd <real repo> pointing inside a git repository.");if(se(r))throw new c("managed_worktree_base",`cwd ${r} 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.");const n=await R(r);return C(P(n),async()=>{const i=await v(r,a),u=he(e),l=`crtr/${e}`;if(d(u))throw new c("worktree_path_exists",`managed worktree path already exists: ${u}`,"Remove the stale path or choose a fresh node id.");if((await s(["show-ref","--verify","--quiet",`refs/heads/${l}`],r)).status===0)throw new c("worktree_branch_exists",`managed worktree branch already exists: ${l}`,"Remove the stale branch or choose a fresh node id.");const _={state:"open",path:u,branch:l,repo_root:r,base_ref:a,base_sha:i,created:new Date().toISOString()};await h(r,["branch",l,i],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");const f=await s(["worktree","add",u,l],r);if(f.status!==0)throw await s(["update-ref","-d",`refs/heads/${l}`,i],r),new c("worktree_add_failed","git worktree add failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.",g(f));return me(r,n),_},{timeoutMs:O(),timeoutError:o(()=>new c("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${n}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}o(Te,"createManagedWorktreeAsync");async function $(t){if(t.state!=="open"||!d(t.path))return null;const e=await s(["rev-parse","--abbrev-ref","HEAD"],t.path),a=await s(["status","--porcelain"],t.path),r=await s(["rev-parse","HEAD"],t.path);if(e.status!==0||e.stdout.trim()!==t.branch||a.status!==0||a.stdout.trim()!==""||r.status!==0)return null;const n=await s(["rev-parse","--git-path","rebase-merge"],t.path);return n.status!==0||d(n.stdout.trim())?null:r.stdout.trim()}o($,"cleanTip");async function A(t,e){try{const a=await v(t.path,t.base_ref);return(await s(["merge-base","--is-ancestor",e,a],t.path)).status===0}catch(a){if(a instanceof c&&a.code==="missing_base_branch")return e===t.base_sha;throw a}}o(A,"containedInLocalBase");function we(t){return{node_id:"",branch:t.branch,worktree_path:t.path,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${t.path} remains intact.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${t.branch} remains checked out at ${t.path}.`}}o(we,"deferred");async function x(t){if(t.state!=="open"||d(t.path))return null;const e=`refs/heads/${t.branch}`,a=await s(["show-ref","--verify","--quiet",e],t.repo_root);if(a.status===1&&a.executionFailed!==!0)return{branchSha:null};if(a.status!==0)return null;const r=await s(["rev-parse","--verify",e],t.repo_root);if(r.status!==0)return null;const n=r.stdout.trim(),i=await s(["worktree","list","--porcelain"],t.repo_root);if(i.status!==0||ie(i.stdout,t.branch)!==null)return null;const u=await de(t.repo_root,t,n);return u===null?null:{branchSha:n,containment:u}}o(x,"proveAbsentPathManagedWorktree");function be(t,e,a){return d(e.path)?null:a.branchSha===null?{node_id:t,branch:e.branch,worktree_path:e.path,worktree_removed:!0,branch_deleted:!0}:a.containment===void 0?null:{node_id:t,branch:e.branch,worktree_path:e.path,worktree_removed:!0,branch_deleted:!1,branch_delete_error:`local branch ${e.branch} is delivered but retained because its checkout status can change outside crtr's repository lock.`}}o(be,"absentPathDrop");async function T(t,e){const a=await x(e);if(a===null)return null;const r=be(t,e,a);return r===null?null:{dropped:r,landedSha:a.branchSha??e.base_sha}}o(T,"concludeAbsentLocked");async function _e(t){const e=(await b(t))?.managed_worktree;return e==null||e.state!=="open"||d(e.path)||await x(e)===null?null:m(e.repo_root,async()=>{const a=(await b(t))?.managed_worktree;if(a==null||a.state!=="open")return null;const r=await T(t,a);return r!==null&&await y(t,a,"complete"),r})}o(_e,"concludeAbsentManagedWorktreeAsync");async function ke(t,e){return e.state!=="open"||d(e.path)||await x(e)===null?null:m(e.repo_root,()=>T(t,e))}o(ke,"concludeAbsentManagedWorktreeOnHost");async function F(t,e,a){const r=await $(e);return r===null||r!==a||!await A(e,r)?null:{...we(e),node_id:t}}o(F,"autoDropCleanLocked");async function Fe(t){const e=(await b(t))?.managed_worktree;if(e==null||e.state!=="open")return null;if(!d(e.path))return(await _e(t))?.dropped??null;const a=await $(e);return a===null||!await A(e,a)?null:m(e.path,async()=>{const r=(await b(t))?.managed_worktree;if(r==null||r.state!=="open")return null;const n=await F(t,r,a);return n!==null&&await y(t,r,"pending"),n})}o(Fe,"autoDropCleanManagedWorktreeAsync");async function Ie(t,e){if(!d(e.path)){const r=await ke(t,e);return r===null?{kind:"open",missing:!0}:{kind:"dropped",dropped:r.dropped,cleanup:"complete"}}const a=await $(e);if(a!==null&&await A(e,a)){const r=await m(e.path,()=>F(t,e,a));if(r!==null)return{kind:"dropped",dropped:r,cleanup:"pending"}}return await le(e)?{kind:"pushed"}:{kind:"open",missing:!d(e.path)}}o(Ie,"finalizeManagedWorktreeOnHost");async function I(t){for(const e of["rebase-merge","rebase-apply"]){const a=await s(["rev-parse","--git-path",e],t);if(a.status!==0||d(a.stdout.trim()))return!0}return!1}o(I,"rebaseInProgress");async function ye(t,e,a){return a.persist.kind==="closed"?await y(t,e,"complete"):await Z(t,{cwd:e.repo_root,abandoned:a.persist.abandoned}),a.result}o(ye,"persistAbandonOutcome");function ge(t){return new c("node_running",`node ${t} is still running`,"Abandon requires a stopped node with no live broker process. From the running owner, use `crtr node worktree close` to land locally, or make the checkout clean, push its current tip to origin, and rerun `crtr push final`.")}o(ge,"nodeRunningError");async function Be(t,e){const a=(await b(t))?.managed_worktree;if(a==null||a.state!=="open")throw new c("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to abandon for this node.");const r=[];try{return await m(a.path,async()=>{const n=await b(t),i=n?.managed_worktree;if(n===null||i===void 0||i===null||i.state!=="open")throw new c("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to abandon for this node.");if(n.status==="active"||n.status==="idle"||te(n.pi_pid))throw ge(t);return ye(t,i,await B(t,i,e,r))})}finally{await H(a.path,r[0])}}o(Be,"abandonManagedWorktreeAsync");async function qe(t,e,a){const r=[];try{return await m(e.path,()=>B(t,e,a,r))}finally{await H(e.path,r[0])}}o(qe,"abandonManagedWorktreeOnHost");async function k(t,e){const{result:a,trash:r}=await pe(t.repo_root,t.path);if(r!==void 0&&e.push(r),a.status!==0)throw new c("worktree_remove_failed",`git worktree remove ${t.path} failed`,"Inspect the worktree manually, then retry.",g(a))}o(k,"removeCheckout");async function B(t,e,a,r){if(!d(e.path))throw new c("worktree_missing",`managed worktree path is missing: ${e.path}`,"Inspect the branch and worktree registration, then retry.");const n=o((p,w,E=e.branch)=>({kind:"abandoned",abandoned:{branch:E,tip_sha:p,at:w,by:a}}),"abandoned"),i=await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),u=await s(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path);if(i!==e.branch){if(u.status===0||i==="HEAD")throw new c("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${i==="HEAD"?"detached HEAD":i})`,`Inspect ${e.path}, then rerun \`crtr node worktree abandon\`.`);if(await I(e.path)||await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new c("dirty_worktree","managed worktree has uncommitted changes",`Commit or stash them in ${e.path}, then rerun \`crtr node worktree abandon\`.`);const p=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the worktree manually, then retry.");return await k(e,r),{result:{node_id:t,branch:i,tip_sha:p,worktree_path:e.path,branch_deleted:!1},persist:n(p,new Date().toISOString(),i)}}const l=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");let _=null;try{const p=await v(e.path,e.base_ref);(await s(["merge-base","--is-ancestor",l,p],e.path)).status===0&&(_=p)}catch(p){if(!(p instanceof c)||p.code!=="missing_base_branch")throw p}const f=new Date().toISOString(),q=await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.");if(_!==null&&l===e.base_sha){const p=await h(e.repo_root,["rev-parse",`${l}^{tree}`],"abandon_tree_failed","Inspect the branch manually, then retry."),w=await h(e.repo_root,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit-tree",p,"-p",l,"-m","crtr-abandon","-m",`Crtr-Abandon: ${t} ${f}`],"abandon_commit_failed","Inspect the branch manually, then retry.");return await h(e.repo_root,["update-ref",`refs/heads/${e.branch}`,w,l],"abandon_marker_failed","The branch changed while abandon was starting; inspect the worktree, then retry."),await k(e,r),(await s(["update-ref","--stdin"],e.repo_root,ue(e.branch,w,`refs/heads/${e.base_ref}`,_))).status===0?{result:{node_id:t,branch:e.branch,tip_sha:w,worktree_path:e.path,branch_deleted:!0},persist:{kind:"closed"}}:{result:{node_id:t,branch:e.branch,tip_sha:w,worktree_path:e.path,branch_deleted:!1},persist:n(w,f)}}if(!await I(e.path)&&q==="")return await k(e,r),{result:{node_id:t,branch:e.branch,tip_sha:l,worktree_path:e.path,branch_deleted:!1},persist:n(l,f)};await h(e.path,["add","--all"],"abandon_stage_failed","Inspect the worktree manually, then retry."),await h(e.path,["-c","user.name=crtr-abandon","-c","user.email=crtr-abandon@localhost","commit","--allow-empty","-m","crtr-abandon","-m",`Crtr-Abandon: ${t} ${f}`],"abandon_commit_failed","Inspect the worktree manually, then retry.");const W=await h(e.path,["rev-parse","HEAD"],"abandon_tip_failed","Inspect the branch manually, then retry.");return await k(e,r),{result:{node_id:t,branch:e.branch,tip_sha:W,worktree_path:e.path,branch_deleted:!1},persist:n(W,f)}}o(B,"abandonLocked");export{Be as abandonManagedWorktreeAsync,qe as abandonManagedWorktreeOnHost,Oe as admitIntoManagedCheckout,Fe as autoDropCleanManagedWorktreeAsync,_e as concludeAbsentManagedWorktreeAsync,ke as concludeAbsentManagedWorktreeOnHost,Te as createManagedWorktreeAsync,Ie as finalizeManagedWorktreeOnHost,Re as rollbackManagedWorktreeAsync};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var P=Object.defineProperty;var o=(e,t)=>P(e,"name",{value:t,configurable:!0});import{statSync as N}from"node:fs";import{isAbsolute as T}from"node:path";import{ApiError as s}from"../../../api/index.js";import{readDaemonActionById as C}from"../../../core/canvas/daemon-actions.js";import{isSafeNodeId as I}from"../../../core/canvas/paths.js";import{getNode as b}from"../../../core/canvas/canvas.js";import{assertScope as $}from"../../../core/scopes.js";import{resolvePageComponents as g}from"../../../core/config.js";import{resolveHumanAction as D}from"../../../core/human-actions.js";import{HUMAN_ACTION_NAME_PATTERN as x}from"../../../core/human/action-binding.js";import{createPageRequest as J,getRequest as F}from"../../../core/human/requests.js";import{preparePageSource as M}from"../../../core/human/page-authoring.js";import{PageCompilerError as B}from"../../../core/human/page-errors.js";import{publishPage as G,validatePageTicketResponses as H}from"../../../core/human/tickets.js";import{cancelHumanTicket as L,resolvePageTicket as U}from"../../human/finish.js";import{inboxPageProjection as K}from"./inbox-page.js";import{actsAsPerson as X,appOf as z}from"../router.js";const V=1e3,q=200,m={placement:"inline",inbox:!0,reply:!1},v=["sessionName","askedBy","emittedAt","profileName","nodeId"];function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(c,"isPlainObject");function l(e,t,n){for(const r of Object.keys(e))if(!t.includes(r))throw new s(400,"invalid_request",`unexpected field in ${n}: ${r}`)}o(l,"requireNoExtraKeys");function i(e){return new s(400,"invalid_request",e)}o(i,"invalid");function w(e){if(!c(e))throw i("`page` must be an object");if(l(e,["dialect","source"],"`page`"),e.dialect!=="jsx"&&e.dialect!=="html")throw i('`page.dialect` must be "jsx" or "html"');if(typeof e.source!="string"||e.source.trim()==="")throw i("`page.source` must be the authored page text");return{dialect:e.dialect,source:e.source}}o(w,"validatePage");function A(e,t){const n=e??t;if(n!=="inline"&&n!=="panel")throw i('`delivery.placement` must be "inline" or "panel"');return n}o(A,"validatePlacement");function Y(e,t){if(e===void 0)return m;if(!c(e))throw i("`delivery` must be an object");l(e,["placement","inbox","reply"],"`delivery`");const n=e.inbox??m.inbox,r=e.reply??m.reply;if(typeof n!="boolean")throw i("`delivery.inbox` must be boolean");if(typeof r!="boolean")throw i("`delivery.reply` must be boolean");if(r&&t===null)throw i("`delivery.reply` requires `requester_node_id`");return{placement:A(e.placement,m.placement),inbox:n,reply:r}}o(Y,"validateCreateDelivery");function Q(e,t){if(e===void 0)return t;if(!c(e))throw i("`delivery` must be an object");return l(e,["placement"],"`delivery`"),{...t,placement:A(e.placement,t.placement)}}o(Q,"validateReplaceDelivery");function W(e){if(e===void 0)return;if(!c(e))throw i("`source` must be an object");l(e,v,"`source`");const t={};for(const n of v){const r=e[n];if(r!==void 0){if(typeof r!="string"||r==="")throw i(`\`source.${n}\` must be a nonempty string`);t[n]=r}}return t}o(W,"validateSource");function Z(e){if(typeof e!="string"||e==="")throw i("`creator_cwd` is required");if(!T(e))throw i("`creator_cwd` must be an absolute path");try{if(!N(e).isDirectory())throw i(`\`creator_cwd\` is not a directory: ${e}`)}catch(t){throw t instanceof s?t:i(`\`creator_cwd\` does not exist: ${e}`)}return e}o(Z,"validateCreatorCwd");function ee(e){if(e!==void 0){if(!c(e))throw i("`action` must be an object");if(l(e,["name","payload"],"`action`"),typeof e.name!="string"||!x.test(e.name))throw i("`action.name` must be a declared action name");return{name:e.name,payload:e.payload??null}}}o(ee,"validateActionSelection");function te(e){if(e==null)return null;if(typeof e!="string"||!I(e))throw i("`requester_node_id` must be a safe node id or null");return e}o(te,"validateRequesterNodeId");function ne(e){if(!c(e))throw i("request body is required");l(e,["page","delivery","source","requester_node_id","creator_cwd","action"],"the request body");const t=W(e.source),n=te(e.requester_node_id),r=ee(e.action);return{page:w(e.page),delivery:Y(e.delivery,n),...t===void 0?{}:{source:t},requesterNodeId:n,creatorCwd:Z(e.creator_cwd),...r===void 0?{}:{action:r}}}o(ne,"validateCreateRequest");function re(e,t){if(!c(e))throw i("request body is required");return l(e,["page","delivery"],"the request body"),{page:w(e.page),delivery:Q(e.delivery,t)}}o(re,"validateReplaceRequest");function _(e,t,n){if(e!==void 0){if(typeof e!="string"||e.trim()===""||e.length>n)throw i(`\`${t}\` must be nonempty after trim and at most ${n} characters`);return e}}o(_,"optionalBoundedString");function oe(e){if(!c(e))throw i("request body is required");if(l(e,["responses","actor"],"the request body"),!c(e.responses))throw i("`responses` must be an object");const t=_(e.actor,"actor",q);return{responses:e.responses,...t===void 0?{}:{actor:t}}}o(oe,"validateRespondRequest");function ie(e){if(e===void 0)return{};if(!c(e))throw i("request body must be an object");l(e,["reason","actor"],"the request body");const t=_(e.reason,"reason",V),n=_(e.actor,"actor",q);return{...t===void 0?{}:{reason:t},...n===void 0?{}:{actor:n}}}o(ie,"validateSettleRequest");function h(e){const t=e.params.request_id;if(typeof t!="string"||t==="")throw i("request id is required");return t}o(h,"requestId");async function f(e){const t=await F(e);if(t===null||t.kind!=="page")throw new s(404,"not_found","no request with that id");return t}o(f,"requirePageRequest");function S(e){try{const t=JSON.parse(e.specification_json);if(!c(t))throw new Error("not an object");return t}catch{throw new s(500,"internal","the request specification could not be read")}}o(S,"manifest");function ae(e){if(e.result_json===null)return null;try{return JSON.parse(e.result_json)}catch{throw new s(500,"internal","the request result could not be read")}}o(ae,"terminalResult");function se(e){if(e.action_json===null)return null;try{const t=JSON.parse(e.action_json);if(t.schema!=="crtr.human-action-binding/v1"||typeof t.name!="string")throw new Error("invalid action");return t}catch{throw new s(500,"internal","the request action could not be read")}}o(se,"frozenAction");function de(e){return e.state!=="settled"?"pending":e.outcome==="answered"?"answered":e.outcome==="dismissed"?"dismissed":"canceled"}o(de,"requestState");async function ce(e){if(e.action_delivery_id===null)return{state:"none",attempt:0};const t=await C(e.action_delivery_id);if(t===null)return{state:"none",attempt:0};const n=t.state==="acknowledged"?"accepted":t.state==="permanent_failed"?"permanent_failed":t.state==="handed_off"?"running":"pending",r={state:n,attempt:t.attempts};return n==="pending"&&t.nextAttemptAt!==null&&(r.next_attempt_at=new Date(t.nextAttemptAt).toISOString()),t.acknowledgedAt!==null&&(r.accepted_at=new Date(t.acknowledgedAt).toISOString()),t.failedAt!==null&&(r.permanent_failed_at=new Date(t.failedAt).toISOString()),t.lastFailure!==null&&(r.last_failure=t.lastFailure),r}o(ce,"deliveryDetail");async function y(e){const t=S(e),n=ae(e),r=de(e),a={request_id:e.request_id,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,kind:e.kind,state:r,title:e.title,source:t.source??{},emitted_at:t.source?.emittedAt??e.created_at};e.subtitle!==null&&(a.subtitle=e.subtitle),e.kind==="page"&&(a.page=await K(e)),n!==null&&(a.settled_at=e.settled_at??e.updated_at,n.kind==="page"&&r==="answered"&&(a.responses=n.responses),n.kind==="canceled"&&n.reason!==void 0&&(a.reason=n.reason),n.kind==="page"&&n.actor!==void 0&&(a.actor=n.actor),n.kind==="canceled"&&n.actor!==void 0&&(a.actor=n.actor));const u=se(e);return u!==null&&(a.action={name:u.name,payload:u.payload},a.delivery=await ce(e)),a}o(y,"requestToDTO");function k(e,t,n,r){try{return M({dialect:e,document:t,source:n,delivery:r,productKinds:g()})}catch(a){throw a instanceof B?a:i(a instanceof Error?a.message:"the page could not be prepared")}}o(k,"prepareOrReject");async function ue(e){const t=ne(e.body),n=t.requesterNodeId??t.source?.nodeId;if(n!=null){const d=await b(n);d!==null&&$(d,"crtr:act")}let r;if(t.action!==void 0){const d=D(t.action.name,t.creatorCwd);if("kind"in d){const E=d.kind==="unknown_action"?`no action named ${d.name} is declared from ${t.creatorCwd}`:`${d.name} is declared in ${d.configOrigin} but unusable: ${d.reason}`;throw new s(400,d.kind,E)}const p=n==null?null:await b(n);if(n&&!p)throw new s(404,"not_found","action requester node not found");if(p&&!X(e.principal)&&p.grantee!==z(e.principal))throw new s(403,"permission_error","action requester belongs to another app");r=JSON.stringify({schema:"crtr.human-action-binding/v1",name:t.action.name,payload:t.action.payload,creatorCwd:t.creatorCwd,configOrigin:d.configOrigin,argv:d.argv,cwd:d.cwd,app:p?.grantee??(e.principal.class==="broker"?e.principal.app:"app:terminal")})}const a=k(t.page.dialect,t.page.source,t.source,t.delivery),u=await J({prepared:a,requester_node_id:t.requesterNodeId,...r===void 0?{}:{action_json:r}});return{status:201,body:{request_id:u.request_id,request_dir:u.request_dir,state:"pending",...t.action===void 0?{}:{action:{name:t.action.name}},delivery_state:"none"}}}o(ue,"handleCreate");async function le(e){return{status:200,body:await y(await f(h(e)))}}o(le,"handleGet");async function fe(e){const t=await f(h(e));if(t.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");const n=S(t),r=re(e.body,n.delivery),a=k(r.page.dialect,r.page.source,n.source,r.delivery);try{await G(t.request_dir,a)}catch(u){throw u instanceof Error&&u.message===`page request is not open: ${t.request_id}`?new s(409,"already_settled","the request already has a terminal result"):u}return{status:200,body:await y(await f(t.request_id))}}o(fe,"handleReplace");function O(e){return e instanceof s?e:e instanceof Error&&e.message.includes("unknown page request")?new s(404,"not_found","no request with that id"):e instanceof Error&&e.message==="page_has_no_response_lifecycle"?new s(409,"not_settleable","this request carries no response lifecycle"):new s(500,"internal","the request could not be settled")}o(O,"settlementError");function R(e){if(e.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");if(!e.settleable)throw new s(409,"not_settleable","this request carries no response lifecycle")}o(R,"requireSettleable");async function pe(e){const t=await f(h(e)),n=oe(e.body);R(t);try{await H(t.request_dir,n.responses)}catch(r){throw i(r instanceof Error?r.message:"the response map is invalid")}try{await U(t.request_id,n.responses,n.actor===void 0?{}:{actor:n.actor})}catch(r){throw O(r)}return{status:200,body:await y(await f(t.request_id))}}o(pe,"handleRespond");async function j(e,t){const n=await f(h(e)),r=ie(e.body);R(n);try{await L(n.request_id,{...r,disposition:t})}catch(a){throw O(a)}return{status:200,body:await y(await f(n.request_id))}}o(j,"settle");function me(){return{status:200,body:{components:[...g()]}}}o(me,"handleComponents");const Ce=[{method:"GET",pattern:"/v1/human/components",handler:o(()=>me(),"handler")},{method:"POST",pattern:"/v1/human/requests",scope:"crtr:act",handler:ue},{method:"GET",pattern:"/v1/human/requests/:request_id",handler:le},{method:"POST",pattern:"/v1/human/requests/:request_id/replace",handler:fe},{method:"POST",pattern:"/v1/human/requests/:request_id/respond",handler:pe},{method:"POST",pattern:"/v1/human/requests/:request_id/dismiss",handler:o(e=>j(e,"dismissed"),"handler")},{method:"POST",pattern:"/v1/human/requests/:request_id/cancel",handler:o(e=>j(e,"canceled"),"handler")}];export{Ce as humanRequestRoutes};
|
|
1
|
+
var P=Object.defineProperty;var o=(e,t)=>P(e,"name",{value:t,configurable:!0});import{statSync as N}from"node:fs";import{isAbsolute as C}from"node:path";import{ApiError as s}from"../../../api/index.js";import{readDaemonActionById as T}from"../../../core/canvas/daemon-actions.js";import{isSafeNodeId as I}from"../../../core/canvas/paths.js";import{isCloudRole as $}from"../../../core/canvas/person-state.js";import{getNode as b}from"../../../core/canvas/canvas.js";import{assertScope as D}from"../../../core/scopes.js";import{resolvePageComponents as g}from"../../../core/config.js";import{resolveHumanAction as x}from"../../../core/human-actions.js";import{HUMAN_ACTION_NAME_PATTERN as J}from"../../../core/human/action-binding.js";import{createPageRequest as F,getRequest as M}from"../../../core/human/requests.js";import{preparePageSource as B}from"../../../core/human/page-authoring.js";import{PageCompilerError as G}from"../../../core/human/page-errors.js";import{publishPage as H,validatePageTicketResponses as L}from"../../../core/human/tickets.js";import{cancelHumanTicket as U,resolvePageTicket as K}from"../../human/finish.js";import{inboxPageProjection as X}from"./inbox-page.js";import{actsAsPerson as z,appOf as V}from"../router.js";const Y=1e3,q=200,m={placement:"inline",inbox:!0,reply:!1},v=["sessionName","askedBy","emittedAt","profileName","nodeId"];function c(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(c,"isPlainObject");function l(e,t,n){for(const r of Object.keys(e))if(!t.includes(r))throw new s(400,"invalid_request",`unexpected field in ${n}: ${r}`)}o(l,"requireNoExtraKeys");function i(e){return new s(400,"invalid_request",e)}o(i,"invalid");function w(e){if(!c(e))throw i("`page` must be an object");if(l(e,["dialect","source"],"`page`"),e.dialect!=="jsx"&&e.dialect!=="html")throw i('`page.dialect` must be "jsx" or "html"');if(typeof e.source!="string"||e.source.trim()==="")throw i("`page.source` must be the authored page text");return{dialect:e.dialect,source:e.source}}o(w,"validatePage");function A(e,t){const n=e??t;if(n!=="inline"&&n!=="panel")throw i('`delivery.placement` must be "inline" or "panel"');return n}o(A,"validatePlacement");function Q(e,t){if(e===void 0)return m;if(!c(e))throw i("`delivery` must be an object");l(e,["placement","inbox","reply"],"`delivery`");const n=e.inbox??m.inbox,r=e.reply??m.reply;if(typeof n!="boolean")throw i("`delivery.inbox` must be boolean");if(typeof r!="boolean")throw i("`delivery.reply` must be boolean");if(r&&t===null)throw i("`delivery.reply` requires `requester_node_id`");return{placement:A(e.placement,m.placement),inbox:n,reply:r}}o(Q,"validateCreateDelivery");function W(e,t){if(e===void 0)return t;if(!c(e))throw i("`delivery` must be an object");return l(e,["placement"],"`delivery`"),{...t,placement:A(e.placement,t.placement)}}o(W,"validateReplaceDelivery");function Z(e){if(e===void 0)return;if(!c(e))throw i("`source` must be an object");l(e,v,"`source`");const t={};for(const n of v){const r=e[n];if(r!==void 0){if(typeof r!="string"||r==="")throw i(`\`source.${n}\` must be a nonempty string`);t[n]=r}}return t}o(Z,"validateSource");function ee(e){if(typeof e!="string"||e==="")throw i("`creator_cwd` is required");if(!C(e))throw i("`creator_cwd` must be an absolute path");if($())return e;try{if(!N(e).isDirectory())throw i(`\`creator_cwd\` is not a directory: ${e}`)}catch(t){throw t instanceof s?t:i(`\`creator_cwd\` does not exist: ${e}`)}return e}o(ee,"validateCreatorCwd");function te(e){if(e!==void 0){if(!c(e))throw i("`action` must be an object");if(l(e,["name","payload"],"`action`"),typeof e.name!="string"||!J.test(e.name))throw i("`action.name` must be a declared action name");return{name:e.name,payload:e.payload??null}}}o(te,"validateActionSelection");function ne(e){if(e==null)return null;if(typeof e!="string"||!I(e))throw i("`requester_node_id` must be a safe node id or null");return e}o(ne,"validateRequesterNodeId");function re(e){if(!c(e))throw i("request body is required");l(e,["page","delivery","source","requester_node_id","creator_cwd","action"],"the request body");const t=Z(e.source),n=ne(e.requester_node_id),r=te(e.action);return{page:w(e.page),delivery:Q(e.delivery,n),...t===void 0?{}:{source:t},requesterNodeId:n,creatorCwd:ee(e.creator_cwd),...r===void 0?{}:{action:r}}}o(re,"validateCreateRequest");function oe(e,t){if(!c(e))throw i("request body is required");return l(e,["page","delivery"],"the request body"),{page:w(e.page),delivery:W(e.delivery,t)}}o(oe,"validateReplaceRequest");function _(e,t,n){if(e!==void 0){if(typeof e!="string"||e.trim()===""||e.length>n)throw i(`\`${t}\` must be nonempty after trim and at most ${n} characters`);return e}}o(_,"optionalBoundedString");function ie(e){if(!c(e))throw i("request body is required");if(l(e,["responses","actor"],"the request body"),!c(e.responses))throw i("`responses` must be an object");const t=_(e.actor,"actor",q);return{responses:e.responses,...t===void 0?{}:{actor:t}}}o(ie,"validateRespondRequest");function ae(e){if(e===void 0)return{};if(!c(e))throw i("request body must be an object");l(e,["reason","actor"],"the request body");const t=_(e.reason,"reason",Y),n=_(e.actor,"actor",q);return{...t===void 0?{}:{reason:t},...n===void 0?{}:{actor:n}}}o(ae,"validateSettleRequest");function h(e){const t=e.params.request_id;if(typeof t!="string"||t==="")throw i("request id is required");return t}o(h,"requestId");async function f(e){const t=await M(e);if(t===null||t.kind!=="page")throw new s(404,"not_found","no request with that id");return t}o(f,"requirePageRequest");function S(e){try{const t=JSON.parse(e.specification_json);if(!c(t))throw new Error("not an object");return t}catch{throw new s(500,"internal","the request specification could not be read")}}o(S,"manifest");function se(e){if(e.result_json===null)return null;try{return JSON.parse(e.result_json)}catch{throw new s(500,"internal","the request result could not be read")}}o(se,"terminalResult");function de(e){if(e.action_json===null)return null;try{const t=JSON.parse(e.action_json);if(t.schema!=="crtr.human-action-binding/v1"||typeof t.name!="string")throw new Error("invalid action");return t}catch{throw new s(500,"internal","the request action could not be read")}}o(de,"frozenAction");function ce(e){return e.state!=="settled"?"pending":e.outcome==="answered"?"answered":e.outcome==="dismissed"?"dismissed":"canceled"}o(ce,"requestState");async function ue(e){if(e.action_delivery_id===null)return{state:"none",attempt:0};const t=await T(e.action_delivery_id);if(t===null)return{state:"none",attempt:0};const n=t.state==="acknowledged"?"accepted":t.state==="permanent_failed"?"permanent_failed":t.state==="handed_off"?"running":"pending",r={state:n,attempt:t.attempts};return n==="pending"&&t.nextAttemptAt!==null&&(r.next_attempt_at=new Date(t.nextAttemptAt).toISOString()),t.acknowledgedAt!==null&&(r.accepted_at=new Date(t.acknowledgedAt).toISOString()),t.failedAt!==null&&(r.permanent_failed_at=new Date(t.failedAt).toISOString()),t.lastFailure!==null&&(r.last_failure=t.lastFailure),r}o(ue,"deliveryDetail");async function y(e){const t=S(e),n=se(e),r=ce(e),a={request_id:e.request_id,inbox_ticket_id:e.inbox_ticket_id,request_dir:e.request_dir,kind:e.kind,state:r,title:e.title,source:t.source??{},emitted_at:t.source?.emittedAt??e.created_at};e.subtitle!==null&&(a.subtitle=e.subtitle),e.kind==="page"&&(a.page=await X(e)),n!==null&&(a.settled_at=e.settled_at??e.updated_at,n.kind==="page"&&r==="answered"&&(a.responses=n.responses),n.kind==="canceled"&&n.reason!==void 0&&(a.reason=n.reason),n.kind==="page"&&n.actor!==void 0&&(a.actor=n.actor),n.kind==="canceled"&&n.actor!==void 0&&(a.actor=n.actor));const u=de(e);return u!==null&&(a.action={name:u.name,payload:u.payload},a.delivery=await ue(e)),a}o(y,"requestToDTO");function k(e,t,n,r){try{return B({dialect:e,document:t,source:n,delivery:r,productKinds:g()})}catch(a){throw a instanceof G?a:i(a instanceof Error?a.message:"the page could not be prepared")}}o(k,"prepareOrReject");async function le(e){const t=re(e.body),n=t.requesterNodeId??t.source?.nodeId;if(n!=null){const d=await b(n);d!==null&&D(d,"crtr:act")}let r;if(t.action!==void 0){const d=x(t.action.name,t.creatorCwd);if("kind"in d){const E=d.kind==="unknown_action"?`no action named ${d.name} is declared from ${t.creatorCwd}`:`${d.name} is declared in ${d.configOrigin} but unusable: ${d.reason}`;throw new s(400,d.kind,E)}const p=n==null?null:await b(n);if(n&&!p)throw new s(404,"not_found","action requester node not found");if(p&&!z(e.principal)&&p.grantee!==V(e.principal))throw new s(403,"permission_error","action requester belongs to another app");r=JSON.stringify({schema:"crtr.human-action-binding/v1",name:t.action.name,payload:t.action.payload,creatorCwd:t.creatorCwd,configOrigin:d.configOrigin,argv:d.argv,cwd:d.cwd,app:p?.grantee??(e.principal.class==="broker"?e.principal.app:"app:terminal")})}const a=k(t.page.dialect,t.page.source,t.source,t.delivery),u=await F({prepared:a,requester_node_id:t.requesterNodeId,...r===void 0?{}:{action_json:r}});return{status:201,body:{request_id:u.request_id,request_dir:u.request_dir,state:"pending",...t.action===void 0?{}:{action:{name:t.action.name}},delivery_state:"none"}}}o(le,"handleCreate");async function fe(e){return{status:200,body:await y(await f(h(e)))}}o(fe,"handleGet");async function pe(e){const t=await f(h(e));if(t.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");const n=S(t),r=oe(e.body,n.delivery),a=k(r.page.dialect,r.page.source,n.source,r.delivery);try{await H(t.request_dir,a)}catch(u){throw u instanceof Error&&u.message===`page request is not open: ${t.request_id}`?new s(409,"already_settled","the request already has a terminal result"):u}return{status:200,body:await y(await f(t.request_id))}}o(pe,"handleReplace");function O(e){return e instanceof s?e:e instanceof Error&&e.message.includes("unknown page request")?new s(404,"not_found","no request with that id"):e instanceof Error&&e.message==="page_has_no_response_lifecycle"?new s(409,"not_settleable","this request carries no response lifecycle"):new s(500,"internal","the request could not be settled")}o(O,"settlementError");function R(e){if(e.state==="settled")throw new s(409,"already_settled","the request already has a terminal result");if(!e.settleable)throw new s(409,"not_settleable","this request carries no response lifecycle")}o(R,"requireSettleable");async function me(e){const t=await f(h(e)),n=ie(e.body);R(t);try{await L(t.request_dir,n.responses)}catch(r){throw i(r instanceof Error?r.message:"the response map is invalid")}try{await K(t.request_id,n.responses,n.actor===void 0?{}:{actor:n.actor})}catch(r){throw O(r)}return{status:200,body:await y(await f(t.request_id))}}o(me,"handleRespond");async function j(e,t){const n=await f(h(e)),r=ae(e.body);R(n);try{await U(n.request_id,{...r,disposition:t})}catch(a){throw O(a)}return{status:200,body:await y(await f(n.request_id))}}o(j,"settle");function he(){return{status:200,body:{components:[...g()]}}}o(he,"handleComponents");const $e=[{method:"GET",pattern:"/v1/human/components",handler:o(()=>he(),"handler")},{method:"POST",pattern:"/v1/human/requests",scope:"crtr:act",handler:le},{method:"GET",pattern:"/v1/human/requests/:request_id",handler:fe},{method:"POST",pattern:"/v1/human/requests/:request_id/replace",handler:pe},{method:"POST",pattern:"/v1/human/requests/:request_id/respond",handler:me},{method:"POST",pattern:"/v1/human/requests/:request_id/dismiss",handler:o(e=>j(e,"dismissed"),"handler")},{method:"POST",pattern:"/v1/human/requests/:request_id/cancel",handler:o(e=>j(e,"canceled"),"handler")}];export{$e as humanRequestRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ee=Object.defineProperty;var s=(e,n)=>Ee(e,"name",{value:n,configurable:!0});import{envProfileId as Ne}from"../../../shared/env.js";import{pausedCanvasProfiles as Ce}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as ne,statSync as te}from"node:fs";import{isAbsolute as x,resolve as L}from"node:path";import{appendSituationalContext as Te,formatSituationalProse as Pe}from"../../../core/runtime/situational-context.js";import{closeNode as De}from"../../../core/runtime/close.js";import{reviveNode as Le}from"../../../core/runtime/revive.js";import{nowIso as V}from"../../../core/fs-utils.js";import{appPaidLaunch as je,assertLaunchModelRegistered as W,forkNode as Me,resolveForkSource as ie,spawnChildPrepared as Ge}from"../../../core/runtime/spawn.js";import{forkSourceNode as re,newNodeId as oe}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ae,childrenOf as Fe,completeCreateRequest as de,findCreateRequest as se,getNode as R,recordCreateRequestNode as Be,reserveCreateRequest as le,reserveCreateRequestNode as Ke,listNodes as xe,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as ce,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as ze}from"../../../core/canvas/waits.js";import{withCanvasWrite as z}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as ue,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn,cronRefusalError as tn}from"../../cron/authority.js";import{cronBirthPlacement as rn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as an,isBeneathRefusal as dn,readdirBeneath as sn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as ln,readNodeSession as cn,readNodeSnapshot as un,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as pn}from"../../../core/substrate/subject.js";import{reviveAll as mn}from"../../../core/runtime/revive-all.js";import{promoteAsync as wn,requestYieldAsync as hn,reshapeNodeAsync as U}from"../../../core/runtime/promote.js";import{recycleNode as yn}from"../../../core/runtime/recycle.js";import{relaunchRoot as _n}from"../../../core/runtime/reset.js";import{assertReopenGate as gn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as bn}from"./broker-recovery.js";import{readOutputRequest as vn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as kn,readGoal as Sn,captureGoalIfAbsent as Rn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as In,hasRoadmap as On}from"../../../core/runtime/roadmap.js";import{renameWindow as An}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as $n,explicitModelIntent as En,normalizeModel as Nn,readMergedLaunchConfigAsync as fe}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Cn}from"../../../core/model-routes.js";import{persistDormantModel as Tn,setModelLive as Pn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as pe}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Dn}from"../../../core/runtime/broker-request.js";import{boundFleet as j}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Ln}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as jn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as me}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Mn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Gn}from"../../../core/human-actions.js";import{parseDurationMs as Fn}from"../../../core/wake.js";import{claimWarmNode as Bn,refillWarmPool as we,resumeWarmClaim as Kn,warmPoolEnabled as xn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as Vn,resolveLaunchTarget as Wn}from"../../../core/runtime/launch-target.js";import{fullName as zn}from"../../../core/canvas/labels.js";import{reportsForNode as he}from"./reports.js";import{requireUsableProfile as Jn}from"./profiles.js";import{assertProfileActive as Un,loadExactProfileManifest as Yn}from"../../../core/profiles/manifest.js";import{getCron as ye}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Hn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Qn}from"../../control.js";import{notFound as T,usage as h}from"../../../core/errors.js";import{assertScope as Xn,validateScopes as _e}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Zn,toNodeDetailDTO as H,toNodeSummaryDTO as qn,toReviveResultDTO as et}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{runsOnBlaxel as nt}from"../environment-of.js";import{actsAsPerson as M,canReadNode as $,mayOnNode as tt,readableNodeIds as it,resolvedScopes as rt}from"../router.js";import{forwardVerb as ot,queryWithoutMachine as at,relayError as dt,unknownError as st,withMachine as lt}from"../../peer/forward.js";import{fileRoot as ct}from"../../../core/spaces/file-root.js";import{activeGrant as ut,payerOfGrant as ft}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as pt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as mt}from"../../../core/grants/terminal.js";import{appRungForGrant as wt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as ht}from"../../../core/model-routes.js";import{listProfileEnvNames as yt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as _t,NO_PROVIDER_CREDENTIAL_MESSAGE as ge}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as gt,mapAsync as be}from"../../../core/async-array.js";async function w(e){const n=await R(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}s(w,"requireMeta");async function Q(e){return{subscribesTo:await ce(e),subscribers:await We(e),children:await Fe(e)}}s(Q,"edgesFor");async function b(e){const n=await w(e);return await H(n,await Q(e))}s(b,"detailOf");async function bt(e){let n=(await he(e)).length;try{n+=sn(await J(e),await ue(e)).length}catch(t){if(!an(t))throw t}return n}s(bt,"countFiles");function vt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&_e(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return n}s(vt,"parseCreateBody");function kt(e){if(e===void 0)return;const n=Fn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(kt,"parseDeadline");function St(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Mn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>me)throw new f(413,"payload_too_large",`serialized payload exceeds ${me} bytes`)}return e}}s(St,"parseOutcomeDelivery");function Rt(e,n){const t=Gn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(Rt,"resolveOutcomeDelivery");function It(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(It,"buildRecipe");function Ot(e,n,t){return!xn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(Ot,"warmRequestFor");import{resolveCreateKind as Tr}from"../../../core/runtime/launch-target.js";function ve(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Cn(e.model,n,e.modelExact===!0)}s(ve,"requestFromLaunch");function At(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!O(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s(At,"withinCeiling");async function ke(e,n,t){const r=(await $n(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await W(ve(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(ke,"assertNodeModelChangeRegistered");async function Se(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron")return;const r=ct({app:t.app,resolved:await rt(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s(Se,"assertCallerReaches");const X=new Map;async function $t(e,n={},t={}){const r=At(vt(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==d.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await $(d,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await re(await ie(r.fork_from))}catch{}if(o?.grantee!==d.app||!await $(d,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await re(await ie(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await R(o)!==null&&!await tt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new f(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await oe(),d.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,d.app));const o=await nn({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw tn(o);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(o.effectiveScopes,p)||!O(d.scopes,p));if(l!==void 0)throw new f(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else d.scopes!==null&&(r.scopes=[...d.scopes])}r.creator!==void 0&&Xn(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&en(r.node_id)&&await R(r.node_id)!==null&&(await se(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=X.get(i);if(a!==void 0)return a;const c=Nt(e,r,i,n,t);X.set(i,c);try{return await c}finally{X.delete(i)}}s($t,"handleCreate");const Re="create_request_in_progress";async function Et(e,n,t){const r=Date.now()+1e4;for(;t!==null;){const i=await R(t);if(i!==null){if(!M(e.principal)&&!await $(e.principal,i.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(t)}}if(Date.now()>=r||(await se(n))?.nodeId!==t)break;await new Promise(a=>setTimeout(a,100))}throw new f(409,Re,"another create with this request_key is in progress; retry it")}s(Et,"awaitForeignCreate");async function Nt(e,n,t,r,i){const a=await le(t);if(a.nodeId!==null&&await R(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await R(a.nodeId);if(!M(e.principal)&&!await $(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===Re)throw c;const d=await le(t);throw(d.nodeId===null||await R(d.nodeId)===null)&&await ae(t,d.nodeId),c}}s(Nt,"handleKeyedCreateRequest");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??kt(n.deadline),c=St(n.outcome_delivery),d=e.principal.class==="cron"?await rn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await ye(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await jn(l)}const p=await Wn(n,{validateKind:$e,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:m,kind:u,cwd:_,launch:S}=p;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!N(_)&&!await nt(m))throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Se(e,_),n.worktree!==void 0&&await Se(e,L(n.pin_cwd??n.cwd??_));const v={...n,kind:u},P=c===void 0?void 0:Rt(c,_),q=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await R(o))?.grant_id??null);if(await W(ve(await je(S,q,n.model)),{cwd:_,profileId:m},t.modelRegistry),await ft(q)!=="app"&&!await _t(m===null?[]:await yt(m))&&!await pt(p))throw new f(412,"no_provider_credential",ge,{error:"no_provider_credential",message:ge,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Ot(v,_,m):null,K=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Ln(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=A===null?null:await Kn(A,i.nodeId,K);if(g===null)throw await ae(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await de(i.requestKey,g),{status:201,body:await b(g)}}if(A!==null){const g=await Bn(A,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},K);if(g!==null)return i!==void 0&&await de(i.requestKey,g),we(A),{status:201,body:await b(g)};B=A}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await oe());if(i!==void 0&&i.nodeId===null){const g=await Ke(i.requestKey,D);if(g!==D)return await Et(e,i.requestKey,g)}const I=It(D===void 0?v:{...v,node_id:D},o,_);d!==null&&(d.rootLifecycle!==void 0&&(I.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&v.scopes===void 0&&(I.scopes=d.scopes),d.run!==void 0&&(I.run=d.run),d.withinCreate!==void 0&&(I.withinCreate=d.withinCreate)),a!==void 0&&(I.deadlineAt=a),P!==void 0&&(I.outcomeDelivery=P),I.readiness=n.root===!0?"await":"launch";const ee=await Ge(I,K,()=>{B!==null&&we(B)});return i!==void 0&&await Be(i.requestKey,ee.node.node_id),{status:201,body:await b(ee.node.node_id)}}}s(G,"handleCreateRequest");function k(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}s(k,"singleQueryValue");function Z(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}s(Z,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}s(F,"oneOf");function Ct(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[S]of e.query)if(!n.has(S))throw h(`unknown nodes query parameter: ${S}`);const t=F(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=k(e,"kind"),a=F(k(e,"mode"),"mode",["base","orchestrator"]),c=k(e,"profile_id"),d=k(e,"profile_prefix"),o=k(e,"parent"),l=Z(k(e,"top_level"),"top_level"),p=k(e,"under"),m=Z(k(e,"under_inclusive"),"under_inclusive"),u=Z(k(e,"hanging"),"hanging"),_=F(k(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}s(Ct,"parseListQuery");async function Tt(e){const n=Ct(e);let t=await xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await it(e.principal);r!==null&&(t=t.filter(d=>r.has(d.node_id)));const i=n.include==="activity"?await qe(t.map(d=>d.node_id)):null,a=t.length>0?Ce():new Set;return{status:200,body:await be(t,async d=>{const o=await qn(d,d.profile_id!==null&&a.has(d.profile_id));if(i!==null){const l=await he(d.node_id);o.activity={latest_report:l[0]??null,final_report:d.final_report===null?null:l.find(p=>p.name===d.final_report)??null,pending_human_count:i[d.node_id]??0}}return o})}}s(Tt,"handleList");async function Pt(e){const n=e.params.id,t=await ot(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:at(e)});if(t.kind==="unknown")throw st(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw dt(t.status,t.body);return{status:t.status,body:lt(t.body,t.machine)}}return await w(n),{status:200,body:await b(n)}}s(Pt,"handleDetail");async function Dt(e){const n=e.params.id;await w(n);const t=await un(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:V()}}}s(Dt,"handleSnapshot");async function Lt(e){const n=e.params.id,t=await pn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(Lt,"handleSubject");function jt(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(jt,"parseMessagesQuery");async function Mt(e){const n=e.params.id,t=await ln(n,jt(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:V()}}}s(Mt,"handleMessages");async function Gt(e){const n=e.params.id;await w(n);const t=await cn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:V()}}}s(Gt,"handleSession");async function Ft(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await fn(n)}}}s(Ft,"handleTranscript");async function Bt(e){const n=e.params.id;await w(n);const t=s(async(i,a)=>({node_id:i,label:(await R(i))?.name??i,dir:await ue(i),self:a,files:await bt(i)}),"root"),r=await gt([await t(n,!0),...await be(await ce(n),async i=>await t(i.node_id,!1))],async i=>await Kt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(Bt,"handleContext");async function Kt(e,n){try{return on(await J(e),n)}catch(t){if(dn(t))return!1;throw t}}s(Kt,"hasDir");async function xt(e){const n=await w(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await Me(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}s(xt,"handleFork");const Vt=1e4;async function Wt(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await gn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await ye(t.cron_id):null,c=await Le(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await Hn(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const d=(await R(n))?.status??"active",o=(c.launch??j().get(n)?.handle)?.exited,l=c.outcome!=="frozen"&&await pe(n,o,Vt);return{status:200,body:et(n,c,d,l)}}s(Wt,"handleRevive");async function zt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await _n(n))?.newNodeId??null}}}s(zt,"handleRelaunchRoot");async function Jt(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Qn(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await De(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Zn(a)}}s(Jt,"handleClose");async function Ut(e){if(!M(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await Je(n),{status:204}}s(Ut,"handleMarkRead");async function Yt(e){const n=e.params.id;await w(n);const t=await yn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Yt,"handleRecycle");async function Ht(e){const n=e.params.id;return await w(n),await U(n,{lifecycle:"terminal"}),await E(e,n,["lifecycle"]),{status:200,body:await b(n)}}s(Ht,"handleDemote");async function Qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await wn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await E(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await H(a.meta,await Q(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}s(Qt,"handlePromote");async function Xt(e){const n=e.params.id;return await w(n),{status:200,body:{request:await vn(n)}}}s(Xt,"handleBrokerStructuredRequest");async function Zt(e){const n=e.params.id,t=e.body??{};if(await bn(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Rn(n,t.text)}}}s(Zt,"handleBrokerGoal");async function qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await kn(t,a);const c=await hn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await H(c.meta,await Q(t))}}s(qt,"handleYield");async function ei(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await R(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await ze(n,t.controller),{status:200,body:await b(n)}}s(ei,"handleWait");async function ni(e){const n=e.principal,t=await mn(n.class==="broker"?async i=>i.grantee===n.app&&await $(n,i.grantee,i.node_id):n.class==="person"&&!M(n)?async i=>await $(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(ni,"handleReviveAll");const ti=new Set(["interrupt","steer","after-turn","next-turn"]);function ii(e){if(e===null)return null;const n=s(r=>{throw new y({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!ti.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(ii,"listenJson");async function E(e,n,t,r){t.length===0&&r===void 0||await z(async i=>{if(r?.(i),t.length===0)return;const a=await Ue(i,n),c=await Qe(i,e),d=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await Ye(i,d,a),await He(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s(E,"recordConfigured");function Ie(e){const n=j().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(Ie,"restartLiveBroker");function Oe(e,n){try{return ne(e)===ne(n)}catch{return!1}}s(Oe,"sameDirectory");async function ri(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),l=await Jn(e,i.profile);Un(l.profileId);const p=Yn(l.profileId).manifest.grantee??"app:terminal";if(p!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(Vn(o.kind)?(await Y(o.kind,o.cwd,l.profileId),await U(t,{profileId:l.profileId})):await C(t,{profile_id:l.profileId}),await E(e,t,["profile"])),i.restart===!0&&Ie(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await w(t),p=N(l.cwd);if(i.keep_session===!0||p&&x(o)&&N(o)&&Oe(l.cwd,o)){if(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=te(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Oe(l.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const S=l.cwd;return S!==u&&(await z(async v=>{await C(t,{cwd:u}),await v.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,S),await Xe(t,S,u)}),await E(e,t,["cwd"])),i.restart===!0&&Ie(t),{status:200,body:await b(t)}}if(await j().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(l.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const m=L(o);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!te(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await z(async()=>{await C(t,{cwd:m}),await Ze(t)}),await E(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await w(t);const c=i.listen===void 0?void 0:ii(i.listen);if(i.scopes!==void 0){const o=_e(i.scopes),l=a.grantee==="app:terminal"?await mt(a):a.grant_id?await ut(a.grant_id):null;if(!o.every(p=>O(a.scopes,p)&&l!==null&&O(l.resolved,p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!O(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await C(t,{scopes:o})}if(i.situational_context!==void 0&&await Te(t,Pe(i.situational_context)),i.model!==void 0){const o=(await fe(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=En(i.model,o),p=await wt(a.grant_id,i.model,l===void 0),m=p?{family:ht,strength:p.strength}:l,u=p?p.model:Nn(i.model,o);await W({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=j();let S=!1;if(await _.isClaimed(t)&&await pe(t,_.get(t)?.handle.exited)&&(S=await Pn(t,u,m).then(()=>!0,v=>{if(v instanceof Dn)return!1;throw v})),!S){if(await _.isClaimed(t)){const v=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",v,{error:"broker_not_ready",message:v,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Tn(t,u,m)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await $e(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;l==="orchestrator"&&!await On(t)&&(m=s(async()=>{const u=await Sn(t);await In(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await U(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await C(t,{name:i.name}),a.window&&An(a.window,zn(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await E(e,t,d,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await b(t)}}s(ri,"handleConfig");async function Ae(e="app:terminal"){return(await fe(process.cwd(),Ne()||null,e)).kinds}s(Ae,"daemonKinds");async function $e(e,n="app:terminal"){const t=Object.keys(await Ae(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s($e,"assertKindServer");async function oi(){const e=await Ae();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}s(oi,"handleListKinds");const Er=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:$t},{method:"GET",pattern:"/v1/nodes",handler:Tt},{method:"GET",pattern:"/v1/kinds",handler:s(()=>oi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:ni},{method:"GET",pattern:"/v1/nodes/:id",handler:Pt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Dt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Lt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Mt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Gt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ft},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:xt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Wt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:zt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Jt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ut},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Yt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ht},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Qt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:qt},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Xt},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Zt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:ei},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ri}];export{ri as handleConfig,$t as handleCreate,xt as handleFork,Tt as handleList,Qt as handlePromote,qt as handleYield,Er as nodeRoutes,Tr as resolveCreateKind};
|
|
1
|
+
var $e=Object.defineProperty;var s=(e,n)=>$e(e,"name",{value:n,configurable:!0});import{envProfileId as Ce}from"../../../shared/env.js";import{pausedCanvasProfiles as Ne}from"../../../core/profiles/manifest.js";import{existsSync as C,realpathSync as te,statSync as ie}from"node:fs";import{isAbsolute as x,resolve as L}from"node:path";import{appendSituationalContext as Te,formatSituationalProse as Pe}from"../../../core/runtime/situational-context.js";import{closeNode as De}from"../../../core/runtime/close.js";import{reviveNode as Le}from"../../../core/runtime/revive.js";import{nowIso as V}from"../../../core/fs-utils.js";import{appPaidLaunch as Me,assertLaunchModelRegistered as W,forkNode as je,resolveForkSource as re,spawnChildPrepared as Ge}from"../../../core/runtime/spawn.js";import{forkSourceNode as oe,newNodeId as ae}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as de,childrenOf as Fe,completeCreateRequest as se,findCreateRequest as le,getNode as k,recordCreateRequestNode as Be,reserveCreateRequest as ce,reserveCreateRequestNode as Ke,listNodes as xe,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as ue,updateNode as N}from"../../../core/canvas/canvas.js";import{armControllerWait as ze}from"../../../core/canvas/waits.js";import{withCanvasWrite as z}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as fe,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn,cronRefusalError as tn}from"../../cron/authority.js";import{cronBirthPlacement as rn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as an,isBeneathRefusal as dn,readdirBeneath as sn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as ln,readNodeSession as cn,readNodeSnapshot as un,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as pn}from"../../../core/substrate/subject.js";import{reviveAll as mn}from"../../../core/runtime/revive-all.js";import{promoteAsync as wn,requestYieldAsync as hn,reshapeNodeAsync as U}from"../../../core/runtime/promote.js";import{recycleNode as yn}from"../../../core/runtime/recycle.js";import{relaunchRoot as _n}from"../../../core/runtime/reset.js";import{assertReopenGate as gn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as bn}from"./broker-recovery.js";import{readOutputRequest as vn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as kn,readGoal as Sn,captureGoalIfAbsent as Rn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as On,hasRoadmap as In}from"../../../core/runtime/roadmap.js";import{renameWindow as An}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as En,explicitModelIntent as $n,normalizeModel as Cn,readMergedLaunchConfigAsync as pe}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Nn}from"../../../core/model-routes.js";import{persistDormantModel as Tn,setModelLive as Pn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as me}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Dn}from"../../../core/runtime/broker-request.js";import{boundFleet as M}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Ln}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Mn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as we}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as jn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Gn}from"../../../core/human-actions.js";import{parseDurationMs as Fn}from"../../../core/wake.js";import{claimWarmNode as Bn,refillWarmPool as he,resumeWarmClaim as Kn,warmPoolEnabled as xn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as Vn,resolveLaunchTarget as Wn}from"../../../core/runtime/launch-target.js";import{fullName as zn}from"../../../core/canvas/labels.js";import{reportsForNode as ye}from"./reports.js";import{requireUsableProfile as Jn}from"./profiles.js";import{assertProfileActive as Un,loadExactProfileManifest as Yn}from"../../../core/profiles/manifest.js";import{getCron as H}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Hn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Qn}from"../../control.js";import{notFound as T,usage as h}from"../../../core/errors.js";import{assertScope as Xn,validateScopes as _e}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Zn,toNodeDetailDTO as Q,toNodeSummaryDTO as qn,toReviveResultDTO as et}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{remoteEnvironmentOf as nt}from"../../../core/runtime/blaxel-environment.js";import{machineEnvironmentOfProfile as tt}from"../../../core/runtime/runner/machine/environment.js";import{isCloudRole as it}from"../../../core/canvas/person-state.js";import{actsAsPerson as j,canReadNode as E,mayOnNode as rt,readableNodeIds as ot,resolvedScopes as at}from"../router.js";import{forwardVerb as dt,queryWithoutMachine as st,relayError as lt,unknownError as ct,withMachine as ut}from"../../peer/forward.js";import{fileRoot as ft}from"../../../core/spaces/file-root.js";import{activeGrant as pt,payerOfGrant as mt}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as wt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as ht}from"../../../core/grants/terminal.js";import{appRungForGrant as yt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as _t}from"../../../core/model-routes.js";import{listProfileEnvNames as gt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as bt,NO_PROVIDER_CREDENTIAL_MESSAGE as ge}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as vt,mapAsync as be}from"../../../core/async-array.js";async function w(e){const n=await k(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}s(w,"requireMeta");async function X(e){return{subscribesTo:await ue(e),subscribers:await We(e),children:await Fe(e)}}s(X,"edgesFor");async function b(e){const n=await w(e);return await Q(n,await X(e))}s(b,"detailOf");async function kt(e){let n=(await ye(e)).length;try{n+=sn(await J(e),await fe(e)).length}catch(t){if(!an(t))throw t}return n}s(kt,"countFiles");function St(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&_e(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return n}s(St,"parseCreateBody");function Rt(e){if(e===void 0)return;const n=Fn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(Rt,"parseDeadline");function Ot(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!jn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>we)throw new f(413,"payload_too_large",`serialized payload exceeds ${we} bytes`)}return e}}s(Ot,"parseOutcomeDelivery");function It(e,n){const t=Gn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(It,"resolveOutcomeDelivery");function At(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(At,"buildRecipe");function Et(e,n,t){return!xn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(Et,"warmRequestFor");import{resolveCreateKind as jr}from"../../../core/runtime/launch-target.js";function ve(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Nn(e.model,n,e.modelExact===!0)}s(ve,"requestFromLaunch");function $t(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!I(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s($t,"withinCeiling");async function ke(e,n,t){const r=(await En(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await W(ve(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(ke,"assertNodeModelChangeRegistered");async function Ct(e){if(!it()||e.app!=="app:terminal")return!1;const n=e.class==="broker"?(await k(e.node))?.profile_id??null:e.cron===null?null:(await H(e.cron))?.profile??null;return n!==null&&await tt(n)!==null}s(Ct,"callerRunsOnMachine");async function Se(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron"||await Ct(t))return;const r=ft({app:t.app,resolved:await at(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s(Se,"assertCallerReaches");const Z=new Map;async function Nt(e,n={},t={}){const r=$t(St(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==d.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await E(d,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await oe(await re(r.fork_from))}catch{}if(o?.grantee!==d.app||!await E(d,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await oe(await re(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await k(o)!==null&&!await rt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new f(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await ae(),d.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,d.app));const o=await nn({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw tn(o);if(r.scopes!==void 0){const l=r.scopes.find(p=>!I(o.effectiveScopes,p)||!I(d.scopes,p));if(l!==void 0)throw new f(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else d.scopes!==null&&(r.scopes=[...d.scopes])}r.creator!==void 0&&Xn(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&en(r.node_id)&&await k(r.node_id)!==null&&(await le(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=Z.get(i);if(a!==void 0)return a;const c=Pt(e,r,i,n,t);Z.set(i,c);try{return await c}finally{Z.delete(i)}}s(Nt,"handleCreate");const Re="create_request_in_progress";async function Tt(e,n,t){const r=Date.now()+1e4;for(;t!==null;){const i=await k(t);if(i!==null){if(!j(e.principal)&&!await E(e.principal,i.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(t)}}if(Date.now()>=r||(await le(n))?.nodeId!==t)break;await new Promise(a=>setTimeout(a,100))}throw new f(409,Re,"another create with this request_key is in progress; retry it")}s(Tt,"awaitForeignCreate");async function Pt(e,n,t,r,i){const a=await ce(t);if(a.nodeId!==null&&await k(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await k(a.nodeId);if(!j(e.principal)&&!await E(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===Re)throw c;const d=await ce(t);throw(d.nodeId===null||await k(d.nodeId)===null)&&await de(t,d.nodeId),c}}s(Pt,"handleKeyedCreateRequest");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??Rt(n.deadline),c=Ot(n.outcome_delivery),d=e.principal.class==="cron"?await rn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await H(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await Mn(l)}const p=await Wn(n,{validateKind:Ee,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:m,kind:u,cwd:_,launch:R}=p;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!C(_)&&await nt(m)===null)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Se(e,_),n.worktree!==void 0&&await Se(e,L(n.pin_cwd??n.cwd??_));const v={...n,kind:u},P=c===void 0?void 0:It(c,_),ee=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await k(o))?.grant_id??null);if(await W(ve(await Me(R,ee,n.model)),{cwd:_,profileId:m},t.modelRegistry),await mt(ee)!=="app"&&!await bt(m===null?[]:await gt(m))&&!await wt(p))throw new f(412,"no_provider_credential",ge,{error:"no_provider_credential",message:ge,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Et(v,_,m):null,K=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Ln(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=A===null?null:await Kn(A,i.nodeId,K);if(g===null)throw await de(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await se(i.requestKey,g),{status:201,body:await b(g)}}if(A!==null){const g=await Bn(A,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},K);if(g!==null)return i!==void 0&&await se(i.requestKey,g),he(A),{status:201,body:await b(g)};B=A}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await ae());if(i!==void 0&&i.nodeId===null){const g=await Ke(i.requestKey,D);if(g!==D)return await Tt(e,i.requestKey,g)}const O=At(D===void 0?v:{...v,node_id:D},o,_);d!==null&&(d.rootLifecycle!==void 0&&(O.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&v.scopes===void 0&&(O.scopes=d.scopes),d.run!==void 0&&(O.run=d.run),d.withinCreate!==void 0&&(O.withinCreate=d.withinCreate)),a!==void 0&&(O.deadlineAt=a),P!==void 0&&(O.outcomeDelivery=P),O.readiness=n.root===!0?"await":"launch";const ne=await Ge(O,K,()=>{B!==null&&he(B)});return i!==void 0&&await Be(i.requestKey,ne.node.node_id),{status:201,body:await b(ne.node.node_id)}}}s(G,"handleCreateRequest");function S(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}s(S,"singleQueryValue");function q(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}s(q,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}s(F,"oneOf");function Dt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[R]of e.query)if(!n.has(R))throw h(`unknown nodes query parameter: ${R}`);const t=F(S(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(S(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=S(e,"kind"),a=F(S(e,"mode"),"mode",["base","orchestrator"]),c=S(e,"profile_id"),d=S(e,"profile_prefix"),o=S(e,"parent"),l=q(S(e,"top_level"),"top_level"),p=S(e,"under"),m=q(S(e,"under_inclusive"),"under_inclusive"),u=q(S(e,"hanging"),"hanging"),_=F(S(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}s(Dt,"parseListQuery");async function Lt(e){const n=Dt(e);let t=await xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await ot(e.principal);r!==null&&(t=t.filter(d=>r.has(d.node_id)));const i=n.include==="activity"?await qe(t.map(d=>d.node_id)):null,a=t.length>0?Ne():new Set;return{status:200,body:await be(t,async d=>{const o=await qn(d,d.profile_id!==null&&a.has(d.profile_id));if(i!==null){const l=await ye(d.node_id);o.activity={latest_report:l[0]??null,final_report:d.final_report===null?null:l.find(p=>p.name===d.final_report)??null,pending_human_count:i[d.node_id]??0}}return o})}}s(Lt,"handleList");async function Mt(e){const n=e.params.id,t=await dt(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:st(e)});if(t.kind==="unknown")throw ct(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw lt(t.status,t.body);return{status:t.status,body:ut(t.body,t.machine)}}return await w(n),{status:200,body:await b(n)}}s(Mt,"handleDetail");async function jt(e){const n=e.params.id;await w(n);const t=await un(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:V()}}}s(jt,"handleSnapshot");async function Gt(e){const n=e.params.id,t=await pn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(Gt,"handleSubject");function Ft(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(Ft,"parseMessagesQuery");async function Bt(e){const n=e.params.id,t=await ln(n,Ft(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:V()}}}s(Bt,"handleMessages");async function Kt(e){const n=e.params.id;await w(n);const t=await cn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:V()}}}s(Kt,"handleSession");async function xt(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await fn(n)}}}s(xt,"handleTranscript");async function Vt(e){const n=e.params.id;await w(n);const t=s(async(i,a)=>({node_id:i,label:(await k(i))?.name??i,dir:await fe(i),self:a,files:await kt(i)}),"root"),r=await vt([await t(n,!0),...await be(await ue(n),async i=>await t(i.node_id,!1))],async i=>await Wt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(Vt,"handleContext");async function Wt(e,n){try{return on(await J(e),n)}catch(t){if(dn(t))return!1;throw t}}s(Wt,"hasDir");async function zt(e){const n=await w(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>I(t,a)),...t.filter(a=>I(n.scopes,a))])],i=await je(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}s(zt,"handleFork");const Jt=1e4;async function Ut(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await gn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await H(t.cron_id):null,c=await Le(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await Hn(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const d=(await k(n))?.status??"active",o=(c.launch??M().get(n)?.handle)?.exited,l=c.outcome!=="frozen"&&await me(n,o,Jt);return{status:200,body:et(n,c,d,l)}}s(Ut,"handleRevive");async function Yt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await _n(n))?.newNodeId??null}}}s(Yt,"handleRelaunchRoot");async function Ht(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Qn(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await De(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Zn(a)}}s(Ht,"handleClose");async function Qt(e){if(!j(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await Je(n),{status:204}}s(Qt,"handleMarkRead");async function Xt(e){const n=e.params.id;await w(n);const t=await yn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Xt,"handleRecycle");async function Zt(e){const n=e.params.id;return await w(n),await U(n,{lifecycle:"terminal"}),await $(e,n,["lifecycle"]),{status:200,body:await b(n)}}s(Zt,"handleDemote");async function qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await wn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await $(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await Q(a.meta,await X(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}s(qt,"handlePromote");async function ei(e){const n=e.params.id;return await w(n),{status:200,body:{request:await vn(n)}}}s(ei,"handleBrokerStructuredRequest");async function ni(e){const n=e.params.id,t=e.body??{};if(await bn(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Rn(n,t.text)}}}s(ni,"handleBrokerGoal");async function ti(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await kn(t,a);const c=await hn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Q(c.meta,await X(t))}}s(ti,"handleYield");async function ii(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await k(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await ze(n,t.controller),{status:200,body:await b(n)}}s(ii,"handleWait");async function ri(e){const n=e.principal,t=await mn(n.class==="broker"?async i=>i.grantee===n.app&&await E(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await E(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(ri,"handleReviveAll");const oi=new Set(["interrupt","steer","after-turn","next-turn"]);function ai(e){if(e===null)return null;const n=s(r=>{throw new y({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!oi.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(ai,"listenJson");async function $(e,n,t,r){t.length===0&&r===void 0||await z(async i=>{if(r?.(i),t.length===0)return;const a=await Ue(i,n),c=await Qe(i,e),d=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await Ye(i,d,a),await He(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s($,"recordConfigured");function Oe(e){const n=M().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(Oe,"restartLiveBroker");function Ie(e,n){try{return te(e)===te(n)}catch{return!1}}s(Ie,"sameDirectory");async function di(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),l=await Jn(e,i.profile);Un(l.profileId);const p=Yn(l.profileId).manifest.grantee??"app:terminal";if(p!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(Vn(o.kind)?(await Y(o.kind,o.cwd,l.profileId),await U(t,{profileId:l.profileId})):await N(t,{profile_id:l.profileId}),await $(e,t,["profile"])),i.restart===!0&&Oe(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await w(t),p=C(l.cwd);if(i.keep_session===!0||p&&x(o)&&C(o)&&Ie(l.cwd,o)){if(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=ie(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Ie(l.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const R=l.cwd;return R!==u&&(await z(async v=>{await N(t,{cwd:u}),await v.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,R),await Xe(t,R,u)}),await $(e,t,["cwd"])),i.restart===!0&&Oe(t),{status:200,body:await b(t)}}if(await M().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(C(l.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const m=L(o);if(!C(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ie(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await z(async()=>{await N(t,{cwd:m}),await Ze(t)}),await $(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await w(t);const c=i.listen===void 0?void 0:ai(i.listen);if(i.scopes!==void 0){const o=_e(i.scopes),l=a.grantee==="app:terminal"?await ht(a):a.grant_id?await pt(a.grant_id):null;if(!o.every(p=>I(a.scopes,p)&&l!==null&&I(l.resolved,p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!I(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await N(t,{scopes:o})}if(i.situational_context!==void 0&&await Te(t,Pe(i.situational_context)),i.model!==void 0){const o=(await pe(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=$n(i.model,o),p=await yt(a.grant_id,i.model,l===void 0),m=p?{family:_t,strength:p.strength}:l,u=p?p.model:Cn(i.model,o);await W({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=M();let R=!1;if(await _.isClaimed(t)&&await me(t,_.get(t)?.handle.exited)&&(R=await Pn(t,u,m).then(()=>!0,v=>{if(v instanceof Dn)return!1;throw v})),!R){if(await _.isClaimed(t)){const v=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",v,{error:"broker_not_ready",message:v,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Tn(t,u,m)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Ee(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;l==="orchestrator"&&!await In(t)&&(m=s(async()=>{const u=await Sn(t);await On(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await U(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await N(t,{name:i.name}),a.window&&An(a.window,zn(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await $(e,t,d,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await b(t)}}s(di,"handleConfig");async function Ae(e="app:terminal"){return(await pe(process.cwd(),Ce()||null,e)).kinds}s(Ae,"daemonKinds");async function Ee(e,n="app:terminal"){const t=Object.keys(await Ae(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s(Ee,"assertKindServer");async function si(){const e=await Ae();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}s(si,"handleListKinds");const Dr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:Nt},{method:"GET",pattern:"/v1/nodes",handler:Lt},{method:"GET",pattern:"/v1/kinds",handler:s(()=>si(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:ri},{method:"GET",pattern:"/v1/nodes/:id",handler:Mt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:jt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Gt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Bt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Kt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:xt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Vt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:zt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Ut},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Yt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Ht},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Qt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Xt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Zt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:qt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:ti},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:ei},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:ni},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:ii},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:di}];export{di as handleConfig,Nt as handleCreate,zt as handleFork,Lt as handleList,qt as handlePromote,ti as handleYield,Dr as nodeRoutes,jr as resolveCreateKind};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var
|
|
1
|
+
var B=Object.defineProperty;var s=(t,e)=>B(t,"name",{value:e,configurable:!0});import{existsSync as W}from"node:fs";import{getNode as d}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as j}from"../../../core/canvas/executions.js";import{markStopSignal as z}from"../../../core/runtime/stop-signals.js";import{emitEvent as J}from"../../../core/events/emit.js";import{push as L,FinalizationError as v,StructuredRequestFinalizationError as H}from"../../../core/feed/feed.js";import{branchIsPushedAtCurrentTip as X,hasOpenManagedWorktree as K,missingWorktreeRecoveryHint as S}from"../../../core/worktree.js";import{autoDropCleanManagedWorktreeAsync as G}from"../../../core/worktree-mutation-async.js";import{finalizeManagedWorktreeOnMachine as U,worktreeMachineOf as V}from"../../../core/worktree-machine.js";import{withCanvasWrite as Y,openDb as Q}from"../../../core/canvas/db.js";import{getMany as Z}from"../../../core/graph/bodies.js";import{heads as ee}from"../../../core/graph/documents.js";import{listObjects as te,nodeObject as re}from"../../../core/graph/objects.js";import{readerFor as ne}from"../../../core/graph/reader.js";import{notFound as ie,usage as f}from"../../../core/errors.js";import{InputError as u}from"../../../core/io.js";import{toReportResultDTO as oe}from"../map.js";import{validateStructuredResult as ae}from"../../../core/runtime/structured-output.js";import{clearSchemaReprompts as se}from"../../../core/runtime/output-result.js";import{getPendingStructuredRequestForNode as _,getStructuredRequest as R,settleStructuredRequestIn as de}from"../../../core/canvas/structured-requests.js";import{ApiError as h}from"../../../api/errors.js";import{applySettlementEffects as E}from"../../structured-requests/effects.js";import{nodeEventStreams as O}from"./node-events.js";import{emitRunEvent as x}from"../../../core/runs/events.js";import{mapAsync as ue}from"../../../core/async-array.js";async function g(t){const e=await d(t);if(e===null)throw ie(`unknown node: ${t}`,{received:t});return e}s(g,"requireNode");function ce(t){if(typeof t!="object"||t===null)throw f("a push report requires a JSON body { tier, body }");const e=t.tier,o=t.delivery_tier,i=t.body;if(e!=="update"&&e!=="urgent"&&e!=="final")throw f(`invalid report tier: ${String(e)} (expected update|urgent|final)`);if(o!==void 0&&o!=="deferred"&&o!=="normal"&&o!=="urgent")throw f(`invalid delivery_tier: ${String(o)} (expected deferred|normal|urgent)`);if(e!=="update"&&o!==void 0)throw f("delivery_tier is only valid for update reports");if(typeof i!="string"||i.trim()==="")throw f("a push report requires a non-empty body");return{tier:e,...o===void 0?{}:{delivery_tier:o},body:i}}s(ce,"parsePushBody");async function le(t){const e=t.params.id;await g(e);const o=ce(t.body);if(o.tier==="final"&&await _(e)!==null)throw new u({error:"structured_result_pending",message:"This node owes a structured result \u2014 a plain `push final` would finish it without recording one.",next:'Submit the result with the `submit_result` tool instead (or `crtr push result`); it validates against the pending schema, records it, and pushes the final report for you. If the schema cannot be honestly satisfied, call `submit_result` with `decline` (or `crtr push result --decline "<reason>" --code <token>`) to record the decline and finish the node.'});const i=o.tier==="final"?(await d(e))?.status:void 0,r=o.tier==="final"?await $(e):void 0,n=await b(e,o);o.tier==="final"&&await C(e);const a=o.tier==="final"&&i!==void 0?{from:i,to:(await d(e))?.status??"done"}:void 0,c=oe(n,a,r),m=(await q(e)).find(p=>p.id===n.reportId);if(m!==void 0){O.report(e,m);const p=(await d(e))?.run_id;p&&await x(p,e,"node.report.pushed",{body:m.body,kind:m.tier==="final"?"final":"update"})}return{status:200,body:c}}s(le,"handlePush");async function $(t){const e=await d(t);if(!K(e))return;const o=await V(e?.profile_id);if(o!==null){const n=await U(o,t);if(n.kind==="dropped")return n.dropped.worktree_path;if(n.kind==="pushed")return;throw T(n.missing?S(n.worktree):N)}const i=await G(t);if(i!==null)return i.worktree_path;if(await X((await d(t)).managed_worktree))return;const r=(await d(t))?.managed_worktree;throw T(r!=null&&r.state==="open"&&!W(r.path)?S(r):N)}s($,"guardFinalWorktree");const N="Make the recorded worktree clean, including untracked files: commit work to retain and remove or ignore only disposable generated files. With its recorded branch checked out and no rebase in progress, push its current tip to a branch on origin, then rerun `crtr push final`; or run `crtr node worktree close` to land the clean worktree into its recorded local base.";function T(t){return new u({error:"open_managed_worktree",message:"This node still owns an open managed worktree that is neither clean and locally landed nor clean with its exact tip on origin \u2014 `push final` cannot finish.",next:t})}s(T,"openManagedWorktreeError");const I=2e3;function fe(t){const e=JSON.stringify(t,null,2);return`Structured output submitted.
|
|
2
2
|
|
|
3
3
|
\`\`\`json
|
|
4
|
-
${e.length
|
|
4
|
+
${e.length>I?`${e.slice(0,I)}
|
|
5
5
|
\u2026 (truncated \u2014 the full result is on the structured request)`:e}
|
|
6
6
|
\`\`\`
|
|
7
|
-
`}s(
|
|
7
|
+
`}s(fe,"submitReportBody");function me(t){return`Structured result declined.
|
|
8
8
|
|
|
9
9
|
Reason: ${t.reason}
|
|
10
10
|
Code: ${t.code}
|
|
11
11
|
Retryable: ${t.retryable?"yes":"no"}
|
|
12
|
-
`}s(
|
|
12
|
+
`}s(me,"declineReportBody");const M=1024,A=64;async function pe(t,e){if(typeof t!="object"||t===null)throw f("a result submission requires a JSON body { value } or { decline, code, retryable }");const o=t.request_id;if(typeof o!="string"||o.trim()===""){const n=await _(e);throw new u({error:"request_id_required",message:`a structured result requires request_id${n===null?"":` (pending request: ${n.request_id})`}`,next:"Pass `--request <request-id>` exactly as named in the structured-output instruction."})}const i=Object.hasOwn(t,"value"),r=Object.hasOwn(t,"decline");if(i&&r)throw f("a result submission carries either { value } or { decline, code, retryable }, not both");if(r){const{decline:n,code:a,retryable:c}=t;if(typeof n!="string"||n.trim()==="")throw new u({error:"missing_decline_reason",message:"A decline needs a reason.",next:'Rerun with `--decline "<one sentence on why the schema cannot be honestly satisfied>" --code <token>`.'});if(n.length>M)throw new u({error:"decline_reason_too_long",message:`A decline reason is at most ${M} characters (got ${n.length}).`,next:"Keep the reason to one plain sentence; put any detail in an artifact and name its path."});if(typeof a!="string"||a.trim()===""||/\s/.test(a.trim())||a.trim().length>A)throw new u({error:"invalid_decline_code",message:`A decline needs a code: one whitespace-free token of at most ${A} characters naming the decline class.`,next:"Rerun with `--code <token>` \u2014 the token your requester documented for this case."});if(typeof c!="boolean")throw f("a decline carries `retryable` as a boolean");return{requestId:o.trim(),declined:{reason:n.trim(),code:a.trim(),retryable:c}}}if(!i)throw f("a result submission requires a JSON body { value } or { decline, code, retryable }");return{requestId:o.trim(),value:t.value}}s(pe,"parseSubmitBody");const he=1024*1024;async function we(t){const e=t.params.id,o=await g(e);await _(e)!==null&&await se(e);const i=await pe(t.body,e),r=await R(i.requestId);if(r===null||r.node_id!==e)throw new h(404,"structured_request_not_found","the named structured request does not belong to this node");if(r.state!=="pending")throw new h(409,r.state==="expired"?"structured_request_expired":"structured_request_settled",`structured request ${r.request_id} is already ${r.state}`);let n;if("value"in i){if(Buffer.byteLength(JSON.stringify(i.value)??"")>he)throw new u({error:"result_too_large",message:"the submitted result is over 1 MiB serialized; nothing was recorded.",next:"Submit a smaller result \u2014 write bulky content to a file and put its path in the result."});try{n=await ae(r.schema,i.value)}catch(l){throw new u({error:"result_schema_mismatch",message:`the submitted result does not match the requested schema: ${l.message}`,next:'Fix the listed fields and submit again; if the schema cannot be honestly satisfied, decline it (`submit_result` with `decline`, or `crtr push result --decline "<reason>" --code <token>`).'})}}const a="declined"in i?me(i.declined):fe(n);if(r.submission==="oneoff"){const l=await Y(async D=>await de(D,r.request_id,"declined"in i?{intended:"declined",declined:i.declined}:{intended:"completed",result:n}));if(!l.changed||l.row===null||l.row.state!=="completed"&&l.row.state!=="declined")throw new h(409,l.row?.state==="expired"?"structured_request_expired":"structured_request_settled",`structured request ${r.request_id} is already ${l.row?.state??"settled"}`);await E(l.row);const y=await b(e,{tier:"update",body:a},void 0,{requestMessageId:r.request_message_id});return await F(e,y.reportId),{status:200,body:{mode:r.submission,report:y.report,notified:[...y.deliveredTo],..."declined"in i?{declined:i.declined}:{}}}}const c=(await d(e))?.status,m=await $(e),p="declined"in i?{kind:"failure",reason:"declined",detailJson:JSON.stringify({schema:"crtr.node-outcome-detail/v1",message:i.declined.reason,declined:i.declined}),structured:{requestId:r.request_id,declined:i.declined,skipEffects:!0}}:{structured:{requestId:r.request_id,value:n,skipEffects:!0}},w=await b(e,{tier:"final",body:a},p);await C(e);const P=await R(r.request_id);await E(P),await F(e,w.reportId);const k=c===void 0?void 0:{from:c,to:(await d(e))?.status??"done"};return{status:200,body:{mode:r.submission,report:w.report,notified:[...w.deliveredTo],..."declined"in i?{declined:i.declined}:{},...k===void 0?{}:{transitioned:k},...m===void 0?{}:{worktree_auto_dropped:!0,worktree_auto_dropped_path:m}}}}s(we,"handleSubmitResult");async function F(t,e){const o=(await q(t)).find(r=>r.id===e);if(o===void 0)return;O.report(t,o);const i=(await d(t))?.run_id;i&&await x(i,t,"node.report.pushed",{body:o.body,kind:o.tier==="final"?"final":"update"})}s(F,"emitReportEvents");async function C(t){try{const e=await j(t);e!==null&&z(t,"pushedFinal",e.executionId)}catch(e){try{J({event:"daemon.node.final-marker.failed",level:"error",node_id:t,error:e})||process.stderr.write(`final marker failed for ${t}: ${String(e)}
|
|
13
13
|
`)}catch{process.stderr.write(`final marker failed for ${t}: ${String(e)}
|
|
14
|
-
`)}}}s(
|
|
14
|
+
`)}}}s(C,"markCommittedFinal");async function b(t,e,o,i){try{return await L(t,{kind:e.tier,body:e.body,...e.delivery_tier===void 0?{}:{deliveryTier:e.delivery_tier},...o===void 0?{}:{outcome:o},...i===void 0?{}:{result:i}})}catch(r){throw r instanceof H?new h(409,r.message,r.message==="structured_request_expired"?"the named structured request expired before this submission committed":"the named structured request is already settled"):r instanceof v&&r.code==="already_finalized"?new u({error:"already_finalized",message:"This node already submitted its canonical final result.",next:"Push an update with the new information, then stop."}):r instanceof v&&r.code==="finalization_forbidden"?new u({error:"finalization_forbidden",message:"A canceled or dead node cannot submit a canonical final result.",next:"Do not push final from this node."}):r}}s(b,"pushOrRethrow");async function q(t){const e=await Q(),o=await te(e,await ne(e,{class:"person"},async()=>[]),{type:"document",kind:"report",owner:await re(e,t)}),i=await ue(o,async n=>({doc:n,head:(await ee(e,n))[0]})),r=await Z(e,i.flatMap(n=>n.head===void 0?[]:[n.head.body_hash]));return i.map(({doc:n,head:a})=>{const c=n.name.match(/-(update|urgent|final)$/)?.[1]??"update";return{name:n.name,id:n.id,tier:c,body:a===void 0?"":r.get(a.body_hash).trim(),created:n.created_at}}).sort((n,a)=>n.created<a.created?1:n.created>a.created?-1:a.name.localeCompare(n.name))}s(q,"reportsForNode");async function ye(t){const e=t.params.id;await g(e);const o=t.query.get("tier"),i=t.query.get("limit"),r=i!==null?Number(i):void 0;let n=await q(e);return o!==null&&(n=n.filter(a=>a.tier===o)),r!==void 0&&Number.isFinite(r)&&r>=0&&(n=n.slice(0,r)),{status:200,body:n}}s(ye,"handleList");const Le=[{method:"POST",pattern:"/v1/nodes/:id/reports",ownerOnly:!0,handler:le},{method:"GET",pattern:"/v1/nodes/:id/reports",handler:ye},{method:"POST",pattern:"/v1/nodes/:id/result",handler:we}];export{Le as reportRoutes,q as reportsForNode};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var r=(e,t)=>p(e,"name",{value:t,configurable:!0});import{closeManagedWorktreeAsync as m}from"../../../core/worktree-close.js";import{abandonManagedWorktreeAsync as l}from"../../../core/worktree-mutation-async.js";import{abandonManagedWorktreeOnMachine as u,closeManagedWorktreeOnMachine as y,worktreeMachineOf as f}from"../../../core/worktree-machine.js";import{listQuarantinedManagedWorktrees as h}from"../../../core/worktree-quarantine.js";import{usage as w}from"../../../core/errors.js";import{ApiError as b}from"../../../api/errors.js";import{getNode as s}from"../../../core/canvas/canvas.js";import{runsOnBlaxel as k}from"../environment-of.js";import{directorySizeBytes as g}from"../../../core/disk-usage.js";import{appsRoot as o,userRoot as O}from"../../../core/layout.js";import{existsSync as v,readdirSync as M}from"node:fs";import{join as W}from"node:path";import{ownerOnly as S}from"../router.js";async function d(e){const t=await s(e);if(t!==null&&await k(t.profile_id??null))throw new b(409,"worktree_not_available",`${e} runs in a sandbox, whose clone is its worktree; push a branch from it instead`)}r(d,"refuseOnBlaxel");async function c(e){return f((await s(e))?.profile_id)}r(c,"machineOf");async function T(e){const t=e.params.id;await d(t);const n=await c(t);return{status:200,body:n!==null?await y(n,t):await m(t)}}r(T,"handleWorktreeClose");async function _(e){const t=e.body?.by,n=typeof t=="string"?t.trim():"";if(n==="")throw w("abandon requires a non-empty invoking identity",{received:e.body,next:"Pass the invoking node id or human identity."});const a=e.params.id;await d(a);const i=await c(a);return{status:200,body:i!==null?await u(i,a,n):await l(a,n)}}r(_,"handleWorktreeAbandon");async function x(){return{status:200,body:await h()}}r(x,"handleQuarantinedWorktrees");async function A(){const e=v(o())?M(o(),{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>a.name).sort():[],t=[{space:"user",path:O()},...e.map(a=>({space:`app:${a}`,path:W(o(),a)}))];return{status:200,body:{spaces:await Promise.all(t.map(async a=>({...a,size_bytes:await g(a.path)})))}}}r(A,"handleSpaces");const H=S([{method:"GET",pattern:"/v1/spaces",handler:A},{method:"POST",pattern:"/v1/nodes/:id/worktree/close",handler:T},{method:"POST",pattern:"/v1/nodes/:id/worktree/abandon",handler:_},{method:"GET",pattern:"/v1/worktrees/quarantined",handler:x}]);export{H as worktreeRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _=Object.defineProperty;var c=(e,n)=>_(e,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as T}from"node:path";import{apiSocketPath as E}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as f}from"../core/events/emit.js";import{createMachineExecutor as P,stopAllBrokers as x}from"../core/runtime/runner/machine/executor.js";import{
|
|
1
|
+
var _=Object.defineProperty;var c=(e,n)=>_(e,"name",{value:n,configurable:!0});import{chmodSync as M,existsSync as S,mkdirSync as h,unlinkSync as g,writeFileSync as I,rmSync as v}from"node:fs";import{createServer as k}from"node:http";import{dirname as T}from"node:path";import{apiSocketPath as E}from"../core/canvas/paths.js";import{bindDaemonEventSource as R}from"../core/events/source.js";import{emitEvent as f}from"../core/events/emit.js";import{createMachineExecutor as P,stopAllBrokers as x}from"../core/runtime/runner/machine/executor.js";import{machineWorktreeHandlers as C}from"../core/worktree-machine.js";import{readPersonCredential as F}from"../core/directory/person-credential.js";import{socketDir as G}from"../core/layout.js";import{isDaemonRunning as b,pidfilePath as u,readPidfile as N}from"./pidfile.js";import{cancelMachineCron as D,runMachineCron as O,stopOrphanedMachineCrons as U}from"./cron/machine-exec.js";import{startMachineLink as Y}from"./machine-link/client.js";import{deleteMoveRecord as w,readMachineConfig as A,readMachineCredential as y,readMoveRecord as H,writeMoveRecord as z}from"./machine-link/config.js";import{notifyMoveFinished as j}from"./machine-link/move-notify.js";function B(e,n){return{ok:!0,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,link_connected:e,signed_in:n,startup_phase:e?"ready":"recovering"}}c(B,"machineHealth");async function de(){const e=A();if(e===void 0)throw new Error("crtrd --role machine needs runtime/machine.json: this install has not been imported as a machine");const n=F()!==void 0;if(n&&y(),b())throw new Error("a crtrd is already running for this home");R(),n||(await x(),await U(),f({level:"info",event:"daemon.machine.signed_out",fields:{environment:e.environmentId}})),h(G(),{recursive:!0,mode:493});const a=E();S(a)&&g(a);let r;const t=k((s,d)=>{const p=(s.method??"GET")==="GET"&&(s.url??"/").split("?")[0]==="/healthz";d.writeHead(p?200:404,{"content-type":"application/json; charset=utf-8"}),d.end(JSON.stringify(p?B(r?.connected()===!0,n):{error:{code:"not_found",message:"a machine-role crtrd serves only /healthz",origin:"runtime"}}))});await new Promise((s,d)=>{t.once("error",d),t.listen(a,()=>{t.off("error",d),M(a,384),s()})}),h(T(u()),{recursive:!0}),I(u(),String(process.pid),"utf8");let i;await W(e.runId,n,()=>i!==void 0);const o=P({apiUrl:e.apiUrl,environmentId:e.environmentId});r=n?Y({apiUrl:e.apiUrl,environmentId:e.environmentId,credential:y,handlers:{start:o.start,wake:o.wake,stop:o.stop,status:o.status,delete:o.delete,viewer:o.viewer,"cron.run":O,"cron.cancel":D,...C}}):void 0,f({level:"info",event:"daemon.machine.started",fields:{environment:e.environmentId}});const l=c(()=>i??=(async()=>{r?.stop(),await new Promise(s=>{t.close(()=>s()),t.closeAllConnections()}),N()===process.pid&&(v(a,{force:!0}),v(u(),{force:!0})),process.off("SIGINT",m),process.off("SIGTERM",m)})(),"teardown"),m=c(()=>{l().then(()=>process.exit(0),()=>process.exit(1))},"onSignal");return process.on("SIGINT",m),process.on("SIGTERM",m),l}c(de,"runMachineDaemon");const J=5e3,L=3e5;async function W(e,n,a){let r;try{r=H()}catch(i){f({level:"warn",event:"daemon.machine.move_record_unreadable",fields:{error:i.message}});return}if(r===void 0||r.state==="running"||r.runId!==e)return;if(r.notified||r.notify===null){w();return}if(r.state==="committed"&&(r={...r,state:"activated"},z(r)),!n)return;const t=r;(async()=>{let i=J;for(;;){try{await j(t),w();return}catch(o){f({level:"warn",event:"daemon.machine.move_notify_failed",fields:{node:t.notify??"",error:o.message}})}if(await new Promise(o=>{setTimeout(o,i).unref()}),a())return;i=Math.min(i*2,L)}})()}c(W,"settleFinishedMove");export{B as machineHealth,de as runMachineDaemon};
|
|
@@ -99,7 +99,7 @@ It refreshes every connection last saved before the cutoff, through the store's
|
|
|
99
99
|
|
|
100
100
|
## Acting without a sign-in
|
|
101
101
|
|
|
102
|
-
A server that acts for a person on their
|
|
102
|
+
A server that acts for a person on their Northlight runtime, for example to publish events to the objects they watch, uses `oauth.appClient(userId)` instead of `oauth.client(userId)`. It stores no connection and refreshes nothing: the SDK signs a `client_credentials` request with your app's key for `sub=user:<id>`, and the directory answers a token and the person's `runtimeUrl`.
|
|
103
103
|
|
|
104
104
|
```ts
|
|
105
105
|
const runtime = await oauth.appClient('user:o1');
|
|
@@ -110,7 +110,7 @@ It needs the app registered with the `app_token_for_user` operation, and an acti
|
|
|
110
110
|
|
|
111
111
|
| Error | Code | Means |
|
|
112
112
|
|---|---|---|
|
|
113
|
-
| `NoHostedRuntimeError` | `no_hosted_runtime` (409) | The person has no
|
|
113
|
+
| `NoHostedRuntimeError` | `no_hosted_runtime` (409) | The person's account has no runtime to act on. Not retryable. |
|
|
114
114
|
| `NotGrantedError` | `not_granted` (409) | The person has no active grant for your app, so they have not signed in to it. Not retryable. |
|
|
115
115
|
| any error with `retryable: true` | `runtime_provisioning` (503), a directory 5xx or a 429 | Try again later. |
|
|
116
116
|
|
package/docs/apps/errors.md
CHANGED
|
@@ -20,7 +20,7 @@ Codes the SDK raises itself are listed in `sdkErrorCodes`, and `CrouterError.cod
|
|
|
20
20
|
| `oauth_nonce_missing` | `exchangeIdentity` was called without the `nonce` from `authorizeUrl`. | Save the nonce in the visitor's session and pass it back. |
|
|
21
21
|
| `oauth_state_mismatch` | The callback's `state` was missing or differed from the saved one. | Refuse the callback. |
|
|
22
22
|
| `not_connected` | `oauth.client(userId)` or a refresh found no stored connection for that person. | Show "sign in again". |
|
|
23
|
-
| `no_hosted_runtime` (409, `NoHostedRuntimeError`) | `oauth.appClient(userId)`: the person has no
|
|
23
|
+
| `no_hosted_runtime` (409, `NoHostedRuntimeError`) | `oauth.appClient(userId)`: the person's account has no runtime to act on. Not retryable. | Skip them. |
|
|
24
24
|
| `not_granted` (409, `NotGrantedError`) | `oauth.appClient(userId)`: the person has no active grant for your app. Not retryable. | Send them through sign-in ([Connections](/docs/concepts/connections#acting-without-a-sign-in)). |
|
|
25
25
|
| `refusal_handler_reentry` | An `onRefusal` handler called `oauth.client` (or a refresh) for the person whose connection it is handling. | Don't call the runtime for `refusal.userId` inside the handler. |
|
|
26
26
|
| `unauthorized` (401, `AuthenticationError`) | The directory refused your app's client assertion (`invalid_client`) on `exchangeCode`, a refresh or `revoke`, including a refresh inside a client from `oauth.client(userId)`. The message names the key id (`kid`) you signed with and asks whether that key's public JWK is registered. `details` is `{oauth_error: 'invalid_client', kid}`, or `key_thumbprint` instead of `kid` for a key with no `kid`. | Check that the key's public JWK is on the app's **Sign-in** tab ([Manage your app](/docs/guides/manage-your-app)). |
|
package/docs/apps/how-it-fits.md
CHANGED
|
@@ -11,9 +11,9 @@ Your app runs on a server you choose. Northlight hosts two other things: the dir
|
|
|
11
11
|
|---|---|---|
|
|
12
12
|
| **Your server** | Anywhere you choose. Your laptop while you develop. | Your pages and logic. It holds the app's private signing key and a stored connection for each person. |
|
|
13
13
|
| **The directory** | `https://account.northlight.ai`, hosted by Northlight | Accounts, app registration (the console at `/console`), consent, tokens and the marketplace. |
|
|
14
|
-
| **The person's runtime** |
|
|
14
|
+
| **The person's runtime** | Northlight's cloud. One shared control plane serves everyone; each of the person's agents runs in its own sandbox. | Their agents, runs, files, documents and providers (sms, search and others), using their own AI subscription. |
|
|
15
15
|
|
|
16
|
-
"Build on Northlight" therefore means three things. Your app's agent work runs on the person's Northlight
|
|
16
|
+
"Build on Northlight" therefore means three things. Your app's agent work runs on the person's Northlight runtime, in Northlight's cloud. People sign in to your app with their Northlight account. And your app can be listed in the Northlight marketplace.
|
|
17
17
|
|
|
18
18
|
```mermaid
|
|
19
19
|
sequenceDiagram
|