@north-light/cli 0.3.789 → 0.3.791

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 (109) hide show
  1. package/dist/api/client.d.ts +3 -1
  2. package/dist/api/client.js +1 -1
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/nodes.d.ts +0 -12
  6. package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +3 -2
  7. package/dist/clients/attach/viewer.js +526 -526
  8. package/dist/commands/canvas-history/shared.js +1 -1
  9. package/dist/commands/node/bash.js +1 -1
  10. package/dist/commands/node/create.js +2 -2
  11. package/dist/commands/node/inspect.js +6 -6
  12. package/dist/commands/node/lifecycle.js +4 -4
  13. package/dist/commands/node-context.js +2 -2
  14. package/dist/commands/person-settings.js +1 -1
  15. package/dist/commands/profile/daemon-profiles.js +4 -4
  16. package/dist/commands/sys.js +1 -1
  17. package/dist/core/canvas/history.d.ts +2 -8
  18. package/dist/core/canvas/history.js +9 -9
  19. package/dist/core/canvas/node-agent-paths.d.ts +5 -0
  20. package/dist/core/canvas/node-agent-paths.js +1 -1
  21. package/dist/core/canvas/node-tokens.js +3 -3
  22. package/dist/core/canvas/paths.d.ts +3 -10
  23. package/dist/core/canvas/paths.js +1 -1
  24. package/dist/core/canvas/person-state.d.ts +5 -7
  25. package/dist/core/canvas/person-state.js +1 -1
  26. package/dist/core/canvas/person.d.ts +3 -30
  27. package/dist/core/canvas/person.js +1 -11
  28. package/dist/core/canvas/render-source.js +1 -1
  29. package/dist/core/config.d.ts +4 -1
  30. package/dist/core/config.js +1 -1
  31. package/dist/core/directory/join.d.ts +4 -6
  32. package/dist/core/directory/join.js +1 -1
  33. package/dist/core/grants/sync.js +1 -1
  34. package/dist/core/human/requests.d.ts +11 -1
  35. package/dist/core/human/requests.js +22 -22
  36. package/dist/core/providers/files.js +1 -1
  37. package/dist/core/review/store.js +1 -1
  38. package/dist/core/runtime/bearings-render.d.ts +2 -2
  39. package/dist/core/runtime/bearings-render.js +11 -11
  40. package/dist/core/runtime/bearings.js +1 -1
  41. package/dist/core/runtime/broker/attachments-fetch.js +1 -1
  42. package/dist/core/runtime/broker/bash-job-launch.d.ts +0 -4
  43. package/dist/core/runtime/broker/bash-job-launch.js +1 -1
  44. package/dist/core/runtime/broker/daemon-ops.d.ts +0 -8
  45. package/dist/core/runtime/broker/daemon-ops.js +1 -1
  46. package/dist/core/runtime/broker/frame-dispatch.d.ts +1 -1
  47. package/dist/core/runtime/broker/frame-dispatch.js +1 -1
  48. package/dist/core/runtime/broker/host-path-tokens.d.ts +5 -0
  49. package/dist/core/runtime/broker/host-path-tokens.js +1 -0
  50. package/dist/core/runtime/broker-extension-render.js +2 -2
  51. package/dist/core/runtime/broker.js +1 -1
  52. package/dist/core/runtime/host.js +3 -3
  53. package/dist/core/runtime/kickoff.d.ts +1 -1
  54. package/dist/core/runtime/kickoff.js +12 -12
  55. package/dist/core/runtime/launch-config-worker.js +1 -1
  56. package/dist/core/runtime/launch-target.d.ts +6 -4
  57. package/dist/core/runtime/launch-target.js +1 -1
  58. package/dist/core/runtime/launch.d.ts +5 -1
  59. package/dist/core/runtime/launch.js +2 -2
  60. package/dist/core/runtime/nodes.js +1 -1
  61. package/dist/core/runtime/revive.js +2 -2
  62. package/dist/core/runtime/runner/blaxel/runner.js +2 -2
  63. package/dist/core/runtime/runner/launch-env.d.ts +7 -0
  64. package/dist/core/runtime/runner/launch-env.js +1 -0
  65. package/dist/core/runtime/runner/machine/executor.js +2 -2
  66. package/dist/core/runtime/runner/machine/runner.js +1 -1
  67. package/dist/core/runtime/runner/types.d.ts +1 -0
  68. package/dist/core/runtime/spawn-env-rows.js +1 -1
  69. package/dist/core/runtime/spawn.js +2 -2
  70. package/dist/core/secrets/environment-owner.js +1 -1
  71. package/dist/core/storage/attachments.d.ts +1 -1
  72. package/dist/core/storage/attachments.js +1 -1
  73. package/dist/core/storage/tables.d.ts +6 -2
  74. package/dist/core/storage/tables.js +4 -4
  75. package/dist/core/substrate/delivery/deliver.js +1 -1
  76. package/dist/core/substrate/delivery/render-boot.js +1 -1
  77. package/dist/daemon/api/handlers/bash-jobs.js +3 -3
  78. package/dist/daemon/api/handlers/canvas.js +5 -5
  79. package/dist/daemon/api/handlers/nodes.js +1 -1
  80. package/dist/daemon/api/handlers/profiles.js +1 -1
  81. package/dist/daemon/api/map.d.ts +1 -4
  82. package/dist/daemon/api/map.js +2 -2
  83. package/dist/daemon/cron/lease-recovery.js +1 -1
  84. package/dist/daemon/cron/machine-fire.js +1 -1
  85. package/dist/daemon/human/sweep.js +1 -1
  86. package/dist/daemon/peer/ingress.d.ts +2 -2
  87. package/dist/daemon/reconcilers/bash-deadline.js +1 -1
  88. package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
  89. package/dist/daemon/runs/observer.js +6 -5
  90. package/dist/pi-extensions/canvas-bash-valve.js +6 -6
  91. package/dist/pi-extensions/canvas-context-intro.js +2 -2
  92. package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
  93. package/package.json +3 -3
  94. package/packages/crouter-api/dist/api/client.js +2 -2
  95. package/packages/crouter-api/dist/api/contract.js +1 -1
  96. package/packages/crouter-api/dist/core/canvas/paths.js +4 -13
  97. package/packages/crouter-api/dist/core/canvas/person-state.js +9 -11
  98. package/packages/crouter-api/dist/core/config.js +10 -0
  99. package/packages/crouter-api/dist/core/directory/join.js +11 -45
  100. package/packages/crouter-api/dist/core/runtime/broker/attachments-fetch.js +18 -2
  101. package/packages/crouter-api/dist/core/runtime/broker/daemon-ops.js +0 -10
  102. package/packages/crouter-api/dist/core/runtime/broker/host-path-tokens.js +21 -0
  103. package/packages/crouter-api/package.json +1 -1
  104. package/packages/crouter-identity/package.json +1 -1
  105. package/packages/crouter-plugin/package.json +3 -3
  106. package/runtime.lock.json +14 -14
  107. package/scripts/sandbox-start.mjs +5 -3
  108. package/dist/commands/sys/join.d.ts +0 -3
  109. package/dist/commands/sys/join.js +0 -1
@@ -1 +1 @@
1
- var M=Object.defineProperty;var o=(t,e)=>M(t,"name",{value:e,configurable:!0});import{openDb as S}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as $}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as F}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as V}from"../../../core/graph/jobs.js";import{boundFleet as C}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as B}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as G}from"../reader.js";import{canRead as H}from"../../../core/graph/access.js";import{ownersByHandle as K}from"../../../core/graph/names.js";import{reposForCwd as U,warmCheckoutIdentities as W}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as J}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as f}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as Y}from"../../../core/env-name.js";import{listProfileEnvNames as z,removeProfileEnvVar as Q,setProfileEnvVar as X}from"../../../core/profiles/env-store.js";import{isDeploymentName as Z,listAppEnvNames as x,removeAppEnvVar as ee,setAppEnvVar as te}from"../../../core/profiles/app-env-store.js";import{addProfileProject as A,addProfileRepo as ae,assertDeliveryLimits as re,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as ie,listProfiles as u,loadProfileManifest as E,pauseProfile as ne,removeProfileProject as oe,renameProfile as se,resumeProfile as de,setProfileDefaultKind as fe,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as le}from"../../profile-delete.js";import{brokerSignalBus as me}from"../../broker-signals/bus.js";import{toProfileDTO as ue}from"../map.js";import{isCloudRole as I,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as k}from"../../../core/environment-repos.js";import{actsAsPerson as g,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const O="root",ye=4096;function v(t,e=[]){return{...ue(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await k()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function R(t,e,r=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==r&&(a.manifest.grantee??"app:terminal")===t))throw new f(400,"invalid_request",`${t} already has a profile named ${e}`)}o(R,"assertNameFree");async function m(t,e){const r=await N(t,e),a=r.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!g(t.principal)&&a!==j(t.principal))throw new f(403,"permission_error",`profile ${r.profileId} belongs to ${a}; only that app changes it`);return r}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const r=c(t),a=e.name.trim();R(r,a),e.default_kind!==void 0&&await h(e.default_kind,process.cwd(),null);const i=e.repositories??[];if(!Array.isArray(i)||i.some(p=>typeof p!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(i.length===0){const p=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r});return{status:201,body:v(p)}}if(!I())throw new f(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new f(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),i),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:r,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const r=e.trim();if(r==="")throw d("profile name must not be empty");return await w(async a=>(await J(a,t,r),await se(t,r)))}o(be,"renameProfileAndHandle");async function Pe(t,e,r){if(I()){await A(t,r);return}await W(r);const i=(await w(async n=>await U(n,r)))[0];await A(t,r,i?.id),i!==void 0&&e[i.name]===void 0&&e[`repo:${i.name}`]===void 0&&await _(t,i.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function Ee(t,e,r,a){const i=await w(async n=>{const s=await G(n,t);for(const p of await K(n,a,"repo"))if(await H(n,s,p))return p;return null});if(i===null)throw new f(404,"not_found",`no repo you can read is named ${a}`);await ae(e,i.id),r[i.name]===void 0&&r[`repo:${i.name}`]===void 0&&await _(e,i.name,"preview")}o(Ee,"addRepoWithDefaultLimit");async function ge(t){const{profileId:e,manifest:r}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&R(r.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,process.cwd(),e),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&re({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await fe(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,r.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await Ee(t,e,r.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await oe(e,a.remove_project),{status:200,body:await l(E(e))}}o(ge,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await z(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,r=Y(e);if(!r.isValid)throw d(`invalid env var name: ${r.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function q(t){const e=D(t);if(Z(e)&&!g(t.principal))throw new f(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(q,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),r=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await X(e,r,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),r=D(t);return{status:200,body:{profile_id:e,changed:await Q(e,r)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,r=t.body??{};r.projects!==void 0&&b(r.projects);const a=c(t);if(e===O&&a==="app:terminal")return{status:200,body:await l(await ie())};if(e===O)throw new f(403,"permission_error","root belongs to the terminal app");const i=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(i!==void 0)return{status:200,body:await l(i)};r.default_kind!==void 0&&await h(r.default_kind,process.cwd(),null);const n=await P(e,r.projects??[],{defaultKind:r.default_kind,metadata:r.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),r=t.body??{};if(typeof r!="object"||r===null||Array.isArray(r))throw d("profile metadata body must be an object",{field:"body"});const a=r,i=a.unset===void 0?[]:a.unset;if(!Array.isArray(i)||i.some(p=>typeof p!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,i);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=E(t.params.name),r=await ne(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}};const i=C();for(const n of a){const s=i.get(n.node_id);if(s!==void 0){await i.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&B(n.pi_pid,n.pi_pid_identity)==="alive"&&await i.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=E(t.params.name),r=await de(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await F(a.node_id)!==null)&&me.markMail(a.node_id);if(r.pausedAt!==null){const a=Date.parse(r.pausedAt);if(!Number.isNaN(a)){const i=Math.max(0,Date.now()-a);await $(e.profileId,i);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>V(s,n.node_id,i))}}return{status:200,body:{profile_id:e.profileId,paused_at:r.manifest.paused_at}}}o(Oe,"handleResume");async function L(t){const e=t.principal;if(g(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await S(),i=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>i.has(n))}const r=await he(e);return u().filter(({profileId:a,manifest:i})=>{const n=i.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(r,s)&&(!ve(e)||T(e.scopes,s))})}o(L,"visibleProfiles");async function N(t,e){const r=await L(t),a=r.find(({profileId:n})=>n===e),i=a?[a]:r.filter(({manifest:n})=>n.name===e);if(i.length===0)throw new f(404,"not_found","profile not found");if(i.length>1)throw new f(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return i[0]}o(N,"requireUsableProfile");async function Re(t){const e=await k();return{status:200,body:(await L(t)).map(r=>v(r,e.get(r.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await N(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return le((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await x(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=q(t),{value:r}=t.body??{};if(typeof r!="string"||!r)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await te(c(t),e,r)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await ee(c(t),q(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:ge},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,N as requireUsableProfile};
1
+ var M=Object.defineProperty;var o=(t,e)=>M(t,"name",{value:e,configurable:!0});import{openDb as S}from"../../../core/canvas/db.js";import{assertLaunchKind as h}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as y,shiftProfileNodeDeadlines as $}from"../../../core/canvas/canvas.js";import{liveExecutionForNode as F}from"../../../core/canvas/executions.js";import{shiftJobDeadlines as V}from"../../../core/graph/jobs.js";import{boundFleet as C}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as B}from"../../../core/canvas/pid.js";import{withCanvasWrite as w}from"../../../core/canvas/db.js";import{readerFor as G}from"../reader.js";import{canRead as H}from"../../../core/graph/access.js";import{ownersByHandle as K}from"../../../core/graph/names.js";import{reposForCwd as U,warmCheckoutIdentities as W}from"../../../core/graph/repo-sync/repos.js";import{renameProfileObject as J}from"../../../core/graph/objects.js";import{usage as d}from"../../../core/errors.js";import{ApiError as f}from"../../../api/errors.js";import{scopeAllowed as T}from"../../../core/scopes.js";import{validateEnvVarName as Y}from"../../../core/env-name.js";import{listProfileEnvNames as z,removeProfileEnvVar as Q,setProfileEnvVar as X}from"../../../core/profiles/env-store.js";import{isDeploymentName as Z,listAppEnvNames as x,removeAppEnvVar as ee,setAppEnvVar as te}from"../../../core/profiles/app-env-store.js";import{addProfileProject as A,addProfileRepo as ae,assertDeliveryLimits as ie,setProfileDeliveryLimit as _,assertProfileProjects as b,createProfile as P,ensureRootProfile as re,listProfiles as u,loadProfileManifest as g,pauseProfile as ne,removeProfileProject as oe,renameProfile as se,resumeProfile as de,setProfileDefaultKind as fe,updateProfileMetadata as pe}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as le}from"../../profile-delete.js";import{brokerSignalBus as me}from"../../broker-signals/bus.js";import{toProfileDTO as ue}from"../map.js";import{isCloudRole as I,personId as ce}from"../../../core/canvas/person-state.js";import{resolveRecipeRepositories as we,repositoriesByProfile as k}from"../../../core/environment-repos.js";import{actsAsPerson as E,appOf as j,boundedByStoredScopes as ve,resolvedScopes as he}from"../router.js";const O="root",ye=4096;function v(t,e=[]){return{...ue(t),...t.manifest.environment_id===void 0?{}:{environment_id:t.manifest.environment_id},repositories:e}}o(v,"toProfileDTO");async function l(t){return v(t,(await k()).get(t.profileId)??[])}o(l,"toProfileDTOWithRepositories");function c(t){return j(t.principal)??"app:terminal"}o(c,"callerApp");function R(t,e,i=null){if(u().some(a=>a.manifest.name===e&&a.profileId!==i&&(a.manifest.grantee??"app:terminal")===t))throw new f(400,"invalid_request",`${t} already has a profile named ${e}`)}o(R,"assertNameFree");async function m(t,e){const i=await N(t,e),a=i.manifest.grantee??"app:terminal";if(t.principal.class!=="person"&&!E(t.principal)&&a!==j(t.principal))throw new f(403,"permission_error",`profile ${i.profileId} belongs to ${a}; only that app changes it`);return i}o(m,"requireOwnProfile");async function _e(t){const e=t.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw d("a profile name is required",{field:"name"});e.projects!==void 0&&b(e.projects);const i=c(t),a=e.name.trim();R(i,a),e.default_kind!==void 0&&await h(e.default_kind,null,null,i);const r=e.repositories??[];if(!Array.isArray(r)||r.some(p=>typeof p!="string"))throw d("repositories must be an array of owner/name strings",{field:"repositories"});if(r.length===0){const p=await P(a,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:i});return{status:201,body:v(p)}}if(!I())throw new f(400,"invalid_request","repositories make a cloud dev profile; this role runs profiles on the machine, so use a project directory instead");if(e.projects!==void 0&&e.projects.length>0)throw new f(400,"invalid_request","a profile with repositories stores no project paths; pass repositories or projects, not both");const n=await we(ce(),r),s=await P(a,[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:i,memoryMb:ye,recipe:{repositories:n,setup_script:null,pi_packages:null}});return{status:201,body:await l(s)}}o(_e,"handleCreate");async function be(t,e){const i=e.trim();if(i==="")throw d("profile name must not be empty");return await w(async a=>(await J(a,t,i),await se(t,i)))}o(be,"renameProfileAndHandle");async function Pe(t,e,i){if(I()){await A(t,i);return}await W(i);const r=(await w(async n=>await U(n,i)))[0];await A(t,i,r?.id),r!==void 0&&e[r.name]===void 0&&e[`repo:${r.name}`]===void 0&&await _(t,r.name,"preview")}o(Pe,"addProjectWithDefaultLimit");async function ge(t,e,i,a){const r=await w(async n=>{const s=await G(n,t);for(const p of await K(n,a,"repo"))if(await H(n,s,p))return p;return null});if(r===null)throw new f(404,"not_found",`no repo you can read is named ${a}`);await ae(e,r.id),i[r.name]===void 0&&i[`repo:${r.name}`]===void 0&&await _(e,r.name,"preview")}o(ge,"addRepoWithDefaultLimit");async function Ee(t){const{profileId:e,manifest:i}=await m(t,t.params.name),a=t.body??{};if(a.name!==void 0&&R(i.grantee??"app:terminal",a.name.trim(),e),a.default_kind!==void 0&&await h(a.default_kind,null,e,i.grantee??"app:terminal"),a.add_project!==void 0&&(b([a.add_project]),a.add_project.path===void 0==(a.add_project.repo===void 0)))throw d("add_project takes exactly one of path and repo",{field:"add_project"});return a.set_delivery_limit!==void 0&&ie({[a.set_delivery_limit.owner]:a.set_delivery_limit.level}),a.name!==void 0&&await be(e,a.name),a.default_kind!==void 0&&await fe(e,a.default_kind),a.add_project?.path!==void 0?await Pe(e,i.delivery_limits??{},a.add_project.path):a.add_project?.repo!==void 0&&await ge(t,e,i.delivery_limits??{},a.add_project.repo),a.set_delivery_limit!==void 0&&await _(e,a.set_delivery_limit.owner,a.set_delivery_limit.level),a.remove_project!==void 0&&await oe(e,a.remove_project),{status:200,body:await l(g(e))}}o(Ee,"handleUpdate");async function je(t){const{profileId:e}=await m(t,t.params.name);return{status:200,body:{profile_id:e,names:await z(e)}}}o(je,"handleEnvList");function D(t){const e=t.params.var,i=Y(e);if(!i.isValid)throw d(`invalid env var name: ${i.errors.join("; ")}`,{field:"name",received:e});return e}o(D,"requireEnvVarName");function q(t){const e=D(t);if(Z(e)&&!E(t.principal))throw new f(403,"permission_error",`${e} is deployment-wide; only a person changes it`);return e}o(q,"requireSelfEnvVarName");async function De(t){const{profileId:e}=await m(t,t.params.name),i=D(t),{value:a}=t.body??{};if(typeof a!="string"||a==="")throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:await X(e,i,a)}}}o(De,"handleEnvSet");async function Te(t){const{profileId:e}=await m(t,t.params.name),i=D(t);return{status:200,body:{profile_id:e,changed:await Q(e,i)}}}o(Te,"handleEnvRemove");async function Ae(t){const e=t.params.name,i=t.body??{};i.projects!==void 0&&b(i.projects);const a=c(t);if(e===O&&a==="app:terminal")return{status:200,body:await l(await re())};if(e===O)throw new f(403,"permission_error","root belongs to the terminal app");const r=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===a);if(r!==void 0)return{status:200,body:await l(r)};i.default_kind!==void 0&&await h(i.default_kind,null,null,a);const n=await P(e,i.projects??[],{defaultKind:i.default_kind,metadata:i.metadata,grantee:a});return{status:200,body:v(n)}}o(Ae,"handleEnsure");async function Ie(t){const e=await m(t,t.params.name),i=t.body??{};if(typeof i!="object"||i===null||Array.isArray(i))throw d("profile metadata body must be an object",{field:"body"});const a=i,r=a.unset===void 0?[]:a.unset;if(!Array.isArray(r)||r.some(p=>typeof p!="string"))throw d("profile metadata `unset` must be an array of strings",{field:"unset"});const n=a.set===void 0?{}:a.set,s=await pe(e.profileId,n,r);return{status:200,body:await l(s)}}o(Ie,"handleSetMetadata");async function ke(t){const e=g(t.params.name),i=await ne(e.profileId),a=(await y(e.profileId)).filter(n=>n.status==="active"||n.status==="idle");if(a.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:i.manifest.paused_at}};const r=C();for(const n of a){const s=r.get(n.node_id);if(s!==void 0){await r.interruptForProfilePause(n.node_id,s.pid);continue}n.pi_pid!=null&&B(n.pi_pid,n.pi_pid_identity)==="alive"&&await r.interruptForProfilePause(n.node_id,n.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:i.manifest.paused_at}}}o(ke,"handlePause");async function Oe(t){const e=g(t.params.name),i=await de(e.profileId);for(const a of await y(e.profileId))(a.status==="active"||a.status==="idle"||await F(a.node_id)!==null)&&me.markMail(a.node_id);if(i.pausedAt!==null){const a=Date.parse(i.pausedAt);if(!Number.isNaN(a)){const r=Math.max(0,Date.now()-a);await $(e.profileId,r);for(const n of await y(e.profileId))n.status!=="dead"&&await w(s=>V(s,n.node_id,r))}}return{status:200,body:{profile_id:e.profileId,paused_at:i.manifest.paused_at}}}o(Oe,"handleResume");async function L(t){const e=t.principal;if(E(e))return u();if(e.class==="person"&&e.sub!==void 0){const a=await S(),r=new Set((await a.prepare("SELECT id FROM profiles WHERE person = ?").all(e.sub)).map(n=>n.id));return u().filter(({profileId:n})=>r.has(n))}const i=await he(e);return u().filter(({profileId:a,manifest:r})=>{const n=r.grantee??"app:terminal";if(n===j(e))return!0;const s=`crtr:memory:rw:${n}:profile:${a}`;return T(i,s)&&(!ve(e)||T(e.scopes,s))})}o(L,"visibleProfiles");async function N(t,e){const i=await L(t),a=i.find(({profileId:n})=>n===e),r=a?[a]:i.filter(({manifest:n})=>n.name===e);if(r.length===0)throw new f(404,"not_found","profile not found");if(r.length>1)throw new f(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return r[0]}o(N,"requireUsableProfile");async function Re(t){const e=await k();return{status:200,body:(await L(t)).map(i=>v(i,e.get(i.profileId)??[]))}}o(Re,"handleList");async function qe(t){return{status:200,body:await l(await N(t,t.params.name))}}o(qe,"handleGet");async function Le(t){return le((await m(t,t.params.name)).profileId,t.body)}o(Le,"handleDelete");const st=[{method:"GET",pattern:"/v1/apps/self/env",handler:o(async t=>({status:200,body:{names:await x(c(t))}}),"handler")},{method:"PUT",pattern:"/v1/apps/self/env/:var",handler:o(async t=>{const e=q(t),{value:i}=t.body??{};if(typeof i!="string"||!i)throw d("a non-empty env value is required",{field:"value"});return{status:200,body:{changed:await te(c(t),e,i)}}},"handler")},{method:"DELETE",pattern:"/v1/apps/self/env/:var",handler:o(async t=>({status:200,body:{changed:await ee(c(t),q(t))}}),"handler")},{method:"PUT",pattern:"/v1/profiles/:name",handler:Ae},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:ke},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:Oe},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Ie},{method:"POST",pattern:"/v1/profiles",handler:_e},{method:"PATCH",pattern:"/v1/profiles/:name",handler:Ee},{method:"GET",pattern:"/v1/profiles/:name/env",handler:je},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:De},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:Te},{method:"DELETE",pattern:"/v1/profiles/:name",handler:Le},{method:"GET",pattern:"/v1/profiles",handler:Re},{method:"GET",pattern:"/v1/profiles/:name",handler:qe}];export{Pe as addProjectWithDefaultLimit,st as profileRoutes,be as renameProfileAndHandle,N as requireUsableProfile};
@@ -6,7 +6,7 @@ import type { ReviveResult } from '../../core/runtime/revive.js';
6
6
  import type { CloseNodeResult } from '../../core/runtime/close.js';
7
7
  import { type PushResult } from '../../core/feed/feed.js';
8
8
  import type { PageFeedback, PageFeedbackComment } from '../../core/human/feedback.js';
9
- import type { CloseResultDTO, CronDTO, CronRunDTO, ErrorBody, NodeEdgesDTO, NodeOutcomeDTO, RunOutcomeDTO, NodeOutcomeSummaryDTO, NodePathsDTO, NodeStatusDTO, OutcomeDeliveryDTO, NodeSummaryDTO, NodeDetailDTO, NodeWorktreeDTO, ProfileDTO, ReviewCommentDTO, ReviewCommentEventDTO, ReviewDTO, FeedbackResultDTO, GraphNodeDTO, PageFeedbackCommentDTO, PageFeedbackDTO, PushReportResultDTO, ReviveResultDTO, SubscriptionDTO } from '../../api/index.js';
9
+ import type { CloseResultDTO, CronDTO, CronRunDTO, ErrorBody, NodeEdgesDTO, NodeOutcomeDTO, RunOutcomeDTO, NodeOutcomeSummaryDTO, NodeStatusDTO, OutcomeDeliveryDTO, NodeSummaryDTO, NodeDetailDTO, NodeWorktreeDTO, ProfileDTO, ReviewCommentDTO, ReviewCommentEventDTO, ReviewDTO, FeedbackResultDTO, GraphNodeDTO, PageFeedbackCommentDTO, PageFeedbackDTO, PushReportResultDTO, ReviveResultDTO, SubscriptionDTO } from '../../api/index.js';
10
10
  /** Project the list-row outcome, or null while this node remains unsettled. */
11
11
  export declare function toNodeOutcomeSummaryDTO(node: NodeRuntime): NodeOutcomeSummaryDTO | null;
12
12
  /** Project the full outcome, or null while this node remains unsettled. */
@@ -62,9 +62,6 @@ export interface NodeEdgesInput {
62
62
  }
63
63
  /** Project a node's spine + subscription edges (absorbs `managers`/`paths`). */
64
64
  export declare function toNodeEdgesDTO(meta: NodeMeta, edges: NodeEdgesInput): NodeEdgesDTO;
65
- /** Absolute filesystem paths for a node (absorbs the `paths` read).
66
- * App assignment comes from the authoritative node row. */
67
- export declare function toNodePathsDTO(nodeId: string, grantee: string): Promise<NodePathsDTO>;
68
65
  /** Project a node's managed git worktree, if any. */
69
66
  export declare function toNodeWorktreeDTO(w: ManagedWorktree): NodeWorktreeDTO;
70
67
  /** Project the hydrated node view (`getNode` → `NodeMeta`) into a detail DTO.
@@ -1,2 +1,2 @@
1
- var k=Object.defineProperty;var i=(e,t)=>k(e,"name",{value:t,configurable:!0});import{join as b}from"node:path";import{liveExecutionForNode as g}from"../../core/canvas/executions.js";import{readOutputResult as y}from"../../core/runtime/output-result.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as h}from"../../core/canvas/crons.js";import{isProfilePaused as x,profileDir as O,sanitizeProfileMetadata as D}from"../../core/profiles/manifest.js";import{nodeMetaPath as T,transcriptPath as E,viewSocketPath as A}from"../../core/canvas/paths.js";import{appForNode as c,contextDir as S,nodeAgentDir as N}from"../../core/canvas/node-agent-paths.js";import{readControllerWaits as z}from"../../core/canvas/waits.js";import{FinalizationError as R}from"../../core/feed/feed.js";import{NodeIdConflictError as C}from"../../core/runtime/nodes.js";import{ScopeDeniedError as j}from"../../core/scopes.js";import{isBeneathRefusal as q}from"../../core/spaces/open-beneath.js";import{CrtrError as a}from"../../core/errors.js";import{WorktreeError as F}from"../../core/worktree.js";import{ApiError as I}from"../../api/errors.js";import{RunError as l}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";async function P(e){try{return await y(e)??null}catch{return null}}i(P,"readStructuredResult");function U(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}i(U,"toNodeOutcomeSummaryDTO");async function f(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,d={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?await P(e.node_id):null,detail:t};return e.outcome_kind==="result"?{...d,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...d,kind:"failure",reason:"declined",declined:t?.declined??null}:{...d,kind:"failure",reason:e.outcome_reason,declined:null}}i(f,"toNodeOutcomeDTO");async function ve(e){const t=await f(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}i(ve,"toRunOutcomeDTO");function ke(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}i(ke,"toOutcomeDeliveryDTO");function be(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}i(be,"toGraphNodeDTO");async function ge(e,t,n){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??await c(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:n,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,last_settled_at:e.last_settled_at??null,outcome:U(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}i(ge,"toNodeSummaryDTO");function G(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}i(G,"toNodeEdgesDTO");async function M(e,t){return{node_dir:await N(e,t),context_dir:await S(e,t),meta_path:T(e),transcript_path:E(e),view_socket:A(e)}}i(M,"toNodePathsDTO");function W(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}i(W,"toNodeWorktreeDTO");async function ye(e,t){const n=await c(e.node_id),d={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:x(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:(await z([e.node_id])).get(e.node_id)?.controllerId??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,runner:(await g(e.node_id))?.runner??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,last_settled_at:e.last_settled_at??null,outcome:await f(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:G(e,t),paths:await M(e.node_id,n)};return e.description!==void 0&&(d.description=e.description),e.title!==void 0&&(d.title=e.title),e.icon!==void 0&&(d.icon=e.icon),e.cycles!==void 0&&(d.cycles=e.cycles),d.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(d.pi_session_id=e.pi_session_id??null),d.model_override=e.model_override??null,e.pi_session_file!==void 0&&(d.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(d.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(d.worktree=W(e.managed_worktree)),d}i(ye,"toNodeDetailDTO");function he(e,t,n,d){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome,ready:d}}i(he,"toReviveResultDTO");function xe(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}i(xe,"toCloseResultDTO");function Oe(e,t,n){const d={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(d.transitioned=t),n!==void 0&&(d.worktree_auto_dropped=!0,d.worktree_auto_dropped_path=n),d}i(Oe,"toReportResultDTO");function De(e){return{node_id:e.node_id,active:e.active,created:e.created}}i(De,"toSubscriptionDTO");function B(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}i(B,"envKeys");function Te(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:B(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:h(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}i(Te,"toCronDTO");function Ee(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}i(Ee,"toCronRunDTO");function Ae(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:D(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,repositories:[],profile_path:O(e.profileId)}}i(Ae,"toProfileDTO");function p(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}i(p,"toReviewDTO");function Se(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}i(Se,"toReviewCommentDTO");function L(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}i(L,"toPageFeedbackCommentDTO");function Ne(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(L)}}i(Ne,"toPageFeedbackDTO");function ze(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}i(ze,"toReviewCommentEventDTO");function Re(e){return{document:e.document,file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}i(Re,"toFeedbackResultDTO");const $=!0,K=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},quote_not_found:{status:409,code:"quote_not_found"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"}});function V(e){const t=m(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof R)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof C)return{status:409,code:"node_id_exists"};if(t instanceof j)return{status:403,code:"scope_denied"};if(q(t))return{status:400,code:"invalid_request"};if(t instanceof _)return K[t.code];if(t instanceof a)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"||t.code==="scope_missing"?{status:403,code:t.code}:{status:Q(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}i(V,"errorToStatus");function m(e){if(!(e instanceof F))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new a(e.code,e.message,t,n)}i(m,"normalizeThrow");function H(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:J(t)}}i(H,"reviewErrorDetails");function J(e){return e.state!=="approved"?p(e):p(e,{result_path:b(e.review_dir,"result.json")})}i(J,"terminalConflictReviewDTO");function Q(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}i(Q,"statusForExitCode");function X(e){const n=(e instanceof Error?e.message:String(e)).split(`
2
- `,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}i(X,"boundedCause");function Ce(e){const t=m(e),{status:n,code:d}=V(t);if(n>=500){const u={error:{code:d,message:X(t),origin:"runtime"}};return t instanceof l&&(u.error.retryable=t.retryable),{status:n,body:u}}const v=t instanceof Error?t.message:String(t),s=t instanceof _?H(t):(t instanceof a||t instanceof I||t instanceof l)&&t.details!==void 0?t.details:void 0,r={error:{code:d,message:v,origin:"runtime"}};return s!==void 0&&(r.error.details=s),t instanceof l&&(t.param&&(r.error.param=t.param),t.scope&&(r.error.scope=t.scope),r.error.retryable=t.retryable),{status:n,body:r}}i(Ce,"toErrorBody");export{K as REVIEW_ERROR_MAP,X as boundedCause,V as errorToStatus,xe as toCloseResultDTO,Te as toCronDTO,Ee as toCronRunDTO,Ce as toErrorBody,Re as toFeedbackResultDTO,be as toGraphNodeDTO,ye as toNodeDetailDTO,G as toNodeEdgesDTO,f as toNodeOutcomeDTO,U as toNodeOutcomeSummaryDTO,M as toNodePathsDTO,ge as toNodeSummaryDTO,W as toNodeWorktreeDTO,ke as toOutcomeDeliveryDTO,L as toPageFeedbackCommentDTO,Ne as toPageFeedbackDTO,Ae as toProfileDTO,Oe as toReportResultDTO,Se as toReviewCommentDTO,ze as toReviewCommentEventDTO,p as toReviewDTO,he as toReviveResultDTO,ve as toRunOutcomeDTO,De as toSubscriptionDTO};
1
+ var b=Object.defineProperty;var i=(e,t)=>b(e,"name",{value:t,configurable:!0});import{join as k}from"node:path";import{liveExecutionForNode as g}from"../../core/canvas/executions.js";import{readOutputResult as y}from"../../core/runtime/output-result.js";import{ReviewOperationError as _}from"../../core/review/types.js";import{cronSinkDisplay as h}from"../../core/canvas/crons.js";import{isProfilePaused as x,profileDir as O,sanitizeProfileMetadata as D}from"../../core/profiles/manifest.js";import{appForNode as c}from"../../core/canvas/node-agent-paths.js";import{readControllerWaits as T}from"../../core/canvas/waits.js";import{FinalizationError as E}from"../../core/feed/feed.js";import{NodeIdConflictError as A}from"../../core/runtime/nodes.js";import{ScopeDeniedError as S}from"../../core/scopes.js";import{isBeneathRefusal as z}from"../../core/spaces/open-beneath.js";import{CrtrError as a}from"../../core/errors.js";import{WorktreeError as N}from"../../core/worktree.js";import{ApiError as R}from"../../api/errors.js";import{RunError as l}from"../../core/runs/operations.js";import{ExitCode as o}from"../../types.js";async function C(e){try{return await y(e)??null}catch{return null}}i(C,"readStructuredResult");function I(e){return e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0?null:{kind:e.outcome_kind,reason:e.outcome_reason,settled_at:e.outcome_at}}i(I,"toNodeOutcomeSummaryDTO");async function f(e){if(e.outcome_at===null||e.outcome_at===void 0||e.outcome_kind===null||e.outcome_kind===void 0||e.outcome_reason===null||e.outcome_reason===void 0)return null;let t=null;if(e.outcome_detail_json!==null&&e.outcome_detail_json!==void 0)try{t=JSON.parse(e.outcome_detail_json)}catch{t=null}const n=e.final_report??null,d={node_id:e.node_id,revision:e.outcome_revision??1,settled_at:e.outcome_at,final_report:n===null?null:`${e.node_id}/${n}`,structured_result:e.outcome_kind==="result"?await C(e.node_id):null,detail:t};return e.outcome_kind==="result"?{...d,kind:"result",reason:e.outcome_reason,declined:null}:e.outcome_reason==="declined"?{...d,kind:"failure",reason:"declined",declined:t?.declined??null}:{...d,kind:"failure",reason:e.outcome_reason,declined:null}}i(f,"toNodeOutcomeDTO");async function se(e){const t=await f(e);return t===null||t.reason==="parked"?null:t.kind==="result"||t.reason==="finished"?{...t,kind:"result",reason:"finalized",declined:null}:t.reason==="declined"?{...t,reason:"declined",details:t.declined}:t.reason==="deadline_exceeded"?{...t,reason:"deadline_exceeded",declined:null}:t.reason==="cap_exhausted"?{...t,reason:"cap_exhausted",declined:null}:t.reason==="closed"||t.reason==="stranded"||t.reason==="retired"?{...t,reason:"canceled",declined:null}:{...t,reason:"runtime_error",declined:null,details:{crouter_reason:t.reason}}}i(se,"toRunOutcomeDTO");function ue(e){const t=e.lastFailure;return{node_id:e.nodeId,state:e.state,action:e.actionName,attempt:e.attempt,next_attempt_at:e.nextAttemptAt===0?null:new Date(e.nextAttemptAt).toISOString(),accepted_at:e.acceptedAt===null?null:new Date(e.acceptedAt).toISOString(),permanent_failed_at:e.permanentFailedAt===null?null:new Date(e.permanentFailedAt).toISOString(),last_failure:t===null?null:{kind:t.kind,...t.exitCode===void 0?{}:{exit_code:t.exitCode},...t.signal===void 0?{}:{signal:t.signal},...t.message===void 0?{}:{message:t.message}},created_at:new Date(e.createdAt).toISOString(),updated_at:new Date(e.updatedAt).toISOString()}}i(ue,"toOutcomeDeliveryDTO");function _e(e){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,status:e.status,frozen_at:e.frozen_at,pi_pid:e.pi_pid,telemetry_context_tokens:e.telemetry_context_tokens,telemetry_last_activity:e.telemetry_last_activity,fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming}}i(_e,"toGraphNodeDTO");async function ce(e,t,n){return{node_id:e.node_id,name:e.name,description:e.description,cycles:e.cycles,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind,profile_id:e.profile_id,scopes:e.scopes,isolated:e.isolated,grantee:e.grantee??await c(e.node_id),profile_paused:t,parent:e.parent,created:e.created,intent:e.intent,waiting_for:n,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid,pi_pid_identity:e.pi_pid_identity,window:e.window,tmux_session:e.tmux_session,pane:e.pane,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,last_settled_at:e.last_settled_at??null,outcome:I(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1}}i(ce,"toNodeSummaryDTO");function j(e,t){return{parent:e.parent??null,spawned_by:e.spawned_by??null,subscribes_to:t.subscribesTo.map(n=>n.node_id),subscribers:t.subscribers.map(n=>n.node_id),children:[...t.children]}}i(j,"toNodeEdgesDTO");function q(e){const t={state:e.state,path:e.path,branch:e.branch,repo_root:e.repo_root,base_ref:e.base_ref,base_sha:e.base_sha,created:e.created};return e.cleanup!==void 0&&(t.cleanup=e.cleanup),e.closed!==void 0&&(t.closed=e.closed),e.abandoned!==void 0&&(t.abandoned={...e.abandoned}),t}i(q,"toNodeWorktreeDTO");async function fe(e,t){const n=await c(e.node_id),d={node_id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,status:e.status,cwd:e.cwd,host_kind:e.host_kind??null,profile_id:e.profile_id??null,scopes:e.scopes??null,isolated:e.isolated===!0,grantee:n,profile_paused:x(e.profile_id),parent:e.parent??null,created:e.created,intent:e.intent??null,waiting_for:(await T([e.node_id])).get(e.node_id)?.controllerId??null,frozen_at:e.frozen_at??null,terminal_reason:e.terminal_reason??null,pi_pid:e.pi_pid??null,pi_pid_identity:e.pi_pid_identity??null,runner:(await g(e.node_id))?.runner??null,window:e.window??null,tmux_session:e.tmux_session??null,pane:e.pane??null,final_report:e.final_report??null,finalized_at:e.finalized_at??null,deadline_at:e.deadline_at??null,telemetry_tokens_in:e.telemetry_tokens_in??null,telemetry_context_tokens:e.telemetry_context_tokens??null,telemetry_last_activity:e.telemetry_last_activity??null,telemetry_updated_at:e.telemetry_updated_at??null,last_settled_at:e.last_settled_at??null,outcome:await f(e),fault:e.fault&&e.fault.link!=="broker\u2194crtrd"?{...e.fault,link:e.fault.link}:null,streaming:e.streaming??!1,creator:e.creator??null,edges:j(e,t)};return e.description!==void 0&&(d.description=e.description),e.title!==void 0&&(d.title=e.title),e.icon!==void 0&&(d.icon=e.icon),e.cycles!==void 0&&(d.cycles=e.cycles),d.context_tokens=e.telemetry_context_tokens??e.telemetry_tokens_in??null,e.pi_session_id!==void 0&&(d.pi_session_id=e.pi_session_id??null),d.model_override=e.model_override??null,e.pi_session_file!==void 0&&(d.pi_session_file=e.pi_session_file??null),e.review_binding!==void 0&&(d.review_binding=e.review_binding===null?null:{...e.review_binding.kind===void 0?{}:{kind:e.review_binding.kind},review_id:e.review_binding.review_id,origin_node_id:e.review_binding.origin_node_id,branch_file:e.review_binding.branch_file,target_file:e.review_binding.target_file}),e.managed_worktree!=null&&(d.worktree=q(e.managed_worktree)),d}i(fe,"toNodeDetailDTO");function pe(e,t,n,d){return{node_id:e,revived:t.launch!==void 0,resumed:t.resumed,status:n,outcome:t.outcome,ready:d}}i(pe,"toReviveResultDTO");function me(e){return{root:e.root,closed:[...e.closed],spared:[...e.spared]}}i(me,"toCloseResultDTO");function ve(e,t,n){const d={report:e.report,notified:[...e.deliveredTo]};return t!==void 0&&(d.transitioned=t),n!==void 0&&(d.worktree_auto_dropped=!0,d.worktree_auto_dropped_path=n),d}i(ve,"toReportResultDTO");function be(e){return{node_id:e.node_id,active:e.active,created:e.created}}i(be,"toSubscriptionDTO");function F(e){if(e===null||e==="")return[];try{const t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.keys(t):[]}catch{return[]}}i(F,"envKeys");function ke(e,t){return{cron_id:e.cron_id,name:e.name,created_by:e.created_by,command:e.command,grant_id:e.grant_id,scopes:e.scopes,origin_run_id:e.origin_run_id,isolated:e.isolated,fire_at:e.fire_at,recur:e.recur,tz:e.tz,expires_at:e.expires_at,anchor_node:e.anchor_node,cancel_on_wake:e.cancel_on_wake,cwd:e.cwd,profile:e.profile,scope:e.scope,env_keys:F(e.env_json),run_timeout_s:e.run_timeout_s,overlap:e.overlap,on_output:e.on_output,sink:h(e.sink),tier:e.tier,state:e.state,held:e.held,run_state:e.run_state,last_run:t==null?null:{finished:t.finished,exit_code:t.exit_code,delivered:t.delivered},created:e.created,updated:e.updated}}i(ke,"toCronDTO");function ge(e){return{run_id:e.run_id,started:e.started,finished:e.finished,duration_ms:e.duration_ms,exit_code:e.exit_code,stdout_head:e.stdout_head,stderr_head:e.stderr_head,delivered:e.delivered}}i(ge,"toCronRunDTO");function ye(e){return{id:e.profileId,app:e.manifest.grantee??"app:terminal",name:e.manifest.name,projects:e.manifest.projects.map(t=>({...t})),delivery_limits:{...e.manifest.delivery_limits},paused_at:e.manifest.paused_at,default_kind:e.manifest.default_kind??"general",metadata:D(e.manifest.metadata),default_dir:null,created_at:e.manifest.created_at,last_used_at:e.manifest.last_used_at,repositories:[],profile_path:O(e.profileId)}}i(ye,"toProfileDTO");function p(e,t={}){const n={review_id:e.review_id,origin_kind:e.origin_kind,origin_node_id:e.origin_node_id,review_dir:e.review_dir,companion_node_id:e.companion_node_id,file:e.file,state:e.state,created:e.created,source_missing:e.source_missing,anchor_base_sha256:e.anchor_base_sha256};return e.document_name!==null&&(n.document=e.document_name),e.opened_at!==null&&(n.opened_at=e.opened_at),e.submit_requested_at!==null&&(n.submit_requested_at=e.submit_requested_at),e.approved_at!==null&&(n.approved_at=e.approved_at),e.changed!==null&&(n.changed=e.changed),e.comments_total!==null&&(n.comments_total=e.comments_total),e.comments_unresolved!==null&&(n.comments_unresolved=e.comments_unresolved),e.canceled_at!==null&&(n.canceled_at=e.canceled_at),e.cancel_reason!==null&&(n.cancel_reason=e.cancel_reason),e.cancel_actor!==null&&(n.cancel_actor=e.cancel_actor),t.result_path!==void 0&&(n.result_path=t.result_path),e.delivery_error!==null&&(n.delivery_error=e.delivery_error),e.projection_error!==null&&(n.projection_error=e.projection_error),n}i(p,"toReviewDTO");function he(e){return{comment_id:e.comment_id,review_id:e.review_id,status:e.status,revision:e.revision,text:e.text,anchor:{...e.anchor},author:{kind:e.author.kind,...e.author.node_id===null?{}:{node_id:e.author.node_id}},updated_by:{kind:e.updated_by.kind,...e.updated_by.node_id===null?{}:{node_id:e.updated_by.node_id}},created_at:e.created_at,updated_at:e.updated_at,...e.resolved_at===null?{}:{resolved_at:e.resolved_at},...e.deleted_at===null?{}:{deleted_at:e.deleted_at},created_seq:e.created_seq}}i(he,"toReviewCommentDTO");function P(e){return{id:e.id,quote:e.quote,...e.context===void 0?{}:{context:e.context},note:e.note,status:e.status,created_at:e.createdAt,...e.resolvedAt===void 0?{}:{resolved_at:e.resolvedAt}}}i(P,"toPageFeedbackCommentDTO");function xe(e){return{companion_node_id:e.companionNodeId??null,open_count:e.comments.filter(t=>t.status==="open").length,comments:e.comments.map(P)}}i(xe,"toPageFeedbackDTO");function Oe(e){return{seq:e.seq,review_id:e.review_id,comment_id:e.comment_id,kind:e.kind,state_change:e.state_change===1,revision_after:e.revision_after,actor:{kind:e.actor.kind,...e.actor.node_id===null?{}:{node_id:e.actor.node_id}},at:e.at,operation_id:e.operation_id,...e.payload===void 0?{}:{payload:e.payload}}}i(Oe,"toReviewCommentEventDTO");function De(e){return{document:e.document,file:e.file,submitted:e.submitted,approved:e.approved,comments:e.comments.map(n=>({...n})),submittedAt:e.submittedAt,savedAt:e.savedAt,reviewId:e.review_id,changed:e.changed,baselineSha256:e.baseline_sha256,approvedSha256:e.approved_sha256,companionNodeId:e.companion_node_id,commentsTotal:e.comments_total,commentsUnresolved:e.comments_unresolved}}i(De,"toFeedbackResultDTO");const U=!0,G=Object.freeze({review_origin_missing:{status:400,code:"review_origin_unavailable"},review_origin_unforkable:{status:400,code:"review_origin_unavailable"},review_branch_unavailable:{status:409,code:"review_branch_unavailable"},branch_lost:{status:409,code:"review_branch_unavailable"},review_companion_unbound:{status:409,code:"review_companion_unbound"},review_bridge_unsubscribed:{status:409,code:"review_bridge_unavailable"},review_target_unreviewable:{status:400,code:"review_file_unreadable"},source_unreadable:{status:409,code:"review_source_unreadable"},delivery_unroutable:{status:409,code:"review_delivery_unroutable"},unknown_review:{status:404,code:"unknown_review"},review_terminal:{status:409,code:"review_terminal_conflict"},review_required:{status:400,code:"review_required"},stale_document:{status:409,code:"stale_document"},stale_revision:{status:409,code:"stale_revision"},unknown_comment:{status:404,code:"unknown_comment"},comment_deleted:{status:409,code:"comment_deleted"},invalid_anchor:{status:400,code:"invalid_anchor"},quote_not_found:{status:409,code:"quote_not_found"},text_too_long:{status:400,code:"text_too_long"},comment_limit_reached:{status:409,code:"comment_limit_reached"},stale_comment:{status:409,code:"stale_comment"}});function W(e){const t=m(e);if(typeof t=="object"&&t!==null&&typeof t.status=="number"&&typeof t.code=="string")return{status:t.status,code:t.code};if(t instanceof E)return t.code==="unknown_node"?{status:404,code:"node_not_found"}:t.code==="already_finalized"?{status:409,code:"already_finalized"}:{status:409,code:"finalization_forbidden"};if(t instanceof A)return{status:409,code:"node_id_exists"};if(t instanceof S)return{status:403,code:"scope_denied"};if(z(t))return{status:400,code:"invalid_request"};if(t instanceof _)return G[t.code];if(t instanceof a)return["kind_owned","name_taken","hop_limit","not_a_queue"].includes(t.code)?{status:409,code:t.code}:t.code==="invalid_publish_token"?{status:401,code:t.code}:t.code==="forbidden"||t.code==="argv_forbidden"||t.code==="scope_missing"?{status:403,code:t.code}:{status:M(t.exitCode),code:t.code};if(t instanceof Error){const n=t.message;if(/unknown node/i.test(n))return{status:404,code:"node_not_found"};if(/finalization latch/i.test(n))return{status:409,code:"already_finalized"};if(/illegal lifecycle transition/i.test(n))return{status:409,code:"illegal_transition"}}return{status:500,code:"internal"}}i(W,"errorToStatus");function m(e){if(!(e instanceof N))return e;const t=e.code==="unknown_node"?o.NOT_FOUND:o.GENERAL,n={error:e.code,message:e.message,next:e.next};return e.detail!==void 0&&(n.received=e.detail),new a(e.code,e.message,t,n)}i(m,"normalizeThrow");function B(e){if(e.code!=="review_terminal")return e.detail;const{review:t,...n}=e.detail;return{...n,review:L(t)}}i(B,"reviewErrorDetails");function L(e){return e.state!=="approved"?p(e):p(e,{result_path:k(e.review_dir,"result.json")})}i(L,"terminalConflictReviewDTO");function M(e){switch(e){case o.NOT_FOUND:return 404;case o.USAGE:return 400;case o.AMBIGUOUS:return 400;case o.NETWORK:return 503;case o.GENERAL:return 400;default:return 500}}i(M,"statusForExitCode");function $(e){const n=(e instanceof Error?e.message:String(e)).split(`
2
+ `,1)[0].trim();return n===""?"internal error":n.length>500?`${n.slice(0,497)}\u2026`:n}i($,"boundedCause");function Te(e){const t=m(e),{status:n,code:d}=W(t);if(n>=500){const u={error:{code:d,message:$(t),origin:"runtime"}};return t instanceof l&&(u.error.retryable=t.retryable),{status:n,body:u}}const v=t instanceof Error?t.message:String(t),s=t instanceof _?B(t):(t instanceof a||t instanceof R||t instanceof l)&&t.details!==void 0?t.details:void 0,r={error:{code:d,message:v,origin:"runtime"}};return s!==void 0&&(r.error.details=s),t instanceof l&&(t.param&&(r.error.param=t.param),t.scope&&(r.error.scope=t.scope),r.error.retryable=t.retryable),{status:n,body:r}}i(Te,"toErrorBody");export{G as REVIEW_ERROR_MAP,$ as boundedCause,W as errorToStatus,me as toCloseResultDTO,ke as toCronDTO,ge as toCronRunDTO,Te as toErrorBody,De as toFeedbackResultDTO,_e as toGraphNodeDTO,fe as toNodeDetailDTO,j as toNodeEdgesDTO,f as toNodeOutcomeDTO,I as toNodeOutcomeSummaryDTO,ce as toNodeSummaryDTO,q as toNodeWorktreeDTO,ue as toOutcomeDeliveryDTO,P as toPageFeedbackCommentDTO,xe as toPageFeedbackDTO,ye as toProfileDTO,ve as toReportResultDTO,he as toReviewCommentDTO,Oe as toReviewCommentEventDTO,p as toReviewDTO,pe as toReviveResultDTO,se as toRunOutcomeDTO,be as toSubscriptionDTO};
@@ -1 +1 @@
1
- var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{setTimeout as R}from"node:timers/promises";import{CRON_DEATH_POLL_MS as x,CRON_KILL_GRACE_MS as O,EMPTY_STDOUT_SHA256 as h}from"./capture.js";import{cronDaemonInstanceId as v,cronOwnerAlive as p,ensureCronOwnerLease as D}from"./live-runs.js";import{crashedOneShotSummary as L,escalateFailure as C}from"./escalation.js";import{settleRun as I}from"./settle.js";import{adoptCronRunId as E,getCron as g,runningCrons as M,stopLeasedCronRun as S,setCronState as T,verifyLeasedCronRun as _}from"../../core/canvas/crons.js";import{claimReconcilerLease as H,releaseReconcilerLease as b,renewReconcilerLease as N}from"../../core/canvas/reconciler-leases.js";import{emitEvent as l}from"../../core/events/emit.js";import{openDb as $}from"../../core/canvas/db.js";import{cronEnvironment as k,fireInSandbox as G,resumeMachineFire as U}from"./machine-fire.js";const c="cron-recovery",f=3e4;async function B(e){const t=w();if(await H(c,e,t,f)===void 0)return;let n=!1;const r=s(async()=>{if(n)return!1;try{n=!await N(c,e,t,f)}catch{n=!0}return!n},"holds"),a=setInterval(()=>{r()},f/3);return a.unref(),{holds:r,release:s(async()=>{clearInterval(a),await b(c,e,t)},"release")}}s(B,"claimRecovery");async function F(e){const t=await g(e.cron_id);if(t===null||t.run_state!=="running"||t.run_execution_id!==e.run_execution_id||t.run_started_at!==e.run_started_at||t.run_lease_owner!==e.run_lease_owner||t.run_lease_owner!==null&&await p(t.run_lease_owner))return null;if(t.run_execution_id!==null)return t;const n=w();return await E(t,n)?{...t,run_execution_id:n}:null}s(F,"reverifyAbandoned");async function oe(e,t={}){await D();for(const n of await M()){if(n.run_lease_owner===v||n.run_lease_owner!==null&&await p(n.run_lease_owner))continue;const r=n.run_pid===null&&n.run_execution_id!==null?await k(n):null,a=r===null&&(n.run_pid===null||!_(n));if(r===null&&!a&&e-(n.run_started_at!=null?new Date(n.run_started_at).getTime():e)<n.run_timeout_s*1e3)continue;const o=await B(n.cron_id);if(o===void 0)continue;let i;try{i=await F(n)}catch(u){throw await o.release(),u}if(i===null){await o.release();continue}if(r!==null){P(i,r,t,o);continue}if(a){W(i,e,t,o);continue}K(i,e,t,o)}}s(oe,"recoverStaleCronLeases");function K(e,t,n,r){const a=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,o={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:-1,timedOut:!0,runTimeoutS:e.run_timeout_s,processErrorMessage:null,stdoutHead:"",stdoutSha256:h,stderrHead:`run timed out after ${e.run_timeout_s}s (recovered stale lease from a prior daemon instance)`},i=(async()=>{await r.holds()&&(await S(e),await V(e),await r.holds()&&await I(e,{outOfBand:!1,outcome:{kind:"disposed",ctx:o},record:{runId:o.runId,startedAtIso:o.startedAtIso,finishedAtMs:t,durationMs:t-a,exitCode:-1,stdoutHead:null,stderrHead:o.stderrHead},lease:{kind:"clear"}}))})().finally(()=>r.release());n.register?.(i),i.catch(u=>{l({level:"error",event:"cron.stale_lease.settle_failed",error:u,fields:{cron_id:e.cron_id}})})}s(K,"recoverTimedOutRun");function P(e,t,n,r){const a=(async()=>{await r.holds()&&await Y(e)&&(t.kind==="machine"?await U(e,t.id):await G(e,{runId:e.run_execution_id,outOfBand:e.run_out_of_band,startedAtIso:e.run_started_at,startedAtMs:Date.parse(e.run_started_at)},()=>{},!0))})().finally(()=>r.release());n.register?.(a),a.catch(o=>{l({level:"error",event:"cron.machine_resume.failed",error:o,fields:{cron_id:e.cron_id,run_id:e.run_execution_id}})})}s(P,"resumeMachineRun");async function Y(e){const t=await(await $()).prepare("UPDATE crons SET run_lease_owner = ?, updated = ? WHERE cron_id = ? AND run_state = 'running' AND run_execution_id = ? AND run_lease_owner IS NOT DISTINCT FROM ?").run(v,new Date().toISOString(),e.cron_id,e.run_execution_id,e.run_lease_owner);return Number(t.changes)>0}s(Y,"takeOverLease");async function V(e){if(!await y(e)&&(await S(e,"SIGKILL"),!await y(e)))throw new Error(`cron ${e.cron_id} run ${e.run_pid} survived SIGKILL`)}s(V,"awaitLeasedRunDeath");async function y(e){const t=Date.now()+O;for(;Date.now()<t;){if(!_(e))return!0;await R(x)}return!_(e)}s(y,"pollLeasedRunGone");function W(e,t,n,r){const a=e.recur==null,o=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,i=e.run_pid===null?"the daemon life that claimed this run ended before its launch pid was recorded \u2014 the command may have started and its outcome is unknown":"the daemon life that owned this run ended before it settled \u2014 the process is gone and its outcome was never observed",u={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:null,timedOut:!1,runTimeoutS:e.run_timeout_s,processErrorMessage:i,stdoutHead:"",stdoutSha256:h,stderrHead:`run outcome unobserved: ${i}`},m=(async()=>{let d=`crashed: ${i}${a?"":" \u2014 the next occurrence is unaffected"}`;if(a){if(!await r.holds())return;if(await T(e.cron_id,"paused"),e.on_output==="silent")d=`crashed: ${i} \u2014 one-shot paused, not re-fired (silent: not escalated)`;else{if(!await r.holds())return;d=`crashed one-shot: ${await C(e,u,L(i))}`}}await r.holds()&&(await I(e,{outOfBand:!1,outcome:{kind:"stated",delivered:d,paused:a},record:{runId:u.runId,startedAtIso:u.startedAtIso,finishedAtMs:t,durationMs:Math.max(0,t-o),exitCode:null,stdoutHead:null,stderrHead:u.stderrHead},lease:"release"}),l({level:"warn",event:"cron.run.unobserved",fields:{cron_id:e.cron_id,name:e.name,one_shot:a}}))})().finally(()=>r.release());n.register?.(m),m.catch(d=>{l({level:"error",event:"cron.crashed_run.settle_failed",error:d,fields:{cron_id:e.cron_id}})})}s(W,"settleCrashedRun");export{oe as recoverStaleCronLeases};
1
+ var A=Object.defineProperty;var s=(e,t)=>A(e,"name",{value:t,configurable:!0});import{randomUUID as w}from"node:crypto";import{setTimeout as R}from"node:timers/promises";import{CRON_DEATH_POLL_MS as x,CRON_KILL_GRACE_MS as O,EMPTY_STDOUT_SHA256 as h}from"./capture.js";import{cronDaemonInstanceId as p,cronOwnerAlive as v,ensureCronOwnerLease as D}from"./live-runs.js";import{crashedOneShotSummary as L,escalateFailure as C}from"./escalation.js";import{settleRun as I}from"./settle.js";import{adoptCronRunId as E,getCron as g,runningCrons as M,stopLeasedCronRun as S,setCronState as T,verifyLeasedCronRun as _}from"../../core/canvas/crons.js";import{claimReconcilerLease as H,releaseReconcilerLease as b,renewReconcilerLease as N}from"../../core/canvas/reconciler-leases.js";import{emitEvent as l}from"../../core/events/emit.js";import{openDb as $}from"../../core/canvas/db.js";import{asPerson as k}from"../reconcilers/node-lifecycle/node-person.js";import{cronEnvironment as G,fireInSandbox as P,resumeMachineFire as U}from"./machine-fire.js";const c="cron-recovery",f=3e4;async function B(e){const t=w();if(await H(c,e,t,f)===void 0)return;let n=!1;const r=s(async()=>{if(n)return!1;try{n=!await N(c,e,t,f)}catch{n=!0}return!n},"holds"),a=setInterval(()=>{r()},f/3);return a.unref(),{holds:r,release:s(async()=>{clearInterval(a),await b(c,e,t)},"release")}}s(B,"claimRecovery");async function F(e){const t=await g(e.cron_id);if(t===null||t.run_state!=="running"||t.run_execution_id!==e.run_execution_id||t.run_started_at!==e.run_started_at||t.run_lease_owner!==e.run_lease_owner||t.run_lease_owner!==null&&await v(t.run_lease_owner))return null;if(t.run_execution_id!==null)return t;const n=w();return await E(t,n)?{...t,run_execution_id:n}:null}s(F,"reverifyAbandoned");async function se(e,t={}){await D();for(const n of await M()){if(n.run_lease_owner===p||n.run_lease_owner!==null&&await v(n.run_lease_owner))continue;const r=n.run_pid===null&&n.run_execution_id!==null?await G(n):null,a=r===null&&(n.run_pid===null||!_(n));if(r===null&&!a&&e-(n.run_started_at!=null?new Date(n.run_started_at).getTime():e)<n.run_timeout_s*1e3)continue;const o=await B(n.cron_id);if(o===void 0)continue;let i;try{i=await F(n)}catch(u){throw await o.release(),u}if(i===null){await o.release();continue}if(r!==null){Y(i,r,t,o);continue}if(a){j(i,e,t,o);continue}K(i,e,t,o)}}s(se,"recoverStaleCronLeases");function K(e,t,n,r){const a=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,o={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:-1,timedOut:!0,runTimeoutS:e.run_timeout_s,processErrorMessage:null,stdoutHead:"",stdoutSha256:h,stderrHead:`run timed out after ${e.run_timeout_s}s (recovered stale lease from a prior daemon instance)`},i=(async()=>{await r.holds()&&(await S(e),await W(e),await r.holds()&&await I(e,{outOfBand:!1,outcome:{kind:"disposed",ctx:o},record:{runId:o.runId,startedAtIso:o.startedAtIso,finishedAtMs:t,durationMs:t-a,exitCode:-1,stdoutHead:null,stderrHead:o.stderrHead},lease:{kind:"clear"}}))})().finally(()=>r.release());n.register?.(i),i.catch(u=>{l({level:"error",event:"cron.stale_lease.settle_failed",error:u,fields:{cron_id:e.cron_id}})})}s(K,"recoverTimedOutRun");function Y(e,t,n,r){const a=(async()=>{await r.holds()&&await V(e)&&await k(e.sub,async()=>{t.kind==="machine"?await U(e,t.id):await P(e,{runId:e.run_execution_id,outOfBand:e.run_out_of_band,startedAtIso:e.run_started_at,startedAtMs:Date.parse(e.run_started_at)},()=>{},!0)})})().finally(()=>r.release());n.register?.(a),a.catch(o=>{l({level:"error",event:"cron.machine_resume.failed",error:o,fields:{cron_id:e.cron_id,run_id:e.run_execution_id}})})}s(Y,"resumeMachineRun");async function V(e){const t=await(await $()).prepare("UPDATE crons SET run_lease_owner = ?, updated = ? WHERE cron_id = ? AND run_state = 'running' AND run_execution_id = ? AND run_lease_owner IS NOT DISTINCT FROM ?").run(p,new Date().toISOString(),e.cron_id,e.run_execution_id,e.run_lease_owner);return Number(t.changes)>0}s(V,"takeOverLease");async function W(e){if(!await y(e)&&(await S(e,"SIGKILL"),!await y(e)))throw new Error(`cron ${e.cron_id} run ${e.run_pid} survived SIGKILL`)}s(W,"awaitLeasedRunDeath");async function y(e){const t=Date.now()+O;for(;Date.now()<t;){if(!_(e))return!0;await R(x)}return!_(e)}s(y,"pollLeasedRunGone");function j(e,t,n,r){const a=e.recur==null,o=e.run_started_at!=null?new Date(e.run_started_at).getTime():t,i=e.run_pid===null?"the daemon life that claimed this run ended before its launch pid was recorded \u2014 the command may have started and its outcome is unknown":"the daemon life that owned this run ended before it settled \u2014 the process is gone and its outcome was never observed",u={runId:e.run_execution_id,startedAtIso:e.run_started_at??new Date(t).toISOString(),exitCode:null,timedOut:!1,runTimeoutS:e.run_timeout_s,processErrorMessage:i,stdoutHead:"",stdoutSha256:h,stderrHead:`run outcome unobserved: ${i}`},m=(async()=>{let d=`crashed: ${i}${a?"":" \u2014 the next occurrence is unaffected"}`;if(a){if(!await r.holds())return;if(await T(e.cron_id,"paused"),e.on_output==="silent")d=`crashed: ${i} \u2014 one-shot paused, not re-fired (silent: not escalated)`;else{if(!await r.holds())return;d=`crashed one-shot: ${await C(e,u,L(i))}`}}await r.holds()&&(await I(e,{outOfBand:!1,outcome:{kind:"stated",delivered:d,paused:a},record:{runId:u.runId,startedAtIso:u.startedAtIso,finishedAtMs:t,durationMs:Math.max(0,t-o),exitCode:null,stdoutHead:null,stderrHead:u.stderrHead},lease:"release"}),l({level:"warn",event:"cron.run.unobserved",fields:{cron_id:e.cron_id,name:e.name,one_shot:a}}))})().finally(()=>r.release());n.register?.(m),m.catch(d=>{l({level:"error",event:"cron.crashed_run.settle_failed",error:d,fields:{cron_id:e.cron_id}})})}s(j,"settleCrashedRun");export{se as recoverStaleCronLeases};
@@ -1 +1 @@
1
- var H=Object.defineProperty;var d=(e,n)=>H(e,"name",{value:n,configurable:!0});import{createHash as U,randomUUID as P}from"node:crypto";import{join as k}from"node:path";import{setTimeout as B}from"node:timers/promises";import{openDb as C}from"../../core/canvas/db.js";import{isCloudRole as F}from"../../core/canvas/person.js";import{withCanvasWrite as j}from"../../core/canvas/db.js";import{getNode as W}from"../../core/canvas/canvas.js";import{contextDir as q}from"../../core/canvas/paths.js";import{runnerForEnvironment as J}from"../../core/runtime/runner/index.js";import{callMachine as $}from"../../core/runtime/runner/machine/call.js";import{machineEnvironmentOfNode as K}from"../../core/runtime/runner/machine/runner.js";import{MachineCallFailedError as V,MachineLostError as X,MachineOfflineError as O}from"../../core/runtime/runner/machine/ops.js";import{environmentSecrets as Y}from"../../core/secrets/environment-secrets.js";import{profileInApp as z}from"../../core/secrets/environment-owner.js";import{getCron as G}from"../../core/canvas/crons.js";import{emitEvent as E}from"../../core/events/emit.js";import{runTokenFor as Q}from"./run-token.js";import{parseArmedEnv as Z}from"./armed-context.js";import{CRON_OUTPUT_HEAD_BYTES as v,formatCronOutputHead as ee}from"./capture.js";import{settleClosedRun as g,settleUnspawnedRun as h}from"./closed.js";import{clearLiveRun as y,registerLiveRun as T}from"./live-runs.js";import{advanceRecurrence as S}from"./recurrence.js";const ne=15,re=2e3;async function xe(e){return!F()||e.profile==null?null:await(await C()).prepare("SELECT e.object AS id, e.kind AS kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(e.profile)??null}d(xe,"cronEnvironment");async function Me(e){return await(await C()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,new Date().toISOString())!==void 0}d(Me,"machineLinkLive");async function A(e,n){const r=e.profile,i=await(await C()).prepare("SELECT person FROM profiles WHERE id = ?").get(r);if(i===void 0)throw new Error(`profile ${r} of cron ${e.cron_id} is not in the control plane`);const t=await Y({person:i.person,app:e.grantee,ownerProfile:r,ownerProfileInApp:await z(r,e.grantee),includeDeployment:!1}),o=e.grantee==="app:terminal",l=e.anchor_node!=null?await W(e.anchor_node):null;return{env:{...t,...Z(e.env_json),...o?{CRTR_PROFILE_ID:r}:{},CRTR_CRON_ID:e.cron_id,CRTR_CRON_NAME:e.name,CRTR_RUN_ID:n,CRTR_API_TOKEN:Q(n),...e.anchor_node!=null?{CRTR_ANCHOR:e.anchor_node}:{}},grantee:e.grantee,profileId:r,contextAnchor:l===null?null:{node:l.node_id,grantee:l.grantee??e.grantee}}}d(A,"prepareRun");async function te(e,n,r,i){const t=(e.run_timeout_s+ne)*1e3;return await $(n,"cron.run",{runId:r,cronId:e.cron_id,command:e.command,cwd:e.cwd,...i,timeoutS:e.run_timeout_s,leaseExpiresAt:new Date(Date.now()+t).toISOString()},{timeoutMs:t})}d(te,"sendCronRun");async function oe(e,n){await x(e,"cron.cancel",{runId:n})}d(oe,"queueCronCancel");async function De(e,n){const r=await K(e);r!==null&&await x(r,"job.stop",{node:e,job:n})}d(De,"queueJobStop");async function x(e,n,r){await j(async i=>{await i.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(P(),e,n,JSON.stringify(r),new Date().toISOString()),await i.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`)})}d(x,"queueMachineCall");async function Ne(e,n,r){const{runId:i,outOfBand:t,startedAtIso:o,startedAtMs:l}=n;let c;try{if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a machine does not have");if(c=await A(e,i),!t&&e.recur!=null){const s=await S(e,l);if(s!==null)throw s}}catch(s){return await h(e,{runId:i,outOfBand:t,startedAtIso:o,startedAtMs:l},"run could not be armed",s)}return await M(e,n,c,r)}d(Ne,"fireOnMachine");async function be(e,n){const r=e.run_execution_id,i=e.run_started_at,t=Date.parse(i),o=e.run_out_of_band,l={environmentId:n,runId:r,outOfBand:o,startedAtIso:i,startedAtMs:t};let c;try{if(c=await A(e,r),!o&&e.recur!=null&&Date.parse(e.fire_at)<=t){const s=await S(e,t);if(s!==null)throw s}}catch(s){return await h(e,l,"run could not be armed",s)}return await M(e,l,c,()=>{})}d(be,"resumeMachineFire");async function M(e,n,r,i){const{environmentId:t,runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s}=n,p={runId:o,replaced:!1,selfCanceled:!1,kill:d(()=>{oe(t,o).catch(_=>{E({level:"error",event:"cron.machine.cancel_failed",error:_,fields:{cron_id:e.cron_id,run_id:o}})})},"kill")};T(e.cron_id,p),i();try{let _=null,m=null;for(;_===null&&m===null;){try{const f=await te(e,t,o,r);if(f.notStarted!==!0){_=f;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:f.stderrHead}})}catch(f){if(f instanceof V){m=f;break}if(!(f instanceof O)&&!(f instanceof X))throw f;if(l&&f instanceof O){m=f;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:f.message}})}if(!p.selfCanceled&&await G(e.cron_id)===null)return null;await B(re)}if(m!==null)return await h(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s},"run failed on the machine",m);const{exitCode:a,stdoutHead:w,stderrHead:u,durationMs:R,stdoutSha256:D}=_,I=a===-1,N=a===null?new Error((u??"the machine reported no exit").slice(0,v)):null,b=p.replaced,L=p.selfCanceled;return await g(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s,finishedAtMs:s+R,code:I?null:a,timedOut:I,processError:N,stdoutHead:w??"",stderrHead:u??"",stdoutSha256:D,wasReplaced:b,wasSelfCanceled:L})}finally{y(e.cron_id,o)}}d(M,"driveFire");const ae="/var/lib/crtr";async function Le(e,n,r,i=!1){const{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c}=n;let s,p;try{if(p=J("blaxel"),p.cronRun===void 0||p.cronCancel===void 0)throw new Error("the registered Blaxel runner cannot run crons");const a=process.env.CRTR_PUBLIC_API_URL;if(!a)throw new Error("CRTR_PUBLIC_API_URL is not set, so a sandbox cron could not reach the API");if(e.anchor_node==null)throw new Error("a hosted cron runs in its anchor node's sandbox, and this cron has no anchor node");if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a sandbox does not have");const w=await A(e,t),u=w.contextAnchor;if(s={...w.env,CRTR_API_URL:a,HOME:k(ae,"apps",e.grantee.replace(/^app:/,""),"home"),...u!==null?{CRTR_CONTEXT_DIR:q(u.node,u.grantee)}:{}},!o&&e.recur!=null&&(!i||Date.parse(e.fire_at)<=c)){const R=await S(e,c);if(R!==null)throw R}}catch(a){return await h(e,n,"run could not be armed",a)}const _=e.anchor_node,m={runId:t,replaced:!1,selfCanceled:!1,kill:d(()=>{p.cronCancel(_,t).catch(a=>{E({level:"error",event:"cron.sandbox.cancel_failed",error:a,fields:{cron_id:e.cron_id,run_id:t}})})},"kill")};T(e.cron_id,m),r();try{let a;try{a=await p.cronRun(_,{runId:t,command:e.command,cwd:e.cwd,env:s,timeoutS:e.run_timeout_s,startedAtMs:c})}catch(u){return await h(e,n,"run failed in the sandbox",u)}const w=d(u=>u.length>v?ee(u.slice(0,v),!0):u,"head");return await g(e,{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c,finishedAtMs:Date.now(),code:a.exitCode,timedOut:a.timedOut,processError:a.error===void 0?null:new Error(a.error),stdoutHead:w(a.stdout),stderrHead:w(a.stderr),stdoutSha256:U("sha256").update(a.stdout).digest("hex"),wasReplaced:m.replaced,wasSelfCanceled:m.selfCanceled})}finally{y(e.cron_id,t)}}d(Le,"fireInSandbox");export{xe as cronEnvironment,Le as fireInSandbox,Ne as fireOnMachine,Me as machineLinkLive,oe as queueCronCancel,De as queueJobStop,be as resumeMachineFire,te as sendCronRun};
1
+ var H=Object.defineProperty;var d=(e,n)=>H(e,"name",{value:n,configurable:!0});import{createHash as U,randomUUID as P}from"node:crypto";import{join as k}from"node:path";import{setTimeout as B}from"node:timers/promises";import{openDb as C}from"../../core/canvas/db.js";import{isCloudRole as F}from"../../core/canvas/person.js";import{withCanvasWrite as j}from"../../core/canvas/db.js";import{getNode as W}from"../../core/canvas/canvas.js";import{runnerForEnvironment as q}from"../../core/runtime/runner/index.js";import{callMachine as J}from"../../core/runtime/runner/machine/call.js";import{machineEnvironmentOfNode as $}from"../../core/runtime/runner/machine/runner.js";import{MachineCallFailedError as K,MachineLostError as V,MachineOfflineError as O}from"../../core/runtime/runner/machine/ops.js";import{environmentSecrets as Y}from"../../core/secrets/environment-secrets.js";import{profileInApp as X}from"../../core/secrets/environment-owner.js";import{getCron as z}from"../../core/canvas/crons.js";import{emitEvent as E}from"../../core/events/emit.js";import{runTokenFor as G}from"./run-token.js";import{parseArmedEnv as Q}from"./armed-context.js";import{CRON_OUTPUT_HEAD_BYTES as v,formatCronOutputHead as Z}from"./capture.js";import{settleClosedRun as g,settleUnspawnedRun as R}from"./closed.js";import{clearLiveRun as y,registerLiveRun as x}from"./live-runs.js";import{advanceRecurrence as A}from"./recurrence.js";const ee=15,ne=2e3;async function ye(e){return!F()||e.profile==null?null:await(await C()).prepare("SELECT e.object AS id, e.kind AS kind FROM profiles p JOIN environments e ON e.object = p.environment_id WHERE p.id = ?").get(e.profile)??null}d(ye,"cronEnvironment");async function xe(e){return await(await C()).prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,new Date().toISOString())!==void 0}d(xe,"machineLinkLive");async function S(e,n){const r=e.profile,a=await(await C()).prepare("SELECT person FROM profiles WHERE id = ?").get(r);if(a===void 0)throw new Error(`profile ${r} of cron ${e.cron_id} is not in the control plane`);const t=await Y({person:a.person,app:e.grantee,ownerProfile:r,ownerProfileInApp:await X(r,e.grantee),includeDeployment:!1}),o=e.grantee==="app:terminal",l=e.anchor_node!=null?await W(e.anchor_node):null;return{env:{...t,...Q(e.env_json),...o?{CRTR_PROFILE_ID:r}:{},CRTR_CRON_ID:e.cron_id,CRTR_CRON_NAME:e.name,CRTR_RUN_ID:n,CRTR_API_TOKEN:G(n),...e.anchor_node!=null?{CRTR_ANCHOR:e.anchor_node}:{}},grantee:e.grantee,profileId:r,contextAnchor:l===null?null:{node:l.node_id,grantee:l.grantee??e.grantee}}}d(S,"prepareRun");async function re(e,n,r,a){const t=(e.run_timeout_s+ee)*1e3;return await J(n,"cron.run",{runId:r,cronId:e.cron_id,command:e.command,cwd:e.cwd,...a,timeoutS:e.run_timeout_s,leaseExpiresAt:new Date(Date.now()+t).toISOString()},{timeoutMs:t})}d(re,"sendCronRun");async function te(e,n){await M(e,"cron.cancel",{runId:n})}d(te,"queueCronCancel");async function Me(e,n){const r=await $(e);r!==null&&await M(r,"job.stop",{node:e,job:n})}d(Me,"queueJobStop");async function M(e,n,r){await j(async a=>{await a.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(P(),e,n,JSON.stringify(r),new Date().toISOString()),await a.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`)})}d(M,"queueMachineCall");async function Te(e,n,r){const{runId:a,outOfBand:t,startedAtIso:o,startedAtMs:l}=n;let c;try{if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a machine does not have");if(c=await S(e,a),!t&&e.recur!=null){const s=await A(e,l);if(s!==null)throw s}}catch(s){return await R(e,{runId:a,outOfBand:t,startedAtIso:o,startedAtMs:l},"run could not be armed",s)}return await T(e,n,c,r)}d(Te,"fireOnMachine");async function be(e,n){const r=e.run_execution_id,a=e.run_started_at,t=Date.parse(a),o=e.run_out_of_band,l={environmentId:n,runId:r,outOfBand:o,startedAtIso:a,startedAtMs:t};let c;try{if(c=await S(e,r),!o&&e.recur!=null&&Date.parse(e.fire_at)<=t){const s=await A(e,t);if(s!==null)throw s}}catch(s){return await R(e,l,"run could not be armed",s)}return await T(e,l,c,()=>{})}d(be,"resumeMachineFire");async function T(e,n,r,a){const{environmentId:t,runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s}=n,w={runId:o,replaced:!1,selfCanceled:!1,kill:d(()=>{te(t,o).catch(f=>{E({level:"error",event:"cron.machine.cancel_failed",error:f,fields:{cron_id:e.cron_id,run_id:o}})})},"kill")};x(e.cron_id,w),a();try{let f=null,m=null;for(;f===null&&m===null;){try{const u=await re(e,t,o,r);if(u.notStarted!==!0){f=u;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:u.stderrHead}})}catch(u){if(u instanceof K){m=u;break}if(!(u instanceof O)&&!(u instanceof V))throw u;if(l&&u instanceof O){m=u;break}E({level:"warn",event:"cron.machine.resend",fields:{cron_id:e.cron_id,run_id:o,why:u.message}})}if(!w.selfCanceled&&await z(e.cron_id)===null)return null;await B(ne)}if(m!==null)return await R(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s},"run failed on the machine",m);const{exitCode:h,stdoutHead:i,stderrHead:_,durationMs:p,stdoutSha256:b}=f,I=h===-1,N=h===null?new Error((_??"the machine reported no exit").slice(0,v)):null,D=w.replaced,L=w.selfCanceled;return await g(e,{runId:o,outOfBand:l,startedAtIso:c,startedAtMs:s,finishedAtMs:s+p,code:I?null:h,timedOut:I,processError:N,stdoutHead:i??"",stderrHead:_??"",stdoutSha256:b,wasReplaced:D,wasSelfCanceled:L})}finally{y(e.cron_id,o)}}d(T,"driveFire");const oe="/var/lib/crtr";async function Ne(e,n,r,a=!1){const{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c}=n;let s,w,f;try{if(f=q("blaxel"),f.cronRun===void 0||f.cronCancel===void 0)throw new Error("the registered Blaxel runner cannot run crons");const i=process.env.CRTR_PUBLIC_API_URL;if(!i)throw new Error("CRTR_PUBLIC_API_URL is not set, so a sandbox cron could not reach the API");if(e.anchor_node==null)throw new Error("a hosted cron runs in its anchor node's sandbox, and this cron has no anchor node");if(e.isolated)throw new Error("an isolated cron needs a root launcher, which a sandbox does not have");const _=await S(e,t);if(w=_.contextAnchor?.grantee??e.grantee,s={..._.env,CRTR_API_URL:i,HOME:k(oe,"apps",e.grantee.replace(/^app:/,""),"home")},!o&&e.recur!=null&&(!a||Date.parse(e.fire_at)<=c)){const p=await A(e,c);if(p!==null)throw p}}catch(i){return await R(e,n,"run could not be armed",i)}const m=e.anchor_node,h={runId:t,replaced:!1,selfCanceled:!1,kill:d(()=>{f.cronCancel(m,t).catch(i=>{E({level:"error",event:"cron.sandbox.cancel_failed",error:i,fields:{cron_id:e.cron_id,run_id:t}})})},"kill")};x(e.cron_id,h),r();try{let i;try{i=await f.cronRun(m,{runId:t,command:e.command,cwd:e.cwd,app:w,env:s,timeoutS:e.run_timeout_s,startedAtMs:c})}catch(p){return await R(e,n,"run failed in the sandbox",p)}const _=d(p=>p.length>v?Z(p.slice(0,v),!0):p,"head");return await g(e,{runId:t,outOfBand:o,startedAtIso:l,startedAtMs:c,finishedAtMs:Date.now(),code:i.exitCode,timedOut:i.timedOut,processError:i.error===void 0?null:new Error(i.error),stdoutHead:_(i.stdout),stderrHead:_(i.stderr),stdoutSha256:U("sha256").update(i.stdout).digest("hex"),wasReplaced:h.replaced,wasSelfCanceled:h.selfCanceled})}finally{y(e.cron_id,t)}}d(Ne,"fireInSandbox");export{ye as cronEnvironment,Ne as fireInSandbox,Te as fireOnMachine,xe as machineLinkLive,te as queueCronCancel,Me as queueJobStop,be as resumeMachineFire,re as sendCronRun};
@@ -1 +1 @@
1
- var m=Object.defineProperty;var n=(e,o)=>m(e,"name",{value:o,configurable:!0});import{existsSync as p,readdirSync as w,rmSync as f}from"node:fs";import{reviewsRoot as a}from"../../core/canvas/paths.js";import{listBindingRequests as y,listRequests as u,listUnprojectedReviews as q,markProjectionError as v}from"../../core/human/requests.js";import{projectAndRetire as d}from"./settle.js";function R(e){return e instanceof Error?e.message:String(e)}n(R,"errorText");async function g(){}n(g,"reconcileUndeliveredTickets");async function k(e){let o=0,c=0,s=0,l=0,i=0;for(const t of await y())try{await e.realizeReview(t.request_id),o+=1}catch{i+=1}try{const t=new Set((await u({kind:"review"})).map(r=>r.request_id));if(p(a()))for(const r of w(a(),{withFileTypes:!0}))r.isDirectory()&&!t.has(r.name)&&(f(`${a()}/${r.name}`,{recursive:!0,force:!0}),c+=1)}catch{i+=1}for(const t of await q())try{await d(t,{project:e.projectReview,retire:e.retireCompanion}),s+=1}catch(r){await v(t.request_id,R(r)),i+=1}for(const t of await u({state:"settled"}))if(!(t.companion_node_id===null||t.companion_retired_at!==null))try{await d(t,{retire:e.retireCompanion}),l+=1}catch{i+=1}return{realized:o,collected:c,reprojected:s,retired:l,failed:i}}n(k,"sweepHumanRequests");export{g as reconcileUndeliveredTickets,k as sweepHumanRequests};
1
+ var d=Object.defineProperty;var n=(e,o)=>d(e,"name",{value:o,configurable:!0});import{existsSync as m,readdirSync as p,rmSync as w}from"node:fs";import{reviewsRoot as a}from"../../core/canvas/paths.js";import{listBindingRequests as f,listRequests as y,listReviewRequestIds as R,listUnprojectedReviews as q,markProjectionError as v}from"../../core/human/requests.js";import{projectAndRetire as u}from"./settle.js";function h(e){return e instanceof Error?e.message:String(e)}n(h,"errorText");async function T(){}n(T,"reconcileUndeliveredTickets");async function k(e){let o=0,c=0,s=0,l=0,r=0;for(const t of await f())try{await e.realizeReview(t.request_id),o+=1}catch{r+=1}try{const t=new Set(await R());if(m(a()))for(const i of p(a(),{withFileTypes:!0}))i.isDirectory()&&!t.has(i.name)&&(w(`${a()}/${i.name}`,{recursive:!0,force:!0}),c+=1)}catch{r+=1}for(const t of await q())try{await u(t,{project:e.projectReview,retire:e.retireCompanion}),s+=1}catch(i){await v(t.request_id,h(i)),r+=1}for(const t of await y({state:"settled"}))if(!(t.companion_node_id===null||t.companion_retired_at!==null))try{await u(t,{retire:e.retireCompanion}),l+=1}catch{r+=1}return{realized:o,collected:c,reprojected:s,retired:l,failed:r}}n(k,"sweepHumanRequests");export{T as reconcileUndeliveredTickets,k as sweepHumanRequests};
@@ -22,8 +22,8 @@ export interface PeerIngressContext {
22
22
  }
23
23
  /** Whether the daemon's own route table serves this request: the routes `servePeer` hands to its router (`peer.*` and every daemon route a forwarded call reaches). */
24
24
  export declare function isDaemonRoute(method: string, pathname: string): Promise<boolean>;
25
- /** The account owner this runtime belongs to: the owner a successful `crtr sys join` recorded (a laptop), else — on a hosted runtime, which is
26
- * provisioned without join — the one `sub` its mirrored grants all carry. Null when neither names exactly one owner. Never throws. */
25
+ /** The account owner this runtime belongs to: the owner a successful `crtr sys signin` registration recorded (a laptop), else — on a hosted runtime, which is
26
+ * provisioned without registration — the one `sub` its mirrored grants all carry. Null when neither names exactly one owner. Never throws. */
27
27
  export declare function runtimeOwner(): Promise<string | null>;
28
28
  /** A bearer the caller already tried to verify and that failed: `servePeer` answers it as its own refusal (and audits it). */
29
29
  export interface PeerRefusal {
@@ -1 +1 @@
1
- var J=Object.defineProperty;var _=(s,e)=>J(s,"name",{value:e,configurable:!0});import{existsSync as v,readFileSync as B,readdirSync as C,statSync as S}from"node:fs";import{bashJobPaths as g,bashJobsDir as E,clearJobDeadlineFile as T,formatBashElapsed as D,isBashJobProcessConfirmedGone as O,readJobSupervisorState as b,signalBashJob as R}from"../../core/bash-jobs.js";import{queueJobStop as L}from"../cron/machine-fire.js";import{killBashJobObject as P,recordBashJobObject as j}from"../../core/spaces/stop.js";import{readFileBeneath as N}from"../../core/spaces/open-beneath.js";import{blobStore as U}from"../../core/blobs/index.js";import{openDb as c,withCanvasWrite as f}from"../../core/canvas/db.js";import{applyJobReport as k,endJobsOfExitedSandboxes as q,endReportedJobs as F,expiredJobs as K,jobRow as z,ownerRunsRemotely as y,recordJobSilence as G,runningJobs as M,setJobDeadline as V}from"../../core/graph/jobs.js";import{publish as Y}from"../../core/graph/events.js";import{envBashSilenceMs as $}from"../../shared/env.js";import{getById as A}from"../../core/graph/objects.js";import{isSafeNodeId as u}from"../../core/canvas/paths.js";import{contextDir as x}from"../../core/canvas/node-agent-paths.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isProfilePaused as H}from"../../core/profiles/manifest.js";import{runThrottledLane as W}from"./throttled-lane.js";const X=300*1e3;function Q(s,e,t){const i=s<t?0:s<2*t?t:s<4*t?2*t:4*t*Math.floor(s/(4*t));return i>e?i:null}_(Q,"dueSilenceThresholdMs");const Z=5*1e3,tt=60*1e3,m=64*1024;class vt{static{_(this,"BashDeadlineReconciler")}startedAt=Date.now();uploadedBytes=new Map;async run(e,t){await this.mirrorSupervisors(t),await this.publishExits(),await W("bash-deadline","",e,Z,tt,i=>this.scan(e,t,i))}async scan(e,t,i){const a=new Set;for(const n of t.rows)if(n.status!=="dead"&&!H(n.profile_id)&&(a.add(n.node_id),!await y(await c(),n.node_id)))try{await this.adoptUnrecorded(n.node_id,await x(n.node_id))}catch(o){p.fresh(()=>{l({level:"error",event:"bash_deadline.scan_failed",...u(n.node_id)?{node_id:n.node_id}:{},error:o})})}for(const n of await K(await c(),e))if(a.has(n.owner)){if(!await i.holds())return;await this.cancel(n)}for(const n of a)try{await this.warnSilent(n,e)}catch(o){p.fresh(()=>{l({level:"error",event:"bash_silence.scan_failed",...u(n)?{node_id:n}:{},error:o})})}}async warnSilent(e,t){const i=$(),a=await y(await c(),e);for(const n of await M(await c(),e)){const o=n.activity??(a?{lastActivityMs:n.startedAtMs,sampledAtMs:t,files:[]}:null);if(n.quietOk||o===null||!a&&t-o.sampledAtMs>X)continue;const r=t-o.lastActivityMs,d=n.silence,I=Q(r,d?.lastActivityMs===o.lastActivityMs?d.thresholdMs:0,i);I!==null&&await f(async h=>{const w=await A(h,n.jobId);w===null||w.type!=="job"||(await z(h,w))?.status!=="running"||(await Y(h,{event:"silent",object:w,actor:null,attrs:{"silent-for":D(r),files:o.files.join(", "),"output-key":n.outputKey}}),await G(h,n.jobId,o.lastActivityMs,I))})}}async mirrorSupervisors(e){for(const t of e.rows)if(t.status!=="dead")try{const i=await M(await c(),t.node_id);if(i.length===0||await y(await c(),t.node_id))continue;const a=await x(t.node_id);for(const n of i)await this.mirror(a,n)}catch(i){p.fresh(()=>{l({level:"error",event:"bash_mirror.failed",...u(t.node_id)?{node_id:t.node_id}:{},error:i})})}}async mirror(e,t){const i=b(e,t.jobId),a=i.pgid??t.pgid??void 0,n=i.pgidIdentity??t.pgidIdentity??void 0,o=i.exitCode===void 0&&O(a,n)&&b(e,t.jobId).exitCode===void 0;i.deadlineMs!==void 0&&(t.deadlineAtMs===null&&await f(r=>V(r,t.jobId,i.deadlineMs)),T(g(e,t.jobId))),await this.uploadOutput(e,t),(i.exitCode!==void 0||o)&&this.uploadedBytes.delete(t.jobId),await f(async r=>k(r,t.jobId,{...i.pgid===void 0||i.pgid===t.pgid?{}:{pgid:i.pgid},...i.pgidIdentity===void 0||i.pgidIdentity===t.pgidIdentity?{}:{pgidIdentity:i.pgidIdentity},...i.activity===void 0?{}:{activity:i.activity},...i.exitCode===void 0?{}:{exitCode:i.exitCode},...o?{vanished:!0}:{}}))}async uploadOutput(e,t){const i=g(e,t.jobId);let a;try{a=S(i.jobLog).size}catch{return}const n=this.uploadedBytes.get(t.jobId)??0;if(a<=n)return;const o=await U(),r=N(i.root,i.jobLog);for(let d=Math.floor(n/m);d*m<r.length;d++)await o.put(`${t.outputKey}/${String(d).padStart(8,"0")}`,r.subarray(d*m,(d+1)*m));this.uploadedBytes.set(t.jobId,r.length)}async publishExits(){try{await f(async e=>{await F(e),await q(e)})}catch(e){p.fresh(()=>l({level:"error",event:"bash_completion.delivery_failed",error:e}))}}async adoptUnrecorded(e,t){let i;try{i=C(E(t))}catch{return}await f(async a=>{for(const n of i){if(await A(a,n)!==null)continue;const o=g(t,n);!v(o.jobBg)||!v(o.cmdSh)||v(o.jobExit)&&S(o.jobExit).mtimeMs<this.startedAt||await j(e,n,{command:B(o.cmdSh,"utf8")})}})}async cancel(e){const t=await y(await c(),e.owner);!t&&(e.pgid===null||e.pgidIdentity===null)||await p.fresh(async()=>{try{if(t||await R(e.pgid,e.pgidIdentity,e.owner),!await P(e.jobId,async()=>null,"deadline"))return;t&&await L(e.owner,e.jobId),l({level:"info",event:"bash_deadline.canceled",...u(e.owner)?{node_id:e.owner}:{},fields:{job_id:e.jobId}})}catch(i){l({level:"error",event:"bash_deadline.notice_failed",...u(e.owner)?{node_id:e.owner}:{},error:i,fields:{job_id:e.jobId}})}})}}export{vt as BashDeadlineReconciler,Q as dueSilenceThresholdMs};
1
+ var J=Object.defineProperty;var _=(s,e)=>J(s,"name",{value:e,configurable:!0});import{existsSync as v,readFileSync as B,readdirSync as C,statSync as S}from"node:fs";import{bashJobPaths as g,bashJobsDir as E,clearJobDeadlineFile as T,formatBashElapsed as D,isBashJobProcessConfirmedGone as O,readJobSupervisorState as b,signalBashJob as R}from"../../core/bash-jobs.js";import{queueJobStop as L}from"../cron/machine-fire.js";import{killBashJobObject as P,recordBashJobObject as j}from"../../core/spaces/stop.js";import{readFileBeneath as N}from"../../core/spaces/open-beneath.js";import{blobStore as U}from"../../core/blobs/index.js";import{openDb as c,withCanvasWrite as f}from"../../core/canvas/db.js";import{applyJobReport as k,endJobsOfExitedSandboxes as q,endReportedJobs as F,expiredJobs as K,jobRow as z,ownerRunsRemotely as y,recordJobSilence as G,runningJobs as M,setJobDeadline as V}from"../../core/graph/jobs.js";import{publish as Y}from"../../core/graph/events.js";import{envBashSilenceMs as $}from"../../shared/env.js";import{getById as A}from"../../core/graph/objects.js";import{isSafeNodeId as u}from"../../core/canvas/paths.js";import{contextDir as x}from"../../core/canvas/node-agent-paths.js";import{emitEvent as l}from"../../core/events/emit.js";import{operationIdContext as p}from"../../core/events/operation-id.js";import{isProfilePaused as H}from"../../core/profiles/manifest.js";import{runThrottledLane as W}from"./throttled-lane.js";const X=300*1e3;function Q(s,e,t){const i=s<t?0:s<2*t?t:s<4*t?2*t:4*t*Math.floor(s/(4*t));return i>e?i:null}_(Q,"dueSilenceThresholdMs");const Z=5*1e3,tt=60*1e3,m=64*1024;class vt{static{_(this,"BashDeadlineReconciler")}startedAt=Date.now();uploadedBytes=new Map;async run(e,t){await this.mirrorSupervisors(t),await this.publishExits(),await W("bash-deadline","",e,Z,tt,i=>this.scan(e,t,i))}async scan(e,t,i){const a=new Set;for(const n of t.rows)if(n.status!=="dead"&&!H(n.profile_id)&&(a.add(n.node_id),!await y(await c(),n.node_id)))try{await this.adoptUnrecorded(n.node_id,await x(n.node_id))}catch(o){p.fresh(()=>{l({level:"error",event:"bash_deadline.scan_failed",...u(n.node_id)?{node_id:n.node_id}:{},error:o})})}for(const n of await K(await c(),e))if(a.has(n.owner)){if(!await i.holds())return;await this.cancel(n)}for(const n of a)try{await this.warnSilent(n,e)}catch(o){p.fresh(()=>{l({level:"error",event:"bash_silence.scan_failed",...u(n)?{node_id:n}:{},error:o})})}}async warnSilent(e,t){const i=$(),a=await y(await c(),e);for(const n of await M(await c(),e)){const o=n.activity??(a?{lastActivityMs:n.startedAtMs,sampledAtMs:t,files:[]}:null);if(n.quietOk||o===null||!a&&t-o.sampledAtMs>X)continue;const r=t-o.lastActivityMs,d=n.silence,I=Q(r,d?.lastActivityMs===o.lastActivityMs?d.thresholdMs:0,i);I!==null&&await f(async h=>{const w=await A(h,n.jobId);w===null||w.type!=="job"||(await z(h,w))?.status!=="running"||(await Y(h,{event:"silent",object:w,actor:null,attrs:{"silent-for":D(r),files:o.files.join(", "),"output-key":n.outputKey}}),await G(h,n.jobId,o.lastActivityMs,I))})}}async mirrorSupervisors(e){for(const t of e.rows)if(t.status!=="dead")try{const i=await M(await c(),t.node_id);if(i.length===0||await y(await c(),t.node_id))continue;const a=await x(t.node_id);for(const n of i)await this.mirror(a,n)}catch(i){p.fresh(()=>{l({level:"error",event:"bash_mirror.failed",...u(t.node_id)?{node_id:t.node_id}:{},error:i})})}}async mirror(e,t){const i=b(e,t.jobId),a=i.pgid??t.pgid??void 0,n=i.pgidIdentity??t.pgidIdentity??void 0,o=process.platform!=="linux"&&i.exitCode===void 0&&O(a,n)&&b(e,t.jobId).exitCode===void 0;i.deadlineMs!==void 0&&(t.deadlineAtMs===null&&await f(r=>V(r,t.jobId,i.deadlineMs)),T(g(e,t.jobId))),await this.uploadOutput(e,t),(i.exitCode!==void 0||o)&&this.uploadedBytes.delete(t.jobId),await f(async r=>k(r,t.jobId,{...i.pgid===void 0||i.pgid===t.pgid?{}:{pgid:i.pgid},...i.pgidIdentity===void 0||i.pgidIdentity===t.pgidIdentity?{}:{pgidIdentity:i.pgidIdentity},...i.activity===void 0?{}:{activity:i.activity},...i.exitCode===void 0?{}:{exitCode:i.exitCode},...o?{vanished:!0}:{}}))}async uploadOutput(e,t){const i=g(e,t.jobId);let a;try{a=S(i.jobLog).size}catch{return}const n=this.uploadedBytes.get(t.jobId)??0;if(a<=n)return;const o=await U(),r=N(i.root,i.jobLog);for(let d=Math.floor(n/m);d*m<r.length;d++)await o.put(`${t.outputKey}/${String(d).padStart(8,"0")}`,r.subarray(d*m,(d+1)*m));this.uploadedBytes.set(t.jobId,r.length)}async publishExits(){try{await f(async e=>{await F(e),await q(e)})}catch(e){p.fresh(()=>l({level:"error",event:"bash_completion.delivery_failed",error:e}))}}async adoptUnrecorded(e,t){let i;try{i=C(E(t))}catch{return}await f(async a=>{for(const n of i){if(await A(a,n)!==null)continue;const o=g(t,n);!v(o.jobBg)||!v(o.cmdSh)||v(o.jobExit)&&S(o.jobExit).mtimeMs<this.startedAt||await j(e,n,{command:B(o.cmdSh,"utf8")})}})}async cancel(e){const t=await y(await c(),e.owner);!t&&(e.pgid===null||e.pgidIdentity===null)||await p.fresh(async()=>{try{if(t||await R(e.pgid,e.pgidIdentity,e.owner),!await P(e.jobId,async()=>null,"deadline"))return;t&&await L(e.owner,e.jobId),l({level:"info",event:"bash_deadline.canceled",...u(e.owner)?{node_id:e.owner}:{},fields:{job_id:e.jobId}})}catch(i){l({level:"error",event:"bash_deadline.notice_failed",...u(e.owner)?{node_id:e.owner}:{},error:i,fields:{job_id:e.jobId}})}})}}export{vt as BashDeadlineReconciler,Q as dueSilenceThresholdMs};
@@ -1 +1 @@
1
- var I=Object.defineProperty;var l=(e,t)=>I(e,"name",{value:t,configurable:!0});import{spawn as T}from"node:child_process";import{statSync as j}from"node:fs";import{delimiter as R,join as b}from"node:path";import{getRow as G,listNodes as C}from"../../core/canvas/index.js";import{isSafeNodeId as E}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as x,recordedPidLiveness as L}from"../../core/canvas/pid.js";import{emitEvent as m}from"../../core/events/emit.js";import{operationIdContext as y}from"../../core/events/operation-id.js";import{isParked as P}from"../../core/runtime/lifecycle.js";import{runThrottledLane as M}from"./throttled-lane.js";const O=60*1e3,V=3,B=300*1e3,W=300*1e3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)&&!P(e)}l(g,"isClosed");function k(){const e=process.env.PATH;if(e===void 0)return null;for(const t of e.split(R)){const o=b(t===""?process.cwd():t,"grove");try{const r=j(o);if(r.isFile()&&(r.mode&73)!==0)return o}catch{}}return null}l(k,"resolveGroveBinary");function D(e,t){return new Promise(o=>{let r;try{r=T(e,[...t],{stdio:["ignore","pipe","pipe"]})}catch(i){o({code:null,signal:null,stdout:"",stderr:"",error:i instanceof Error?i:new Error(String(i))});return}let s="",d="",a=!1;const u=l(i=>{a||(a=!0,o(i))},"settle");r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{d+=i.toString()}),r.on("error",i=>u({code:null,signal:null,stdout:s,stderr:d,error:i})),r.on("close",(i,c)=>u({code:i,signal:c,stdout:s,stderr:d}))})}l(D,"executeGrove");const F={resolveBinary:k,listTerminalNodes:l(async()=>await C({status:[...N]}),"listTerminalNodes"),getNodeRow:G,execute:D,captureLiveness:x};function Y(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||!Array.isArray(t.projects))return null;const o=[];for(const r of t.projects){if(typeof r!="object"||r===null)continue;const s=r.name,d=r.instances;if(!(typeof s!="string"||!Array.isArray(d)))for(const a of d){if(typeof a!="object"||a===null)continue;const u=a.name,i=a.slot,c=a.spec?.labels,p=typeof c=="object"&&c!==null?c.owner:void 0;typeof u=="string"&&typeof i=="number"&&typeof p=="string"&&o.push({project:s,name:u,slot:i,owner:p})}}return o}l(Y,"instancesFromInventory");async function $(e,t,o){return g(e)&&!await t.isClaimed(e.node_id)&&e.frozen_at===null&&L(e.pi_pid,e.pi_pid_identity,o)==="dead"}l($,"engineIsGone");async function z(e,t,o){if(await t.isClaimed(e.node_id))return!1;const r=await o(e.node_id);return r!==null&&g(r)&&r.frozen_at===null&&r.pi_pid===e.pi_pid&&r.pi_pid_identity===e.pi_pid_identity}l(z,"stillEligible");function S(e){if(e.error!==void 0)return e.error;const t=e.stderr.trim()||e.stdout.trim()||`Grove exited with ${e.signal??e.code??"an unknown status"}`;return new Error(t)}l(S,"executionError");function h(e){return`${e.project}/${e.name}`}l(h,"instanceKey");class ne{static{l(this,"GroveInstanceSweepReconciler")}operations;retryAfter=new Map;constructor(t=F){this.operations=t}run(t,o){if(!o.lifecycle.acceptsDetachedWork())return;const r=M("grove-instance-sweep","",t,O,B,s=>this.sweep(t,o.fleet,s)).then(()=>{}).catch(s=>{y.fresh(()=>m({level:"error",event:"grove.sweep.failed",error:s}))});o.lifecycle.registerDetached(r)}async sweep(t,o,r){const s=this.operations.resolveBinary();if(s===null)return;let d;try{d=(await this.operations.listTerminalNodes()).filter(g)}catch(n){y.fresh(()=>{m({level:"error",event:"grove.sweep.scan_failed",error:n})});return}if(d.length===0)return;const a=await this.operations.execute(s,["list","--json"]);if(a.error!==void 0||a.code!==0||a.signal!==null){y.fresh(()=>{m({level:"error",event:"grove.sweep.list_failed",error:S(a)})});return}const u=Y(a.stdout);if(u===null){y.fresh(()=>{m({level:"error",event:"grove.sweep.list_failed",error:new Error("grove list --json returned invalid inventory JSON")})});return}const i=new Map(d.map(n=>[n.node_id,n])),c=u.filter(n=>i.get(n.owner)!==void 0&&(this.retryAfter.get(h(n))??Number.NEGATIVE_INFINITY)<=t).sort((n,f)=>n.project.localeCompare(f.project)||n.slot-f.slot||n.name.localeCompare(f.name));if(c.length===0)return;let p=Number(r.state??0);(!Number.isInteger(p)||p>=c.length)&&(p=0);const v=Math.min(V,c.length),A=Array.from({length:v},(n,f)=>c[(p+f)%c.length]);if(!await r.save(String((p+v)%c.length)))return;const w=await this.operations.captureLiveness();if(w!==null)for(const n of A){const f=i.get(n.owner);if(!await $(f,o,w)||!await z(f,o,this.operations.getNodeRow))continue;if(!await r.holds())return;const _=await this.operations.execute(s,["uproot",h(n),"--force"]);if(_.error===void 0&&_.code===0&&_.signal===null){this.retryAfter.delete(h(n)),y.fresh(()=>{m({level:"info",event:"grove.sweep.reconciled",outcome:"succeeded",...E(n.owner)?{node_id:n.owner}:{fields:{affected_node_id:n.owner}}})});continue}this.retryAfter.set(h(n),t+W),y.fresh(()=>{m({level:"error",event:"grove.sweep.failed",outcome:"failed",...E(n.owner)?{node_id:n.owner}:{fields:{affected_node_id:n.owner}},error:S(_)})})}}}export{V as GROVE_INSTANCE_SWEEP_BUDGET,O as GROVE_INSTANCE_SWEEP_INTERVAL_MS,W as GROVE_INSTANCE_SWEEP_RETRY_DELAY_MS,ne as GroveInstanceSweepReconciler};
1
+ var I=Object.defineProperty;var l=(e,t)=>I(e,"name",{value:t,configurable:!0});import{spawn as T}from"node:child_process";import{statSync as j}from"node:fs";import{delimiter as R,join as b}from"node:path";import{getRow as G,listNodes as C}from"../../core/canvas/index.js";import{isSafeNodeId as E}from"../../core/canvas/paths.js";import{captureLivenessSnapshotAsync as x,recordedPidLiveness as L}from"../../core/canvas/pid.js";import{emitEvent as m}from"../../core/events/emit.js";import{operationIdContext as y}from"../../core/events/operation-id.js";import{isParked as P}from"../../core/runtime/lifecycle.js";import{runThrottledLane as M}from"./throttled-lane.js";const O=60*1e3,V=3,B=300*1e3,W=300*1e3,N=["done","dead","canceled"];function g(e){return N.includes(e.status)&&!P(e)}l(g,"isClosed");function k(){const e=process.env.PATH;if(e===void 0)return null;for(const t of e.split(R)){const o=b(t===""?".":t,"grove");try{const r=j(o);if(r.isFile()&&(r.mode&73)!==0)return o}catch{}}return null}l(k,"resolveGroveBinary");function D(e,t){return new Promise(o=>{let r;try{r=T(e,[...t],{stdio:["ignore","pipe","pipe"]})}catch(i){o({code:null,signal:null,stdout:"",stderr:"",error:i instanceof Error?i:new Error(String(i))});return}let s="",d="",a=!1;const u=l(i=>{a||(a=!0,o(i))},"settle");r.stdout.on("data",i=>{s+=i.toString()}),r.stderr.on("data",i=>{d+=i.toString()}),r.on("error",i=>u({code:null,signal:null,stdout:s,stderr:d,error:i})),r.on("close",(i,c)=>u({code:i,signal:c,stdout:s,stderr:d}))})}l(D,"executeGrove");const F={resolveBinary:k,listTerminalNodes:l(async()=>await C({status:[...N]}),"listTerminalNodes"),getNodeRow:G,execute:D,captureLiveness:x};function Y(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||!Array.isArray(t.projects))return null;const o=[];for(const r of t.projects){if(typeof r!="object"||r===null)continue;const s=r.name,d=r.instances;if(!(typeof s!="string"||!Array.isArray(d)))for(const a of d){if(typeof a!="object"||a===null)continue;const u=a.name,i=a.slot,c=a.spec?.labels,p=typeof c=="object"&&c!==null?c.owner:void 0;typeof u=="string"&&typeof i=="number"&&typeof p=="string"&&o.push({project:s,name:u,slot:i,owner:p})}}return o}l(Y,"instancesFromInventory");async function $(e,t,o){return g(e)&&!await t.isClaimed(e.node_id)&&e.frozen_at===null&&L(e.pi_pid,e.pi_pid_identity,o)==="dead"}l($,"engineIsGone");async function z(e,t,o){if(await t.isClaimed(e.node_id))return!1;const r=await o(e.node_id);return r!==null&&g(r)&&r.frozen_at===null&&r.pi_pid===e.pi_pid&&r.pi_pid_identity===e.pi_pid_identity}l(z,"stillEligible");function S(e){if(e.error!==void 0)return e.error;const t=e.stderr.trim()||e.stdout.trim()||`Grove exited with ${e.signal??e.code??"an unknown status"}`;return new Error(t)}l(S,"executionError");function h(e){return`${e.project}/${e.name}`}l(h,"instanceKey");class ne{static{l(this,"GroveInstanceSweepReconciler")}operations;retryAfter=new Map;constructor(t=F){this.operations=t}run(t,o){if(!o.lifecycle.acceptsDetachedWork())return;const r=M("grove-instance-sweep","",t,O,B,s=>this.sweep(t,o.fleet,s)).then(()=>{}).catch(s=>{y.fresh(()=>m({level:"error",event:"grove.sweep.failed",error:s}))});o.lifecycle.registerDetached(r)}async sweep(t,o,r){const s=this.operations.resolveBinary();if(s===null)return;let d;try{d=(await this.operations.listTerminalNodes()).filter(g)}catch(n){y.fresh(()=>{m({level:"error",event:"grove.sweep.scan_failed",error:n})});return}if(d.length===0)return;const a=await this.operations.execute(s,["list","--json"]);if(a.error!==void 0||a.code!==0||a.signal!==null){y.fresh(()=>{m({level:"error",event:"grove.sweep.list_failed",error:S(a)})});return}const u=Y(a.stdout);if(u===null){y.fresh(()=>{m({level:"error",event:"grove.sweep.list_failed",error:new Error("grove list --json returned invalid inventory JSON")})});return}const i=new Map(d.map(n=>[n.node_id,n])),c=u.filter(n=>i.get(n.owner)!==void 0&&(this.retryAfter.get(h(n))??Number.NEGATIVE_INFINITY)<=t).sort((n,f)=>n.project.localeCompare(f.project)||n.slot-f.slot||n.name.localeCompare(f.name));if(c.length===0)return;let p=Number(r.state??0);(!Number.isInteger(p)||p>=c.length)&&(p=0);const v=Math.min(V,c.length),A=Array.from({length:v},(n,f)=>c[(p+f)%c.length]);if(!await r.save(String((p+v)%c.length)))return;const w=await this.operations.captureLiveness();if(w!==null)for(const n of A){const f=i.get(n.owner);if(!await $(f,o,w)||!await z(f,o,this.operations.getNodeRow))continue;if(!await r.holds())return;const _=await this.operations.execute(s,["uproot",h(n),"--force"]);if(_.error===void 0&&_.code===0&&_.signal===null){this.retryAfter.delete(h(n)),y.fresh(()=>{m({level:"info",event:"grove.sweep.reconciled",outcome:"succeeded",...E(n.owner)?{node_id:n.owner}:{fields:{affected_node_id:n.owner}}})});continue}this.retryAfter.set(h(n),t+W),y.fresh(()=>{m({level:"error",event:"grove.sweep.failed",outcome:"failed",...E(n.owner)?{node_id:n.owner}:{fields:{affected_node_id:n.owner}},error:S(_)})})}}}export{V as GROVE_INSTANCE_SWEEP_BUDGET,O as GROVE_INSTANCE_SWEEP_INTERVAL_MS,W as GROVE_INSTANCE_SWEEP_RETRY_DELAY_MS,ne as GroveInstanceSweepReconciler};
@@ -1,6 +1,7 @@
1
- var M=Object.defineProperty;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{openDb as d,withCanvasWrite as C}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as R,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as D}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as N}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as g,emitRunSettlement as T,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",E=1e4,Y=250;async function w(t,e,i){return await C(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,t,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await i()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,i,n,s,r){this.nodeId=e,this.runId=i,this.owner=n,this.status=s,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,i,n){const s=await d(),r=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===i?"node.settled":"child.settled"),a=await s.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),o=new v(e,i,n,a?JSON.parse(a.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await o.writeStream(null,null),await o.poll(),o}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<E/3?!0:await x(c,this.nodeId,this.owner,E)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,i,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
2
- WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],i===null?null:JSON.stringify(i),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await D(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const i=e.pi_pid===null?"dormant":e.status;if(this.status!==i){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,i,e.intent??null))).held){this.close();return}this.status=i}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const a=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const o of a)await L(o.node_id,this.runId),await p.get(o.node_id)?.poll()}this.outcomeRevision=n.revision;const s=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?T(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...s===void 0?{}:{result:s}}):T(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const a=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(a,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(o=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:o}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await N(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await $(this.nodeId),i=await this.viewAdmitted();if(this.client||this.closed||!i){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:y(),attends:!1}));const s=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const a=r.message.content;if(!Array.isArray(a))return;const o=a.at(-1);if(o&&typeof o=="object"&&"type"in o&&(o.type==="toolCall"?this.block={kind:"tool_call",name:"name"in o&&typeof o.name=="string"?o.name:""}:(o.type==="text"||o.type==="thinking")&&(this.block={kind:o.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const f=a.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),m=a.filter(u=>u?.type==="text").map(u=>u.text).join(""),k=f.startsWith(this.thinking)?f.slice(this.thinking.length):f,b=m.startsWith(this.output)?m.slice(this.output.length):m;this.thinking=f,this.output=m,this.pendingThinking+=k,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>s(r)).catch(a=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:a})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,i=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!i)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await g(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),i&&await g(this.runId,this.nodeId,"node.output_text.delta",{delta:i})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await R(c,this.nodeId,this.owner)}).then(()=>{}).catch(i=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:i})});const e=this.client;this.client=void 0,e?.close()}}async function $(t){const e=await N(t);if(e===null)return new O(t,{recordsViewerFaults:!1});const i=await W(e.runner).viewerAddress(e);return i.kind==="machine"?new A(t,()=>U(i.environmentId,t)):i.kind==="unix"?new O(t,{recordsViewerFaults:!1}):new A(t,()=>q(i.url,i.headers))}l($,"viewTransport");async function pe(t){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function fe(t){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(t);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(fe,"openAssistantBlock");async function me(){const t=[...p.values()];for(const e of t)e.close();await Promise.all(t.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(me,"closeRunObserversForTests");async function I(t){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(t,t)!==void 0}l(I,"runRootExists");const _=new Map;async function L(t,e){const i=_.get(t);if(i)return i;if(p.has(t))return;const n=Q(t,e).finally(()=>_.delete(t));return _.set(t,n),n}l(L,"ensureRunObserver");async function Q(t,e){if(!await I(e))return;const i=y();if(await F(c,t,i,E)!==void 0)try{if(t!==e){const n=await D(t);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,t)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(t,i,()=>g(e,t,"child.started",{child_node_id:t,kind:n.kind}))).held)return}await v.start(t,e,i)}catch(n){throw await R(c,t,i).catch(()=>{}),n}}l(Q,"startRunObserver");async function we(){const t=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id, n.pi_pid, COALESCE(n.outcome_revision, 1) AS revision, e.body_json
1
+ var C=Object.defineProperty;var l=(i,e)=>C(i,"name",{value:e,configurable:!0});import{randomUUID as R}from"node:crypto";import{openDb as d,withCanvasWrite as M}from"../../core/canvas/db.js";import{claimReconcilerLease as F,releaseReconcilerLease as D,renewReconcilerLease as x}from"../../core/canvas/reconciler-leases.js";import{getNode as y}from"../../core/canvas/canvas.js";import{BrokerClient as H,SocketTransport as O}from"../../core/broker-client/client.js";import{liveExecutionForNode as T}from"../../core/canvas/executions.js";import{runnerForExecution as W}from"../../core/runtime/runner/index.js";import{connectWssView as q}from"../../core/runtime/view-socket.js";import{openMachineView as U}from"../machine-link/forward.js";import{ViewLinkTransport as A}from"./view-transport.js";import{emitRunEvent as E,emitRunSettlement as N,emitRunStatus as j}from"../../core/runs/events.js";import{cancelOpenQuestions as P}from"../../core/runs/questions.js";import{emitEvent as h}from"../../core/events/emit.js";import{runUsage as V}from"../../core/ledger/index.js";import{toRunOutcomeDTO as B}from"../api/map.js";import{readOutputResult as J}from"../../core/runtime/output-result.js";const p=new Map,c="run-observer",g=1e4,Y=250;async function w(i,e,t){return await M(async n=>await n.prepare("SELECT 1 AS held FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ? FOR SHARE").get(c,i,e,new Date().toISOString())===void 0?{held:!1}:{held:!0,value:await t()})}l(w,"whileHoldingLease");class v{static{l(this,"RunObserver")}nodeId;runId;owner;client;timer;status;piPid=null;outcomeRevision;openAssistant=!1;assistantStartSequence=0;block=null;thinking="";output="";pendingThinking="";pendingOutput="";flushTimer;closed=!1;lastRenewAt=Date.now();released=Promise.resolve();polling;frames=Promise.resolve();constructor(e,t,n,a,r){this.nodeId=e,this.runId=t,this.owner=n,this.status=a,this.outcomeRevision=r,this.timer=setInterval(()=>{this.pollOrClose()},250),this.timer.unref(),p.set(e,this)}static async start(e,t,n){const a=await d(),r=await a.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = ? ORDER BY sequence_number DESC LIMIT 1").get(e,e===t?"node.settled":"child.settled"),o=await a.prepare("SELECT body_json FROM run_events WHERE node_id = ? AND type = 'node.status.changed' ORDER BY sequence_number DESC LIMIT 1").get(e),s=new v(e,t,n,o?JSON.parse(o.body_json).status:void 0,r?JSON.parse(r.body_json).outcome.revision:void 0);return await s.writeStream(null,null),await s.poll(),s}async pollOrClose(){try{await this.poll()}catch(e){this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:e})}}poll(){return this.polling===void 0&&(this.polling=this.pollOnce().finally(()=>{this.polling=void 0})),this.polling}async holdLease(){return Date.now()-this.lastRenewAt<g/3?!0:await x(c,this.nodeId,this.owner,g)?(this.lastRenewAt=Date.now(),!0):!1}async writeStream(e,t,n=!1){return(await(await d()).prepare(`UPDATE nodes SET ${n?"":`stream_message_seq = ${e===null?"NULL":"(SELECT event_cursor FROM nodes WHERE node_id = ?)"},`} stream_block = ?
2
+ WHERE node_id = ? AND EXISTS (SELECT 1 FROM reconciler_leases WHERE lane = ? AND key = ? AND owner = ? AND expires_at > ?)`).run(...e===null||n?[]:[this.runId],t===null?null:JSON.stringify(t),this.nodeId,c,this.nodeId,this.owner,new Date().toISOString())).changes===1}async pollOnce(){if(this.closed)return;if(!await this.holdLease()){this.close();return}const e=await y(this.nodeId);if(!e||e.run_id!==this.runId||!await I(this.runId)){this.close();return}this.piPid=e.pi_pid??null;const t=e.pi_pid===null?"dormant":e.status;if(this.status!==t){if(!(await w(this.nodeId,this.owner,()=>j(this.runId,this.nodeId,t,e.intent??null))).held){this.close();return}this.status=t}const n=await B(e);if(n&&n.revision!==this.outcomeRevision&&Date.now()-Date.parse(n.settled_at)<720*60*6e4){if(this.nodeId===this.runId){const o=await(await d()).prepare("SELECT node_id FROM nodes WHERE run_id = ? AND node_id != ? ORDER BY created DESC").all(this.runId,this.runId);for(const s of o)await k(s.node_id,this.runId),await p.get(s.node_id)?.poll()}this.outcomeRevision=n.revision;const a=this.nodeId===this.runId&&n.kind==="result"?await J(this.nodeId):void 0;if(!(await w(this.nodeId,this.owner,async()=>this.nodeId===this.runId?N(this.runId,this.nodeId,"node.settled",{outcome:n,usage:await V(this.runId),...a===void 0?{}:{result:a}}):N(this.runId,this.nodeId,"child.settled",{child_node_id:this.nodeId,outcome:n}))).held){this.close();return}if(e.grantee&&e.grantee!=="app:terminal"){const o=this.nodeId===this.runId?{run_id:this.runId}:{node_id:this.nodeId};P(o,this.nodeId===this.runId?"the run settled":"the asking node was closed").catch(s=>h({level:"error",event:"daemon.runs.question_cancel_failed",node_id:this.nodeId,error:s}))}}e.pi_pid===null?this.close():await this.connect()}async settlePoll(){await this.polling?.catch(()=>{}),await this.frames,await this.released}async viewAdmitted(){const e=await T(this.nodeId);return!(e?.runner==="blaxel"&&e.idleAt!==null)}async dropView(){const e=this.client;e&&(this.client=void 0,await this.frames,await this.flushDeltas(),this.discardDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null),e.close())}async connect(){if(this.closed)return;if(!await this.viewAdmitted()){await this.dropView();return}if(this.client)return;const e=await X(this.nodeId),t=await this.viewAdmitted();if(this.client||this.closed||!t){e.destroy();return}const n=new H(this.nodeId,{transport:e});this.client=n,n.on("connect",()=>n.send({type:"hello",role:"observer",client_id:R(),attends:!1}));const a=l(async r=>{if(!(this.closed||this.client!==n)){if(r.type==="message_start"&&r.message.role==="assistant"){if(this.discardDeltas(),this.openAssistant=!0,this.block=null,this.thinking="",this.output="",!await this.writeStream("run-cursor",null)){this.close();return}this.assistantStartSequence=Number((await(await d()).prepare("SELECT stream_message_seq FROM nodes WHERE node_id = ?").get(this.nodeId)).stream_message_seq)}if(r.type==="message_update"&&r.message.role==="assistant"&&this.openAssistant){const o=r.message.content;if(!Array.isArray(o))return;const s=o.at(-1);if(s&&typeof s=="object"&&"type"in s&&(s.type==="toolCall"?this.block={kind:"tool_call",name:"name"in s&&typeof s.name=="string"?s.name:""}:(s.type==="text"||s.type==="thinking")&&(this.block={kind:s.type})),!await this.writeStream(null,this.block,!0)){this.close();return}const m=o.filter(u=>u?.type==="thinking").map(u=>u.thinking).join(""),f=o.filter(u=>u?.type==="text").map(u=>u.text).join(""),L=m.startsWith(this.thinking)?m.slice(this.thinking.length):m,b=f.startsWith(this.output)?f.slice(this.output.length):f;this.thinking=m,this.output=f,this.pendingThinking+=L,this.pendingOutput+=b,(this.pendingThinking||this.pendingOutput)&&!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushDeltas().catch(u=>h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:u}))},Y),this.flushTimer.unref())}r.type==="message_end"&&r.message.role==="assistant"&&(await this.flushDeltas(),this.openAssistant=!1,this.block=null,await this.writeStream(null,null))}},"handleFrame");n.on("frame",r=>{this.frames=this.frames.then(()=>a(r)).catch(o=>{this.close(),h({level:"error",event:"daemon.runs.observer_failed",node_id:this.nodeId,error:o})})}),n.on("error",()=>{}),n.on("close",()=>{this.client===n&&(this.client=void 0,this.discardDeltas(),this.openAssistant=!1,this.block=null,this.released=this.released.then(async()=>{await this.writeStream(null,null)}).catch(()=>{}))}),n.connect()}async flushDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0;const e=this.pendingThinking,t=this.pendingOutput;if(this.pendingThinking="",this.pendingOutput="",!this.openAssistant||!e&&!t)return;(await w(this.nodeId,this.owner,async()=>{if(await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND sequence_number >= ? AND type IN ('node.output_text.done', 'node.thinking.done', 'usage') LIMIT 1").get(this.runId,this.nodeId,this.assistantStartSequence)){this.openAssistant=!1;return}e&&await E(this.runId,this.nodeId,"node.thinking.delta",{delta:e}),t&&await E(this.runId,this.nodeId,"node.output_text.delta",{delta:t})})).held||this.close()}discardDeltas(){this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.pendingThinking="",this.pendingOutput=""}close(){if(this.closed)return;this.closed=!0,this.discardDeltas(),clearInterval(this.timer),p.delete(this.nodeId),this.released=this.released.then(async()=>{await this.writeStream(null,null),await D(c,this.nodeId,this.owner)}).then(()=>{}).catch(t=>{h({level:"error",event:"daemon.runs.observer_release_failed",node_id:this.nodeId,error:t})});const e=this.client;this.client=void 0,e?.close()}}async function X(i){const e=await T(i);if(e===null)return new O(i,{recordsViewerFaults:!1});const t=await W(e.runner).viewerAddress(e);return t.kind==="machine"?new A(i,()=>U(t.environmentId,i)):t.kind==="unix"?new O(i,{recordsViewerFaults:!1}):new A(i,()=>q(t.url,t.headers))}l(X,"viewTransport");async function pe(i){const e=await(await d()).prepare("SELECT stream_message_seq FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(i);return e?.stream_message_seq==null?null:Number(e.stream_message_seq)}l(pe,"openAssistantMessageStartSequence");async function me(i){const e=await(await d()).prepare("SELECT stream_message_seq, stream_block FROM node_rows WHERE node_id = ? AND pi_pid IS NOT NULL").get(i);return e?.stream_message_seq==null||e.stream_block===null?null:JSON.parse(e.stream_block)}l(me,"openAssistantBlock");async function fe(){const i=[...p.values()];for(const e of i)e.close();await Promise.all(i.map(e=>e.settlePoll())),await Promise.all([..._.values()].map(e=>e.catch(()=>{})))}l(fe,"closeRunObserversForTests");async function I(i){return await(await d()).prepare("SELECT 1 FROM nodes WHERE node_id = ? AND run_id = ? AND event_cursor IS NOT NULL").get(i,i)!==void 0}l(I,"runRootExists");const _=new Map;async function k(i,e){const t=_.get(i);if(t)return t;if(p.has(i))return;const n=$(i,e).finally(()=>_.delete(i));return _.set(i,n),n}l(k,"ensureRunObserver");async function $(i,e){if(!await I(e))return;const t=R();if(await F(c,i,t,g)!==void 0)try{if(i!==e){const n=await y(i);if(!await(await d()).prepare("SELECT 1 FROM run_events WHERE run_id = ? AND node_id = ? AND type = 'child.started' LIMIT 1").get(e,i)&&n&&Date.now()-Date.parse(n.created)<720*60*6e4&&!(await w(i,t,()=>E(e,i,"child.started",{child_node_id:i,kind:n.kind}))).held)return}await v.start(i,e,t)}catch(n){throw await D(c,i,t).catch(()=>{}),n}}l($,"startRunObserver");async function we(){const i=new Date(Date.now()-2592e6).toISOString(),e=await(await d()).prepare(`SELECT n.node_id, n.run_id
3
3
  FROM node_rows n
4
- LEFT JOIN run_events e ON n.pi_pid IS NULL AND e.run_id = n.run_id AND e.node_id = n.node_id
5
- AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
6
- WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'))`).all(t),i=new Map;for(const s of e){const r=i.get(s.node_id)??{node_id:s.node_id,run_id:s.run_id,reported:!1};s.body_json!==null&&JSON.parse(s.body_json).outcome?.revision===s.revision&&(r.reported=!0),i.set(s.node_id,r)}const n=[...i.values()].filter(s=>!s.reported);for(const s of n)try{await L(s.node_id,s.run_id),S.delete(s.node_id)}catch(r){X(s.node_id,r)}}l(we,"pollRunObservers");const S=new Map;function X(t,e){const i=e instanceof Error?e.message:String(e);S.get(t)!==i&&(S.set(t,i),h({level:"error",event:"daemon.runs.observer_failed",node_id:t,error:e}))}l(X,"reportObserverFailure");export{me as closeRunObserversForTests,L as ensureRunObserver,fe as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,$ as viewTransport};
4
+ WHERE n.run_id IS NOT NULL AND (n.pi_pid IS NOT NULL OR (n.outcome_at IS NOT NULL AND n.outcome_at > ? AND n.outcome_reason != 'parked'
5
+ AND NOT EXISTS (SELECT 1 FROM run_events e WHERE e.run_id = n.run_id AND e.node_id = n.node_id
6
+ AND e.type = CASE WHEN n.node_id = n.run_id THEN 'node.settled' ELSE 'child.settled' END
7
+ AND (e.body_json::json #>> '{outcome,revision}') = COALESCE(n.outcome_revision, 1)::text)))`).all(i);for(const t of e)try{await k(t.node_id,t.run_id),S.delete(t.node_id)}catch(n){Q(t.node_id,n)}}l(we,"pollRunObservers");const S=new Map;function Q(i,e){const t=e instanceof Error?e.message:String(e);S.get(i)!==t&&(S.set(i,t),h({level:"error",event:"daemon.runs.observer_failed",node_id:i,error:e}))}l(Q,"reportObserverFailure");export{fe as closeRunObserversForTests,k as ensureRunObserver,me as openAssistantBlock,pe as openAssistantMessageStartSequence,we as pollRunObservers,X as viewTransport};
@@ -1,7 +1,7 @@
1
- var fe=Object.defineProperty;var o=(e,n)=>fe(e,"name",{value:n,configurable:!0});import{envBashAutoBgDeadlineMs as q,envBashValveMs as he,envNodeId as be}from"../shared/env.js";import{closeSync as me,existsSync as v,mkdirSync as X,openSync as pe,readFileSync as Y,readSync as ge,rmSync as Q,statSync as Z,writeFileSync as M}from"node:fs";import{homedir as we}from"node:os";import{dirname as ye}from"node:path";import{performance as N}from"node:perf_hooks";import{backgroundBashJob as ee,bashJobPaths as ve,clearJobDeadlineFile as Ee,writeJobDeadlineFile as _e,cancelBashJobProcessTree as je,countJobLogLines as Se,formatBashElapsed as te,newBashJobId as ke,normalizeBashJobPurpose as Ie,tailJobLog as Ae}from"../core/bash-jobs.js";import{MAX_BACKGROUND_BASH_LOG_BYTES as gt,BACKGROUND_BASH_LOG_TRUNCATION_MARKER as wt}from"../core/bash-job-supervisor.js";import{brokerApiUrl as Be,recordBackgroundedJob as Le,reportBrokerJob as xe,stopBrokerBashJob as Oe}from"../core/runtime/broker/daemon-ops.js";import{bashJobsUseLauncher as Te,launchBashJobSupervisor as Je}from"../core/runtime/broker/bash-job-launch.js";import{JobReporter as Re}from"../core/runtime/broker/job-reporter.js";import{bashCommandRefusal as $e}from"../core/bash-guard.js";import{readConfig as Me}from"../core/config.js";import{PREVIEW_RESULT_PATH_ENV as Ne,previewResultPath as Ce}from"../core/preview-result-path.js";import{Type as S}from"typebox";import{createBashToolDefinition as ne}from"@earendil-works/pi-coding-agent";const oe=200,De=5e3;function Pe(){return he()}o(Pe,"resolveValveMs");function Ue(e){return ve(e,ke())}o(Ue,"makeJobPaths");const k=new Set;let re=!1;function ie(){for(const e of[...k])try{ee(e),k.delete(e)}catch(n){process.stderr.write(`crtr: failed to background bash job ${e.jobId} during broker termination: ${n.message}
2
- `)}}o(ie,"backgroundLiveJobsForTermination");function Fe(){re||(re=!0,process.prependListener("SIGTERM",ie),process.platform!=="win32"&&process.prependListener("SIGHUP",ie))}o(Fe,"installTerminationHandoff");const Ge=64*1024;function C(e,n,i){let s;try{s=Z(e)}catch{return n}if(s.size<=n)return n;const c=pe(e,"r");try{for(;n<s.size;){const b=Math.min(Ge,s.size-n),m=Buffer.allocUnsafe(b),u=ge(c,m,0,b,n);if(u===0)break;i(m.subarray(0,u)),n+=u}return n}finally{me(c)}}o(C,"tailOnce");function E(e){try{Q(e,{recursive:!0,force:!0})}catch{}}o(E,"cleanupJobDir");function He(e){try{const n=Y(e,"utf8").trim(),i=Number(n);return Number.isFinite(i)?i:null}catch{return null}}o(He,"readExitCode");function Ve(e){try{if(Z(e).isDirectory())return{cwd:e}}catch{}const n=we();return{cwd:n,warning:`[working directory no longer exists: ${e}; running from ${n}]
3
- `}}o(Ve,"resolveExecutionCwd");function se(e,n,i=()=>null,s,c=()=>{}){return{exec:o(async(b,m,{onData:u,signal:f,timeout:p,env:I})=>new Promise((_,d)=>{const w=i();if(f?.aborted){d(new Error("aborted"));return}const A=$e(b,m);if(A!==null){d(new Error(A));return}const t=Ue(n);X(t.dir,{recursive:!0}),M(t.cmdSh,b),M(t.jobLog,""),M(t.jobRun,"");let l=0,g=!1,j,B,L,D=!1;const ae=Te(),P=N.now();let U=0,x=P;const F=o(()=>N.now()-P-U,"foregroundMs"),ce=Pe();let y;const ue=o(()=>{y&&clearInterval(y),f&&f.removeEventListener("abort",z),k.delete(t)},"teardown"),h=o(r=>{g||(g=!0,ue(),r())},"finish");let G=!1;function O(r=!1){if(g||G)return;G=!0,y&&clearInterval(y);const a=r?Date.now()+q():void 0;a!==void 0&&_e(t,a),Le(e,t.jobId,{command:Y(t.cmdSh,"utf8"),...w===null?{}:{purpose:w},...a===void 0?{}:{deadline_at_ms:a}}).then(()=>{try{Ee(t)}catch{}H(r,"")},$=>H(r,`
4
- [crtr could not record job ${t.jobId} (${$.message}); it will NOT message you when it exits. Watch its log.]`))}o(O,"finishBackground");function H(r,a){const $=te(F());let K="";if(r){const le=q();K=`It will be CANCELED in ${te(le)} unless you claim it: crtr node bash extend ${t.jobId} --for <duration> (or --keep to run to completion). `}const W=`
5
- [backgrounded as job ${t.jobId} after ${$} in the foreground${r?" (auto)":""}. `+K+(a===""?"It will interrupt you with a message when it exits. ":"")+`Watch: tail -f ${t.jobLog} ; stop: crtr node bash kill ${t.jobId}]`;u(Buffer.from(W+a)),c({jobId:t.jobId,logPath:t.jobLog,notice:W+a}),h(()=>_({exitCode:0}))}o(H,"handOff");function V(){l=C(t.jobLog,l,u);const r=He(t.jobExit);h(()=>_({exitCode:r})),E(t.dir)}o(V,"finishForeground");function de(r=!1){const a=ee(t);if(a==="backgrounded"||a==="already-backgrounded"){O(r);return}if(a==="finished"){V();return}h(()=>d(new Error(`bash job ${t.jobId} disappeared before it could be backgrounded`))),E(t.dir)}o(de,"requestBackground");function T(r){if(!(g||D)){if(l=C(t.jobLog,l,u),v(t.jobBg)){O();return}if(!v(t.jobExit)){if(j===void 0){L??=r;return}if(ae){D=!0,Oe(e,t.jobId).then(()=>{h(()=>d(r)),E(t.dir)},a=>h(()=>d(a)));return}j!==void 0&&B!==void 0&&je(j,B),h(()=>d(r)),E(t.dir)}}}o(T,"requestStop");function z(){T(new Error("aborted"))}o(z,"onAbort"),f&&f.addEventListener("abort",z,{once:!0});const J=Ve(m);J.warning&&u(Buffer.from(J.warning));let R=I??process.env;s!==void 0&&(X(ye(s),{recursive:!0}),Q(s,{force:!0}),R={...R,[Ne]:s}),Je(e,t,n,J.cwd,R).then(r=>{j=r.pgid,B=r.identity,k.add(t),L!==void 0&&T(L)},r=>{h(()=>d(r)),E(t.dir)}),y=setInterval(()=>{const r=N.now();if(r-x>De&&(U+=r-x-oe),x=r,l=C(t.jobLog,l,u),v(t.jobDone)){V();return}if(v(t.jobBg)){O();return}if(v(t.jobExit))return;const a=F();if(p!==void 0&&p>0){a>=p*1e3&&T(new Error(`timeout:${p}`));return}a>=ce&&de(!0)},oe)}),"exec")}}o(se,"createValveOperations");const ze=["One short clause naming what this step is FOR, in the words of the person you",'are working for \u2014 "Reading the Acme thread", not "Fetching emails" and never','"Running GMAIL_FETCH_EMAILS". A person reads this while the command runs; it',"is the only thing they see of this step. Under about eight words. Omit it for","steps that only touch your own scratch work."].join(" "),Ke=3;function We(e){const n=Ae(e.logPath,Ke),i=Math.max(0,Se(e.logPath)-n.length),s=n.length===0?"(no output yet)":n.join(`
1
+ var le=Object.defineProperty;var o=(e,t)=>le(e,"name",{value:t,configurable:!0});import{envBashAutoBgDeadlineMs as W,envBashValveMs as fe,envNodeId as me}from"../shared/env.js";import{closeSync as pe,existsSync as E,mkdirSync as q,openSync as he,readFileSync as X,readSync as be,rmSync as Y,statSync as Q,writeFileSync as J}from"node:fs";import{homedir as ge}from"node:os";import{dirname as we}from"node:path";import{performance as N}from"node:perf_hooks";import{backgroundBashJob as Z,bashJobPaths as ye,clearJobDeadlineFile as Ee,writeJobDeadlineFile as ve,cancelBashJobProcessTree as je,countJobLogLines as _e,formatBashElapsed as ee,newBashJobId as Se,normalizeBashJobPurpose as Ie,tailJobLog as ke}from"../core/bash-jobs.js";import{MAX_BACKGROUND_BASH_LOG_BYTES as pt,BACKGROUND_BASH_LOG_TRUNCATION_MARKER as ht}from"../core/bash-job-supervisor.js";import{brokerApiUrl as Ae,recordBackgroundedJob as Be,reportBrokerJob as Le}from"../core/runtime/broker/daemon-ops.js";import{launchBashJobSupervisor as xe}from"../core/runtime/broker/bash-job-launch.js";import{JobReporter as Oe}from"../core/runtime/broker/job-reporter.js";import{bashCommandRefusal as Te}from"../core/bash-guard.js";import{readConfig as Re}from"../core/config.js";import{PREVIEW_RESULT_PATH_ENV as $e,previewResultPath as Me}from"../core/preview-result-path.js";import{Type as _}from"typebox";import{createBashToolDefinition as te}from"@earendil-works/pi-coding-agent";const ne=200,Je=5e3;function Ne(){return fe()}o(Ne,"resolveValveMs");function Ce(e){return ye(e,Se())}o(Ce,"makeJobPaths");const S=new Set;let oe=!1;function re(){for(const e of[...S])try{Z(e),S.delete(e)}catch(t){process.stderr.write(`crtr: failed to background bash job ${e.jobId} during broker termination: ${t.message}
2
+ `)}}o(re,"backgroundLiveJobsForTermination");function De(){oe||(oe=!0,process.prependListener("SIGTERM",re),process.platform!=="win32"&&process.prependListener("SIGHUP",re))}o(De,"installTerminationHandoff");const Pe=64*1024;function C(e,t,i){let s;try{s=Q(e)}catch{return t}if(s.size<=t)return t;const c=he(e,"r");try{for(;t<s.size;){const m=Math.min(Pe,s.size-t),p=Buffer.allocUnsafe(m),d=be(c,p,0,m,t);if(d===0)break;i(p.subarray(0,d)),t+=d}return t}finally{pe(c)}}o(C,"tailOnce");function I(e){try{Y(e,{recursive:!0,force:!0})}catch{}}o(I,"cleanupJobDir");function Fe(e){try{const t=X(e,"utf8").trim(),i=Number(t);return Number.isFinite(i)?i:null}catch{return null}}o(Fe,"readExitCode");function Ue(e){try{if(Q(e).isDirectory())return{cwd:e}}catch{}const t=ge();return{cwd:t,warning:`[working directory no longer exists: ${e}; running from ${t}]
3
+ `}}o(Ue,"resolveExecutionCwd");function ie(e,t,i=()=>null,s,c=()=>{}){return{exec:o(async(m,p,{onData:d,signal:l,timeout:h,env:k})=>new Promise((v,f)=>{const g=i();if(l?.aborted){f(new Error("aborted"));return}const A=Te(m,p);if(A!==null){f(new Error(A));return}const n=Ce(t);q(n.dir,{recursive:!0}),J(n.cmdSh,m),J(n.jobLog,""),J(n.jobRun,"");let u=0,b=!1,j,B,L,se=!1;const D=N.now();let P=0,x=D;const F=o(()=>N.now()-D-P,"foregroundMs"),ae=Ne();let w;const ce=o(()=>{w&&clearInterval(w),l&&l.removeEventListener("abort",V),S.delete(n)},"teardown"),y=o(r=>{b||(b=!0,ce(),r())},"finish");let U=!1;function O(r=!1){if(b||U)return;U=!0,w&&clearInterval(w);const a=r?Date.now()+W():void 0;a!==void 0&&ve(n,a),Be(e,n.jobId,{command:X(n.cmdSh,"utf8"),...g===null?{}:{purpose:g},...a===void 0?{}:{deadline_at_ms:a}}).then(()=>{try{Ee(n)}catch{}G(r,"")},M=>G(r,`
4
+ [crtr could not record job ${n.jobId} (${M.message}); it will NOT message you when it exits. Watch its log.]`))}o(O,"finishBackground");function G(r,a){const M=ee(F());let z="";if(r){const ue=W();z=`It will be CANCELED in ${ee(ue)} unless you claim it: crtr node bash extend ${n.jobId} --for <duration> (or --keep to run to completion). `}const K=`
5
+ [backgrounded as job ${n.jobId} after ${M} in the foreground${r?" (auto)":""}. `+z+(a===""?"It will interrupt you with a message when it exits. ":"")+`Watch: tail -f ${n.jobLog} ; stop: crtr node bash kill ${n.jobId}]`;d(Buffer.from(K+a)),c({jobId:n.jobId,logPath:n.jobLog,notice:K+a}),y(()=>v({exitCode:0}))}o(G,"handOff");function H(){u=C(n.jobLog,u,d);const r=Fe(n.jobExit);y(()=>v({exitCode:r})),I(n.dir)}o(H,"finishForeground");function de(r=!1){const a=Z(n);if(a==="backgrounded"||a==="already-backgrounded"){O(r);return}if(a==="finished"){H();return}y(()=>f(new Error(`bash job ${n.jobId} disappeared before it could be backgrounded`))),I(n.dir)}o(de,"requestBackground");function T(r){if(!(b||se)){if(u=C(n.jobLog,u,d),E(n.jobBg)){O();return}if(!E(n.jobExit)){if(j===void 0){L??=r;return}j!==void 0&&B!==void 0&&je(j,B),y(()=>f(r)),I(n.dir)}}}o(T,"requestStop");function V(){T(new Error("aborted"))}o(V,"onAbort"),l&&l.addEventListener("abort",V,{once:!0});const R=Ue(p);R.warning&&d(Buffer.from(R.warning));let $=k??process.env;s!==void 0&&(q(we(s),{recursive:!0}),Y(s,{force:!0}),$={...$,[$e]:s}),xe(e,n,t,R.cwd,$).then(r=>{j=r.pgid,B=r.identity,S.add(n),L!==void 0&&T(L)},r=>{y(()=>f(r)),I(n.dir)}),w=setInterval(()=>{const r=N.now();if(r-x>Je&&(P+=r-x-ne),x=r,u=C(n.jobLog,u,d),E(n.jobDone)){H();return}if(E(n.jobBg)){O();return}if(E(n.jobExit))return;const a=F();if(h!==void 0&&h>0){a>=h*1e3&&T(new Error(`timeout:${h}`));return}a>=ae&&de(!0)},ne)}),"exec")}}o(ie,"createValveOperations");const Ge=["One short clause naming what this step is FOR, in the words of the person you",'are working for \u2014 "Reading the Acme thread", not "Fetching emails" and never','"Running GMAIL_FETCH_EMAILS". A person reads this while the command runs; it',"is the only thing they see of this step. Under about eight words. Omit it for","steps that only touch your own scratch work."].join(" "),He=3;function Ve(e){const t=ke(e.logPath,He),i=Math.max(0,_e(e.logPath)-t.length),s=t.length===0?"(no output yet)":t.join(`
6
6
  `),c=i===0?"":`
7
- [${i} earlier output line${i===1?"":"s"} are in the job log only]`;return{content:[{type:"text",text:`${s}${c}${e.notice}`}],details:void 0}}o(We,"handoffResult");function qe(e){return{...e,parameters:S.Object({purpose:S.Optional(S.String({description:ze})),...e.parameters.properties})}}o(qe,"withPurpose");const Xe=["A command that needs longer than one call \u2014 a test lane, a build, a soak \u2014 is started with","`crtr node bash run '<command>'`, which returns at once and wakes you with the exit code; the job is a canvas","object others can watch. Do not use `&`, `nohup`, `setsid`, or a cron that polls a log. A foreground command","past 5 minutes is moved to a job automatically; a `timeout` kills it and everything it started."].join(" ");function Ye(e){const{command:n,...i}=e.parameters.properties;return{...e,parameters:S.Object({command:{...n,description:`${n.description??""} ${Xe}`.trim()},...i})}}o(Ye,"withJobGuidance");function Qe(e,n,i,s){const c=Ye(ne(i,{operations:se(e,n)}));return{...s?qe(c):c,execute:o(async(u,f,p,I,_)=>{const d=s?Ie(f.purpose):null;let w=null;const t=await ne(i,{operations:se(e,n,()=>d,Ce(u),g=>{w=g})}).execute(u,f,p,I,_),l=w;return l===null?t:We(l)},"execute")}}o(Qe,"createValveToolDefinition");function Ze(e){const n=be();if(n===void 0||n.trim()==="")return;const i=process.env.CRTR_CONTEXT_DIR;i===void 0||i.trim()===""||(Fe(),Be()!==void 0&&new Re(i,(s,c)=>xe(n,s,c)).start(),e.on("session_start",(s,c)=>{e.registerTool(Qe(n,i,c.cwd,Me("user").bash_tool_purpose))}))}o(Ze,"default");export{wt as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,gt as MAX_BACKGROUND_BASH_LOG_BYTES,se as createValveOperations,Qe as createValveToolDefinition,Ze as default};
7
+ [${i} earlier output line${i===1?"":"s"} are in the job log only]`;return{content:[{type:"text",text:`${s}${c}${e.notice}`}],details:void 0}}o(Ve,"handoffResult");function ze(e){return{...e,parameters:_.Object({purpose:_.Optional(_.String({description:Ge})),...e.parameters.properties})}}o(ze,"withPurpose");const Ke=["A command that needs longer than one call \u2014 a test lane, a build, a soak \u2014 is started with","`crtr node bash run '<command>'`, which returns at once and wakes you with the exit code; the job is a canvas","object others can watch. Do not use `&`, `nohup`, `setsid`, or a cron that polls a log. A foreground command","past 5 minutes is moved to a job automatically; a `timeout` kills it and everything it started."].join(" ");function We(e){const{command:t,...i}=e.parameters.properties;return{...e,parameters:_.Object({command:{...t,description:`${t.description??""} ${Ke}`.trim()},...i})}}o(We,"withJobGuidance");function qe(e,t,i,s){const c=We(te(i,{operations:ie(e,t)}));return{...s?ze(c):c,execute:o(async(d,l,h,k,v)=>{const f=s?Ie(l.purpose):null;let g=null;const n=await te(i,{operations:ie(e,t,()=>f,Me(d),b=>{g=b})}).execute(d,l,h,k,v),u=g;return u===null?n:Ve(u)},"execute")}}o(qe,"createValveToolDefinition");function Xe(e){const t=me();if(t===void 0||t.trim()==="")return;const i=process.env.CRTR_CONTEXT_DIR;i===void 0||i.trim()===""||(De(),(Ae()!==void 0||process.platform==="linux")&&new Oe(i,(s,c)=>Le(t,s,c)).start(),e.on("session_start",(s,c)=>{e.registerTool(qe(t,i,c.cwd,Re("user").bash_tool_purpose))}))}o(Xe,"default");export{ht as BACKGROUND_BASH_LOG_TRUNCATION_MARKER,pt as MAX_BACKGROUND_BASH_LOG_BYTES,ie as createValveOperations,qe as createValveToolDefinition,Xe as default};
@@ -1,2 +1,2 @@
1
- var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{envNodeId as b}from"../shared/env.js";import{CONTEXT_INTRO_CUSTOM_TYPE as a,formatCard as C}from"../shared/generated-context.js";import{brokerDelivery as f}from"../core/runtime/broker/daemon-ops.js";import{boundExtensionState as l}from"../core/runtime/broker/boot-state.js";import{takeCycleBoot as T}from"../core/runtime/broker/cycle-start.js";import{buildForkBearingsFromState as p}from"../core/runtime/broker-extension-render.js";import{acknowledgePersonaBaseline as _}from"../core/runtime/broker-persona-guidance.js";async function S(e){return(await f(e,{activity:"boot"})).content}s(S,"buildContextIntro");async function A(e){const t=await l(e);return p(t,t.situational_card??"")}s(A,"buildForkContextIntro");function y(e){const t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>typeof r?.text=="string").map(r=>r.text).join(`
2
- `):""}s(y,"entryText");function I(e){e.on("session_start",async(t,r)=>{const n=b();if(n===void 0||n.trim()==="")return;const g=t?.reason,i=await l(n);if(i.warm_spare||g==="new"&&i.node.parent===null)return;const c=r.sessionManager.getBranch().filter(o=>o.type==="custom_message"&&o.customType===a);if(c.some(o=>o.details?.nodeId===n||y(o).includes(n)))return;const d=T(n),u=d??await f(n,{activity:"boot",inherited:c.length>0}),x=u.inherited===!0?p(i,i.situational_card??""):u.content,m=C("bearings",{},x);if(e.sendMessage({customType:a,content:m,display:!0,details:{nodeId:n}}),!r.sessionManager.getBranch().some(o=>o.type==="custom_message"&&o.customType===a&&o.details?.nodeId===n&&y(o)===m))throw new Error(`Pi did not materialize the context baseline for ${n}`);d===void 0&&await _(i)})}s(I,"registerCanvasContextIntro");var j=I;export{a as CONTEXT_INTRO_CUSTOM_TYPE,S as buildContextIntro,A as buildForkContextIntro,j as default,I as registerCanvasContextIntro};
1
+ var w=Object.defineProperty;var s=(e,t)=>w(e,"name",{value:t,configurable:!0});import{envNodeId as T}from"../shared/env.js";import{CONTEXT_INTRO_CUSTOM_TYPE as a,formatCard as b}from"../shared/generated-context.js";import{expandHostPathTokens as C}from"../core/runtime/broker/host-path-tokens.js";import{brokerDelivery as f}from"../core/runtime/broker/daemon-ops.js";import{boundExtensionState as p}from"../core/runtime/broker/boot-state.js";import{takeCycleBoot as _}from"../core/runtime/broker/cycle-start.js";import{buildForkBearingsFromState as l}from"../core/runtime/broker-extension-render.js";import{acknowledgePersonaBaseline as h}from"../core/runtime/broker-persona-guidance.js";async function j(e){return(await f(e,{activity:"boot"})).content}s(j,"buildContextIntro");async function z(e){const t=await p(e);return l(t,t.situational_card??"")}s(z,"buildForkContextIntro");function y(e){const t=e.content;return typeof t=="string"?t:Array.isArray(t)?t.filter(r=>typeof r?.text=="string").map(r=>r.text).join(`
2
+ `):""}s(y,"entryText");function I(e){e.on("session_start",async(t,r)=>{const o=T();if(o===void 0||o.trim()==="")return;const g=t?.reason,i=await p(o);if(i.warm_spare||g==="new"&&i.node.parent===null)return;const c=r.sessionManager.getBranch().filter(n=>n.type==="custom_message"&&n.customType===a);if(c.some(n=>n.details?.nodeId===o||y(n).includes(o)))return;const d=_(o),u=d??await f(o,{activity:"boot",inherited:c.length>0}),x=u.inherited===!0?l(i,i.situational_card??""):u.content,m=b("bearings",{},C(x));if(e.sendMessage({customType:a,content:m,display:!0,details:{nodeId:o}}),!r.sessionManager.getBranch().some(n=>n.type==="custom_message"&&n.customType===a&&n.details?.nodeId===o&&y(n)===m))throw new Error(`Pi did not materialize the context baseline for ${o}`);d===void 0&&await h(i)})}s(I,"registerCanvasContextIntro");var D=I;export{a as CONTEXT_INTRO_CUSTOM_TYPE,j as buildContextIntro,z as buildForkContextIntro,D as default,I as registerCanvasContextIntro};