@north-light/cli 0.3.694 → 0.3.696

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/README.md +4 -7
  2. package/dist/api/command-manifest/result.d.ts +5 -5
  3. package/dist/api/command-manifest/result.js +1 -1
  4. package/dist/api/contract.d.ts +1 -1
  5. package/dist/api/contract.js +1 -1
  6. package/dist/api/dto/run-events.d.ts +1 -0
  7. package/dist/api/dto/run-events.js +1 -0
  8. package/dist/api/dto/worktree.d.ts +0 -4
  9. package/dist/builtin-memory/crouter-concepts/lifecycle-and-wakes.md +1 -1
  10. package/dist/builtin-memory/crouter-concepts/nodes-and-the-canvas.md +2 -2
  11. package/dist/builtin-memory/crouter-concepts/profiles-kinds-and-modes.md +1 -1
  12. package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +1 -1
  13. package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
  14. package/dist/builtin-memory/crouter-sdk/INDEX.md +3 -3
  15. package/dist/builtin-memory/crouter-sdk/README.md +14 -42
  16. package/dist/builtin-memory/crouter-sdk/client.md +5 -7
  17. package/dist/builtin-memory/crouter-sdk/docker.md +1 -1
  18. package/dist/builtin-memory/crouter-sdk/errors.md +4 -44
  19. package/dist/builtin-memory/crouter-sdk/getting-started.md +11 -83
  20. package/dist/builtin-memory/crouter-sdk/release-notes.md +10 -0
  21. package/dist/builtin-memory/crouter-sdk/resources.md +11 -44
  22. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +6 -7
  23. package/dist/clients/attach/session/connection.d.ts +11 -2
  24. package/dist/clients/attach/session/connection.js +1 -1
  25. package/dist/clients/attach/session/keys.d.ts +2 -0
  26. package/dist/clients/attach/session/keys.js +1 -1
  27. package/dist/clients/attach/session/pane-tag.d.ts +3 -3
  28. package/dist/clients/attach/session/reconnect.js +1 -1
  29. package/dist/clients/attach/viewer.js +539 -538
  30. package/dist/commands/node-worktree.js +1 -1
  31. package/dist/commands/surface/node/placement.d.ts +2 -2
  32. package/dist/commands/surface/node/placement.js +1 -1
  33. package/dist/commands/surface.js +1 -1
  34. package/dist/core/broker-client/client.d.ts +6 -9
  35. package/dist/core/broker-client/client.js +1 -1
  36. package/dist/core/broker-client/transport-relay.d.ts +12 -1
  37. package/dist/core/broker-client/transport-relay.js +1 -1
  38. package/dist/core/canvas/canvas.js +5 -5
  39. package/dist/core/canvas/types.d.ts +0 -2
  40. package/dist/core/conversation-store/row-store.js +10 -10
  41. package/dist/core/graph/names.js +9 -9
  42. package/dist/core/keybindings/attach-control.d.ts +3 -0
  43. package/dist/core/keybindings/attach-control.js +1 -1
  44. package/dist/core/keybindings/catalog.js +1 -1
  45. package/dist/core/ledger/chunks.d.ts +3 -1
  46. package/dist/core/ledger/chunks.js +2 -2
  47. package/dist/core/ledger/index.d.ts +1 -1
  48. package/dist/core/ledger/index.js +1 -1
  49. package/dist/core/ledger/read.d.ts +4 -0
  50. package/dist/core/ledger/read.js +2 -2
  51. package/dist/core/llm/run.js +2 -2
  52. package/dist/core/logged-step-timings.d.ts +7 -0
  53. package/dist/core/logged-step-timings.js +1 -0
  54. package/dist/core/permissions/evaluator.d.ts +2 -1
  55. package/dist/core/permissions/evaluator.js +2 -2
  56. package/dist/core/providers/receipts.js +1 -1
  57. package/dist/core/runs/operations.js +8 -8
  58. package/dist/core/runtime/broker/model-adapter.js +3 -3
  59. package/dist/core/runtime/broker.js +1 -1
  60. package/dist/core/runtime/nodes.d.ts +1 -1
  61. package/dist/core/runtime/nodes.js +1 -1
  62. package/dist/core/runtime/placement-tmux.d.ts +1 -1
  63. package/dist/core/runtime/placement-tmux.js +1 -1
  64. package/dist/core/runtime/revive.js +2 -2
  65. package/dist/core/runtime/runner/machine/executor.d.ts +0 -3
  66. package/dist/core/runtime/runner/machine/executor.js +1 -1
  67. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  68. package/dist/core/runtime/runner/machine/ops.d.ts +7 -13
  69. package/dist/core/runtime/runner/machine/ops.js +1 -1
  70. package/dist/core/runtime/runner/machine/runner.d.ts +3 -2
  71. package/dist/core/runtime/runner/machine/runner.js +1 -1
  72. package/dist/core/runtime/tmux-bindings.js +3 -3
  73. package/dist/core/runtime/tmux-driver.d.ts +0 -10
  74. package/dist/core/runtime/tmux-driver.js +6 -6
  75. package/dist/core/step-timings.d.ts +7 -1
  76. package/dist/core/step-timings.js +1 -1
  77. package/dist/core/worktree-close.js +4 -6
  78. package/dist/core/worktree-landing.d.ts +0 -38
  79. package/dist/core/worktree-landing.js +2 -3
  80. package/dist/core/worktree-sweep.d.ts +0 -1
  81. package/dist/core/worktree-sweep.js +4 -6
  82. package/dist/core/worktree.d.ts +0 -4
  83. package/dist/core/worktree.js +13 -15
  84. package/dist/daemon/api/app-listener.d.ts +1 -0
  85. package/dist/daemon/api/app-listener.js +10 -10
  86. package/dist/daemon/api/bridge.js +5 -5
  87. package/dist/daemon/api/handlers/attach.js +1 -1
  88. package/dist/daemon/api/handlers/conversations.js +3 -3
  89. package/dist/daemon/api/server.d.ts +1 -1
  90. package/dist/daemon/api/server.js +1 -1
  91. package/dist/daemon/cron/armed-context.js +1 -1
  92. package/dist/daemon/crtrd.js +20 -18
  93. package/dist/daemon/machine-daemon.js +1 -1
  94. package/dist/daemon/machine-link/client.d.ts +7 -1
  95. package/dist/daemon/machine-link/client.js +1 -1
  96. package/dist/daemon/machine-link/forward.d.ts +2 -4
  97. package/dist/daemon/machine-link/forward.js +1 -1
  98. package/dist/daemon/machine-link/holder.js +5 -5
  99. package/dist/daemon/pidfile.js +2 -1
  100. package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
  101. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  102. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +1 -1
  103. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +2 -2
  104. package/dist/daemon/runs/append-section.js +2 -2
  105. package/dist/daemon/runs/observer.js +3 -3
  106. package/docs/apps/guides/stream-a-run.md +6 -7
  107. package/docs/concepts/lifecycle-and-wakes.md +1 -1
  108. package/docs/concepts/nodes-and-the-canvas.md +2 -2
  109. package/docs/concepts/profiles-kinds-and-modes.md +1 -1
  110. package/docs/concepts/scopes-and-trust.md +1 -1
  111. package/docs/concepts/why-a-daemon.md +1 -1
  112. package/docs/sdk/README.md +13 -41
  113. package/docs/sdk/client.md +5 -7
  114. package/docs/sdk/docker.md +1 -1
  115. package/docs/sdk/errors.md +3 -43
  116. package/docs/sdk/getting-started.md +11 -83
  117. package/docs/sdk/release-notes.md +10 -0
  118. package/docs/sdk/resources.md +11 -44
  119. package/package.json +3 -3
  120. package/packages/crouter-api/dist/api/command-manifest/result.js +15 -15
  121. package/packages/crouter-api/dist/api/contract.js +1 -1
  122. package/packages/crouter-api/dist/api/dto/run-events.js +1 -1
  123. package/packages/crouter-api/dist/clients/attach/session/connection.js +73 -25
  124. package/packages/crouter-api/dist/clients/attach/session/keys.js +1 -0
  125. package/packages/crouter-api/dist/clients/attach/session/reconnect.js +11 -15
  126. package/packages/crouter-api/dist/clients/attach/viewer.js +42 -5
  127. package/packages/crouter-api/dist/commands/node-worktree.js +1 -5
  128. package/packages/crouter-api/dist/commands/surface/node/placement.js +2 -2
  129. package/packages/crouter-api/dist/commands/surface.js +2 -3
  130. package/packages/crouter-api/dist/core/broker-client/client.js +5 -17
  131. package/packages/crouter-api/dist/core/broker-client/transport-relay.js +24 -7
  132. package/packages/crouter-api/dist/core/canvas/canvas.js +2 -3
  133. package/packages/crouter-api/dist/core/conversation-store/row-store.js +7 -4
  134. package/packages/crouter-api/dist/core/graph/names.js +7 -20
  135. package/packages/crouter-api/dist/core/keybindings/attach-control.js +1 -0
  136. package/packages/crouter-api/dist/core/keybindings/catalog.js +2 -1
  137. package/packages/crouter-api/dist/core/ledger/chunks.js +7 -3
  138. package/packages/crouter-api/dist/core/ledger/index.js +1 -1
  139. package/packages/crouter-api/dist/core/ledger/read.js +18 -1
  140. package/packages/crouter-api/dist/core/llm/run.js +1 -1
  141. package/packages/crouter-api/dist/core/logged-step-timings.js +52 -0
  142. package/packages/crouter-api/dist/core/permissions/evaluator.js +15 -1
  143. package/packages/crouter-api/dist/core/providers/receipts.js +1 -12
  144. package/packages/crouter-api/dist/core/runs/operations.js +5 -4
  145. package/packages/crouter-api/dist/core/runtime/broker/model-adapter.js +14 -3
  146. package/packages/crouter-api/dist/core/runtime/nodes.js +2 -2
  147. package/packages/crouter-api/dist/core/runtime/placement-tmux.js +1 -1
  148. package/packages/crouter-api/dist/core/runtime/revive.js +5 -5
  149. package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +2 -7
  150. package/packages/crouter-api/dist/core/runtime/runner/machine/runner.js +14 -32
  151. package/packages/crouter-api/dist/core/runtime/tmux-bindings.js +1 -1
  152. package/packages/crouter-api/dist/core/runtime/tmux-driver.js +0 -18
  153. package/packages/crouter-api/dist/core/step-timings.js +7 -2
  154. package/packages/crouter-api/dist/core/worktree-close.js +5 -51
  155. package/packages/crouter-api/dist/core/worktree-landing.js +0 -48
  156. package/packages/crouter-api/dist/core/worktree.js +9 -74
  157. package/packages/crouter-api/dist/daemon/cron/armed-context.js +3 -3
  158. package/packages/crouter-api/dist/daemon/machine-link/forward.js +22 -10
  159. package/packages/crouter-api/dist/daemon/machine-link/holder.js +7 -0
  160. package/packages/crouter-api/dist/daemon/pidfile.js +1 -1
  161. package/packages/crouter-api/dist/daemon/runs/append-section.js +2 -8
  162. package/packages/crouter-api/dist/daemon/runs/observer.js +3 -4
  163. package/packages/crouter-api/package.json +1 -1
  164. package/packages/crouter-identity/package.json +1 -1
  165. package/packages/crouter-plugin/dist/serve.js +1 -1
  166. package/packages/crouter-plugin/package.json +3 -3
  167. package/runtime.lock.json +14 -14
  168. package/scripts/self-update.mjs +7 -3
  169. package/dist/builtin-memory/crouter-sdk/bash.md +0 -40
  170. package/dist/builtin-memory/crouter-sdk/files.md +0 -50
  171. package/dist/builtin-memory/crouter-sdk/guides/README.md +0 -18
  172. package/dist/builtin-memory/crouter-sdk/guides/event-driven-assistant.md +0 -91
  173. package/dist/builtin-memory/crouter-sdk/guides/fan-out-pipeline.md +0 -57
  174. package/dist/builtin-memory/crouter-sdk/guides/human-approval.md +0 -79
  175. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +0 -55
  176. package/dist/builtin-memory/crouter-sdk/nodes.md +0 -195
  177. package/dist/builtin-memory/crouter-sdk/streaming.md +0 -151
  178. package/dist/commands/surface-reload.d.ts +0 -7
  179. package/dist/commands/surface-reload.js +0 -1
  180. package/docs/sdk/bash.md +0 -39
  181. package/docs/sdk/files.md +0 -49
  182. package/docs/sdk/guides/README.md +0 -17
  183. package/docs/sdk/guides/event-driven-assistant.md +0 -24
  184. package/docs/sdk/guides/fan-out-pipeline.md +0 -24
  185. package/docs/sdk/guides/human-approval.md +0 -24
  186. package/docs/sdk/guides/typed-extraction.md +0 -24
  187. package/docs/sdk/nodes.md +0 -194
  188. package/docs/sdk/streaming.md +0 -149
  189. package/packages/crouter-api/dist/commands/surface-reload.js +0 -129
@@ -1,6 +1,4 @@
1
- var P=Object.defineProperty;var s=(t,e)=>P(t,"name",{value:e,configurable:!0});import{existsSync as b,realpathSync as q}from"node:fs";import{resolve as I}from"node:path";import{getNode as $,recordDisposalGrant as B,recordLandIntent as F}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as H}from"./exclusive-lock.js";import{gitAsync as i}from"./git.js";import{proveBranchContained as S}from"./worktree-containment.js";import{concludeAbsentManagedWorktreeAsync as G,concludeAbsentManagedWorktreeOnHost as T}from"./worktree-mutation-async.js";import{parseStatusPorcelain as N,planLandIntoCheckout as j}from"./worktree-landing.js";import{WORKTREE_LOCK_WAIT_MS as W,checkoutPathForBranchInList as K,missingWorktreeRecoveryHint as z,persistClosedWorktreeState as Q,samePath as C,worktreeLockPathForCommonDir as L,WorktreeError as l}from"./worktree.js";import{shellQuote as D}from"../shared/shell-quote.js";function u(t){return(t.stderr.trim()||t.stdout.trim()).trim()}s(u,"detailOf");async function d(t,e,a,r){const n=await i(e,t);if(n.status!==0)throw new l(a,`git ${e.join(" ")} failed`,r,u(n));return n.stdout.trim()}s(d,"runGit");async function E(t){const e=await d(t,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return q(I(t,e))}s(E,"commonGitDir");async function J(t,e){const a=`refs/heads/${e}`,r=await i(["show-ref","--verify","--quiet",a],t);if(r.status===1&&r.executionFailed!==!0)throw new l("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){const n=r.processError===void 0?"":`
2
- process error: ${r.processError}`;throw new l("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}
3
- stderr: ${r.stderr.trim()||"<empty>"}${n}`)}return d(t,["rev-parse","--verify",a],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}s(J,"resolveLandableBase");async function U(t){for(const e of["rebase-merge","rebase-apply"]){const a=await d(t,["rev-parse","--git-path",e],"git_path_failed","Inspect the worktree manually, then retry.");if(b(a))return!0}return!1}s(U,"rebaseInProgress");async function M(t,e,a){const r=await i(["worktree","list","--porcelain"],t);if(r.status!==0)return!1;let n=null;for(const c of r.stdout.split(`
4
- `))if(c.startsWith("worktree "))n=c.slice(9).trim();else if(n!==null&&C(n,e)&&c===`branch refs/heads/${a}`)return!0;return!1}s(M,"registeredWorktree");function v(t){return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${t.path} remains intact. After its node exits, run \`git -C ${D(t.repo_root)} worktree remove ${D(t.path)}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${t.branch} remains checked out at ${t.path}; delete it only after that checkout is removed and its landed commit is still contained in ${t.base_ref}.`}}s(v,"deferredCleanupResult");async function O(t,e){const a=await i(["rev-parse","--verify","--quiet","refs/stash"],t);a.status===0&&a.stdout.trim()===e&&await i(["stash","drop"],t)}s(O,"dropStashIfStillTip");async function V(t,e,a,r){const n=await i(["status","--porcelain"],t);if(n.status!==0)return{ok:!1,detail:u(n)};const c=await i(["diff","--name-only",a,r],t);if(c.status!==0)return{ok:!1,detail:u(c)};const y=c.stdout.split(`
5
- `).map(_=>_.trim()).filter(_=>_!==""),f=j(N(n.stdout),y);if(f.kind==="refuse")return{ok:!1,detail:`untracked files in ${t} would be overwritten by the incoming commits: ${f.collisions.join(", ")}`};const p=s(async()=>{const _=await i(["merge","--ff-only",r],t);return _.status===0?{ok:!0}:{ok:!1,detail:u(_)}},"merge");if(f.kind==="direct")return p();const w=await i(["rev-parse","--verify","--quiet","refs/stash"],t),A=w.status===0?w.stdout.trim():null,m=await i(["stash","push","--message",`crtr landing ${e}`],t);if(m.status!==0)return{ok:!1,detail:u(m)};const k=await i(["rev-parse","--verify","--quiet","refs/stash"],t),o=k.status===0?k.stdout.trim():null;if(o===null||o===A)return p();const h=`local changes from ${t} are retained in stash ${o}; recover them with \`git -C ${D(t)} stash apply ${o}\` and resolve any conflict.`,g=await p();return g.ok?(await i(["stash","apply",o],t)).status===0?(await O(t,o),{ok:!0}):(await i(["reset","--hard",r],t),{ok:!0,stash:`the shared base checkout was reset to landed commit ${r} because local changes conflicted with it. ${h}`}):(await i(["stash","apply",o],t)).status===0?(await O(t,o),g):{ok:!1,detail:`${g.detail}
6
- ${h}`}}s(V,"landIntoBaseCheckout");async function x(t){const e=await $(t);if(e===null)throw new l("unknown_node",`unknown node: ${t}`,"Run this from a live node, or pass a real node id once that command supports it.");const a=e?.managed_worktree?.state==="open"?e.managed_worktree:null;if(a===null)throw new l("no_managed_worktree",`node ${t} has no open managed worktree`,"Nothing to close for this node.");return X(t,a,await R(t,a))}s(x,"closeLocked");async function X(t,e,a){if(a.kind==="blocked"){const r=(await $(t))?.managed_worktree;throw r!=null&&r.state==="open"&&await F(t,{at:new Date().toISOString(),blocked:a.blocked}),new l("land_base_failed",a.blocked,a.next,a.detail)}return a.disposal!==void 0&&await B(t,a.disposal),await Q(t,e,"pending"),a.result}s(X,"persistCloseOutcome");async function R(t,e){if(!b(e.path))throw new l("worktree_missing",`managed worktree path is missing: ${e.path}`,z(e));if(await U(e.path))throw new l("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(await d(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new l("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${e.path}, then rerun \`crtr node worktree close\`.`);const r=await d(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),n=await d(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(r!==e.branch){if((await i(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path)).status===0||r==="HEAD"||!await M(e.repo_root,e.path,r))throw new l("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${r==="HEAD"?"detached HEAD":r})`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);if(await S(e.path,e,n)===null)throw new l("branch_moved_unlanded",`managed worktree's recorded branch ${e.branch} no longer exists; its checkout is now on ${r} at ${n}, which carries content local base branch '${e.base_ref}' does not yet contain`,`Land or push ${r} through its own workflow before closing.`);const h=await E(e.path);if(!await M(e.repo_root,e.path,r)||await d(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==r||await d(e.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==n)throw new l("wrong_branch",`managed worktree at ${e.path} changed while closing`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);return{kind:"closed",disposal:{observed_branch:r,observed_sha:n,common_dir:h,authorized:new Date().toISOString()},result:{node_id:t,branch:r,worktree_path:e.path,landed_sha:n,...v(e),branch_delete_error:`${r} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}}if(await S(e.path,e,n)!==null)return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:n,...v(e)}};let c;try{c=await J(e.path,e.base_ref)}catch(o){if(!(o instanceof l)||o.code!=="missing_base_branch"||n!==e.base_sha)throw o;return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:e.base_sha,...v(e)}}}const y=await i(["rebase",c],e.path);if(y.status!==0)throw new l("rebase_failed",`rebase onto local base branch '${e.base_ref}' did not complete`,`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`,u(y));const f=await d(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),p=s((o,h,g)=>({kind:"blocked",blocked:o,next:h,detail:g}),"blocked"),w=await i(["merge-base","--is-ancestor",c,f],e.path);if(w.status!==0)return p(`rebased worktree is not a fast-forward of local base branch '${e.base_ref}'`,"Ask the user how to land this managed worktree.",u(w));const A=await d(e.path,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry."),m=K(A,e.base_ref);let k;if(m!==null){const o=await i(["rev-parse","HEAD"],m);if(o.status!==0||o.stdout.trim()!==c)return p(`local base branch '${e.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${m}, then rerun \`crtr node worktree close\`.`,o.status!==0?u(o):`expected ${c}, found ${o.stdout.trim()}`);const h=await V(m,e.branch,c,f);if(!h.ok)return p(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,`Local base branch '${e.base_ref}' is checked out at ${m} in a state that blocks a fast-forward.`,h.detail);k=h.stash}else{const o=await i(["update-ref",`refs/heads/${e.base_ref}`,f,c],e.path);if(o.status!==0)return p(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,"Ask the user how to land this managed worktree.",u(o))}return{kind:"closed",result:{node_id:t,branch:e.branch,worktree_path:e.path,landed_sha:f,...v(e),...k===void 0?{}:{base_checkout_stash:k}}}}s(R,"closeOutcome");async function he(t){const e=(await $(t))?.managed_worktree;if(e==null||e.state!=="open")return x(t);if(!b(e.path)){const c=await G(t);if(c!==null)return Y(t,c)}const a=(await $(t))?.managed_worktree;if(a==null||a.state!=="open")return x(t);const r=b(a.path)?a.path:a.repo_root,n=await E(r);return H(L(n),()=>x(t),{timeoutMs:Math.min(W,25e3),timeoutError:s(()=>new l("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")})}s(he,"closeManagedWorktreeAsync");async function de(t,e){if(!b(e.path)){const r=await T(t,e);if(r!==null)return{kind:"concluded",conclusion:r}}const a=await E(b(e.path)?e.path:e.repo_root);return H(L(a),()=>R(t,e),{timeoutMs:Math.min(W,25e3),timeoutError:s(()=>new l("worktree_lock_timeout",`timed out waiting to create a managed worktree in ${a}`,"Wait for the other managed-worktree operation to finish, then retry."),"timeoutError")})}s(de,"closeManagedWorktreeOnHost");function Y(t,e){return{node_id:t,branch:e.dropped.branch,worktree_path:e.dropped.worktree_path,landed_sha:e.landedSha,worktree_removed:!0,branch_deleted:e.dropped.branch_deleted,...e.dropped.branch_delete_error===void 0?{}:{branch_delete_error:e.dropped.branch_delete_error}}}s(Y,"concludedCloseResult");export{he as closeManagedWorktreeAsync,de as closeManagedWorktreeOnHost,Y as concludedCloseResult,X as persistCloseOutcome};
1
+ var L=Object.defineProperty;var o=(r,e)=>L(r,"name",{value:e,configurable:!0});import{existsSync as u,realpathSync as M}from"node:fs";import{resolve as O}from"node:path";import{getNode as k,recordDisposalGrant as R,recordLandIntent as P}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as v}from"./exclusive-lock.js";import{gitAsync as l}from"./git.js";import{proveBranchContained as A}from"./worktree-containment.js";import{concludeAbsentManagedWorktreeAsync as B,concludeAbsentManagedWorktreeOnHost as F}from"./worktree-mutation-async.js";import{WORKTREE_LOCK_WAIT_MS as D,checkoutPathForBranchInList as G,missingWorktreeRecoveryHint as I,persistClosedWorktreeState as T,samePath as q,worktreeLockPathForCommonDir as E,WorktreeError as s}from"./worktree.js";import{shellQuote as x}from"../shared/shell-quote.js";function p(r){return(r.stderr.trim()||r.stdout.trim()).trim()}o(p,"detailOf");async function h(r,e,t,a){const n=await l(e,r);if(n.status!==0)throw new s(t,`git ${e.join(" ")} failed`,a,p(n));return n.stdout.trim()}o(h,"runGit");async function w(r){const e=await h(r,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return M(O(r,e))}o(w,"commonGitDir");async function K(r,e){const t=`refs/heads/${e}`,a=await l(["show-ref","--verify","--quiet",t],r);if(a.status===1&&a.executionFailed!==!0)throw new s("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(a.status!==0){const n=a.processError===void 0?"":`
2
+ process error: ${a.processError}`;throw new s("base_branch_inspection_failed",`could not inspect local base branch '${e}' (git show-ref exited with status ${a.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${a.status}
3
+ stderr: ${a.stderr.trim()||"<empty>"}${n}`)}return h(r,["rev-parse","--verify",t],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(K,"resolveLandableBase");async function N(r){for(const e of["rebase-merge","rebase-apply"]){const t=await h(r,["rev-parse","--git-path",e],"git_path_failed","Inspect the worktree manually, then retry.");if(u(t))return!0}return!1}o(N,"rebaseInProgress");async function H(r,e,t){const a=await l(["worktree","list","--porcelain"],r);if(a.status!==0)return!1;let n=null;for(const c of a.stdout.split(`
4
+ `))if(c.startsWith("worktree "))n=c.slice(9).trim();else if(n!==null&&q(n,e)&&c===`branch refs/heads/${t}`)return!0;return!1}o(H,"registeredWorktree");function _(r){return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${r.path} remains intact. After its node exits, run \`git -C ${x(r.repo_root)} worktree remove ${x(r.path)}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${r.branch} remains checked out at ${r.path}; delete it only after that checkout is removed and its landed commit is still contained in ${r.base_ref}.`}}o(_,"deferredCleanupResult");async function j(r,e){const t=await l(["merge","--ff-only",e],r);return t.status===0?{ok:!0}:{ok:!1,detail:p(t)}}o(j,"landIntoBaseCheckout");async function g(r){const e=await k(r);if(e===null)throw new s("unknown_node",`unknown node: ${r}`,"Run this from a live node, or pass a real node id once that command supports it.");const t=e?.managed_worktree?.state==="open"?e.managed_worktree:null;if(t===null)throw new s("no_managed_worktree",`node ${r} has no open managed worktree`,"Nothing to close for this node.");return z(r,t,await W(r,t))}o(g,"closeLocked");async function z(r,e,t){if(t.kind==="blocked"){const a=(await k(r))?.managed_worktree;throw a!=null&&a.state==="open"&&await P(r,{at:new Date().toISOString(),blocked:t.blocked}),new s("land_base_failed",t.blocked,t.next,t.detail)}return t.disposal!==void 0&&await R(r,t.disposal),await T(r,e,"pending"),t.result}o(z,"persistCloseOutcome");async function W(r,e){if(!u(e.path))throw new s("worktree_missing",`managed worktree path is missing: ${e.path}`,I(e));if(await N(e.path))throw new s("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(await h(e.path,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")!=="")throw new s("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${e.path}, then rerun \`crtr node worktree close\`.`);const a=await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry."),n=await h(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(a!==e.branch){if((await l(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],e.path)).status===0||a==="HEAD"||!await H(e.repo_root,e.path,a))throw new s("wrong_branch",`managed worktree is not on its recorded branch (expected ${e.branch}, found ${a==="HEAD"?"detached HEAD":a})`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);if(await A(e.path,e,n)===null)throw new s("branch_moved_unlanded",`managed worktree's recorded branch ${e.branch} no longer exists; its checkout is now on ${a} at ${n}, which carries content local base branch '${e.base_ref}' does not yet contain`,`Land or push ${a} through its own workflow before closing.`);const d=await w(e.path);if(!await H(e.repo_root,e.path,a)||await h(e.path,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==a||await h(e.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")!==n)throw new s("wrong_branch",`managed worktree at ${e.path} changed while closing`,`Inspect ${e.path}, then rerun \`crtr node worktree close\`.`);return{kind:"closed",disposal:{observed_branch:a,observed_sha:n,common_dir:d,authorized:new Date().toISOString()},result:{node_id:r,branch:a,worktree_path:e.path,landed_sha:n,..._(e),branch_delete_error:`${a} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}}if(await A(e.path,e,n)!==null)return{kind:"closed",result:{node_id:r,branch:e.branch,worktree_path:e.path,landed_sha:n,..._(e)}};let c;try{c=await K(e.path,e.base_ref)}catch(i){if(!(i instanceof s)||i.code!=="missing_base_branch"||n!==e.base_sha)throw i;return{kind:"closed",result:{node_id:r,branch:e.branch,worktree_path:e.path,landed_sha:e.base_sha,..._(e)}}}const y=await l(["rebase",c],e.path);if(y.status!==0)throw new s("rebase_failed",`rebase onto local base branch '${e.base_ref}' did not complete`,`Resolve conflicts in ${e.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`,p(y));const b=await h(e.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),m=o((i,d,S)=>({kind:"blocked",blocked:i,next:d,detail:S}),"blocked"),$=await l(["merge-base","--is-ancestor",c,b],e.path);if($.status!==0)return m(`rebased worktree is not a fast-forward of local base branch '${e.base_ref}'`,"Ask the user how to land this managed worktree.",p($));const C=await h(e.path,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry."),f=G(C,e.base_ref);if(f!==null){const i=await l(["rev-parse","HEAD"],f);if(i.status!==0||i.stdout.trim()!==c)return m(`local base branch '${e.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${f}, then rerun \`crtr node worktree close\`.`,i.status!==0?p(i):`expected ${c}, found ${i.stdout.trim()}`);const d=await j(f,b);if(!d.ok)return m(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,`Local base branch '${e.base_ref}' is checked out at ${f} in a state that blocks a fast-forward.`,d.detail)}else{const i=await l(["update-ref",`refs/heads/${e.base_ref}`,b,c],e.path);if(i.status!==0)return m(`could not fast-forward local base branch '${e.base_ref}' to this worktree`,"Ask the user how to land this managed worktree.",p(i))}return{kind:"closed",result:{node_id:r,branch:e.branch,worktree_path:e.path,landed_sha:b,..._(e)}}}o(W,"closeOutcome");async function ne(r){const e=(await k(r))?.managed_worktree;if(e==null||e.state!=="open")return g(r);if(!u(e.path)){const c=await B(r);if(c!==null)return Q(r,c)}const t=(await k(r))?.managed_worktree;if(t==null||t.state!=="open")return g(r);const a=u(t.path)?t.path:t.repo_root,n=await w(a);return v(E(n),()=>g(r),{timeoutMs:Math.min(D,25e3),timeoutError:o(()=>new s("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(ne,"closeManagedWorktreeAsync");async function oe(r,e){if(!u(e.path)){const a=await F(r,e);if(a!==null)return{kind:"concluded",conclusion:a}}const t=await w(u(e.path)?e.path:e.repo_root);return v(E(t),()=>W(r,e),{timeoutMs:Math.min(D,25e3),timeoutError:o(()=>new s("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(oe,"closeManagedWorktreeOnHost");function Q(r,e){return{node_id:r,branch:e.dropped.branch,worktree_path:e.dropped.worktree_path,landed_sha:e.landedSha,worktree_removed:!0,branch_deleted:e.dropped.branch_deleted,...e.dropped.branch_delete_error===void 0?{}:{branch_delete_error:e.dropped.branch_delete_error}}}o(Q,"concludedCloseResult");export{ne as closeManagedWorktreeAsync,oe as closeManagedWorktreeOnHost,Q as concludedCloseResult,z as persistCloseOutcome};
@@ -1,41 +1,3 @@
1
- /** Tracked-but-modified and untracked paths from `git status --porcelain`. */
2
- export interface CheckoutStatus {
3
- /** Paths with modifications to a tracked file (staged, unstaged, or both). */
4
- tracked: string[];
5
- /** Paths Git does not track at all. */
6
- untracked: string[];
7
- }
8
- /** Split `git status --porcelain` (v1 format) into tracked modifications and
9
- * untracked paths. A rename entry (`R old -> new`) reports the destination:
10
- * that is the path an incoming commit would collide with. */
11
- export declare function parseStatusPorcelain(porcelain: string): CheckoutStatus;
12
- export type LandPlan =
13
- /** Nothing local overlaps the incoming commits — fast-forward directly. */
14
- {
15
- kind: 'direct';
16
- }
17
- /** Local modifications touch incoming files; land underneath them. */
18
- | {
19
- kind: 'stash';
20
- overlapping: string[];
21
- }
22
- /** An incoming commit adds a path that already exists here, untracked. */
23
- | {
24
- kind: 'refuse';
25
- collisions: string[];
26
- };
27
- /** How to fast-forward a base checkout that may hold local changes.
28
- *
29
- * Git is less fragile than it looks here: a fast-forward refuses only when an
30
- * incoming commit touches a file with local modifications, so DISJOINT local
31
- * changes are carried along fine and need no stash at all. Overlap is the
32
- * blocker, not dirt.
33
- *
34
- * Untracked files are different. They also do not block a fast-forward unless
35
- * an incoming commit adds the same path — and that collision is a refusal
36
- * rather than a stash, because sweeping a person's untracked file into a stash
37
- * to make room for a commit is not a trade this code may make on their behalf. */
38
- export declare function planLandIntoCheckout(status: CheckoutStatus, incoming: readonly string[]): LandPlan;
39
1
  /** The `git update-ref --stdin` body that deletes a managed branch ONLY while
40
2
  * the ref that proved its content already landed is still at the exact SHA the
41
3
  * proof inspected. Compare-and-delete is the whole ownership guard: a branch
@@ -1,4 +1,3 @@
1
- var a=Object.defineProperty;var o=(e,n)=>a(e,"name",{value:n,configurable:!0});function u(e){const n=[],s=[];for(const t of e.split(`
2
- `)){if(t.length<4)continue;const r=t.slice(0,2),i=t.slice(3),c=i.includes(" -> ")?i.slice(i.indexOf(" -> ")+4):i,l=c.startsWith('"')&&c.endsWith('"')?c.slice(1,-1):c;r==="??"?s.push(l):r!=="!!"&&n.push(l)}return{tracked:n,untracked:s}}o(u,"parseStatusPorcelain");function f(e,n){const s=new Set(n),t=e.untracked.filter(i=>s.has(i));if(t.length>0)return{kind:"refuse",collisions:t};const r=e.tracked.filter(i=>s.has(i));return r.length>0?{kind:"stash",overlapping:r}:{kind:"direct"}}o(f,"planLandIntoCheckout");function h(e,n,s,t){return`verify ${s} ${t}
1
+ var i=Object.defineProperty;var r=(e,n)=>i(e,"name",{value:n,configurable:!0});function a(e,n,t,f){return`verify ${t} ${f}
3
2
  delete refs/heads/${e} ${n}
4
- `}o(h,"refDeleteTransactionStdin");export{u as parseStatusPorcelain,f as planLandIntoCheckout,h as refDeleteTransactionStdin};
3
+ `}r(a,"refDeleteTransactionStdin");export{a as refDeleteTransactionStdin};
@@ -3,7 +3,6 @@ export type SweepOutcome =
3
3
  /** The checkout and branch are gone and the record is marked complete. */
4
4
  {
5
5
  status: 'complete';
6
- stash?: string;
7
6
  }
8
7
  /** Nothing to do: no record, already reconciled, or the node came back. */
9
8
  | {
@@ -1,6 +1,4 @@
1
- var q=Object.defineProperty;var c=(t,e)=>q(t,"name",{value:e,configurable:!0});import{createHash as z}from"node:crypto";import{existsSync as w,realpathSync as Q}from"node:fs";import{isAbsolute as V,relative as j,resolve as v,sep as G}from"node:path";import{completeCleanup as J,getNode as E,recordSweepAttempt as X,resumableNodeCwds as Y}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as Z}from"./exclusive-lock.js";import{gitAsync as d}from"./git.js";import{proveBranchContained as D,upstreamTip as I}from"./worktree-containment.js";import{parseStatusPorcelain as tt,planLandIntoCheckout as et,refDeleteTransactionStdin as at}from"./worktree-landing.js";import{shellQuote as rt}from"../shared/shell-quote.js";import{deleteTrashAsync as st,removeWorktreeCheckoutAsync as B}from"./worktree-remove.js";import{WORKTREE_LOCK_WAIT_MS as nt,canonicalPath as L,checkoutPathForBranchInList as M,samePath as C,worktreeLockPathForCommonDir as it}from"./worktree.js";const A=[2,5,15,30,60],ot=A.length;function S(t){return t==null||t.state==="abandoned"?!1:t.state==="open"||t.cleanup!=="complete"}c(S,"isReconcilable");function Ht(t,e){const r=t.sweep?.next_attempt;if(r===void 0)return!0;const a=Date.parse(r);return Number.isNaN(a)||a<=e}c(Ht,"isDueForSweep");async function m(t,e){const r=await d(["rev-parse","--verify","--quiet",e],t);return r.status===0?r.stdout.trim():null}c(m,"revParseRef");function h(t){return(t.stderr.trim()||t.stdout.trim()).trim()}c(h,"detailOf");async function F(t){const e=await d(["rev-parse","--git-common-dir"],t);if(e.status!==0)return null;try{return Q(v(t,e.stdout.trim()))}catch{return null}}c(F,"commonGitDirAsync");async function lt(t){for(const e of["rebase-merge","rebase-apply"]){const r=await d(["rev-parse","--git-path",e],t);if(r.status!==0)return null;if(w(v(t,r.stdout.trim())))return!0}return!1}c(lt,"isRebaseInProgressAsync");function ut(t){for(const e of t.split(`
2
- `))if(e.startsWith("worktree "))return e.slice(9).trim();return null}c(ut,"mainWorktreePath");function ct(t,e,r){let a=null;for(const s of t.split(`
3
- `))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&s===`branch refs/heads/${r}`&&C(a,e))return a;return null}c(ct,"registeredCheckoutPath");async function dt(t){const e=w(t.path),r=e?t.path:t.repo_root,a=await m(r,`refs/heads/${t.base_ref}`),s=await I(r,t.base_ref),n=await m(r,`refs/heads/${t.branch}`);if(!e)return{base:a,upstream:s?.sha??null,branch:n,checkout:"absent"};const i=await d(["rev-parse","HEAD"],t.path),o=await d(["status","--porcelain"],t.path),l=i.status!==0||o.status!==0?null:z("sha256").update(`${i.stdout.trim()}
4
- ${o.stdout}`).digest("hex");return{base:a,upstream:s?.sha??null,branch:n,checkout:l}}c(dt,"observe");function ft(t,e){return t.checkout===null||e.checkout===null?!1:t.base===e.base&&t.upstream===e.upstream&&t.branch===e.branch&&t.checkout===e.checkout}c(ft,"sameObservation");async function ht(t,e,r,a,s,n){if(r.status!=="refused"&&r.status!=="failed"||!await n.stillEligible())return;const i=(e.sweep?.attempts??0)+1,o=A[Math.min(i,A.length)-1]??A[0],l=(await E(t))?.managed_worktree;l==null||!S(l)||await X(t,{reason:r.reason,...r.detail===void 0?{}:{detail:r.detail},observed:a,attempts:i,lastAttemptAt:new Date(s).toISOString(),nextAttemptAt:new Date(s+o*6e4).toISOString(),quarantined:i>=ot})}c(ht,"recordUnfinished");async function pt(t,e,r,a,s){const n=await d(["status","--porcelain"],t);if(n.status!==0)return{ok:!1,detail:h(n)};const i=await d(["diff","--name-only",r,a],t);if(i.status!==0)return{ok:!1,detail:h(i)};const o=i.stdout.split(`
5
- `).map(p=>p.trim()).filter(p=>p!==""),l=et(tt(n.stdout),o);if(l.kind==="refuse")return{ok:!1,detail:`untracked files in ${t} would be overwritten by the incoming commits: ${l.collisions.join(", ")}`};if(!await s.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=c(async()=>{const p=await d(["merge","--ff-only",a],t);return p.status===0?{ok:!0}:{ok:!1,detail:h(p)}},"merge");if(l.kind==="direct")return u();const b=await m(t,"refs/stash"),g=await d(["stash","push","--message",`crtr landing ${e}`],t);if(g.status!==0)return{ok:!1,detail:h(g)};const f=await m(t,"refs/stash");if(f===null||f===b)return u();const k=`local changes from ${t} are retained in stash ${f}; recover them with \`git -C ${rt(t)} stash apply ${f}\` and resolve any conflict.`,_=await u();return _.ok?(await d(["stash","apply",f],t)).status===0?(await U(t,f),{ok:!0}):(await d(["reset","--hard",a],t),{ok:!0,stash:`the shared base checkout was reset to landed commit ${a} because local changes conflicted with it. ${k}`}):(await d(["stash","apply",f],t)).status===0?(await U(t,f),_):{ok:!1,detail:`${_.detail}
6
- ${k}`}}c(pt,"landIntoBaseCheckoutAsync");async function U(t,e){await m(t,"refs/stash")===e&&await d(["stash","drop"],t)}c(U,"dropStashIfStillTip");async function mt(t,e,r){const a=await m(t.path,`refs/heads/${t.base_ref}`);if(a===null)return{ok:!1,detail:`local base branch '${t.base_ref}' does not resolve`};if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const s=await d(["rebase",a],t.path);if(s.status!==0)return await d(["rebase","--abort"],t.path),{ok:!1,detail:h(s)};const n=await m(t.path,"HEAD");if(n===null)return{ok:!1,detail:"could not read the rebased worktree tip"};if((await d(["merge-base","--is-ancestor",a,n],t.path)).status!==0)return{ok:!1,detail:`the rebased branch is not a fast-forward of '${t.base_ref}'`};const i=M(e,t.base_ref);if(i===null){if(!await r.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=await d(["update-ref",`refs/heads/${t.base_ref}`,n,a],t.path);return u.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:h(u)}}const o=await d(["rev-parse","HEAD"],i);if(o.status!==0||o.stdout.trim()!==a)return{ok:!1,detail:`base checkout ${i} is not at ${a}`};const l=await pt(i,t.branch,a,n,r);return l.ok?{ok:!0,landedSha:n,...l.stash===void 0?{}:{stash:l.stash}}:l}c(mt,"finishBlockedLand");const $={status:"skipped",reason:"node_no_longer_terminal"},x={status:"skipped",reason:"checkout_in_use"};function bt(t,e){const r=j(t,e);return r===""||r!==".."&&!r.startsWith(`..${G}`)&&!V(r)}c(bt,"isWithinDirectory");async function P(t,e){const r=[v(e),L(e)];return(await Y(t)).some(({cwd:a})=>{const s=[v(a),L(a)];return r.some(n=>s.some(i=>bt(n,i)))})}c(P,"checkoutHasDependents");async function Nt(t,e,r=Date.now()){const a=(await E(t))?.managed_worktree;if(!S(a)||a==null)return{status:"skipped",reason:"already_reconciled"};if(w(a.path)&&await P(t,a.path))return x;const s=w(a.path)?a.path:a.repo_root;if(!w(s))return await T(t,a,{status:"refused",reason:"repo_unavailable",detail:`neither the recorded checkout nor repository root exists, so ${a.branch} cannot be proved absent`},{base:null,upstream:null,branch:null,checkout:null},r,e);const n=await F(s);if(n===null)return await T(t,a,{status:"failed",reason:"git_dir_unreadable",detail:`could not resolve the git common dir from ${s}`},{base:null,upstream:null,branch:null,checkout:null},r,e);let i={base:null,upstream:null,branch:null,checkout:null},o;const l=[];try{o=await Z(it(n),async()=>{if(!await e.stillEligible())return $;const u=(await E(t))?.managed_worktree;return!S(u)||u==null?{status:"skipped",reason:"already_reconciled"}:(i=await dt(u),u.sweep!==void 0&&ft(u.sweep.observed,i)?{status:"refused",reason:u.sweep.reason,...u.sweep.detail===void 0?{}:{detail:u.sweep.detail},unchanged:!0}:w(u.path)?await _t(t,u,e,l):await kt(t,u,i,e))},{timeoutMs:nt,timeoutError:c(()=>new Error(`timed out waiting for the managed-worktree lock on ${n}`),"timeoutError")})}catch(u){o={status:"failed",reason:"lock_unavailable",detail:u instanceof Error?u.message:String(u)}}return await st(a.path,l[0]),await T(t,a,o,i,r,e)}c(Nt,"reconcileManagedWorktree");async function T(t,e,r,a,s,n){return await ht(t,e,r,a,s,n),r}c(T,"finish");async function H(t,e,r){if(!await r.stillEligible())return $;const a=(await E(t))?.managed_worktree;return a==null||a.path!==e.path||a.branch!==e.branch?{status:"skipped",reason:"record_changed"}:(await J(t),{status:"complete"})}c(H,"persistComplete");async function kt(t,e,r,a){const s=e.repo_root;if(r.branch===null){const l=await d(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],s);return l.status!==1?{status:"failed",reason:"branch_inspection_failed",detail:h(l)}:await H(t,e,a)}const n=await d(["worktree","list","--porcelain"],s);if(n.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:h(n)};const i=M(n.stdout,e.branch);if(i!==null)return{status:"refused",reason:"branch_checked_out_elsewhere",detail:`${e.branch} is checked out at ${i}`};const o=await D(s,e,r.branch);return o===null?{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries content no base or upstream ref contains; its checkout is already gone, so the branch is the only copy`}:K(t,e,s,r.branch,o,a)}c(kt,"concludeAbsentCheckout");async function _t(t,e,r,a){const s=await d(["worktree","list","--porcelain"],e.path);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:h(s)};const n=e.disposal,i=n?.observed_branch??e.branch,o=ct(s.stdout,e.path,i);if(o===null)return{status:"refused",reason:"not_registered",detail:`${e.path} is not registered to refs/heads/${i}; crtr will not act on a path it cannot prove it owns`};const l=ut(s.stdout);if(l===null||C(l,o)||!w(l))return{status:"refused",reason:"repo_unavailable",detail:`the repository's main checkout is unavailable, so ${e.path} cannot be removed from outside itself`};const u=await lt(e.path);if(u===null)return{status:"failed",reason:"git_path_failed",detail:`could not inspect in-progress operations in ${e.path}`};if(u)return{status:"refused",reason:"rebase_in_progress",detail:`${e.path} is mid-rebase`};const b=await d(["rev-parse","--abbrev-ref","HEAD"],e.path);if(b.status!==0)return{status:"failed",reason:"branch_check_failed",detail:h(b)};if(b.stdout.trim()!==i)return{status:"refused",reason:"wrong_branch",detail:`expected ${i}, found ${b.stdout.trim()==="HEAD"?"detached HEAD":b.stdout.trim()}`};const g=await d(["status","--porcelain"],e.path);if(g.status!==0)return{status:"failed",reason:"status_failed",detail:h(g)};if(g.stdout.trim()!=="")return{status:"refused",reason:"dirty_worktree",detail:`${e.path} has uncommitted changes`};let f=await m(e.path,"HEAD");if(f===null)return{status:"failed",reason:"head_unreadable",detail:`could not read HEAD in ${e.path}`};if(n!==void 0){if(await F(e.path)!==n.common_dir||f!==n.observed_sha)return{status:"refused",reason:"disposal_authorization_stale",detail:`${e.path} changed since \`close\` authorized its disposal; rerun \`crtr node worktree close\` from that node to re-authorize, or ask the user with \`crtr human send\``};if(!await r.stillEligible())return $;if(await P(t,o))return x;const{result:W,trash:R}=await B(l,o);return R!==void 0&&a.push(R),W.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:h(W)}:await H(t,e,r)}let k=await D(e.path,e,f),_;if(k===null&&e.land_intent!==void 0){const y=await mt(e,s.stdout,r);if(!y.ok)return y.ineligible===!0?$:{status:"refused",reason:"land_blocked",detail:y.detail};f=y.landedSha,_=y.stash,k=await D(e.path,e,f)}if(k===null)return{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries commits its base does not contain, and this node never asked to land them`};if(!await r.stillEligible())return $;if(await P(t,o))return x;const{result:p,trash:N}=await B(l,o);if(N!==void 0&&a.push(N),p.status!==0)return{status:"refused",reason:"worktree_remove_failed",detail:h(p)};const O=await K(t,e,l,f,k,r);return O.status==="complete"&&_!==void 0?{status:"complete",stash:_}:O}c(_t,"reconcilePresentCheckout");async function K(t,e,r,a,s,n){if(!await n.stillEligible())return $;const i=at(e.branch,a,s.containingRef,s.containingSha),o=await d(["update-ref","--stdin"],r,i);return o.status!==0?{status:"refused",reason:"branch_delete_failed",detail:h(o)}:await H(t,e,n)}c(K,"deleteBranchAndComplete");export{Ht as isDueForSweep,S as isReconcilable,Nt as reconcileManagedWorktree};
1
+ var L=Object.defineProperty;var l=(t,e)=>L(t,"name",{value:e,configurable:!0});import{createHash as U}from"node:crypto";import{existsSync as h,realpathSync as K}from"node:fs";import{isAbsolute as q,relative as z,resolve as g,sep as V}from"node:path";import{completeCleanup as G,getNode as y,recordSweepAttempt as Q,resumableNodeCwds as j}from"./canvas/index.js";import{withExclusiveDirectoryLockAsync as J}from"./exclusive-lock.js";import{gitAsync as d}from"./git.js";import{proveBranchContained as $,upstreamTip as X}from"./worktree-containment.js";import{refDeleteTransactionStdin as Y}from"./worktree-landing.js";import{deleteTrashAsync as Z,removeWorktreeCheckoutAsync as O}from"./worktree-remove.js";import{WORKTREE_LOCK_WAIT_MS as I,canonicalPath as W,checkoutPathForBranchInList as R,samePath as B,worktreeLockPathForCommonDir as ee}from"./worktree.js";const v=[2,5,15,30,60],te=v.length;function A(t){return t==null||t.state==="abandoned"?!1:t.state==="open"||t.cleanup!=="complete"}l(A,"isReconcilable");function Ee(t,e){const a=t.sweep?.next_attempt;if(a===void 0)return!0;const r=Date.parse(a);return Number.isNaN(r)||r<=e}l(Ee,"isDueForSweep");async function _(t,e){const a=await d(["rev-parse","--verify","--quiet",e],t);return a.status===0?a.stdout.trim():null}l(_,"revParseRef");function f(t){return(t.stderr.trim()||t.stdout.trim()).trim()}l(f,"detailOf");async function M(t){const e=await d(["rev-parse","--git-common-dir"],t);if(e.status!==0)return null;try{return K(g(t,e.stdout.trim()))}catch{return null}}l(M,"commonGitDirAsync");async function ae(t){for(const e of["rebase-merge","rebase-apply"]){const a=await d(["rev-parse","--git-path",e],t);if(a.status!==0)return null;if(h(g(t,a.stdout.trim())))return!0}return!1}l(ae,"isRebaseInProgressAsync");function re(t){for(const e of t.split(`
2
+ `))if(e.startsWith("worktree "))return e.slice(9).trim();return null}l(re,"mainWorktreePath");function se(t,e,a){let r=null;for(const s of t.split(`
3
+ `))if(s.startsWith("worktree "))r=s.slice(9).trim();else if(r!==null&&s===`branch refs/heads/${a}`&&B(r,e))return r;return null}l(se,"registeredCheckoutPath");async function ne(t){const e=h(t.path),a=e?t.path:t.repo_root,r=await _(a,`refs/heads/${t.base_ref}`),s=await X(a,t.base_ref),n=await _(a,`refs/heads/${t.branch}`);if(!e)return{base:r,upstream:s?.sha??null,branch:n,checkout:"absent"};const i=await d(["rev-parse","HEAD"],t.path),o=await d(["status","--porcelain"],t.path),c=i.status!==0||o.status!==0?null:U("sha256").update(`${i.stdout.trim()}
4
+ ${o.stdout}`).digest("hex");return{base:r,upstream:s?.sha??null,branch:n,checkout:c}}l(ne,"observe");function ie(t,e){return t.checkout===null||e.checkout===null?!1:t.base===e.base&&t.upstream===e.upstream&&t.branch===e.branch&&t.checkout===e.checkout}l(ie,"sameObservation");async function oe(t,e,a,r,s,n){if(a.status!=="refused"&&a.status!=="failed"||!await n.stillEligible())return;const i=(e.sweep?.attempts??0)+1,o=v[Math.min(i,v.length)-1]??v[0],c=(await y(t))?.managed_worktree;c==null||!A(c)||await Q(t,{reason:a.reason,...a.detail===void 0?{}:{detail:a.detail},observed:r,attempts:i,lastAttemptAt:new Date(s).toISOString(),nextAttemptAt:new Date(s+o*6e4).toISOString(),quarantined:i>=te})}l(oe,"recordUnfinished");async function le(t,e,a){const r=await _(t.path,`refs/heads/${t.base_ref}`);if(r===null)return{ok:!1,detail:`local base branch '${t.base_ref}' does not resolve`};if(!await a.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const s=await d(["rebase",r],t.path);if(s.status!==0)return await d(["rebase","--abort"],t.path),{ok:!1,detail:f(s)};const n=await _(t.path,"HEAD");if(n===null)return{ok:!1,detail:"could not read the rebased worktree tip"};if((await d(["merge-base","--is-ancestor",r,n],t.path)).status!==0)return{ok:!1,detail:`the rebased branch is not a fast-forward of '${t.base_ref}'`};const i=R(e,t.base_ref);if(i===null){if(!await a.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const u=await d(["update-ref",`refs/heads/${t.base_ref}`,n,r],t.path);return u.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:f(u)}}const o=await d(["rev-parse","HEAD"],i);if(o.status!==0||o.stdout.trim()!==r)return{ok:!1,detail:`base checkout ${i} is not at ${r}`};if(!await a.stillEligible())return{ok:!1,detail:"node is no longer terminal",ineligible:!0};const c=await d(["merge","--ff-only",n],i);return c.status===0?{ok:!0,landedSha:n}:{ok:!1,detail:f(c)}}l(le,"finishBlockedLand");const m={status:"skipped",reason:"node_no_longer_terminal"},D={status:"skipped",reason:"checkout_in_use"};function ue(t,e){const a=z(t,e);return a===""||a!==".."&&!a.startsWith(`..${V}`)&&!q(a)}l(ue,"isWithinDirectory");async function S(t,e){const a=[g(e),W(e)];return(await j(t)).some(({cwd:r})=>{const s=[g(r),W(r)];return a.some(n=>s.some(i=>ue(n,i)))})}l(S,"checkoutHasDependents");async function $e(t,e,a=Date.now()){const r=(await y(t))?.managed_worktree;if(!A(r)||r==null)return{status:"skipped",reason:"already_reconciled"};if(h(r.path)&&await S(t,r.path))return D;const s=h(r.path)?r.path:r.repo_root;if(!h(s))return await C(t,r,{status:"refused",reason:"repo_unavailable",detail:`neither the recorded checkout nor repository root exists, so ${r.branch} cannot be proved absent`},{base:null,upstream:null,branch:null,checkout:null},a,e);const n=await M(s);if(n===null)return await C(t,r,{status:"failed",reason:"git_dir_unreadable",detail:`could not resolve the git common dir from ${s}`},{base:null,upstream:null,branch:null,checkout:null},a,e);let i={base:null,upstream:null,branch:null,checkout:null},o;const c=[];try{o=await J(ee(n),async()=>{if(!await e.stillEligible())return m;const u=(await y(t))?.managed_worktree;return!A(u)||u==null?{status:"skipped",reason:"already_reconciled"}:(i=await ne(u),u.sweep!==void 0&&ie(u.sweep.observed,i)?{status:"refused",reason:u.sweep.reason,...u.sweep.detail===void 0?{}:{detail:u.sweep.detail},unchanged:!0}:h(u.path)?await de(t,u,e,c):await ce(t,u,i,e))},{timeoutMs:I,timeoutError:l(()=>new Error(`timed out waiting for the managed-worktree lock on ${n}`),"timeoutError")})}catch(u){o={status:"failed",reason:"lock_unavailable",detail:u instanceof Error?u.message:String(u)}}return await Z(r.path,c[0]),await C(t,r,o,i,a,e)}l($e,"reconcileManagedWorktree");async function C(t,e,a,r,s,n){return await oe(t,e,a,r,s,n),a}l(C,"finish");async function x(t,e,a){if(!await a.stillEligible())return m;const r=(await y(t))?.managed_worktree;return r==null||r.path!==e.path||r.branch!==e.branch?{status:"skipped",reason:"record_changed"}:(await G(t),{status:"complete"})}l(x,"persistComplete");async function ce(t,e,a,r){const s=e.repo_root;if(a.branch===null){const c=await d(["show-ref","--verify","--quiet",`refs/heads/${e.branch}`],s);return c.status!==1?{status:"failed",reason:"branch_inspection_failed",detail:f(c)}:await x(t,e,r)}const n=await d(["worktree","list","--porcelain"],s);if(n.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:f(n)};const i=R(n.stdout,e.branch);if(i!==null)return{status:"refused",reason:"branch_checked_out_elsewhere",detail:`${e.branch} is checked out at ${i}`};const o=await $(s,e,a.branch);return o===null?{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries content no base or upstream ref contains; its checkout is already gone, so the branch is the only copy`}:F(t,e,s,a.branch,o,r)}l(ce,"concludeAbsentCheckout");async function de(t,e,a,r){const s=await d(["worktree","list","--porcelain"],e.path);if(s.status!==0)return{status:"failed",reason:"worktree_list_failed",detail:f(s)};const n=e.disposal,i=n?.observed_branch??e.branch,o=se(s.stdout,e.path,i);if(o===null)return{status:"refused",reason:"not_registered",detail:`${e.path} is not registered to refs/heads/${i}; crtr will not act on a path it cannot prove it owns`};const c=re(s.stdout);if(c===null||B(c,o)||!h(c))return{status:"refused",reason:"repo_unavailable",detail:`the repository's main checkout is unavailable, so ${e.path} cannot be removed from outside itself`};const u=await ae(e.path);if(u===null)return{status:"failed",reason:"git_path_failed",detail:`could not inspect in-progress operations in ${e.path}`};if(u)return{status:"refused",reason:"rebase_in_progress",detail:`${e.path} is mid-rebase`};const b=await d(["rev-parse","--abbrev-ref","HEAD"],e.path);if(b.status!==0)return{status:"failed",reason:"branch_check_failed",detail:f(b)};if(b.stdout.trim()!==i)return{status:"refused",reason:"wrong_branch",detail:`expected ${i}, found ${b.stdout.trim()==="HEAD"?"detached HEAD":b.stdout.trim()}`};const E=await d(["status","--porcelain"],e.path);if(E.status!==0)return{status:"failed",reason:"status_failed",detail:f(E)};if(E.stdout.trim()!=="")return{status:"refused",reason:"dirty_worktree",detail:`${e.path} has uncommitted changes`};let p=await _(e.path,"HEAD");if(p===null)return{status:"failed",reason:"head_unreadable",detail:`could not read HEAD in ${e.path}`};if(n!==void 0){if(await M(e.path)!==n.common_dir||p!==n.observed_sha)return{status:"refused",reason:"disposal_authorization_stale",detail:`${e.path} changed since \`close\` authorized its disposal; rerun \`crtr node worktree close\` from that node to re-authorize, or ask the user with \`crtr human send\``};if(!await a.stillEligible())return m;if(await S(t,o))return D;const{result:T,trash:N}=await O(c,o);return N!==void 0&&r.push(N),T.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:f(T)}:await x(t,e,a)}let w=await $(e.path,e,p);if(w===null&&e.land_intent!==void 0){const k=await le(e,s.stdout,a);if(!k.ok)return k.ineligible===!0?m:{status:"refused",reason:"land_blocked",detail:k.detail};p=k.landedSha,w=await $(e.path,e,p)}if(w===null)return{status:"refused",reason:"unlanded_work",detail:`${e.branch} carries commits its base does not contain, and this node never asked to land them`};if(!await a.stillEligible())return m;if(await S(t,o))return D;const{result:H,trash:P}=await O(c,o);return P!==void 0&&r.push(P),H.status!==0?{status:"refused",reason:"worktree_remove_failed",detail:f(H)}:await F(t,e,c,p,w,a)}l(de,"reconcilePresentCheckout");async function F(t,e,a,r,s,n){if(!await n.stillEligible())return m;const i=Y(e.branch,r,s.containingRef,s.containingSha),o=await d(["update-ref","--stdin"],a,i);return o.status!==0?{status:"refused",reason:"branch_delete_failed",detail:f(o)}:await x(t,e,n)}l(F,"deleteBranchAndComplete");export{Ee as isDueForSweep,A as isReconcilable,$e as reconcileManagedWorktree};
@@ -52,10 +52,6 @@ export interface CloseManagedWorktreeResult {
52
52
  /** Always false while the pending-cleanup checkout has this branch checked out. */
53
53
  branch_deleted: boolean;
54
54
  branch_delete_error?: string;
55
- /** Present ONLY when landing had to stash local changes in the base checkout
56
- * and re-applying them conflicted: names the preserved stash and how to
57
- * re-apply it. Its absence means nothing local was left over. */
58
- base_checkout_stash?: string;
59
55
  }
60
56
  /** The ONE authoritative closed-worktree state transition, shared by every
61
57
  * closing path (explicit `closeManagedWorktreeLocked` land, the clean
@@ -1,18 +1,16 @@
1
- var Z=Object.defineProperty;var o=(e,r)=>Z(e,"name",{value:r,configurable:!0});import{existsSync as k,mkdirSync as H,readFileSync as ee,realpathSync as N,rmSync as te,writeFileSync as re}from"node:fs";import{createHash as ne}from"node:crypto";import{dirname as oe,isAbsolute as ae,join as se,relative as ie,resolve as C,sep as ce}from"node:path";import{gitAsync as he,gitSync as i}from"./git.js";import{crtrHome as O}from"./canvas/paths.js";import{closeWorktreeAndRepoint as ue,getNode as v,recordLandIntent as le}from"./canvas/index.js";import{CONFIG_FILE as de,CRTR_DIR_NAME as A,STATE_FILE as fe}from"../types.js";import{withExclusiveDirectoryLock as pe,withExclusiveDirectoryLockAsync as me}from"./exclusive-lock.js";import{parseStatusPorcelain as be,planLandIntoCheckout as ke,refDeleteTransactionStdin as _e}from"./worktree-landing.js";import{shellQuote as w}from"../shared/shell-quote.js";class f extends Error{static{o(this,"WorktreeError")}code;next;detail;constructor(r,t,n,a){super(t),this.name="WorktreeError",this.code=r,this.next=n,this.detail=a}}function _(e,r,t,n){const a=i(r,e);if(a.status!==0){const s=(a.stderr.trim()||a.stdout.trim()).trim();throw new f(t,`git ${r.join(" ")} failed`,n,s)}return a.stdout.trim()}o(_,"runGit");function F(){return`${O()}/worktrees`}o(F,"managedWorktreesRoot");function ge(e){return`${F()}/${e}`}o(ge,"managedWorktreePath");function Xe(e){return e?.managed_worktree?.state==="open"}o(Xe,"hasOpenManagedWorktree");async function x(e){const t=(await v(e))?.managed_worktree;return t?.state==="open"?t:null}o(x,"openManagedWorktreeForNode");function we(e){const r=i(["rev-parse","--show-toplevel"],e);if(r.status!==0){const t=(r.stderr.trim()||r.stdout.trim()).trim();throw new f("not_git_repo",`cwd ${e} is not a git repository`,"Pass --cwd <real repo> pointing inside a git repository.",t)}return r.stdout.trim()}o(we,"repoRootFor");function ye(e){const r=ie(E(F()),E(e));return r!==""&&r!==".."&&!r.startsWith(`..${ce}`)&&!ae(r)}o(ye,"isManagedWorktreeBase");function $e(e,r){const t=`refs/heads/${r}`,n=i(["show-ref","--verify","--quiet",t],e);if(n.status===0)return!0;if(n.status===1&&n.executionFailed!==!0)return!1;const a=n.stderr.trim()||"<empty>",s=n.processError===void 0?"":`
2
- process error: ${n.processError}`;throw new f("recorded_branch_inspection_failed",`could not inspect recorded branch '${r}' (git show-ref exited with status ${n.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${n.status}
3
- stderr: ${a}${s}`)}o($e,"recordedBranchExists");function R(e,r){const t=`refs/heads/${r}`,n=i(["show-ref","--verify","--quiet",t],e);if(n.status===1&&n.executionFailed!==!0)throw new f("missing_base_branch",`managed worktree base '${r}' 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(n.status!==0){const a=n.stderr.trim()||"<empty>",s=n.processError===void 0?"":`
4
- process error: ${n.processError}`;throw new f("base_branch_inspection_failed",`could not inspect local base branch '${r}' (git show-ref exited with status ${n.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${n.status}
5
- stderr: ${a}${s}`)}return _(e,["rev-parse","--verify",t],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(R,"resolveLandableBase");function ve(e,r){const t=_(e,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry.");return I(t,r)}o(ve,"checkoutPathForBranch");function I(e,r){let t=null;for(const n of e.split(`
6
- `))if(n.startsWith("worktree "))t=n.slice(9).trim();else if(n===`branch refs/heads/${r}`)return t;return null}o(I,"checkoutPathForBranchInList");function xe(e,r){return e===r||E(e)===E(r)}o(xe,"samePath");function E(e){try{return N.native(e)}catch{return C(e)}}o(E,"canonicalPath");const q=3e4;function G(e){const r=`${O()}/worktree-locks`;return H(r,{recursive:!0}),`${r}/${ne("sha256").update(e).digest("hex")}`}o(G,"worktreeLockPathForCommonDir");function S(e){const r=_(e,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return N(C(e,r))}o(S,"commonGitDir");function B(e,r){const t=S(e);return pe(G(t),r,{timeoutMs:q,timeoutError:o(()=>new f("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(B,"withRepositoryWorktreeLock");async function j(e,r){const t=S(e);return me(G(t),r,{timeoutMs:q,timeoutError:o(()=>new f("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(j,"withRepositoryWorktreeLockAsync");function D(e,r,t){const n=i(["worktree","list","--porcelain"],e);if(n.status!==0)return null;let a=null;for(const s of n.stdout.split(`
7
- `))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&xe(a,r)&&s===`branch refs/heads/${t}`)return!0;return!1}o(D,"registeredWorktree");function Ee(e,r,t){const n=[],a=`refs/heads/${r}`,s=i(["rev-parse","--verify","--quiet",a],e);s.status===0&&n.push({ref:a,sha:s.stdout.trim()});const u=i(["rev-parse","--symbolic-full-name","--verify",`${r}@{upstream}`],e),h=u.status===0&&u.stdout.trim().startsWith("refs/")?u.stdout.trim():`refs/remotes/origin/${r}`,m=i(["rev-parse","--verify","--quiet",h],e);if(m.status===0&&n.push({ref:h,sha:m.stdout.trim()}),n.length===0)return null;for(const d of n)if(i(["merge-base","--is-ancestor",t,d.sha],e).status===0)return{containingRef:d.ref,containingSha:d.sha};for(const d of n){const l=i(["cherry",d.sha,t],e);if(l.status!==0)continue;if(l.stdout.split(`
8
- `).map(c=>c.trim()).filter(c=>c!=="").every(c=>c.startsWith("-")))return{containingRef:d.ref,containingSha:d.sha}}for(const d of n){const l=i(["rev-parse","--verify",`${d.sha}^{tree}`],e);if(l.status!==0)continue;const b=i(["merge-tree","--write-tree",d.sha,t],e);if(b.status===0&&b.stdout.split(`
9
- `)[0]?.trim()===l.stdout.trim())return{containingRef:d.ref,containingSha:d.sha}}return null}o(Ee,"proveBranchContained");function K(e,r){const t=i(["rev-parse","--verify",`refs/heads/${e.branch}`],e.repo_root);if(t.status!==0||t.stdout.trim()!==e.base_sha)return;const n=D(e.repo_root,e.path,e.branch);if(n!==null){if(n){if(i(["worktree","remove","--force",e.path],e.repo_root).status!==0||D(e.repo_root,e.path,e.branch)!==!1)return}else if(r&&k(e.path))try{te(e.path,{recursive:!0,force:!0})}catch{return}try{i(["update-ref","-d",`refs/heads/${e.branch}`,e.base_sha],e.repo_root)}catch{}}}o(K,"rollbackManagedWorktreeLocked");function ze(e){B(e.repo_root,()=>K(e,!1))}o(ze,"rollbackManagedWorktree");const Se="# crtr: exclude crtr's own untracked project-scope bookkeeping (auto-added at managed-worktree creation)",De=[`/${A}/${de}`,`/${A}/${fe}`,`/${A}/operations.db*`];function We(e){try{const r=se(S(e),"info","exclude");H(oe(r),{recursive:!0});let t="";try{t=ee(r,"utf8")}catch{}const n=new Set(t.split(`
10
- `).map(h=>h.trim())),a=De.filter(h=>!n.has(h));if(a.length===0)return;const u=(t.length>0&&!t.endsWith(`
1
+ var Q=Object.defineProperty;var o=(e,r)=>Q(e,"name",{value:r,configurable:!0});import{existsSync as b,mkdirSync as C,readFileSync as J,realpathSync as L,rmSync as V,writeFileSync as Y}from"node:fs";import{createHash as Z}from"node:crypto";import{dirname as ee,isAbsolute as te,join as re,relative as ne,resolve as T,sep as oe}from"node:path";import{gitAsync as ae,gitSync as c}from"./git.js";import{crtrHome as P}from"./canvas/paths.js";import{closeWorktreeAndRepoint as se,getNode as w,recordLandIntent as ie}from"./canvas/index.js";import{CONFIG_FILE as ce,CRTR_DIR_NAME as S,STATE_FILE as he}from"../types.js";import{withExclusiveDirectoryLock as ue,withExclusiveDirectoryLockAsync as le}from"./exclusive-lock.js";import{refDeleteTransactionStdin as de}from"./worktree-landing.js";import{shellQuote as _}from"../shared/shell-quote.js";class d extends Error{static{o(this,"WorktreeError")}code;next;detail;constructor(r,t,n,a){super(t),this.name="WorktreeError",this.code=r,this.next=n,this.detail=a}}function k(e,r,t,n){const a=c(r,e);if(a.status!==0){const s=(a.stderr.trim()||a.stdout.trim()).trim();throw new d(t,`git ${r.join(" ")} failed`,n,s)}return a.stdout.trim()}o(k,"runGit");function H(){return`${P()}/worktrees`}o(H,"managedWorktreesRoot");function fe(e){return`${H()}/${e}`}o(fe,"managedWorktreePath");function Ie(e){return e?.managed_worktree?.state==="open"}o(Ie,"hasOpenManagedWorktree");async function y(e){const t=(await w(e))?.managed_worktree;return t?.state==="open"?t:null}o(y,"openManagedWorktreeForNode");function pe(e){const r=c(["rev-parse","--show-toplevel"],e);if(r.status!==0){const t=(r.stderr.trim()||r.stdout.trim()).trim();throw new d("not_git_repo",`cwd ${e} is not a git repository`,"Pass --cwd <real repo> pointing inside a git repository.",t)}return r.stdout.trim()}o(pe,"repoRootFor");function me(e){const r=ne($(H()),$(e));return r!==""&&r!==".."&&!r.startsWith(`..${oe}`)&&!te(r)}o(me,"isManagedWorktreeBase");function be(e,r){const t=`refs/heads/${r}`,n=c(["show-ref","--verify","--quiet",t],e);if(n.status===0)return!0;if(n.status===1&&n.executionFailed!==!0)return!1;const a=n.stderr.trim()||"<empty>",s=n.processError===void 0?"":`
2
+ process error: ${n.processError}`;throw new d("recorded_branch_inspection_failed",`could not inspect recorded branch '${r}' (git show-ref exited with status ${n.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${n.status}
3
+ stderr: ${a}${s}`)}o(be,"recordedBranchExists");function D(e,r){const t=`refs/heads/${r}`,n=c(["show-ref","--verify","--quiet",t],e);if(n.status===1&&n.executionFailed!==!0)throw new d("missing_base_branch",`managed worktree base '${r}' 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(n.status!==0){const a=n.stderr.trim()||"<empty>",s=n.processError===void 0?"":`
4
+ process error: ${n.processError}`;throw new d("base_branch_inspection_failed",`could not inspect local base branch '${r}' (git show-ref exited with status ${n.status})`,"Inspect the repository and its Git metadata, then retry.",`status: ${n.status}
5
+ stderr: ${a}${s}`)}return k(e,["rev-parse","--verify",t],"base_branch_resolve_failed","Inspect the local base branch, then retry.")}o(D,"resolveLandableBase");function ke(e,r){const t=k(e,["worktree","list","--porcelain"],"worktree_list_failed","Inspect the repository worktrees manually, then retry.");return N(t,r)}o(ke,"checkoutPathForBranch");function N(e,r){let t=null;for(const n of e.split(`
6
+ `))if(n.startsWith("worktree "))t=n.slice(9).trim();else if(n===`branch refs/heads/${r}`)return t;return null}o(N,"checkoutPathForBranchInList");function _e(e,r){return e===r||$(e)===$(r)}o(_e,"samePath");function $(e){try{return L.native(e)}catch{return T(e)}}o($,"canonicalPath");const O=3e4;function F(e){const r=`${P()}/worktree-locks`;return C(r,{recursive:!0}),`${r}/${Z("sha256").update(e).digest("hex")}`}o(F,"worktreeLockPathForCommonDir");function v(e){const r=k(e,["rev-parse","--git-common-dir"],"git_common_dir_failed","Inspect the repository git metadata, then retry.");return L(T(e,r))}o(v,"commonGitDir");function G(e,r){const t=v(e);return ue(F(t),r,{timeoutMs:O,timeoutError:o(()=>new d("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(G,"withRepositoryWorktreeLock");async function I(e,r){const t=v(e);return le(F(t),r,{timeoutMs:O,timeoutError:o(()=>new d("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(I,"withRepositoryWorktreeLockAsync");function x(e,r,t){const n=c(["worktree","list","--porcelain"],e);if(n.status!==0)return null;let a=null;for(const s of n.stdout.split(`
7
+ `))if(s.startsWith("worktree "))a=s.slice(9).trim();else if(a!==null&&_e(a,r)&&s===`branch refs/heads/${t}`)return!0;return!1}o(x,"registeredWorktree");function ge(e,r,t){const n=[],a=`refs/heads/${r}`,s=c(["rev-parse","--verify","--quiet",a],e);s.status===0&&n.push({ref:a,sha:s.stdout.trim()});const h=c(["rev-parse","--symbolic-full-name","--verify",`${r}@{upstream}`],e),l=h.status===0&&h.stdout.trim().startsWith("refs/")?h.stdout.trim():`refs/remotes/origin/${r}`,m=c(["rev-parse","--verify","--quiet",l],e);if(m.status===0&&n.push({ref:l,sha:m.stdout.trim()}),n.length===0)return null;for(const p of n)if(c(["merge-base","--is-ancestor",t,p.sha],e).status===0)return{containingRef:p.ref,containingSha:p.sha};for(const p of n){const u=c(["cherry",p.sha,t],e);if(u.status!==0)continue;if(u.stdout.split(`
8
+ `).map(f=>f.trim()).filter(f=>f!=="").every(f=>f.startsWith("-")))return{containingRef:p.ref,containingSha:p.sha}}for(const p of n){const u=c(["rev-parse","--verify",`${p.sha}^{tree}`],e);if(u.status!==0)continue;const i=c(["merge-tree","--write-tree",p.sha,t],e);if(i.status===0&&i.stdout.split(`
9
+ `)[0]?.trim()===u.stdout.trim())return{containingRef:p.ref,containingSha:p.sha}}return null}o(ge,"proveBranchContained");function B(e,r){const t=c(["rev-parse","--verify",`refs/heads/${e.branch}`],e.repo_root);if(t.status!==0||t.stdout.trim()!==e.base_sha)return;const n=x(e.repo_root,e.path,e.branch);if(n!==null){if(n){if(c(["worktree","remove","--force",e.path],e.repo_root).status!==0||x(e.repo_root,e.path,e.branch)!==!1)return}else if(r&&b(e.path))try{V(e.path,{recursive:!0,force:!0})}catch{return}try{c(["update-ref","-d",`refs/heads/${e.branch}`,e.base_sha],e.repo_root)}catch{}}}o(B,"rollbackManagedWorktreeLocked");function Be(e){G(e.repo_root,()=>B(e,!1))}o(Be,"rollbackManagedWorktree");const we="# crtr: exclude crtr's own untracked project-scope bookkeeping (auto-added at managed-worktree creation)",ye=[`/${S}/${ce}`,`/${S}/${he}`,`/${S}/operations.db*`];function $e(e){try{const r=re(v(e),"info","exclude");C(ee(r),{recursive:!0});let t="";try{t=J(r,"utf8")}catch{}const n=new Set(t.split(`
10
+ `).map(l=>l.trim())),a=ye.filter(l=>!n.has(l));if(a.length===0)return;const h=(t.length>0&&!t.endsWith(`
11
11
  `)?`
12
- `:"")+Se+`
12
+ `:"")+we+`
13
13
  `+a.join(`
14
14
  `)+`
15
- `;re(r,t+u)}catch{}}o(We,"seedManagedWorktreeExclude");function Qe(e,r,t="main"){const n=we(e);if(ye(n))throw new f("managed_worktree_base",`cwd ${n} is a managed worktree and cannot be used as a managed worktree base`,"Pass `--cwd` pointing at the repository\u2019s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.");return B(n,()=>{const a=R(n,t),s=ge(r),u=`crtr/${r}`;if(k(s))throw new f("worktree_path_exists",`managed worktree path already exists: ${s}`,"Remove the stale path or choose a fresh node id.");if(i(["show-ref","--verify","--quiet",`refs/heads/${u}`],n).status===0)throw new f("worktree_branch_exists",`managed worktree branch already exists: ${u}`,"Remove the stale branch or choose a fresh node id.");const h={state:"open",path:s,branch:u,repo_root:n,base_ref:t,base_sha:a,created:new Date().toISOString()};_(n,["branch",u,a],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");try{return _(n,["worktree","add",s,u],"worktree_add_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree."),We(n),h}catch(m){throw K(h,!0),m}})}o(Qe,"createManagedWorktree");function Ae(e){return _(e,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")}o(Ae,"statusPorcelain");function U(e){return _(e,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")}o(U,"currentBranch");function X(e,r){return _(e,["rev-parse","--git-path",r],"git_path_failed","Inspect the worktree manually, then retry.")}o(X,"gitPath");function M(e){return k(X(e,"rebase-merge"))||k(X(e,"rebase-apply"))}o(M,"isRebaseInProgress");async function $(e,r,t="pending"){const n=await v(e);await ue(e,{cwd:r.repo_root,cleanup:t,closedAt:new Date().toISOString(),unbindSession:n?.pi_session_id!=null||n?.pi_session_file!=null})}o($,"persistClosedWorktreeState");async function Re(e,r){const t=(await v(e))?.managed_worktree;t==null||t.state!=="open"||await le(e,{at:new Date().toISOString(),blocked:r})}o(Re,"recordBlockedLandIntent");function Me(e,r,t,n){const a=i(["status","--porcelain"],e);if(a.status!==0)return{ok:!1,detail:(a.stderr.trim()||a.stdout.trim()).trim()};const s=i(["diff","--name-only",t,n],e);if(s.status!==0)return{ok:!1,detail:(s.stderr.trim()||s.stdout.trim()).trim()};const u=s.stdout.split(`
16
- `).map(g=>g.trim()).filter(g=>g!==""),h=ke(be(a.stdout),u);if(h.kind==="refuse")return{ok:!1,detail:`untracked files in ${e} would be overwritten by the incoming commits: ${h.collisions.join(", ")}`};const m=o(()=>{const g=i(["merge","--ff-only",n],e);return g.status===0?{ok:!0}:{ok:!1,detail:(g.stderr.trim()||g.stdout.trim()).trim()}},"merge");if(h.kind==="direct")return m();const d=i(["rev-parse","--verify","--quiet","refs/stash"],e),l=d.status===0?d.stdout.trim():null,b=i(["stash","push","--message",`crtr landing ${r}`],e);if(b.status!==0)return{ok:!1,detail:(b.stderr.trim()||b.stdout.trim()).trim()};const c=i(["rev-parse","--verify","--quiet","refs/stash"],e),p=c.status===0?c.stdout.trim():null;if(p===null||p===l)return m();const y=`local changes from ${e} are retained in stash ${p}; recover them with \`git -C ${w(e)} stash apply ${p}\` and resolve any conflict.`,W=m();return W.ok?i(["stash","apply",p],e).status===0?(z(e,p),{ok:!0}):(i(["reset","--hard",n],e),{ok:!0,stash:`the shared base checkout was reset to landed commit ${n} because local changes conflicted with it. ${y}`}):i(["stash","apply",p],e).status===0?(z(e,p),W):{ok:!1,detail:`${W.detail}
17
- ${y}`}}o(Me,"landIntoBaseCheckout");function z(e,r){const t=i(["rev-parse","--verify","--quiet","refs/stash"],e);t.status===0&&t.stdout.trim()===r&&i(["stash","drop"],e)}o(z,"dropStashIfStillTip");function L(e){const r=`git -C ${w(e.repo_root)} worktree remove ${w(e.path)}`;return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${e.path} remains intact. After its node exits, run \`${r}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${e.branch} remains checked out at ${e.path}; delete it only after that checkout is removed and its landed commit is still contained in ${e.base_ref}.`}}o(L,"deferredCleanupResult");async function Le(e,r,t){if(D(r.repo_root,r.path,t)!==!0)throw new f("wrong_branch",`managed worktree's recorded branch ${r.branch} no longer exists, and its checkout at ${r.path} is not registered to ${t} either`,`Inspect ${r.path} and its git worktree registration, then ask the user with \`crtr human send\` if you are unsure how to proceed.`);const n=_(r.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.");if(Ee(r.path,r.base_ref,n)===null)throw new f("branch_moved_unlanded",`managed worktree's recorded branch ${r.branch} no longer exists; its checkout is now on ${t} at ${n}, which carries content local base branch '${r.base_ref}' does not yet contain`,`Land or push ${t} through its own workflow (merge its PR, or fast-forward '${r.base_ref}' to include it) before closing, or ask the user with \`crtr human send\` if you are unsure how ${t} should be delivered.`);const s=S(r.repo_root),u=D(r.repo_root,r.path,t)===!0,h=U(r.path)===t,m=_(r.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")===n;if(!u||!h||!m)throw new f("wrong_branch",`managed worktree at ${r.path} changed while closing`,`Inspect ${r.path}, then rerun \`crtr node worktree close\`.`);const d={observed_branch:t,observed_sha:n,common_dir:s,authorized:new Date().toISOString()};await $(e,{...r,disposal:d},"pending");const l=`git -C ${w(r.repo_root)} worktree remove ${w(r.path)}`;return{node_id:e,branch:t,worktree_path:r.path,landed_sha:n,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${r.path} remains intact. After its node exits, run \`${l}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`${t} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}o(Le,"closeBranchMovedWorktree");async function Te(e,r){const t=(await v(e))?.managed_worktree;if(t==null)return{message:`node ${e} has no managed worktree`,next:`Nothing to ${r} for this node.`};if(t.state==="abandoned"){const n=t.abandoned?.branch??t.branch;return{message:`node ${e}'s managed worktree was already abandoned`,next:`Nothing to ${r} for this node; its work was retained on branch ${n}.`}}return t.state==="closed"?t.cleanup==="complete"?{message:`node ${e}'s managed worktree is already closed and its cleanup is complete`,next:`Nothing to ${r} for this node.`}:{message:`node ${e}'s managed worktree is already closed; this is not lost ownership \u2014 its checkout at ${t.path} is scheduled for automatic cleanup once that is safe`,next:`Nothing to ${r} for this node. The daemon sweep finishes removing ${t.path} on its own; inspect it directly only if it still needs manual attention.`}:{message:`node ${e} has no open managed worktree`,next:`Nothing to ${r} for this node.`}}o(Te,"noManagedWorktreeMessage");async function Q(e){if(await v(e)===null)throw new f("unknown_node",`unknown node: ${e}`,"Run this from a live node, or pass a real node id once that command supports it.");const t=await x(e);if(t===null){const{message:c,next:p}=await Te(e,"close");throw new f("no_managed_worktree",c,p)}if(!k(t.path)){const c=T(t);if(c===null)throw new f("worktree_missing",`managed worktree path is missing: ${t.path}`,J(t));if(await V(e,t,c)===null)throw new f("worktree_missing",`managed worktree path is missing: ${t.path}`,J(t));return{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:c.branchSha??t.base_sha,worktree_removed:!0,branch_deleted:!0}}if(M(t.path))throw new f("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${t.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(Ae(t.path)!=="")throw new f("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${t.path} (or ask the user with \`crtr human send\` if you do not know whether to keep it), then rerun \`crtr node worktree close\`.`);const a=U(t.path);if(a!==t.branch){const c=a==="HEAD"?"detached HEAD":a,p=$e(t.path,t.branch);if(p||a==="HEAD")throw new f("wrong_branch",`managed worktree is not on its recorded branch (expected ${t.branch}, found ${c})`,p?`Check out ${t.branch} in ${t.path} before closing, or ask the user with \`crtr human send\` if you are unsure why it changed, then rerun \`crtr node worktree close\`.`:`The recorded branch ${t.branch} no longer exists, and ${t.path} is in detached HEAD, so there is no branch to preserve. Check out or create a branch there before closing, or ask the user with \`crtr human send\` if you are unsure how to proceed.`);return await Le(e,t,a)}let s;try{s=R(t.path,t.base_ref)}catch(c){const p=_(t.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(!(c instanceof f)||c.code!=="missing_base_branch"||p!==t.base_sha)throw c;return await $(e,t,"pending"),{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:t.base_sha,...L(t)}}const u=i(["rebase",s],t.path);if(u.status!==0){const c=(u.stderr.trim()||u.stdout.trim()).trim();throw new f("rebase_failed",`rebase onto local base branch '${t.base_ref}' did not complete`,`Resolve conflicts in ${t.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`. If the blocker is not mechanical, ask the user with \`crtr human send\`.`,c)}const h=_(t.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),m=o(async(c,p,y)=>(await Re(e,c),new f("land_base_failed",c,p,y)),"blocked"),d=i(["merge-base","--is-ancestor",s,h],t.path);if(d.status!==0)throw await m(`rebased worktree is not a fast-forward of local base branch '${t.base_ref}'`,"Ask the user with `crtr human send` how to land this managed worktree.",(d.stderr.trim()||d.stdout.trim()).trim());const l=ve(t.path,t.base_ref);if(l!==null){const c=i(["rev-parse","HEAD"],l),p=c.stdout.trim();if(c.status!==0||p!==s){const y=c.status!==0?(c.stderr.trim()||p).trim():`expected ${s}, found ${p}`;throw await m(`local base branch '${t.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${l}, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`,y)}}let b;if(l!==null){const c=Me(l,t.branch,s,h);if(!c.ok)throw await m(`could not fast-forward local base branch '${t.base_ref}' to this worktree`,`Local base branch '${t.base_ref}' is checked out at ${l} in a state that blocks a fast-forward. Reconcile it there, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`,c.detail);b=c.stash}else{const c=i(["update-ref",`refs/heads/${t.base_ref}`,h,s],t.path);if(c.status!==0)throw await m(`could not fast-forward local base branch '${t.base_ref}' to this worktree`,"Ask the user with `crtr human send` how to land this managed worktree.",(c.stderr.trim()||c.stdout.trim()).trim())}return await $(e,t,"pending"),{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:h,...L(t),...b===void 0?{}:{base_checkout_stash:b}}}o(Q,"closeManagedWorktreeLocked");async function Je(e){const r=await x(e);return r===null?await Q(e):await j(k(r.path)?r.path:r.repo_root,async()=>await Q(e))}o(Je,"closeManagedWorktree");function Pe(e,r,t,n){const a=_e(e.branch,r,t,n),s=i(["update-ref","--stdin"],e.repo_root,a),u=s.status===0;if(u)return{branchDeleted:u};const h=(s.stderr.trim()||s.stdout.trim()).trim();return{branchDeleted:u,branchDeleteError:`local branch ${e.branch} could not be deleted automatically (${h}); run \`git -C ${w(e.repo_root)} branch -D ${w(e.branch)}\` after confirming it is merged.`}}o(Pe,"bestEffortDeleteBranchWithContainmentProof");function T(e){if(e.state!=="open"||k(e.path))return null;const r=`refs/heads/${e.branch}`,t=i(["show-ref","--verify","--quiet",r],e.repo_root);if(t.status===1)return{branchSha:null};if(t.status!==0)return null;const n=i(["rev-parse","--verify",r],e.repo_root);if(n.status!==0)return null;const a=n.stdout.trim(),s=i(["worktree","list","--porcelain"],e.repo_root);if(s.status!==0||I(s.stdout,e.branch)!==null)return null;const u=[],h=`refs/heads/${e.base_ref}`,m=i(["show-ref","--verify","--quiet",h],e.repo_root);if(m.status===0){const l=i(["rev-parse","--verify",h],e.repo_root);if(l.status!==0)return null;u.push({ref:h,sha:l.stdout.trim()})}else if(m.status!==1)return null;const d=i(["rev-parse","--symbolic-full-name","--verify",`${e.base_ref}@{upstream}`],e.repo_root);if(d.status===0){const l=d.stdout.trim(),b=i(["rev-parse","--verify",l],e.repo_root);l.startsWith("refs/")&&b.status===0&&u.push({ref:l,sha:b.stdout.trim()})}else{const l=`refs/remotes/origin/${e.base_ref}`,b=i(["show-ref","--verify","--quiet",l],e.repo_root);if(b.status===0){const c=i(["rev-parse","--verify",l],e.repo_root);c.status===0&&u.push({ref:l,sha:c.stdout.trim()})}else if(b.status!==1)return null}for(const l of u)if(i(["merge-base","--is-ancestor",a,l.sha],e.repo_root).status===0)return{branchSha:a,containingRef:l.ref,containingSha:l.sha};return null}o(T,"proveAbsentPathManagedWorktree");function J(e){return`The recorded checkout path is gone, but crtr cannot prove ${e.branch} is already delivered. Push or land ${e.branch}, then rerun \`crtr push final\`; if you cannot establish what happened to the branch, ask the user with \`crtr human send\`.`}o(J,"missingWorktreeRecoveryHint");function P(e){if(e.state!=="open"||!k(e.path)||M(e.path))return null;const r=i(["rev-parse","--abbrev-ref","HEAD"],e.path);if(r.status!==0||r.stdout.trim()!==e.branch)return null;const t=i(["status","--porcelain"],e.path);if(t.status!==0||t.stdout.trim()!=="")return null;const n=i(["rev-parse","HEAD"],e.path);if(n.status!==0)return null;const a=n.stdout.trim();let s;try{s=R(e.path,e.base_ref)}catch(h){if(h instanceof f&&h.code==="missing_base_branch"&&a===e.base_sha)return{branchSha:a,baseSha:e.base_sha};throw h}return i(["merge-base","--is-ancestor",a,s],e.path).status!==0?null:{branchSha:a,baseSha:s}}o(P,"proveCleanEmptyManagedWorktree");async function V(e,r,t){if(k(r.path))return null;if(t.branchSha===null)return await $(e,r,"complete"),{node_id:e,branch:r.branch,worktree_path:r.path,worktree_removed:!0,branch_deleted:!0};if(t.containingRef===void 0||t.containingSha===void 0)return null;const{branchDeleted:n}=Pe(r,t.branchSha,t.containingRef,t.containingSha);return n?(await $(e,r,"complete"),{node_id:e,branch:r.branch,worktree_path:r.path,worktree_removed:!0,branch_deleted:!0}):null}o(V,"autoDropAbsentPathManagedWorktreeLocked");async function He(e,r,t){const n=P(r);return n===null||n.branchSha!==t.branchSha?null:(await $(e,r,"pending"),{node_id:e,branch:r.branch,worktree_path:r.path,...L(r)})}o(He,"autoDropCleanManagedWorktreeLocked");function Y(e){if(e.state!=="open"||!k(e.path)||M(e.path))return null;const r=i(["status","--porcelain"],e.path);if(r.status!==0||r.stdout.trim()!=="")return null;const t=i(["rev-parse","HEAD"],e.path);return t.status===0?t.stdout.trim():null}o(Y,"cleanCurrentCheckoutTip");async function Ve(e){const r=Y(e);if(r===null)return!1;const t=process.env.GIT_SSH_COMMAND??process.env.GIT_SSH??"ssh",n=await he(["ls-remote","--exit-code","--heads","origin"],e.path,void 0,{timeoutMs:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:`${t} -o BatchMode=yes`}});return n.status!==0||!n.stdout.split(`
18
- `).some(s=>{const[u,h]=s.split(" ",2);return u===r&&h?.startsWith("refs/heads/")===!0})?!1:Y(e)===r}o(Ve,"branchIsPushedAtCurrentTip");async function Ye(e){const r=await x(e);if(r===null)return null;const t=!k(r.path);return(t?T(r)===null:P(r)===null)?null:await j(t?r.repo_root:r.path,async()=>{const n=await x(e);if(n===null)return null;if(!k(n.path)){const s=T(n);return s===null?null:await V(e,n,s)}const a=P(n);return a===null?null:await He(e,n,a)})}o(Ye,"autoDropCleanManagedWorktree");export{q as WORKTREE_LOCK_WAIT_MS,f as WorktreeError,Ye as autoDropCleanManagedWorktree,He as autoDropCleanManagedWorktreeLocked,Ve as branchIsPushedAtCurrentTip,E as canonicalPath,I as checkoutPathForBranchInList,Je as closeManagedWorktree,Qe as createManagedWorktree,Xe as hasOpenManagedWorktree,ye as isManagedWorktreeBase,M as isRebaseInProgress,ge as managedWorktreePath,F as managedWorktreesRoot,J as missingWorktreeRecoveryHint,x as openManagedWorktreeForNode,$ as persistClosedWorktreeState,P as proveCleanEmptyManagedWorktree,ze as rollbackManagedWorktree,xe as samePath,G as worktreeLockPathForCommonDir};
15
+ `;Y(r,t+h)}catch{}}o($e,"seedManagedWorktreeExclude");function qe(e,r,t="main"){const n=pe(e);if(me(n))throw new d("managed_worktree_base",`cwd ${n} is a managed worktree and cannot be used as a managed worktree base`,"Pass `--cwd` pointing at the repository\u2019s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.");return G(n,()=>{const a=D(n,t),s=fe(r),h=`crtr/${r}`;if(b(s))throw new d("worktree_path_exists",`managed worktree path already exists: ${s}`,"Remove the stale path or choose a fresh node id.");if(c(["show-ref","--verify","--quiet",`refs/heads/${h}`],n).status===0)throw new d("worktree_branch_exists",`managed worktree branch already exists: ${h}`,"Remove the stale branch or choose a fresh node id.");const l={state:"open",path:s,branch:h,repo_root:n,base_ref:t,base_sha:a,created:new Date().toISOString()};k(n,["branch",h,a],"worktree_branch_create_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.");try{return k(n,["worktree","add",s,h],"worktree_add_failed","Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree."),$e(n),l}catch(m){throw B(l,!0),m}})}o(qe,"createManagedWorktree");function ve(e){return k(e,["status","--porcelain"],"status_failed","Inspect the worktree manually, then retry.")}o(ve,"statusPorcelain");function q(e){return k(e,["rev-parse","--abbrev-ref","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")}o(q,"currentBranch");function K(e,r){return k(e,["rev-parse","--git-path",r],"git_path_failed","Inspect the worktree manually, then retry.")}o(K,"gitPath");function W(e){return b(K(e,"rebase-merge"))||b(K(e,"rebase-apply"))}o(W,"isRebaseInProgress");async function g(e,r,t="pending"){const n=await w(e);await se(e,{cwd:r.repo_root,cleanup:t,closedAt:new Date().toISOString(),unbindSession:n?.pi_session_id!=null||n?.pi_session_file!=null})}o(g,"persistClosedWorktreeState");async function xe(e,r){const t=(await w(e))?.managed_worktree;t==null||t.state!=="open"||await ie(e,{at:new Date().toISOString(),blocked:r})}o(xe,"recordBlockedLandIntent");function Ee(e,r){const t=c(["merge","--ff-only",r],e);return t.status===0?{ok:!0}:{ok:!1,detail:(t.stderr.trim()||t.stdout.trim()).trim()}}o(Ee,"landIntoBaseCheckout");function A(e){const r=`git -C ${_(e.repo_root)} worktree remove ${_(e.path)}`;return{worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${e.path} remains intact. After its node exits, run \`${r}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`cleanup pending: local branch ${e.branch} remains checked out at ${e.path}; delete it only after that checkout is removed and its landed commit is still contained in ${e.base_ref}.`}}o(A,"deferredCleanupResult");async function Se(e,r,t){if(x(r.repo_root,r.path,t)!==!0)throw new d("wrong_branch",`managed worktree's recorded branch ${r.branch} no longer exists, and its checkout at ${r.path} is not registered to ${t} either`,`Inspect ${r.path} and its git worktree registration, then ask the user with \`crtr human send\` if you are unsure how to proceed.`);const n=k(r.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.");if(ge(r.path,r.base_ref,n)===null)throw new d("branch_moved_unlanded",`managed worktree's recorded branch ${r.branch} no longer exists; its checkout is now on ${t} at ${n}, which carries content local base branch '${r.base_ref}' does not yet contain`,`Land or push ${t} through its own workflow (merge its PR, or fast-forward '${r.base_ref}' to include it) before closing, or ask the user with \`crtr human send\` if you are unsure how ${t} should be delivered.`);const s=v(r.repo_root),h=x(r.repo_root,r.path,t)===!0,l=q(r.path)===t,m=k(r.path,["rev-parse","HEAD"],"branch_check_failed","Inspect the worktree manually, then retry.")===n;if(!h||!l||!m)throw new d("wrong_branch",`managed worktree at ${r.path} changed while closing`,`Inspect ${r.path}, then rerun \`crtr node worktree close\`.`);const p={observed_branch:t,observed_sha:n,common_dir:s,authorized:new Date().toISOString()};await g(e,{...r,disposal:p},"pending");const u=`git -C ${_(r.repo_root)} worktree remove ${_(r.path)}`;return{node_id:e,branch:t,worktree_path:r.path,landed_sha:n,worktree_removed:!1,worktree_remove_error:`cleanup pending: the caller checkout at ${r.path} remains intact. After its node exits, run \`${u}\` after confirming it is safe to delete.`,branch_deleted:!1,branch_delete_error:`${t} is not a crtr-managed branch and will never be deleted automatically; it is preserved once the checkout above is removed.`}}o(Se,"closeBranchMovedWorktree");async function De(e,r){const t=(await w(e))?.managed_worktree;if(t==null)return{message:`node ${e} has no managed worktree`,next:`Nothing to ${r} for this node.`};if(t.state==="abandoned"){const n=t.abandoned?.branch??t.branch;return{message:`node ${e}'s managed worktree was already abandoned`,next:`Nothing to ${r} for this node; its work was retained on branch ${n}.`}}return t.state==="closed"?t.cleanup==="complete"?{message:`node ${e}'s managed worktree is already closed and its cleanup is complete`,next:`Nothing to ${r} for this node.`}:{message:`node ${e}'s managed worktree is already closed; this is not lost ownership \u2014 its checkout at ${t.path} is scheduled for automatic cleanup once that is safe`,next:`Nothing to ${r} for this node. The daemon sweep finishes removing ${t.path} on its own; inspect it directly only if it still needs manual attention.`}:{message:`node ${e} has no open managed worktree`,next:`Nothing to ${r} for this node.`}}o(De,"noManagedWorktreeMessage");async function j(e){if(await w(e)===null)throw new d("unknown_node",`unknown node: ${e}`,"Run this from a live node, or pass a real node id once that command supports it.");const t=await y(e);if(t===null){const{message:i,next:f}=await De(e,"close");throw new d("no_managed_worktree",i,f)}if(!b(t.path)){const i=R(t);if(i===null)throw new d("worktree_missing",`managed worktree path is missing: ${t.path}`,U(t));if(await X(e,t,i)===null)throw new d("worktree_missing",`managed worktree path is missing: ${t.path}`,U(t));return{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:i.branchSha??t.base_sha,worktree_removed:!0,branch_deleted:!0}}if(W(t.path))throw new d("rebase_in_progress","this managed worktree is mid-rebase",`Resolve conflicts in ${t.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`.`);if(ve(t.path)!=="")throw new d("dirty_worktree","managed worktree has uncommitted changes",`Commit the work in ${t.path} (or ask the user with \`crtr human send\` if you do not know whether to keep it), then rerun \`crtr node worktree close\`.`);const a=q(t.path);if(a!==t.branch){const i=a==="HEAD"?"detached HEAD":a,f=be(t.path,t.branch);if(f||a==="HEAD")throw new d("wrong_branch",`managed worktree is not on its recorded branch (expected ${t.branch}, found ${i})`,f?`Check out ${t.branch} in ${t.path} before closing, or ask the user with \`crtr human send\` if you are unsure why it changed, then rerun \`crtr node worktree close\`.`:`The recorded branch ${t.branch} no longer exists, and ${t.path} is in detached HEAD, so there is no branch to preserve. Check out or create a branch there before closing, or ask the user with \`crtr human send\` if you are unsure how to proceed.`);return await Se(e,t,a)}let s;try{s=D(t.path,t.base_ref)}catch(i){const f=k(t.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`.");if(!(i instanceof d)||i.code!=="missing_base_branch"||f!==t.base_sha)throw i;return await g(e,t,"pending"),{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:t.base_sha,...A(t)}}const h=c(["rebase",s],t.path);if(h.status!==0){const i=(h.stderr.trim()||h.stdout.trim()).trim();throw new d("rebase_failed",`rebase onto local base branch '${t.base_ref}' did not complete`,`Resolve conflicts in ${t.path}, run \`git rebase --continue\` there, then rerun \`crtr node worktree close\`. If the blocker is not mechanical, ask the user with \`crtr human send\`.`,i)}const l=k(t.path,["rev-parse","HEAD"],"landed_sha_failed","Inspect the worktree checkout manually, then rerun `crtr node worktree close`."),m=o(async(i,f,E)=>(await xe(e,i),new d("land_base_failed",i,f,E)),"blocked"),p=c(["merge-base","--is-ancestor",s,l],t.path);if(p.status!==0)throw await m(`rebased worktree is not a fast-forward of local base branch '${t.base_ref}'`,"Ask the user with `crtr human send` how to land this managed worktree.",(p.stderr.trim()||p.stdout.trim()).trim());const u=ke(t.path,t.base_ref);if(u!==null){const i=c(["rev-parse","HEAD"],u),f=i.stdout.trim();if(i.status!==0||f!==s){const E=i.status!==0?(i.stderr.trim()||f).trim():`expected ${s}, found ${f}`;throw await m(`local base branch '${t.base_ref}' changed while this worktree was closing`,`Reconcile the base checkout at ${u}, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`,E)}}if(u!==null){const i=Ee(u,l);if(!i.ok)throw await m(`could not fast-forward local base branch '${t.base_ref}' to this worktree`,`Local base branch '${t.base_ref}' is checked out at ${u} in a state that blocks a fast-forward. Reconcile it there, then rerun \`crtr node worktree close\`. If you are unsure, ask the user with \`crtr human send\`.`,i.detail)}else{const i=c(["update-ref",`refs/heads/${t.base_ref}`,l,s],t.path);if(i.status!==0)throw await m(`could not fast-forward local base branch '${t.base_ref}' to this worktree`,"Ask the user with `crtr human send` how to land this managed worktree.",(i.stderr.trim()||i.stdout.trim()).trim())}return await g(e,t,"pending"),{node_id:e,branch:t.branch,worktree_path:t.path,landed_sha:l,...A(t)}}o(j,"closeManagedWorktreeLocked");async function Ke(e){const r=await y(e);return r===null?await j(e):await I(b(r.path)?r.path:r.repo_root,async()=>await j(e))}o(Ke,"closeManagedWorktree");function We(e,r,t,n){const a=de(e.branch,r,t,n),s=c(["update-ref","--stdin"],e.repo_root,a),h=s.status===0;if(h)return{branchDeleted:h};const l=(s.stderr.trim()||s.stdout.trim()).trim();return{branchDeleted:h,branchDeleteError:`local branch ${e.branch} could not be deleted automatically (${l}); run \`git -C ${_(e.repo_root)} branch -D ${_(e.branch)}\` after confirming it is merged.`}}o(We,"bestEffortDeleteBranchWithContainmentProof");function R(e){if(e.state!=="open"||b(e.path))return null;const r=`refs/heads/${e.branch}`,t=c(["show-ref","--verify","--quiet",r],e.repo_root);if(t.status===1)return{branchSha:null};if(t.status!==0)return null;const n=c(["rev-parse","--verify",r],e.repo_root);if(n.status!==0)return null;const a=n.stdout.trim(),s=c(["worktree","list","--porcelain"],e.repo_root);if(s.status!==0||N(s.stdout,e.branch)!==null)return null;const h=[],l=`refs/heads/${e.base_ref}`,m=c(["show-ref","--verify","--quiet",l],e.repo_root);if(m.status===0){const u=c(["rev-parse","--verify",l],e.repo_root);if(u.status!==0)return null;h.push({ref:l,sha:u.stdout.trim()})}else if(m.status!==1)return null;const p=c(["rev-parse","--symbolic-full-name","--verify",`${e.base_ref}@{upstream}`],e.repo_root);if(p.status===0){const u=p.stdout.trim(),i=c(["rev-parse","--verify",u],e.repo_root);u.startsWith("refs/")&&i.status===0&&h.push({ref:u,sha:i.stdout.trim()})}else{const u=`refs/remotes/origin/${e.base_ref}`,i=c(["show-ref","--verify","--quiet",u],e.repo_root);if(i.status===0){const f=c(["rev-parse","--verify",u],e.repo_root);f.status===0&&h.push({ref:u,sha:f.stdout.trim()})}else if(i.status!==1)return null}for(const u of h)if(c(["merge-base","--is-ancestor",a,u.sha],e.repo_root).status===0)return{branchSha:a,containingRef:u.ref,containingSha:u.sha};return null}o(R,"proveAbsentPathManagedWorktree");function U(e){return`The recorded checkout path is gone, but crtr cannot prove ${e.branch} is already delivered. Push or land ${e.branch}, then rerun \`crtr push final\`; if you cannot establish what happened to the branch, ask the user with \`crtr human send\`.`}o(U,"missingWorktreeRecoveryHint");function M(e){if(e.state!=="open"||!b(e.path)||W(e.path))return null;const r=c(["rev-parse","--abbrev-ref","HEAD"],e.path);if(r.status!==0||r.stdout.trim()!==e.branch)return null;const t=c(["status","--porcelain"],e.path);if(t.status!==0||t.stdout.trim()!=="")return null;const n=c(["rev-parse","HEAD"],e.path);if(n.status!==0)return null;const a=n.stdout.trim();let s;try{s=D(e.path,e.base_ref)}catch(l){if(l instanceof d&&l.code==="missing_base_branch"&&a===e.base_sha)return{branchSha:a,baseSha:e.base_sha};throw l}return c(["merge-base","--is-ancestor",a,s],e.path).status!==0?null:{branchSha:a,baseSha:s}}o(M,"proveCleanEmptyManagedWorktree");async function X(e,r,t){if(b(r.path))return null;if(t.branchSha===null)return await g(e,r,"complete"),{node_id:e,branch:r.branch,worktree_path:r.path,worktree_removed:!0,branch_deleted:!0};if(t.containingRef===void 0||t.containingSha===void 0)return null;const{branchDeleted:n}=We(r,t.branchSha,t.containingRef,t.containingSha);return n?(await g(e,r,"complete"),{node_id:e,branch:r.branch,worktree_path:r.path,worktree_removed:!0,branch_deleted:!0}):null}o(X,"autoDropAbsentPathManagedWorktreeLocked");async function Ae(e,r,t){const n=M(r);return n===null||n.branchSha!==t.branchSha?null:(await g(e,r,"pending"),{node_id:e,branch:r.branch,worktree_path:r.path,...A(r)})}o(Ae,"autoDropCleanManagedWorktreeLocked");function z(e){if(e.state!=="open"||!b(e.path)||W(e.path))return null;const r=c(["status","--porcelain"],e.path);if(r.status!==0||r.stdout.trim()!=="")return null;const t=c(["rev-parse","HEAD"],e.path);return t.status===0?t.stdout.trim():null}o(z,"cleanCurrentCheckoutTip");async function je(e){const r=z(e);if(r===null)return!1;const t=process.env.GIT_SSH_COMMAND??process.env.GIT_SSH??"ssh",n=await ae(["ls-remote","--exit-code","--heads","origin"],e.path,void 0,{timeoutMs:1e4,env:{...process.env,GIT_TERMINAL_PROMPT:"0",GIT_SSH_COMMAND:`${t} -o BatchMode=yes`}});return n.status!==0||!n.stdout.split(`
16
+ `).some(s=>{const[h,l]=s.split(" ",2);return h===r&&l?.startsWith("refs/heads/")===!0})?!1:z(e)===r}o(je,"branchIsPushedAtCurrentTip");async function Ue(e){const r=await y(e);if(r===null)return null;const t=!b(r.path);return(t?R(r)===null:M(r)===null)?null:await I(t?r.repo_root:r.path,async()=>{const n=await y(e);if(n===null)return null;if(!b(n.path)){const s=R(n);return s===null?null:await X(e,n,s)}const a=M(n);return a===null?null:await Ae(e,n,a)})}o(Ue,"autoDropCleanManagedWorktree");export{O as WORKTREE_LOCK_WAIT_MS,d as WorktreeError,Ue as autoDropCleanManagedWorktree,Ae as autoDropCleanManagedWorktreeLocked,je as branchIsPushedAtCurrentTip,$ as canonicalPath,N as checkoutPathForBranchInList,Ke as closeManagedWorktree,qe as createManagedWorktree,Ie as hasOpenManagedWorktree,me as isManagedWorktreeBase,W as isRebaseInProgress,fe as managedWorktreePath,H as managedWorktreesRoot,U as missingWorktreeRecoveryHint,y as openManagedWorktreeForNode,g as persistClosedWorktreeState,M as proveCleanEmptyManagedWorktree,Be as rollbackManagedWorktree,_e as samePath,F as worktreeLockPathForCommonDir};
@@ -26,5 +26,6 @@ export declare function createAppListener(config: NonNullable<ScopeConfig['runti
26
26
  stream?: RunStreamOptions;
27
27
  }): Promise<{
28
28
  ready: Promise<void>;
29
+ port: () => number;
29
30
  close: () => Promise<void>;
30
31
  }>;
@@ -1,24 +1,24 @@
1
- var Z=Object.defineProperty;var i=(e,n)=>Z(e,"name",{value:n,configurable:!0});import{AsyncResource as ee}from"node:async_hooks";import{randomUUID as te}from"node:crypto";import{createServer as ne}from"node:http";import{Router as V,causedByOf as re}from"./router.js";import{toErrorBody as ae}from"./map.js";import{objectRoutes as oe}from"./handlers/objects.js";import{customObjectRoutes as ie}from"./handlers/custom-objects.js";import{checkRoutes as se}from"./handlers/check.js";import{chargeRoutes as ue}from"./handlers/charges.js";import{docRoutes as ce}from"./handlers/docs.js";import{relationRoutes as de}from"./handlers/relations.js";import{schemaRoutes as le}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as fe}from"../readiness.js";import{errorCodes as z}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as pe,RUNTIME_VERSION_HEADER as he,minimumRuntimeRefusal as we}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ye,CONTRACT_LEVEL as G,REQUIRED_CONTRACT_HEADER as _e,contractRefusal as ge}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as ve,parseTraceparent as Re}from"../../shared/traceparent.js";import{AppPrincipalResolver as Oe}from"./principal.js";import{isDaemonRoute as be,runtimeOwner as Ee,servePeer as Y}from"../peer/ingress.js";import{applySyncNotice as Ae}from"./sync-notice.js";import{ownMachineId as Se}from"../../core/peer/directory.js";import{handleRunOperation as Te,integer as Ne}from"./handlers/runs.js";import{runAnthropicMessages as Ce}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Ie,parseLlmRequest as Pe,runLlm as ke}from"../../core/llm/run.js";import{parseUsageMonth as Me,usageFor as He}from"../../core/ledger/index.js";import{capFields as De}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as F,MODEL_CONTEXT_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{RunError as l,cloudPersonScope as Be,runIsRunning as xe}from"../../core/runs/operations.js";import{requireRun as L}from"./router.js";import{deferHead as je}from"./deferred-head.js";import{readRunEvents as W,registerGrantStream as Je,subscribeRunEvents as Le}from"../../core/runs/events.js";import{activeGrant as q,payerOfGrant as Ue}from"../../core/grants/mirror.js";async function Xe(e){if(await Ue(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Xe,"appPaidGone");import{releaseGrantWaiters as $e}from"../../core/grants/watch.js";import{emitEvent as Ve}from"../../core/events/emit.js";import{runNotices as ze}from"../run-notices.js";import{handleRuntimeSignIn as Ge,isRuntimeSignInPath as Ye}from"./key-signin.js";import{listAppProfiles as Fe}from"./handlers/app-profiles.js";import{handleTransferOperation as Qe,TRANSFER_OPERATIONS as We}from"./handlers/transfer.js";import{handleQuestionOperation as qe,QUESTION_OPERATIONS as Ke}from"./handlers/questions.js";import{removeVendorAccount as Ze,vendorStatus as et}from"./handlers/vendor-status.js";import{handleMemoryOperation as tt,MEMORY_OPERATIONS as nt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as rt,handleExec as at}from"./handlers/exec.js";import{abortOnClose as U,callerFromApp as ot,handleProviderOperation as it,PROVIDER_OPERATIONS as st,providerFailure as ut}from"./handlers/providers.js";function ct(e){return Object.prototype.hasOwnProperty.call(z,e)?z[e]:void 0}i(ct,"fixedRow");function dt(e){const n=ct(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(dt,"errorType");function lt(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(lt,"appDetails");function x(e,n,o){const m=lt(e.details);return{error:{code:e.code,message:e.message,...m===void 0?{}:{details:m},type:dt(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...De(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function mt(e,n,o,m,c){const y=n instanceof l?n:new l(500,"server_failure","runtime request failed");if(n instanceof l||console.error("[app-listener]",`trace_id=${m}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
2
- data: ${JSON.stringify(x(y,o,c))}
1
+ var Z=Object.defineProperty;var i=(e,n)=>Z(e,"name",{value:n,configurable:!0});import{AsyncResource as ee}from"node:async_hooks";import{randomUUID as te}from"node:crypto";import{createServer as ne}from"node:http";import{Router as V,causedByOf as re}from"./router.js";import{toErrorBody as ae}from"./map.js";import{objectRoutes as oe}from"./handlers/objects.js";import{customObjectRoutes as ie}from"./handlers/custom-objects.js";import{checkRoutes as se}from"./handlers/check.js";import{chargeRoutes as ue}from"./handlers/charges.js";import{docRoutes as de}from"./handlers/docs.js";import{relationRoutes as ce}from"./handlers/relations.js";import{schemaRoutes as le}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as fe}from"../readiness.js";import{errorCodes as z}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as pe,RUNTIME_VERSION_HEADER as he,minimumRuntimeRefusal as we}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ye,CONTRACT_LEVEL as G,REQUIRED_CONTRACT_HEADER as _e,contractRefusal as ge}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as ve,parseTraceparent as Re}from"../../shared/traceparent.js";import{AppPrincipalResolver as Oe}from"./principal.js";import{isDaemonRoute as be,runtimeOwner as Ee,servePeer as Y}from"../peer/ingress.js";import{applySyncNotice as Ae}from"./sync-notice.js";import{ownMachineId as Se}from"../../core/peer/directory.js";import{handleRunOperation as Te,integer as Ne}from"./handlers/runs.js";import{runAnthropicMessages as Ce}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Ie,parseLlmRequest as Pe,runLlm as ke}from"../../core/llm/run.js";import{parseUsageMonth as Me,usageFor as He}from"../../core/ledger/index.js";import{capFields as De}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as F,MODEL_CONTEXT_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{RunError as l,cloudPersonScope as Be,runIsRunning as xe}from"../../core/runs/operations.js";import{requireRun as L}from"./router.js";import{deferHead as je}from"./deferred-head.js";import{readRunEvents as W,registerGrantStream as Je,subscribeRunEvents as Le}from"../../core/runs/events.js";import{activeGrant as q,payerOfGrant as Ue}from"../../core/grants/mirror.js";async function Xe(e){if(await Ue(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Xe,"appPaidGone");import{releaseGrantWaiters as $e}from"../../core/grants/watch.js";import{emitEvent as Ve}from"../../core/events/emit.js";import{runNotices as ze}from"../run-notices.js";import{handleRuntimeSignIn as Ge,isRuntimeSignInPath as Ye}from"./key-signin.js";import{listAppProfiles as Fe}from"./handlers/app-profiles.js";import{handleTransferOperation as Qe,TRANSFER_OPERATIONS as We}from"./handlers/transfer.js";import{handleQuestionOperation as qe,QUESTION_OPERATIONS as Ke}from"./handlers/questions.js";import{removeVendorAccount as Ze,vendorStatus as et}from"./handlers/vendor-status.js";import{handleMemoryOperation as tt,MEMORY_OPERATIONS as nt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as rt,handleExec as at}from"./handlers/exec.js";import{abortOnClose as U,callerFromApp as ot,handleProviderOperation as it,PROVIDER_OPERATIONS as st,providerFailure as ut}from"./handlers/providers.js";function dt(e){return Object.prototype.hasOwnProperty.call(z,e)?z[e]:void 0}i(dt,"fixedRow");function ct(e){const n=dt(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(ct,"errorType");function lt(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(lt,"appDetails");function x(e,n,o){const m=lt(e.details);return{error:{code:e.code,message:e.message,...m===void 0?{}:{details:m},type:ct(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...De(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function mt(e,n,o,m,d){const y=n instanceof l?n:new l(500,"server_failure","runtime request failed");if(n instanceof l||console.error("[app-listener]",`trace_id=${m}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
2
+ data: ${JSON.stringify(x(y,o,d))}
3
3
 
4
- `);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,c)))}i(mt,"fail");function X(e){return Array.isArray(e)?e[0]:e}i(X,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function K(e,n=F){const o=[];let m=0;for await(const c of e){if(m+=c.length,m>n)throw new l(400,"invalid_request","request body too large");o.push(c)}return Buffer.concat(o)}i(K,"rawBodyOf");async function I(e,n=F){const o=await K(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function ft(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return Ne(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(ft,"cursor");function pt(e){return`id: ${e.sequence_number}
4
+ `);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(mt,"fail");function X(e){return Array.isArray(e)?e[0]:e}i(X,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function K(e,n=F){const o=[];let m=0;for await(const d of e){if(m+=d.length,m>n)throw new l(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(K,"rawBodyOf");async function I(e,n=F){const o=await K(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function ft(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return Ne(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(ft,"cursor");function pt(e){return`id: ${e.sequence_number}
5
5
  event: ${e.type}
6
6
  data: ${JSON.stringify(e)}
7
7
 
8
- `}i(pt,"frame");const ht=6e4;async function wt(e,n,o,m,c,y,A,S={},r){await L(m,o);let t=await W(o,c);if(c>t.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(c<t.latest_sequence&&(t.earliest_sequence===null||c<t.earliest_sequence-1))throw new l(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":A==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),A==="sse"?n.write(`: connected
8
+ `}i(pt,"frame");const ht=6e4;async function wt(e,n,o,m,d,y,S,O={},r){await L(m,o);let t=await W(o,d);if(d>t.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new l(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":S==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),S==="sse"?n.write(`: connected
9
9
 
10
- `):n.flushHeaders();let p=c;const _=await ze().streamOpened(o);let v=!1,T=!1,N=!1,O;const h=new Promise(f=>{O=f}),R=i(()=>{v||(v=!0,_(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),O())},"end"),a=i(()=>{N=!1,b()},"onDrain"),H=i(f=>{v||n.write(A==="sse"?`event: error
10
+ `):n.flushHeaders();let p=d;const _=await ze().streamOpened(o);let v=!1,T=!1,N=!1,b;const h=new Promise(f=>{b=f}),R=i(()=>{v||(v=!0,_(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),b())},"end"),a=i(()=>{N=!1,E()},"onDrain"),H=i(f=>{v||n.write(S==="sse"?`event: error
11
11
  data: ${JSON.stringify(x(f,y,o))}
12
12
 
13
13
  `:`${JSON.stringify({type:"error",...x(f,y,o)})}
14
- `),R()},"error"),b=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await W(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(A==="sse"?pt(f):`${JSON.stringify(f)}
15
- `),p=f.sequence_number}}catch(f){H(f instanceof l?f:new l(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new l(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in m||await q(m.grant)!==null,"grantActive"),C=await Le(o,ee.bind(b)),u="class"in m?()=>{}:Je(m.grant,P),B=setInterval(()=>{!v&&!N&&A==="sse"&&n.write(`: keepalive
14
+ `),R()},"error"),E=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await W(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(S==="sse"?pt(f):`${JSON.stringify(f)}
15
+ `),p=f.sequence_number}}catch(f){H(f instanceof l?f:new l(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new l(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in m||await q(m.grant)!==null,"grantActive"),C=await Le(o,ee.bind(E)),u="class"in m?()=>{}:Je(m.grant,P),B=setInterval(()=>{!v&&!N&&S==="sse"&&n.write(`: keepalive
16
16
 
17
- `)},15e3),s=S.idleMs??ht,w=S.isRunning??xe;let d=Date.now(),E=p;const k=i(async()=>{if(v||A!=="sse")return;const f=Date.now();let $=!0;try{$=await w(o)}catch{}if(!v){if($||p!==E){d=f,E=p;return}f-d<s||N||(n.write(`event: idle
17
+ `)},15e3),s=O.idleMs??ht,w=O.isRunning??xe;let c=Date.now(),A=p;const k=i(async()=>{if(v||S!=="sse")return;const f=Date.now();let $=!0;try{$=await w(o)}catch{}if(!v){if($||p!==A){c=f,A=p;return}f-c<s||N||(n.write(`event: idle
18
18
  data: {}
19
19
 
20
- `),R())}},"checkIdle"),M=setInterval(()=>{k().catch(f=>Ve({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},S.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await b(),h}i(wt,"streamRunEvents");function yt(e,n,o,m={}){const c=new V,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");c.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const A=new V().registerAll(oe).registerAll(ie).registerAll(ce).registerAll(le).registerAll(de).registerAll(se).registerAll(ue);return i((r,t,p)=>(async()=>{je(r,t,m.deferHead);const _=te();t.setHeader("Request-Id",_);const v=Re(X(r.headers.traceparent))??ve();t.setHeader(he,J()),t.setHeader(ye,G);let T;try{const N=X(r.headers[pe.toLowerCase()]),O=we(N,J())??ge(X(r.headers[_e.toLowerCase()]),G,{legacyMinimum:N,runtimeVersion:J()});if(O!==null)throw O.status===400?new l(400,O.code,O.message,O.param):new l(426,O.code,O.message,void 0,O.details);const h=new URL(r.url??"/","http://runtime.local");if(Ye(h.pathname)){await Ge(r,t,h,e);return}const R=c.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let b,P;if(p!==void 0)b=p;else if(!H&&r.headers.authorization!==void 0)try{b=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Ee,self:Se,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(b?.chain[0]?.sub.startsWith("runtime:")){await Y(r,t,D,b);return}if(b===void 0&&a===void 0&&await be(r.method??"GET",h.pathname)){await Y(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await fe({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new l(503,"runtime_starting","runtime_starting");if(!R||!a)throw new l(404,"not_found","unknown operation");T=R.params.run_id;const C=re(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Ae(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await et());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await Ze(await I(r)));return}if(b===void 0)throw P??new l(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(b,a.scope);if(t.setHeader("Request-Id",_),T&&await L(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=A.match(a.method,h.pathname);if(!s)throw new l(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let d;try{d=await s.handler(w)}catch(E){const{status:k,body:M}=ae(E);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,E),new l(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(d.rawBody!==void 0||d.status===204||d.body===void 0){t.writeHead(d.status,d.headers??{}),t.end(d.rawBody);return}t.writeHead(d.status,{"Content-Type":"application/json; charset=utf-8",...d.headers??{}}),t.end(JSON.stringify(d.body));return}if(a.stream){await wt(r,t,T,u,ft(r,h.searchParams),_,"sse",m.stream,v);return}if(a.name==="llm"){const s=Pe(await I(r,Q)),w=new AbortController,d=i(()=>w.abort(),"abort");t.on("close",d);try{const E=await ke(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
20
+ `),R())}},"checkIdle"),M=setInterval(()=>{k().catch(f=>Ve({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},O.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await E(),h}i(wt,"streamRunEvents");function yt(e,n,o,m={}){const d=new V,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const S=new V().registerAll(oe).registerAll(ie).registerAll(de).registerAll(le).registerAll(ce).registerAll(se).registerAll(ue);return i((r,t,p)=>(async()=>{je(r,t,m.deferHead);const _=te();t.setHeader("Request-Id",_);const v=Re(X(r.headers.traceparent))??ve();t.setHeader(he,J()),t.setHeader(ye,G);let T;try{const N=X(r.headers[pe.toLowerCase()]),b=we(N,J())??ge(X(r.headers[_e.toLowerCase()]),G,{legacyMinimum:N,runtimeVersion:J()});if(b!==null)throw b.status===400?new l(400,b.code,b.message,b.param):new l(426,b.code,b.message,void 0,b.details);const h=new URL(r.url??"/","http://runtime.local");if(Ye(h.pathname)){await Ge(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let E,P;if(p!==void 0)E=p;else if(!H&&r.headers.authorization!==void 0)try{E=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Ee,self:Se,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(E?.chain[0]?.sub.startsWith("runtime:")){await Y(r,t,D,E);return}if(E===void 0&&a===void 0&&await be(r.method??"GET",h.pathname)){await Y(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await fe({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new l(503,"runtime_starting","runtime_starting");if(!R||!a)throw new l(404,"not_found","unknown operation");T=R.params.run_id;const C=re(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Ae(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await et());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await Ze(await I(r)));return}if(E===void 0)throw P??new l(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(E,a.scope);if(t.setHeader("Request-Id",_),T&&await L(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=S.match(a.method,h.pathname);if(!s)throw new l(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let c;try{c=await s.handler(w)}catch(A){const{status:k,body:M}=ae(A);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,A),new l(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream){await wt(r,t,T,u,ft(r,h.searchParams),_,"sse",m.stream,v);return}if(a.name==="llm"){const s=Pe(await I(r,Q)),w=new AbortController,c=i(()=>w.abort(),"abort");t.on("close",c);try{const A=await ke(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
21
21
 
22
22
  `)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},Ie(await q(u.grant)??await Xe(u.grant)),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
23
23
 
24
- `)):g(t,200,E.completion)}finally{t.off("close",d)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=U(t);try{await Ce(await K(r,Q),r.headers,s,{grant:u.grant,sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=U(t);try{g(t,200,await at(u,await I(r,rt),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await He(u.grantee,Me(h.searchParams.get("month")),Be(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Fe(u));return}if(Ke.has(a.name)){const s=await qe(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(st.has(a.name)){const{signal:s,release:w}=U(t);try{const d=await it(a.name,ot(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,d.status,d.body)}catch(d){const E=ut(d,_,!0);t.writeHead(E.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...E.headers}),t.end(JSON.stringify(E.body))}finally{w()}return}if(nt.has(a.name)){const s=await tt(a.name,{class:"app",app:u.grantee,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(We.has(a.name)){const s=await Qe(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Te(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){mt(t,N,_,v,T)}})(),"handle")}i(yt,"createAppRequestHandler");async function ln(e,n,o,m={}){const c=e.listener;if(!e.issuer||!e.audience||!c?.address||!Number.isInteger(c.port)||c.port<1||c.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(c.address))throw new Error("runtime listener must bind a specific address");const y=new Oe(e.issuer,e.audience,o,e.jwksUrl),A=yt(y,n,o,m),S=ne((t,p)=>{A(t,p)});return{ready:new Promise((t,p)=>{S.once("error",p),S.listen(c.port,c.address,()=>{S.off("error",p),t()})}),close:i(async()=>{y.close(),$e(),S.closeAllConnections(),await new Promise((t,p)=>S.close(_=>_?p(_):t()))},"close")}}i(ln,"createAppListener");export{ht as RUN_STREAM_IDLE_MS,ln as createAppListener,yt as createAppRequestHandler,ft as cursor,wt as streamRunEvents};
24
+ `)):g(t,200,A.completion)}finally{t.off("close",c)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=U(t);try{await Ce(await K(r,Q),r.headers,s,{grant:u.grant,sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=U(t);try{g(t,200,await at(u,await I(r,rt),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await He(u.grantee,Me(h.searchParams.get("month")),Be(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Fe(u));return}if(Ke.has(a.name)){const s=await qe(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(st.has(a.name)){const{signal:s,release:w}=U(t);try{const c=await it(a.name,ot(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,c.status,c.body)}catch(c){const A=ut(c,_,!0);t.writeHead(A.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...A.headers}),t.end(JSON.stringify(A.body))}finally{w()}return}if(nt.has(a.name)){const s=await tt(a.name,{class:"app",app:u.grantee,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(We.has(a.name)){const s=await Qe(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Te(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){mt(t,N,_,v,T)}})(),"handle")}i(yt,"createAppRequestHandler");async function ln(e,n,o,m={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<0||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const y=new Oe(e.issuer,e.audience,o,e.jwksUrl),S=yt(y,n,o,m),O=ne((t,p)=>{S(t,p)});return{ready:new Promise((t,p)=>{O.once("error",p),O.listen(d.port,d.address,()=>{O.off("error",p),t()})}),port:i(()=>O.address().port,"port"),close:i(async()=>{y.close(),$e(),O.closeAllConnections(),await new Promise((t,p)=>O.close(_=>_?p(_):t()))},"close")}}i(ln,"createAppListener");export{ht as RUN_STREAM_IDLE_MS,ln as createAppListener,yt as createAppRequestHandler,ft as cursor,wt as streamRunEvents};
@@ -1,8 +1,8 @@
1
- var K=Object.defineProperty;var i=(r,e)=>K(r,"name",{value:e,configurable:!0});import{WebSocketServer as Q}from"ws";import{isSafeNodeId as N,viewSocketPath as z}from"../../core/canvas/paths.js";import{getNode as T}from"../../core/canvas/index.js";import{requestPersonId as G,runAsPerson as X}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as Y,CLIENT_READ_CAPS as Z,FrameDecoder as I,FrameOverflowError as ee}from"../../core/runtime/broker-protocol.js";import{emitEvent as A}from"../../core/events/emit.js";import{classify as R}from"../../core/fault-classifier.js";import{clearFault as g,markNodeRead as re,recordFault as $}from"../../core/canvas/recovery.js";import{decideAttachRevive as te}from"../../core/runtime/revive.js";import{connectViewSocket as ne,connectWssView as ie,probeViewSocket as ae,waitForBrokerViewSocket as oe,waitForWssView as P}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as ce,recordExecutionAwake as se}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as le}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as fe}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as ue}from"../../core/spaces/open-beneath.js";import{openMachineView as me,probeMachineView as de,waitForMachineView as he}from"../machine-link/forward.js";import{attachViewer as F,detachViewer as ye,holdViewerForRedial as we,presentViewer as pe}from"./viewer-presence.js";const O=3e4,ve=new Q({noServer:!0,maxPayload:Y.maxLineBytes}),ke=25e3,ge=6e4;function be(r,e=ke,s=ge){let n=!0,h=!1,u=Date.now();const l=i(()=>{n=!0},"acknowledge"),a=i(()=>{h||(h=!0,clearInterval(o),r.off("pong",l))},"stop");r.on("pong",l);const o=setInterval(()=>{if(Date.now()-u>s){n=!0;return}if(!n){a(),r.terminate();return}n=!1;try{r.ping()}catch{a(),r.terminate()}},e);return o.unref(),{stop:a,noteActivity:i(()=>{u=Date.now()},"noteActivity")}}i(be,"startRemoteAttachHeartbeat");function C(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}i(C,"clampReason");function p(r,e,s,n,h){const u=JSON.stringify({error:{code:n,message:h,origin:"runtime"}}),l=`HTTP/1.1 ${e} ${s}\r
1
+ var re=Object.defineProperty;var i=(r,e)=>re(r,"name",{value:e,configurable:!0});import{WebSocketServer as te}from"ws";import{general as ne}from"../../core/errors.js";import{toErrorBody as ie}from"./map.js";import{isSafeNodeId as D,viewSocketPath as oe}from"../../core/canvas/paths.js";import{getNode as U}from"../../core/canvas/index.js";import{requestPersonId as ae,runAsPerson as ce}from"../../core/canvas/person-state.js";import{BROKER_READ_CAPS as se,CLIENT_READ_CAPS as fe,FrameDecoder as le,FrameOverflowError as ue}from"../../core/runtime/broker-protocol.js";import{emitEvent as A}from"../../core/events/emit.js";import{addStepTiming as de}from"../../core/step-timings.js";import{markAt as me,timedSpan as T,withLoggedStepTimings as he}from"../../core/logged-step-timings.js";import{classify as O}from"../../core/fault-classifier.js";import{clearFault as E,markNodeRead as pe,recordFault as V}from"../../core/canvas/recovery.js";import{decideAttachRevive as we}from"../../core/runtime/revive.js";import{connectViewSocket as ye,connectWssView as ke,probeViewSocket as ve,waitForBrokerViewSocket as ge,waitForWssView as L}from"../../core/runtime/view-socket.js";import{liveExecutionForNode as _e,recordExecutionAwake as be}from"../../core/canvas/executions.js";import{settleSandboxBeforeWake as Ae}from"../reconcilers/ledger-sandbox.js";import{runnerForExecution as Ee}from"../../core/runtime/runner/index.js";import{isBeneathRefusal as Se}from"../../core/spaces/open-beneath.js";import{openMachineView as xe,waitForMachineView as H}from"../machine-link/forward.js";import{attachViewer as J,detachViewer as Re,holdViewerForRedial as $e,presentViewer as Be}from"./viewer-presence.js";const j=3e4,Ce=new te({noServer:!0,maxPayload:se.maxLineBytes}),Te=25e3,Oe=6e4;function Ve(r,e=Te,a=Oe){let n=!0,c=!1,m=Date.now();const h=i(()=>{n=!0},"acknowledge"),u=i(()=>{c||(c=!0,clearInterval(v),r.off("pong",h))},"stop");r.on("pong",h);const v=setInterval(()=>{if(Date.now()-m>a){n=!0;return}if(!n){u(),r.terminate();return}n=!1;try{r.ping()}catch{u(),r.terminate()}},e);return v.unref(),{stop:u,noteActivity:i(()=>{m=Date.now()},"noteActivity")}}i(Ve,"startRemoteAttachHeartbeat");function N(r){const e=Buffer.from(r,"utf8");return e.byteLength<=123?r:e.subarray(0,123).toString("utf8")}i(N,"clampReason");function k(r,e,a,n,c){de("refused_status",e);const m=JSON.stringify({error:{code:n,message:c,origin:"runtime"}}),h=`HTTP/1.1 ${e} ${a}\r
2
2
  content-type: application/json; charset=utf-8\r
3
- content-length: ${Buffer.byteLength(u)}\r
3
+ content-length: ${Buffer.byteLength(m)}\r
4
4
  connection: close\r
5
5
  \r
6
- `+u;try{r.end(l)}catch{try{r.destroy()}catch{}}}i(p,"refuseUpgrade");function _e(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const s=r.headers["x-crtr-attach-revive"];return(Array.isArray(s)?s[0]:s)==="0"}i(_e,"reviveOptedOut");function Ae(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Ae,"wakeParkedRequested");function D(r){return r===1e3||r===1001||r===1005}i(D,"isCleanViewerClose");function y(r,e,s){s.catch(n=>A({level:"error",event:e,node_id:r,error:n}))}i(y,"detach");async function W(r){const e=await ce(r);return e===null||e.runner==="process"?{kind:"unix",path:z(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await le(e.executionId,Date.now()),await se(e.executionId)),fe(e.runner).viewerAddress(e))}i(W,"brokerViewAddress");function Ee(r,e){return e.kind==="machine"?me(e.environmentId,r):e.kind==="wss"?ie(e.url,e.headers):ne(r)}i(Ee,"connectBrokerView");function Se(r,e,s){return e.kind==="machine"?de(e.environmentId,r,s):e.kind==="wss"?P(e.url,e.headers,void 0,s):ae(r,s)}i(Se,"probeBrokerView");async function xe(r,e,s,n){const h=[];let u=i(t=>{h.push(t)},"relayMessage");if(r.on("message",t=>u(t)),!N(e)){try{r.close(1008,C(`invalid node id: ${e}`))}catch{}return}if(await T(e)===null){try{r.close(1011,C(`no node ${e}`))}catch{}return}await g(e,{link:"viewer\u2194crtrd"});const l=Ee(e,s),a=new I(Z);let o=!1,v=!1,d,b=!1,V=!1,E="controller",B=Promise.resolve(),_=!1;const S=[];let x=!1;l.on("connect",()=>{b=!0,!o&&_&&y(e,"daemon.bridge.presence_failed",F(e,r)),y(e,"daemon.bridge.connect_failed",g(e,{link:"relay\u2194broker"}))});const w=i((t,f,c=!1)=>{if(!o){if(o=!0,y(e,"daemon.bridge.presence_failed",c?we(e,r):ye(e,r)),d?.stop(),!l.destroyed)try{l.destroy()}catch{}try{r.close(t,C(f))}catch{}}},"teardown");d=be(r);const M=i(async t=>{d?.noteActivity();let f;try{f=a.push(t)}catch(c){const m=c instanceof ee?`broker sent an oversized frame (${c.message})`:`failed to decode a broker frame for ${e}`;w(1009,m);return}S.push(...f),x||await U()},"onData"),U=i(async()=>{x=!0;try{for(;S.length>0&&!o;){const t=S.splice(0);let f;try{f=await n(E)}catch(m){A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:m}),w(1011,"revoked");return}if(o)return;if(!f){w(1008,"revoked");return}let c=!1;for(const m of t)r.readyState===r.OPEN&&(r.send(JSON.stringify(m)),m?.type==="welcome"&&(c=!0));if(_&&c)try{await pe(e,r)&&await re(e)}catch(m){A({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:m})}}}finally{x=!1}},"drainOutbound");l.on("data",t=>y(e,"daemon.bridge.data_failed",M(t)));const H=i(async t=>{const f=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const c=R("relay\u2194broker",t);await $(e,{link:"relay\u2194broker",op:"bridge socket",kind:c.kind,retry:{disposition:"manual"},message:t.message})}finally{w(1011,f,!0)}},"onSocketError");l.on("error",t=>y(e,"daemon.bridge.socket_error_failed",H(t)));const L=i(async t=>{if(!(o||t))try{await g(e,{link:"relay\u2194broker"})}finally{w(1e3,"broker socket closed",!0)}},"onSocketClose");l.on("close",t=>y(e,"daemon.bridge.socket_close_failed",L(t)));const J=i(async(t,f)=>{const c=f.toString("utf8");if(o){D(t)&&await g(e,{link:"viewer\u2194crtrd"});return}try{if(D(t))await g(e,{link:"viewer\u2194crtrd"});else if(!v){v=!0;const m=R("viewer\u2194crtrd",{code:t,reason:c});await $(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:m.kind,retry:{disposition:"auto"},message:c||`remote attach closed (${t})`})}}finally{w(t,c||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,f)=>y(e,"daemon.bridge.ws_close_failed",J(t,f)));const q=i(async()=>{try{if(!v){v=!0;const t=R("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await $(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{w(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>y(e,"daemon.bridge.ws_error_failed",q())),u=i(t=>{if(o||l.destroyed)return;d?.noteActivity();const c=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!V)try{const k=JSON.parse(c);k?.type==="hello"&&(V=!0,E=k.role==="observer"?"observer":"controller",_=k.attends!==!1,_&&b&&y(e,"daemon.bridge.presence_failed",F(e,r)))}catch{}const m=c.endsWith(`
7
- `)?c:c+`
8
- `,j=i(()=>{try{l.write(m)}catch{}},"write");B=B.then(async()=>{o||(await n(E)?j():w(1008,"revoked"))}).catch(k=>{A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:k}),w(1011,"revoked")})},"relayMessage");for(const t of h.splice(0))u(t)}i(xe,"bridgeConnection");async function qe(r,e,s,n,h){const u=G(),l=u===void 0?h:a=>X(u,()=>h(a));e.on("error",()=>{});try{if(!N(n)){p(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await T(n)===null){p(e,404,"Not Found","node_not_found",`no node ${n}`);return}let a;if(_e(r)){if(a=await W(n),!await Se(n,a,a.kind==="wss"?O:250)){p(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let o;try{const d=await te(n,{resume:!0,capacity:"refuse"},Ae(r));if(d.parked){p(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}o=d.result.launch?.exited}catch(d){const b=d instanceof Error?d.message:String(d);p(e,409,"Conflict","attach_revive_failed",`attach revive failed: ${b}`);return}if(a=await W(n),!(a.kind==="machine"?await he(a.environmentId,n,o,O):a.kind==="wss"?await P(a.url,a.headers,o):await oe(n,o))){p(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;ve.handleUpgrade(r,e,s,o=>y(n,"daemon.bridge.connection_failed",xe(o,n,a,l)))}catch(a){const o=a instanceof Error?a.message:String(a);if(ue(a)){p(e,400,"Bad Request","invalid_request",o);return}p(e,500,"Internal Server Error","internal",`attach upgrade failed: ${o}`)}}i(qe,"handleAttachUpgrade");export{ke as REMOTE_ATTACH_HEARTBEAT_MS,ge as REMOTE_ATTACH_QUIET_MS,qe as handleAttachUpgrade,D as isCleanViewerClose,p as refuseUpgrade,be as startRemoteAttachHeartbeat};
6
+ `+m;try{r.end(h)}catch{try{r.destroy()}catch{}}}i(k,"refuseUpgrade");function q(r,e){const{status:a,body:n}=ie(e);k(r,a,"Refused",n.error.code,n.error.message)}i(q,"refuseWithError");function Ne(r){if(new URL(r.url??"/","http://127.0.0.1").searchParams.get("revive")==="0")return!0;const a=r.headers["x-crtr-attach-revive"];return(Array.isArray(a)?a[0]:a)==="0"}i(Ne,"reviveOptedOut");function Pe(r){return new URL(r.url??"/","http://127.0.0.1").searchParams.get("wakeParked")==="1"}i(Pe,"wakeParkedRequested");function K(r){return r===1e3||r===1001||r===1005}i(K,"isCleanViewerClose");function w(r,e,a){a.catch(n=>A({level:"error",event:e,node_id:r,error:n}))}i(w,"detach");async function Q(r){const e=await _e(r);return e===null||e.runner==="process"?{kind:"unix",path:oe(r)}:(e.runner==="blaxel"&&e.idleAt!==null&&(await Ae(e.executionId,Date.now()),await be(e.executionId)),Ee(e.runner).viewerAddress(e))}i(Q,"brokerViewAddress");function Fe(r,e){return e.kind==="machine"?xe(e.environmentId,r):e.kind==="wss"?ke(e.url,e.headers):ye(r)}i(Fe,"connectBrokerView");function Me(r,e,a){return e.kind==="wss"?L(e.url,e.headers,void 0,a):ve(r,a)}i(Me,"probeBrokerView");async function We(r,e,a,n,c){const m=[];let h=i(t=>{m.push(t)},"relayMessage");if(r.on("message",t=>h(t)),!D(e)){c?.destroy();try{r.close(1008,N(`invalid node id: ${e}`))}catch{}return}if(await U(e)===null){c?.destroy();try{r.close(1011,N(`no node ${e}`))}catch{}return}const u=performance.now();await E(e,{link:"viewer\u2194crtrd"});const v=performance.now(),o=c??Fe(e,a),f=i(()=>Math.round((performance.now()-v)*10)/10,"sinceOpen"),g=i(t=>{A({level:"info",event:"daemon.timing.bridge_channel",node_id:e,fields:{step:t,address_kind:a.kind,since_open_ms:f(),since_bridge_start_ms:Math.round((performance.now()-u)*10)/10}})},"bridgeMark");c===void 0&&g("channel_opened");const _=new le(fe);let y=!1,S=!1,x,P=!1,F=!1,$="controller",M=Promise.resolve(),R=!1;const B=[];let C=!1;const W=i(()=>{c===void 0&&g("channel_connected"),P=!0,!y&&R&&w(e,"daemon.bridge.presence_failed",J(e,r)),w(e,"daemon.bridge.connect_failed",E(e,{link:"relay\u2194broker"}))},"onBrokerConnect");c===void 0&&o.on("connect",W);const p=i((t,l,s=!1)=>{if(!y){if(y=!0,w(e,"daemon.bridge.presence_failed",s?$e(e,r):Re(e,r)),x?.stop(),!o.destroyed)try{o.destroy()}catch{}try{r.close(t,N(l))}catch{}}},"teardown");x=Ve(r);const z=i(async t=>{x?.noteActivity();let l;try{l=_.push(t)}catch(s){const d=s instanceof ue?`broker sent an oversized frame (${s.message})`:`failed to decode a broker frame for ${e}`;p(1009,d);return}B.push(...l),C||await G()},"onData"),G=i(async()=>{C=!0;try{for(;B.length>0&&!y;){const t=B.splice(0);let l;try{l=await n($)}catch(d){A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:d}),p(1011,"revoked");return}if(y)return;if(!l){p(1008,"revoked");return}let s=!1;for(const d of t)r.readyState===r.OPEN&&(r.send(JSON.stringify(d)),d?.type==="welcome"&&(s=!0,g("welcome_forwarded")));if(R&&s)try{await Be(e,r)&&await pe(e)}catch(d){A({level:"warn",event:"daemon.bridge.present_failed",node_id:e,error:d})}}}finally{C=!1}},"drainOutbound");o.on("data",t=>w(e,"daemon.bridge.data_failed",z(t)));const X=i(async t=>{const l=t.code==="ECONNREFUSED"||t.code==="ENOENT"?`no running broker for ${e}`:`view socket error for ${e}: ${t.message}`;try{const s=O("relay\u2194broker",t);await V(e,{link:"relay\u2194broker",op:"bridge socket",kind:s.kind,retry:{disposition:"manual"},message:t.message})}finally{p(1011,l,!0)}},"onSocketError");o.on("error",t=>w(e,"daemon.bridge.socket_error_failed",X(t)));const Y=i(async t=>{if(!(y||t))try{await E(e,{link:"relay\u2194broker"})}finally{p(1e3,"broker socket closed",!0)}},"onSocketClose");o.on("close",t=>w(e,"daemon.bridge.socket_close_failed",Y(t)));const Z=i(async(t,l)=>{const s=l.toString("utf8");if(y){K(t)&&await E(e,{link:"viewer\u2194crtrd"});return}try{if(K(t))await E(e,{link:"viewer\u2194crtrd"});else if(!S){S=!0;const d=O("viewer\u2194crtrd",{code:t,reason:s});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:d.kind,retry:{disposition:"auto"},message:s||`remote attach closed (${t})`})}}finally{p(t,s||`remote attach closed (${t})`)}},"onWsClose");r.on("close",(t,l)=>w(e,"daemon.bridge.ws_close_failed",Z(t,l)));const I=i(async()=>{try{if(!S){S=!0;const t=O("viewer\u2194crtrd",{code:1006,reason:"remote attach websocket error"});await V(e,{link:"viewer\u2194crtrd",op:"remote attach websocket",kind:t.kind,retry:{disposition:"auto"},message:"remote attach websocket error"})}}finally{p(1011,"remote attach websocket error")}},"onWsError");r.on("error",()=>w(e,"daemon.bridge.ws_error_failed",I())),h=i(t=>{if(y||o.destroyed)return;x?.noteActivity();const s=(Array.isArray(t)?Buffer.concat(t):Buffer.isBuffer(t)?t:Buffer.from(new Uint8Array(t))).toString("utf8");if(!F)try{const b=JSON.parse(s);b?.type==="hello"&&(g("hello_received"),F=!0,$=b.role==="observer"?"observer":"controller",R=b.attends!==!1,R&&P&&w(e,"daemon.bridge.presence_failed",J(e,r)))}catch{}const d=s.endsWith(`
7
+ `)?s:s+`
8
+ `,ee=i(()=>{try{o.write(d)}catch{}},"write");M=M.then(async()=>{y||(await n($)?ee():p(1008,"revoked"))}).catch(b=>{A({level:"error",event:"daemon.bridge.attach_recheck_failed",node_id:e,error:b}),p(1011,"revoked")})},"relayMessage");for(const t of m.splice(0))h(t);c!==void 0&&(c.destroyed?p(1011,`no running broker for ${e}`,!0):W())}i(We,"bridgeConnection");async function cr(r,e,a,n,c){await he("attach_upgrade",{node:n},r,()=>De(r,e,a,n,c))}i(cr,"handleAttachUpgrade");async function De(r,e,a,n,c){const m=ae(),h=m===void 0?c:o=>ce(m,()=>c(o));e.on("error",()=>{});let u,v=!1;try{if(!D(n)){k(e,400,"Bad Request","invalid_node_id",`invalid node id: ${n}`);return}if(await T("admission",async()=>await U(n)===null)){k(e,404,"Not Found","node_not_found",`no node ${n}`);return}let o;if(Ne(r)){o=await Q(n);let f;if(o.kind==="machine"?(u=await H(o.environmentId,n,void 0,250)??void 0,f=u!==void 0):f=await Me(n,o,o.kind==="wss"?j:250),!f){k(e,409,"Conflict","node_dormant",`node ${n} is dormant and revive was opted out (?revive=0)`);return}}else{let f;try{const _=await T("revive_decision",async()=>await we(n,{resume:!0,capacity:"refuse"},Pe(r)));if(_.parked){k(e,409,"Conflict","node_dormant",`node ${n} is parked; attach with ?wakeParked=1 to wake it`);return}f=_.result.launch?.exited}catch(_){q(e,_);return}if(o=await T("address_lookup",async()=>await Q(n)),o.kind==="machine"&&(u=await H(o.environmentId,n,f,j)??void 0),!(o.kind==="machine"?u!==void 0:o.kind==="wss"?await L(o.url,o.headers,f):await ge(n,f))){o.kind==="machine"?q(e,ne(`the broker for ${n} on its machine did not accept a viewer after revive`)):k(e,409,"Conflict","broker_not_ready",`broker view socket for ${n} did not become listenable after revive`);return}}if(e.destroyed)return;me("upgrading"),Ce.handleUpgrade(r,e,a,f=>{v=!0,w(n,"daemon.bridge.connection_failed",We(f,n,o,h,u).catch(g=>{throw u?.destroy(),g}))})}catch(o){const f=o instanceof Error?o.message:String(o);if(Se(o)){k(e,400,"Bad Request","invalid_request",f);return}k(e,500,"Internal Server Error","internal",`attach upgrade failed: ${f}`)}finally{v||u?.destroy()}}i(De,"attachUpgrade");export{Te as REMOTE_ATTACH_HEARTBEAT_MS,Oe as REMOTE_ATTACH_QUIET_MS,cr as handleAttachUpgrade,K as isCleanViewerClose,k as refuseUpgrade,Ve as startRemoteAttachHeartbeat};