@north-light/cli 0.3.709 → 0.3.711
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/input/controller.d.ts +1 -1
- package/dist/clients/attach/input/controller.js +2 -2
- package/dist/clients/attach/render/chat-view.d.ts +13 -2
- package/dist/clients/attach/render/chat-view.js +2 -2
- package/dist/clients/attach/session/input-wiring.d.ts +2 -2
- package/dist/clients/attach/session/layout-record.d.ts +15 -0
- package/dist/clients/attach/session/layout-record.js +1 -0
- package/dist/clients/attach/session/reconnect.d.ts +8 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/session/teardown.d.ts +2 -0
- package/dist/clients/attach/session/teardown.js +3 -3
- package/dist/clients/attach/slash/dispatch.js +2 -2
- package/dist/clients/attach/slash/recover.d.ts +10 -0
- package/dist/clients/attach/slash/recover.js +3 -0
- package/dist/clients/attach/viewer.js +520 -516
- package/dist/commands/human/prompts.js +1 -1
- package/dist/commands/human/request.js +1 -1
- package/dist/commands/sys/doctor.js +1 -1
- package/dist/commands/sys/tutorial/scenario.js +2 -2
- package/dist/core/broker-client/client.d.ts +2 -0
- package/dist/core/broker-client/client.js +1 -1
- package/dist/core/broker-client/transport-relay.d.ts +6 -0
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/broker-client/transport.d.ts +4 -0
- package/dist/core/canvas/daemon-actions.d.ts +1 -1
- package/dist/core/canvas/daemon-actions.js +7 -7
- package/dist/core/canvas/deliveries.d.ts +1 -1
- package/dist/core/canvas/deliveries.js +21 -21
- package/dist/core/canvas/executions.d.ts +1 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +2 -2
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +5 -3
- package/dist/core/canvas/reconciler-leases.d.ts +4 -0
- package/dist/core/canvas/reconciler-leases.js +5 -5
- package/dist/core/canvas/schema-pg/028-machine-calls-worktree-sweep.sql +6 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/conversation-store/client.js +2 -2
- package/dist/core/conversation-store/index.d.ts +5 -2
- package/dist/core/conversation-store/row-store.js +14 -12
- package/dist/core/graph/package-docs.js +5 -5
- package/dist/core/graph/package-publish.js +4 -3
- package/dist/core/human/requests.js +19 -19
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/runtime/broker/client-registry.d.ts +1 -1
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker/turn-replies.js +3 -1
- package/dist/core/runtime/broker-protocol.d.ts +4 -4
- package/dist/core/runtime/broker-protocol.js +3 -3
- package/dist/core/runtime/broker-request.d.ts +2 -0
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -1
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +2 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +11 -1
- package/dist/core/runtime/runner/machine/ops.js +1 -1
- package/dist/core/runtime/session-cycles.d.ts +21 -0
- package/dist/core/runtime/session-cycles.js +1 -1
- package/dist/core/runtime/tmux-driver.d.ts +7 -0
- package/dist/core/runtime/tmux-driver.js +6 -6
- package/dist/core/worktree-machine.d.ts +4 -1
- package/dist/core/worktree-machine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +14 -3
- package/dist/core/worktree-sweep.js +4 -4
- package/dist/daemon/api/app-listener.js +1 -1
- package/dist/daemon/api/handlers/charges.d.ts +1 -1
- package/dist/daemon/api/handlers/charges.js +1 -1
- package/dist/daemon/api/handlers/conversations.js +4 -3
- package/dist/daemon/api/handlers/environments.d.ts +1 -1
- package/dist/daemon/api/handlers/environments.js +1 -1
- package/dist/daemon/api/handlers/limits.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/cron/live-runs.d.ts +3 -0
- package/dist/daemon/cron/live-runs.js +1 -1
- package/dist/daemon/cron/machine-fire.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/due-sources.d.ts +1 -1
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.js +7 -7
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +4 -4
- package/dist/daemon/human/finish.js +3 -3
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/delivery-lane.js +2 -2
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/requested-stops.js +2 -2
- package/dist/daemon/runs/observer.d.ts +4 -0
- package/dist/daemon/runs/observer.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/package.json +4 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/clients/attach/input/capabilities.js +1 -0
- package/packages/crouter-api/dist/clients/attach/input/controller.js +2 -2
- package/packages/crouter-api/dist/clients/attach/render/chat-view.js +40 -3
- package/packages/crouter-api/dist/clients/attach/session/layout-record.js +52 -0
- package/packages/crouter-api/dist/clients/attach/session/reconnect.js +41 -2
- package/packages/crouter-api/dist/clients/attach/session/teardown.js +2 -0
- package/packages/crouter-api/dist/clients/attach/slash/dispatch.js +12 -0
- package/packages/crouter-api/dist/clients/attach/slash/recover.js +133 -0
- package/packages/crouter-api/dist/clients/attach/viewer.js +24 -5
- package/packages/crouter-api/dist/commands/human/prompts.js +11 -18
- package/packages/crouter-api/dist/commands/human/request.js +3 -0
- package/packages/crouter-api/dist/commands/sys/doctor.js +17 -0
- package/packages/crouter-api/dist/commands/sys/tutorial/scenario.js +1 -0
- package/packages/crouter-api/dist/core/broker-client/client.js +4 -0
- package/packages/crouter-api/dist/core/broker-client/transport-relay.js +45 -0
- package/packages/crouter-api/dist/core/canvas/daemon-actions.js +3 -2
- package/packages/crouter-api/dist/core/canvas/deliveries.js +7 -3
- package/packages/crouter-api/dist/core/canvas/executions.js +8 -7
- package/packages/crouter-api/dist/core/canvas/reconciler-leases.js +4 -0
- package/packages/crouter-api/dist/core/canvas/schema-version.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/client.js +1 -1
- package/packages/crouter-api/dist/core/conversation-store/row-store.js +14 -1
- package/packages/crouter-api/dist/core/graph/package-docs.js +8 -3
- package/packages/crouter-api/dist/core/graph/package-publish.js +8 -1
- package/packages/crouter-api/dist/core/human/requests.js +2 -2
- package/packages/crouter-api/dist/core/runtime/broker-ownership.js +6 -0
- package/packages/crouter-api/dist/core/runtime/broker-protocol.js +4 -4
- package/packages/crouter-api/dist/core/runtime/broker-request.js +1 -1
- package/packages/crouter-api/dist/core/runtime/model-swap.js +2 -1
- package/packages/crouter-api/dist/core/runtime/placement-tmux.js +3 -3
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +1 -1
- package/packages/crouter-api/dist/core/runtime/runner/machine/executor.js +235 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/ops.js +1 -1
- package/packages/crouter-api/dist/core/runtime/session-cycles.js +90 -8
- package/packages/crouter-api/dist/core/runtime/tmux-driver.js +11 -0
- package/packages/crouter-api/dist/core/worktree-machine.js +20 -0
- package/packages/crouter-api/dist/core/worktree-sweep.js +439 -0
- package/packages/crouter-api/dist/daemon/api/operations.js +3 -3
- package/packages/crouter-api/dist/daemon/api/router.js +1 -4
- package/packages/crouter-api/dist/daemon/cron/live-runs.js +4 -5
- package/packages/crouter-api/dist/daemon/cron/machine-fire.js +3 -3
- package/packages/crouter-api/dist/daemon/human/finish.js +2 -1
- package/packages/crouter-api/dist/daemon/human/settle.js +1 -6
- package/packages/crouter-api/dist/daemon/runs/observer.js +1 -1
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/install-runtime.mjs +18 -1
- package/scripts/lib/install-source.mjs +49 -0
- package/dist/daemon/reconcilers/idle-sandbox.d.ts +0 -18
- package/dist/daemon/reconcilers/idle-sandbox.js +0 -7
|
@@ -1 +1 @@
|
|
|
1
|
-
var G=Object.defineProperty;var d=(e,t)=>G(e,"name",{value:t,configurable:!0});import{toErrorBody as L}from"./map.js";import{emitEvent as H}from"../../core/events/emit.js";import{scopeAllowed as l,ScopeDeniedError as I}from"../../core/scopes.js";import{coveredByAny as F}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as J}from"../../core/canvas/person.js";import{activeGrant as M,activeGrantsOfPerson as Y,grantFor as O}from"../../core/grants/mirror.js";import{getNode as h}from"../../core/canvas/canvas.js";import{ownedRun as Z,RunError as E}from"../../core/runs/operations.js";import{openDb as y}from"../../core/canvas/db.js";import{check as V,permits as q}from"../../core/permissions/evaluator.js";import{readerFor as b}from"./reader.js";import{checkCronFire as X}from"../cron/authority.js";import{operationFor as K}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{getRequest as R,getRequestByInboxTicket as N}from"../../core/human/requests.js";import{requireVisibleReview as v}from"../../core/review/store.js";import{getComment as S}from"../../core/review/comments.js";import{getStructuredRequest as ee}from"../../core/canvas/structured-requests.js";async function te(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e.method==="POST"&&(r==="/v1/human/requests"||r==="/v1/human/reviews")){const i=r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id,c=r==="/v1/human/requests"&&i==null;if(i!==t.node&&!c)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const w=a.source;if(w&&typeof w=="object"&&"nodeId"in w&&w.nodeId!==t.node)throw new u(403,"other_app_run","request source must name the calling node")}if(r==="/v1/human/reviews/self/comments"&&e.method==="GET"&&n.get("actor_node_id")!==t.node)throw new u(403,"other_app_run","self review requires the calling node");if(r.includes("/comments")&&e.method!=="GET"&&a.actor_node_id!==t.node)throw new u(403,"other_app_run","comment author must be the calling node");if(o.comment_id&&!await S(o.comment_id))throw new u(404,"not_found","comment not found")}d(te,"authorizeHumanBody");function C(e){return e.class==="broker"||e.class==="cron"}d(C,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function g(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(g,"actsAsPerson");async function $(e){const t=await O(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d($,"forwardedGrant");async function T(e){if(e.class==="person"&&e.sub!==void 0)return(await Y(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await $(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>F(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await X({grantee:e.app,sub:e.sub,grant_id:e.grant,scopes:e.scopes});if(o.allowed)return o.effectiveScopes;throw o.reason==="grant_missing"||o.reason==="grant_revoked"?new u(401,"grant_revoked",o.message):new u(403,"scope_missing",o.message)}const t=e.grant?await M(e.grant):await O(e.app,e.sub);if(t&&t.grantee===e.app&&t.sub===e.sub)return t.resolved;throw new u(401,"grant_revoked","the node grant is not active")}d(T,"resolvedScopes");function U(e){return"class"in e?k(e):e.grantee}d(U,"runCallerApp");function W(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(W,"asRequestPrincipal");async function f(e,t,o){const n=W(e);if(g(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await y();return await V(s,await b(s,{principal:n}),t,o)}d(f,"mayOnNode");async function Pe(e){if(g(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await y(),o=await q(t,await b(t,{principal:e}),"read"),n=await t.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${o.sql}`).all(...o.params);return new Set(n.map(s=>s.id))}d(Pe,"readableNodeIds");async function pe(e,t){if(g(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await q(o,await b(o,{principal:e}),"read"),s=await o.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND o.id = ANY(?::text[]) AND ${n.sql}`).all([...t],...n.params);return new Set(s.map(r=>r.id))}d(pe,"readableAmong");async function ze(e,t){if(g(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await q(o,await b(o,{principal:e}),"read"),s=new Set;for(let r=0;r<t.length;r+=500){const a=t.slice(r,r+500),i=await o.prepareUncached(`SELECT r.inbox_ticket_id AS id FROM human_requests r JOIN node_rows n ON n.node_id = r.requester_node_id JOIN objects o ON o.id = n.node_id WHERE r.inbox_ticket_id IN (${a.map(()=>"?").join(",")}) AND ${n.sql}`).all(...a,...n.params);for(const c of i)s.add(c.id)}return s}d(ze,"readableTicketIds");async function j(e,t,o){const n=W(e);return g(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:l(await T(n),o)&&(!C(n)||l(n.scopes,o))}d(j,"mayReadApp");async function De(e,t,o){return o===void 0?await j(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(De,"canReadRun");async function Ge(e,t,o=!1,n=!1){const s=await h(t);if(!s||s.parent!==null||s.run_id!==t||!s.grantee||s.deleting_at&&!n)throw new E(404,"not_found","run not found");if(!await f(e,"read",t))throw new E(404,"not_found","run not found");if(o&&U(e)!==null&&U(e)!==s.grantee)throw new E(403,"other_app_run","cannot change another app's run");return await Z(t,s.grantee,n)}d(Ge,"requireRun");async function oe(e,t,o){return o===void 0?await j(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(oe,"canReadNode");const P=new Set(["messages.post.58","messages.post.59"]);async function ne(e,t,o){if(!e.classes.includes(t.class)&&!(t.class!=="anonymous"&&t.class!=="machine"&&t.class!=="import"&&t.class!=="forwarded"&&e.classes.includes("anonymous")))throw new u(403,"permission_error","this operation is not available to the caller");if(e.resource==="daemon-control"&&J())throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available on a shared cloud role");if(t.class==="forwarded"&&t.actor.kind==="app"&&await $(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||g(t))return;if(t.class==="person")return await re(e,t,o);const n=await T(t);if(e.scope&&(!l(n,e.scope)||C(t)&&!l(t.scopes,e.scope)))throw new u(403,"scope_missing",`missing scope ${e.scope}`);if(t.class==="app")return;const s=k(t);t.class==="broker"&&await ue(e,t,o,n);const r=o.id;if((e.resource==="node-read"||e.resource==="node-write")&&r!==void 0){const a=await h(r);if(!a)return;if(e.resource==="node-write"){const i=P.has(e.name);if(a.grantee!==s&&!i)throw new u(403,"other_app_run","cannot change another app's node");if(!await f(t,i&&a.grantee!==s?"message":"read",r))throw a.grantee!==s?new u(403,"other_app_run","cannot change another app's node"):new u(404,"not_found","node not found")}if(e.resource==="node-read"&&!await f(t,"read",r))throw new u(404,"not_found","node not found")}}d(ne,"authorizeOperation");async function re(e,t,o){if(e.resource==="daemon-bash")throw new u(403,"permission_error","a shell on the daemon host is not available to a person bearer");if(e.resource==="daemon-control")throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available to a person bearer");if(e.resource==="human")return await se(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await ae(e,t,o.request_id);const n=o.id;if(!(e.resource!=="node-read"&&e.resource!=="node-write"||n===void 0||!await h(n))&&!await f(t,P.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(re,"authorizePersonNode");async function se(e,t,o){const n=o.ticket_id!==void 0?new u(404,"ticket_not_found","no matching ticket"):new u(404,"not_found","no request with that id"),s=o.request_id?await R(o.request_id):o.ticket_id?await N(o.ticket_id):null,r=o.comment_id?await S(o.comment_id):null,a=o.review_id?await v(o.review_id).catch(()=>null):r?await v(r.review_id).catch(()=>null):null;if((o.request_id??o.ticket_id??o.review_id??o.comment_id)===void 0)return;const c=s?.requester_node_id??a?.origin_node_id;if(!c||!await h(c)||!await f(t,e.method==="GET"?"read":"edit",c))throw n}d(se,"authorizePersonHuman");async function ae(e,t,o){const n=await ee(o);if(n!==null&&(n.node_id===null||!await h(n.node_id)||!await f(t,e.method==="GET"?"read":"edit",n.node_id)))throw new u(404,"structured_request_not_found",`unknown structured request: ${o}`)}d(ae,"authorizePersonStructuredRequest");async function de(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(e.method==="POST"&&(s==="/v1/human/requests"||s==="/v1/human/reviews")){const r=n.source,a=s.endsWith("/reviews")?n.origin_node_id:n.requester_node_id;if(typeof a!="string")throw new u(403,"permission_error","a request must name a node the person acts on");const i=s.endsWith("/requests")&&r&&typeof r=="object"&&"nodeId"in r?r.nodeId:void 0;for(const c of[a,i])if(c!==void 0&&(typeof c!="string"||!await h(c)||!await f(t,"edit",c)))throw new u(404,"not_found","node not found")}if(s==="/v1/structured-requests"){const r=n.target,a=r&&typeof r=="object"&&"kind"in r&&r.kind==="node"&&"node_id"in r?r.node_id:void 0;if(typeof a=="string"&&await h(a)&&!await f(t,"message",a))throw new u(404,"node_not_found",`unknown node: ${a}`)}}d(de,"authorizePersonBody");async function ue(e,t,o,n){if(e.resource==="daemon-bash"&&(!l(n,"crtr:files:rw:user:.")||!l(t.scopes,"crtr:files:rw:user:.")))throw new u(403,"scope_missing","missing scope crtr:files:rw:user:.");if(e.resource==="human"){const r=e.path,a=e.method==="GET";if(!a&&(r.endsWith("/respond")||r.endsWith("/submit")||r.endsWith("/dismiss")||r.endsWith("/progress")||r.endsWith("/comment-ranges")||r.includes("/feedback-comments")))throw new u(403,"permission_error","only the person may answer or edit the human inbox");const i=o.request_id?await R(o.request_id):o.ticket_id?await N(o.ticket_id):null,c=o.comment_id?await S(o.comment_id):null,w=o.review_id?await v(o.review_id):c?await v(c.review_id):null,m=i?.requester_node_id??w?.origin_node_id;if(m!=null){const _=await h(m);if(_&&(a?!await oe(t,_.grantee??"app:terminal",m):_.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(_&&!a&&!await f(t,"read",m))throw new u(404,"not_found","human request not found")}else if(i||w)throw new u(403,"permission_error","only the person may access a request without a node")}const s=o.id;if(e.resource==="node-own"&&s!==void 0&&s!==t.node)throw new u(403,"other_app_run","the operation requires the calling node")}d(ue,"authorizeBrokerOnly");function ie(e,t){if(!l(e,t))throw new I("the bearer token",t)}d(ie,"assertCeiling");function ce(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ce,"ownerOnlyError");const fe="Crtr-Caused-By",we=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function he(e){const t=e[fe.toLowerCase()];return typeof t=="string"&&we.test(t)?t:void 0}d(he,"causedByOf");function Le(e){return e.map(t=>({...t,ownerOnly:!0}))}d(Le,"ownerOnly");class He{static{d(this,"Router")}routes=[];register(t){const o=K(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:p(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??Q}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=p(o);for(const r of this.routes){if(r.method!==n)continue;const a=me(r.segments,s);if(a!==null)return{handler:r.handler,params:a,operation:r.operation,maxBodyBytes:r.maxBodyBytes}}return null}async handle(t,o,n,s={class:"person"}){try{const r=new URL(t.url??"/","http://127.0.0.1"),a=(t.method??"GET").toUpperCase(),i=this.match(a,r.pathname);if(i===null){D(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await ne(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw ce();i.operation.scope&&ie(n,i.operation.scope)}let c;try{c=await le(t,i.maxBodyBytes)}catch(A){const B=A instanceof z?"payload_too_large":"invalid_request";D(o,B==="payload_too_large"?413:400,B,A.message);return}s.class==="person"&&s.sub!==void 0&&await de(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await te(i.operation,s,i.params,r.searchParams,c);const w=he(t.headers),m={...w===void 0?{}:{causedBy:w},method:a,path:r.pathname,params:i.params,query:r.searchParams,body:c,ceiling:n,principal:s,...s.class==="anonymous"&&typeof t.headers.authorization=="string"?{publishToken:t.headers.authorization.slice(7)}:{},req:t,res:o},_=await i.handler(m);o.writableEnded||_e(o,_)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){x(o,503,{error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}});return}const{status:a,body:i}=L(r);a>=500&&H({event:"api.request.failed",level:"error",error:r instanceof Error?r:new Error(String(r)),...s.class==="broker"?{node_id:s.node}:{},fields:{method:(t.method??"GET").toUpperCase(),path:t.url??""}}),x(o,a,i)}}}function p(e){return e.split("/").filter(t=>t.length>0)}d(p,"splitPath");function me(e,t){if(e.length!==t.length)return null;const o={};for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(r);else if(s!==r)return null}return o}d(me,"matchSegments");class z extends Error{static{d(this,"BodyTooLargeError")}}async function le(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new z(`request body exceeds ${t} bytes`);o.push(a)}if(n===0)return;const s=Buffer.concat(o).toString("utf8").trim();if(s!=="")try{return JSON.parse(s)}catch{throw new Error("request body is not valid JSON")}}d(le,"readJsonBody");function _e(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(_e,"writeResult");function x(e,t,o){if(e.headersSent){e.end();return}e.writeHead(t,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}d(x,"writeJson");function D(e,t,o,n){x(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(D,"writeError");export{fe as CAUSED_BY_HEADER,He as Router,g as actsAsPerson,k as appOf,ie as assertCeiling,oe as canReadNode,De as canReadRun,he as causedByOf,f as mayOnNode,Le as ownerOnly,ce as ownerOnlyError,pe as readableAmong,Pe as readableNodeIds,ze as readableTicketIds,Ge as requireRun,T as resolvedScopes,U as runCallerApp};
|
|
1
|
+
var L=Object.defineProperty;var d=(e,t)=>L(e,"name",{value:t,configurable:!0});import{toErrorBody as p}from"./map.js";import{emitEvent as H}from"../../core/events/emit.js";import{scopeAllowed as m,ScopeDeniedError as I}from"../../core/scopes.js";import{coveredByAny as F}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as J}from"../../core/canvas/person.js";import{activeGrant as M,activeGrantsOfPerson as Y,grantFor as R}from"../../core/grants/mirror.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as Z,RunError as E}from"../../core/runs/operations.js";import{openDb as y}from"../../core/canvas/db.js";import{check as V,permits as S}from"../../core/permissions/evaluator.js";import{readerFor as b}from"./reader.js";import{checkCronFire as X}from"../cron/authority.js";import{operationFor as K}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{getRequest as O,getRequestByInboxTicket as N}from"../../core/human/requests.js";import{requireVisibleReview as v}from"../../core/review/store.js";import{getComment as q}from"../../core/review/comments.js";import{getStructuredRequest as ee}from"../../core/canvas/structured-requests.js";async function te(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(e.method==="POST"&&(r==="/v1/human/requests"||r==="/v1/human/reviews")){if((r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id)!==t.node)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const c=a.source;if(c&&typeof c=="object"&&"nodeId"in c&&c.nodeId!==t.node)throw new u(403,"other_app_run","request source must name the calling node")}if(r==="/v1/human/reviews/self/comments"&&e.method==="GET"&&n.get("actor_node_id")!==t.node)throw new u(403,"other_app_run","self review requires the calling node");if(r.includes("/comments")&&e.method!=="GET"&&a.actor_node_id!==t.node)throw new u(403,"other_app_run","comment author must be the calling node");if(o.comment_id&&!await q(o.comment_id))throw new u(404,"not_found","comment not found")}d(te,"authorizeHumanBody");function C(e){return e.class==="broker"||e.class==="cron"}d(C,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function l(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(l,"actsAsPerson");async function $(e){const t=await R(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d($,"forwardedGrant");async function T(e){if(e.class==="person"&&e.sub!==void 0)return(await Y(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await $(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>F(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await X({grantee:e.app,sub:e.sub,grant_id:e.grant,scopes:e.scopes});if(o.allowed)return o.effectiveScopes;throw o.reason==="grant_missing"||o.reason==="grant_revoked"?new u(401,"grant_revoked",o.message):new u(403,"scope_missing",o.message)}const t=e.grant?await M(e.grant):await R(e.app,e.sub);if(t&&t.grantee===e.app&&t.sub===e.sub)return t.resolved;throw new u(401,"grant_revoked","the node grant is not active")}d(T,"resolvedScopes");function U(e){return"class"in e?k(e):e.grantee}d(U,"runCallerApp");function W(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(W,"asRequestPrincipal");async function f(e,t,o){const n=W(e);if(l(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await y();return await V(s,await b(s,{principal:n}),t,o)}d(f,"mayOnNode");async function Pe(e){if(l(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await y(),o=await S(t,await b(t,{principal:e}),"read"),n=await t.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND ${o.sql}`).all(...o.params);return new Set(n.map(s=>s.id))}d(Pe,"readableNodeIds");async function ze(e,t){if(l(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await S(o,await b(o,{principal:e}),"read"),s=await o.prepareUncached(`SELECT o.id FROM objects o WHERE o.type = 'node' AND o.deleted_at IS NULL AND o.id = ANY(?::text[]) AND ${n.sql}`).all([...t],...n.params);return new Set(s.map(r=>r.id))}d(ze,"readableAmong");async function De(e,t){if(l(e))return new Set(t);if(e.class==="anonymous"||e.class==="machine"||e.class==="import"||t.length===0)return new Set;const o=await y(),n=await S(o,await b(o,{principal:e}),"read"),s=new Set;for(let r=0;r<t.length;r+=500){const a=t.slice(r,r+500),i=await o.prepareUncached(`SELECT r.inbox_ticket_id AS id FROM human_requests r JOIN node_rows n ON n.node_id = r.requester_node_id JOIN objects o ON o.id = n.node_id WHERE r.inbox_ticket_id IN (${a.map(()=>"?").join(",")}) AND ${n.sql}`).all(...a,...n.params);for(const c of i)s.add(c.id)}return s}d(De,"readableTicketIds");async function j(e,t,o){const n=W(e);return l(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:m(await T(n),o)&&(!C(n)||m(n.scopes,o))}d(j,"mayReadApp");async function Ge(e,t,o){return o===void 0?await j(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(Ge,"canReadRun");async function Le(e,t,o=!1,n=!1){const s=await w(t);if(!s||s.parent!==null||s.run_id!==t||!s.grantee||s.deleting_at&&!n)throw new E(404,"not_found","run not found");if(!await f(e,"read",t))throw new E(404,"not_found","run not found");if(o&&U(e)!==null&&U(e)!==s.grantee)throw new E(403,"other_app_run","cannot change another app's run");return await Z(t,s.grantee,n)}d(Le,"requireRun");async function oe(e,t,o){return o===void 0?await j(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(oe,"canReadNode");const P=new Set(["messages.post.58","messages.post.59"]);async function ne(e,t,o){if(!e.classes.includes(t.class)&&!(t.class!=="anonymous"&&t.class!=="machine"&&t.class!=="import"&&t.class!=="forwarded"&&e.classes.includes("anonymous")))throw new u(403,"permission_error","this operation is not available to the caller");if(e.resource==="daemon-control"&&J())throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available on a shared cloud role");if(t.class==="forwarded"&&t.actor.kind==="app"&&await $(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||l(t))return;if(t.class==="person")return await re(e,t,o);const n=await T(t);if(e.scope&&(!m(n,e.scope)||C(t)&&!m(t.scopes,e.scope)))throw new u(403,"scope_missing",`missing scope ${e.scope}`);if(t.class==="app")return;const s=k(t);t.class==="broker"&&await ue(e,t,o,n);const r=o.id;if((e.resource==="node-read"||e.resource==="node-write")&&r!==void 0){const a=await w(r);if(!a)return;if(e.resource==="node-write"){const i=P.has(e.name);if(a.grantee!==s&&!i)throw new u(403,"other_app_run","cannot change another app's node");if(!await f(t,i&&a.grantee!==s?"message":"read",r))throw a.grantee!==s?new u(403,"other_app_run","cannot change another app's node"):new u(404,"not_found","node not found")}if(e.resource==="node-read"&&!await f(t,"read",r))throw new u(404,"not_found","node not found")}}d(ne,"authorizeOperation");async function re(e,t,o){if(e.resource==="daemon-bash")throw new u(403,"permission_error","a shell on the daemon host is not available to a person bearer");if(e.resource==="daemon-control")throw new u(403,"permission_error","restarting, migrating, admitting or draining the daemon is not available to a person bearer");if(e.resource==="human")return await se(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await ae(e,t,o.request_id);const n=o.id;if(!(e.resource!=="node-read"&&e.resource!=="node-write"||n===void 0||!await w(n))&&!await f(t,P.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(re,"authorizePersonNode");async function se(e,t,o){const n=o.ticket_id!==void 0?new u(404,"ticket_not_found","no matching ticket"):new u(404,"not_found","no request with that id"),s=o.request_id?await O(o.request_id):o.ticket_id?await N(o.ticket_id):null,r=o.comment_id?await q(o.comment_id):null,a=o.review_id?await v(o.review_id).catch(()=>null):r?await v(r.review_id).catch(()=>null):null;if((o.request_id??o.ticket_id??o.review_id??o.comment_id)===void 0)return;const c=s?.requester_node_id??a?.origin_node_id;if(!c||!await w(c)||!await f(t,e.method==="GET"?"read":"edit",c))throw n}d(se,"authorizePersonHuman");async function ae(e,t,o){const n=await ee(o);if(n!==null&&(n.node_id===null||!await w(n.node_id)||!await f(t,e.method==="GET"?"read":"edit",n.node_id)))throw new u(404,"structured_request_not_found",`unknown structured request: ${o}`)}d(ae,"authorizePersonStructuredRequest");async function de(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(e.method==="POST"&&(s==="/v1/human/requests"||s==="/v1/human/reviews")){const r=n.source,a=s.endsWith("/reviews")?n.origin_node_id:n.requester_node_id;if(typeof a!="string")throw new u(403,"permission_error","a request must name a node the person acts on");const i=s.endsWith("/requests")&&r&&typeof r=="object"&&"nodeId"in r?r.nodeId:void 0;for(const c of[a,i])if(c!==void 0&&(typeof c!="string"||!await w(c)||!await f(t,"edit",c)))throw new u(404,"not_found","node not found")}if(s==="/v1/structured-requests"){const r=n.target,a=r&&typeof r=="object"&&"kind"in r&&r.kind==="node"&&"node_id"in r?r.node_id:void 0;if(typeof a=="string"&&await w(a)&&!await f(t,"message",a))throw new u(404,"node_not_found",`unknown node: ${a}`)}}d(de,"authorizePersonBody");async function ue(e,t,o,n){if(e.resource==="daemon-bash"&&(!m(n,"crtr:files:rw:user:.")||!m(t.scopes,"crtr:files:rw:user:.")))throw new u(403,"scope_missing","missing scope crtr:files:rw:user:.");if(e.resource==="human"){const r=e.path,a=e.method==="GET";if(!a&&(r.endsWith("/respond")||r.endsWith("/submit")||r.endsWith("/dismiss")||r.endsWith("/progress")||r.endsWith("/comment-ranges")||r.includes("/feedback-comments")))throw new u(403,"permission_error","only the person may answer or edit the human inbox");const i=o.request_id?await O(o.request_id):o.ticket_id?await N(o.ticket_id):null,c=o.comment_id?await q(o.comment_id):null,g=o.review_id?await v(o.review_id):c?await v(c.review_id):null,h=i?.requester_node_id??g?.origin_node_id;if(h!=null){const _=await w(h);if(_&&(a?!await oe(t,_.grantee??"app:terminal",h):_.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(_&&!a&&!await f(t,"read",h))throw new u(404,"not_found","human request not found")}else if(i||g)throw new u(403,"permission_error","only the person may access a request without a node")}const s=o.id;if(e.resource==="node-own"&&s!==void 0&&s!==t.node)throw new u(403,"other_app_run","the operation requires the calling node")}d(ue,"authorizeBrokerOnly");function ie(e,t){if(!m(e,t))throw new I("the bearer token",t)}d(ie,"assertCeiling");function ce(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ce,"ownerOnlyError");const fe="Crtr-Caused-By",we=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function he(e){const t=e[fe.toLowerCase()];return typeof t=="string"&&we.test(t)?t:void 0}d(he,"causedByOf");function pe(e){return e.map(t=>({...t,ownerOnly:!0}))}d(pe,"ownerOnly");class He{static{d(this,"Router")}routes=[];register(t){const o=K(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:z(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??Q}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=z(o);for(const r of this.routes){if(r.method!==n)continue;const a=me(r.segments,s);if(a!==null)return{handler:r.handler,params:a,operation:r.operation,maxBodyBytes:r.maxBodyBytes}}return null}async handle(t,o,n,s={class:"person"}){try{const r=new URL(t.url??"/","http://127.0.0.1"),a=(t.method??"GET").toUpperCase(),i=this.match(a,r.pathname);if(i===null){G(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await ne(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw ce();i.operation.scope&&ie(n,i.operation.scope)}let c;try{c=await _e(t,i.maxBodyBytes)}catch(A){const B=A instanceof D?"payload_too_large":"invalid_request";G(o,B==="payload_too_large"?413:400,B,A.message);return}s.class==="person"&&s.sub!==void 0&&await de(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await te(i.operation,s,i.params,r.searchParams,c);const g=he(t.headers),h={...g===void 0?{}:{causedBy:g},method:a,path:r.pathname,params:i.params,query:r.searchParams,body:c,ceiling:n,principal:s,...s.class==="anonymous"&&typeof t.headers.authorization=="string"?{publishToken:t.headers.authorization.slice(7)}:{},req:t,res:o},_=await i.handler(h);o.writableEnded||le(o,_)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){x(o,503,{error:{code:"runtime_starting",message:"grant sync is not ready",type:"server_error",origin:"runtime",retryable:!0}});return}const{status:a,body:i}=p(r);a>=500&&H({event:"api.request.failed",level:"error",error:r instanceof Error?r:new Error(String(r)),...s.class==="broker"?{node_id:s.node}:{},fields:{method:(t.method??"GET").toUpperCase(),path:t.url??""}}),x(o,a,i)}}}function z(e){return e.split("/").filter(t=>t.length>0)}d(z,"splitPath");function me(e,t){if(e.length!==t.length)return null;const o={};for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(r);else if(s!==r)return null}return o}d(me,"matchSegments");class D extends Error{static{d(this,"BodyTooLargeError")}}async function _e(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new D(`request body exceeds ${t} bytes`);o.push(a)}if(n===0)return;const s=Buffer.concat(o).toString("utf8").trim();if(s!=="")try{return JSON.parse(s)}catch{throw new Error("request body is not valid JSON")}}d(_e,"readJsonBody");function le(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(le,"writeResult");function x(e,t,o){if(e.headersSent){e.end();return}e.writeHead(t,{"content-type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}d(x,"writeJson");function G(e,t,o,n){x(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(G,"writeError");export{fe as CAUSED_BY_HEADER,He as Router,l as actsAsPerson,k as appOf,ie as assertCeiling,oe as canReadNode,Ge as canReadRun,he as causedByOf,f as mayOnNode,pe as ownerOnly,ce as ownerOnlyError,ze as readableAmong,Pe as readableNodeIds,De as readableTicketIds,Le as requireRun,T as resolvedScopes,U as runCallerApp};
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { CronRefusalReason } from './authority.js';
|
|
2
2
|
export declare const cronDaemonInstanceId: `${string}-${string}-${string}-${string}-${string}`;
|
|
3
|
+
/** A process that owns cron run leases keeps this heartbeat: a `reconciler_leases` row keyed by its instance id. Another process
|
|
4
|
+
* recovers a run it does not own only once that owner's heartbeat has lapsed, so a live peer still building a run's context
|
|
5
|
+
* (no pid recorded yet) is never taken for a crashed one. */
|
|
3
6
|
export declare const CRON_OWNER_HEARTBEAT_TTL_MS = 15000;
|
|
4
7
|
/** Call before naming this process the owner of a cron run lease. Keeps the heartbeat alive from then on; the heartbeat stops
|
|
5
8
|
* itself if a beat fails, and the next call restarts it. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var d=Object.defineProperty;var n=(e,t)=>d(e,"name",{value:t,configurable:!0});import{randomUUID as
|
|
1
|
+
var d=Object.defineProperty;var n=(e,t)=>d(e,"name",{value:t,configurable:!0});import{randomUUID as E}from"node:crypto";import{DAEMON_OWNER_LANE as u,claimReconcilerLease as x,renewReconcilerLease as R}from"../../core/canvas/reconciler-leases.js";import{openDb as w}from"../../core/canvas/db.js";const a=E(),f=15e3,l=5e3;let o,s=0;async function p(){if(await R(u,a,a,f)){s=Date.now();return}await x(u,a,a,f),s=Date.now()}n(p,"beat");async function D(){o!==void 0&&Date.now()-s<l||(await p(),o===void 0&&(o=setInterval(()=>{p().catch(()=>{clearInterval(o),o=void 0})},l),o.unref()))}n(D,"ensureCronOwnerLease");async function O(e){return await(await w()).prepare("SELECT 1 AS alive FROM reconciler_leases WHERE lane = ? AND key = ? AND expires_at > ?").get(u,e,new Date().toISOString())!==void 0}n(O,"cronOwnerAlive");const i=new Map;function C(e){return i.get(e)}n(C,"liveRunFor");function N(e,t){i.set(e,t)}n(N,"registerLiveRun");function g(e,t){const r=i.get(e);r!==void 0&&r.runId===t&&i.delete(e)}n(g,"clearLiveRun");function I(e,t){const r=i.get(e);return r===void 0||r.runId!==t?!1:(r.selfCanceled=!0,!0)}n(I,"markSelfCanceledCronRun");const c=new Map;function L(e){c.set(e.executionId,e)}n(L,"registerCronExecution");function S(e){return c.get(e)}n(S,"cronExecutionFor");function T(e){c.delete(e)}n(T,"dropCronExecution");function M(){return[...c.values()]}n(M,"cronExecutions");export{f as CRON_OWNER_HEARTBEAT_TTL_MS,g as clearLiveRun,a as cronDaemonInstanceId,S as cronExecutionFor,M as cronExecutions,O as cronOwnerAlive,T as dropCronExecution,D as ensureCronOwnerLease,C as liveRunFor,I as markSelfCanceledCronRun,L as registerCronExecution,N as registerLiveRun};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
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};
|
package/dist/daemon/crtrd.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var lr=Object.defineProperty;var s=(e,l)=>lr(e,"name",{value:l,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startBrokerMemoryCap as pr}from"./broker-memory-cap.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as fr}from"../core/peer/directory.js";import{createPeerRelay as ur}from"./peer/relay-service.js";import{writeFileSync as hr,readFileSync as wr,rmSync as vr,mkdirSync as xe,existsSync as P,unlinkSync as De,chmodSync as Te}from"node:fs";import{createServer as Y}from"node:http";import{dirname as gr}from"node:path";import{envCrtrdTcp as Ce,envDocumentPort as yr}from"../shared/env.js";import{openCanvasConversationStore as Sr,serveCanvasConversationStore as _r}from"../core/canvas/sessions.js";import{installConversationStore as br}from"../core/conversation-store/index.js";import{pollRunObservers as kr}from"./runs/observer.js";import{randomBytes as Le}from"node:crypto";import{apiSocketPath as $e,crtrHome as Rr}from"../core/canvas/paths.js";import{activeAppUsers as Pr}from"../core/spaces/users.js";import{ensureAppSpace as Er,ensureUserFiles as Ir}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as xr}from"./launcher-events.js";import{initializeEmptyLayout as Dr,layoutNeedsMigration as Tr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Cr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Lr}from"../core/profiles/relocate.js";import{getNode as $r,getRow as Ar,listNodesForSupervision as Ne,listParkedResidentsWithWakeMail as Nr,setFrozen as Me}from"../core/canvas/index.js";import{createApiServer as Mr,closeServer as Oe}from"./api/server.js";import{Router as Or}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Fr}from"./api/document-listener.js";import{documentSecret as Br}from"./api/document-secret.js";import{createAppListener as Hr}from"./api/app-listener.js";import{registerMachineEnvironment as jr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as zr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Ur,resolvePerson as qr,retireLocalPerson as Wr,setPersonId as Jr}from"../core/canvas/person.js";import{backfillNodeApps as Ge,runPermissionsBoot as Kr}from"../core/permissions/boot.js";import{startRunNotices as Vr}from"./run-notices.js";import{startGrantEffects as Yr}from"./reconcilers/grant-effects.js";import{syncPackages as Qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Xr}from"../core/model-auth/activations.js";import{createGrantSync as Zr,GRANT_SYNC_INTERVAL_S as Fe}from"../core/grants/sync.js";import{sweepSandboxes as et}from"../core/grants/on-sync.js";import{rebuildCronExecutions as rt}from"./cron/run-socket.js";import{hasSyncedGrants as tt}from"../core/grants/mirror.js";import{readConfig as fe}from"../core/config.js";import{reconcileUndeliveredTickets as nt}from"./human/sweep.js";import{resetHandedOffDeliveries as ot}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as it}from"../core/canvas/daemon-actions.js";import{sweepReviews as at}from"./review/sweep.js";import{pidfilePath as ue}from"./pidfile.js";import{rendererWarning as st}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ct}from"./supervise-cadence.js";import{createResumeDetector as lt}from"./resume-detector.js";import{setFatalFaultAnnouncer as dt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as pt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as mt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ft}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ut}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ht}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as vt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as gt}from"./reconcilers/action-lane.js";import{endLiveExecution as yt,hasObservedExit as St,latestExecutionForNode as _t,migrateLegacyExecutionIdentities as bt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as kt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as Rt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Et}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as It}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as xt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Dt}from"../core/ledger/rates.js";import{IdleSandboxReconciler as Tt}from"./reconcilers/idle-sandbox.js";import{LedgerSandboxReconciler as Ct}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Lt}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as $t}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as he}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as At}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as Nt}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Mt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Ot}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Gt,subscribeImageBuilt as Ft}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Bt}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Be,capturePidCommand as Ht,captureTeardownSnapshot as He,isPidAlive as jt,isAnyPidAlive as je,killProcessTreePids as ze}from"../core/canvas/pid.js";import{bindFleet as zt,boundFleet as Ue}from"../core/runtime/fleet.js";import{bindDaemonControl as Ut,clearDaemonControl as qt}from"./control.js";import{execDaemon as Wt,spawnDaemon as Jt}from"./manage.js";import{reconcileAndMigrateBoot as Kt}from"../core/canvas/boot.js";import{resolveInstallId as Vt}from"../core/canvas/install-id.js";import{setInstallId as Yt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Qt,daemonOwnershipApplies as Xt,daemonOwnershipClaimed as Zt,releaseDaemonOwnership as qe}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as en,closeAllDbs as we,openDb as rn,withCanvasWrite as ve}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as tn}from"../core/canvas/import-sqlite.js";import{ensurePostgres as nn,ensurePostgresHealthy as on,stopPostgres as an,withPostgresStartLock as sn}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as cn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as ln}from"./api/handlers/broker-ops.js";import{reconcilePackages as dn}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as pn}from"../core/scoped-state/migrate-app-installs.js";import{publish as mn,readBuiltinSnapshot as fn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as un,reapStaleSpares as hn}from"../core/runtime/warm-pool.js";import{DaemonFleet as wn}from"./fleet.js";import{copyNodeFilesToRows as vn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as gn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as yn}from"../core/events/source.js";import{activateCanvasImport as Sn,MigrationBlockedError as _n,runForcedCanvasImport as bn}from"../migrations/activation.js";import{adoptInstallPerson as kn,convertLegacyScopedStore as Rn,personStoresCopied as Pn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as En}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as We,installPreludeSnapshot as In}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ge}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ye}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as ma}from"../core/runtime/broker-ownership.js";function Se(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(Se,"brokerCommandEpoch");const xn=5e3,Ke=150;async function Dn(e){const l=Be();if(l===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=Rr(),m=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ye(w,f)||Se(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||m.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of m){const c=Ht(i.pid);if(c===null||!c.includes("broker-cli.js")||!ye(c,f)||Se(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=He(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+xn;for(;Date.now()<h&&o.some(i=>je(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];je(c)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):ze(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Be();if(d===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ye(w,f)&&Se(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:g,sigkilled:y}})}s(Dn,"reapPriorEpochBrokers");const Tn=5e3;async function Cn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await $r(o))?.status;(h==="active"||h==="idle")&&await Me(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:He(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,Tn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),m])));const g=[];for(const o of f)jt(o.pid)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):ze(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await yt(o,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Cn,"teardownFleet");function Q(...e){xe(gr(ue()),{recursive:!0}),hr(ue(),[process.pid,...e].join(`
|
|
1
|
+
var lr=Object.defineProperty;var s=(e,l)=>lr(e,"name",{value:l,configurable:!0});import{applyBootSettings as dr}from"./boot-settings.js";import{startBrokerMemoryCap as pr}from"./broker-memory-cap.js";import{startPeerOutbox as mr}from"./peer/outbox.js";import{reportMachineStatus as fr}from"../core/peer/directory.js";import{createPeerRelay as ur}from"./peer/relay-service.js";import{writeFileSync as hr,readFileSync as wr,rmSync as vr,mkdirSync as xe,existsSync as P,unlinkSync as De,chmodSync as Te}from"node:fs";import{createServer as Y}from"node:http";import{dirname as gr}from"node:path";import{envCrtrdTcp as Ce,envDocumentPort as yr}from"../shared/env.js";import{openCanvasConversationStore as Sr,serveCanvasConversationStore as _r}from"../core/canvas/sessions.js";import{installConversationStore as br}from"../core/conversation-store/index.js";import{pollRunObservers as kr}from"./runs/observer.js";import{randomBytes as Le}from"node:crypto";import{apiSocketPath as $e,crtrHome as Rr}from"../core/canvas/paths.js";import{activeAppUsers as Pr}from"../core/spaces/users.js";import{ensureAppSpace as Er,ensureUserFiles as Ir}from"../core/spaces/space.js";import{LAUNCHER_SOCKET as C}from"../launcher/spec.js";import{launcherRequest as N}from"../launcher/client.js";import{installLauncherEventSink as xr}from"./launcher-events.js";import{initializeEmptyLayout as Dr,layoutNeedsMigration as Tr,socketDir as Ae}from"../core/layout.js";import{migrateLooseKeys as Cr}from"../core/layout-migrate/loose-keys.js";import{relocateProfileFolders as Lr}from"../core/profiles/relocate.js";import{getNode as $r,getRow as Ar,listNodesForSupervision as Ne,listParkedResidentsWithWakeMail as Nr,setFrozen as Me}from"../core/canvas/index.js";import{createApiServer as Mr,closeServer as Oe}from"./api/server.js";import{Router as Or}from"./api/router.js";import{healthRoutes as Gr}from"./api/handlers/health.js";import{createDocumentListener as Fr}from"./api/document-listener.js";import{documentSecret as Br}from"./api/document-secret.js";import{createAppListener as Hr}from"./api/app-listener.js";import{registerMachineEnvironment as jr}from"../core/environments.js";import{registerBlaxelRunnerFromEnv as zr}from"../core/secrets/blaxel-register.js";import{markCloudRole as Ur,resolvePerson as qr,retireLocalPerson as Wr,setPersonId as Jr}from"../core/canvas/person.js";import{backfillNodeApps as Ge,runPermissionsBoot as Kr}from"../core/permissions/boot.js";import{startRunNotices as Vr}from"./run-notices.js";import{startGrantEffects as Yr}from"./reconcilers/grant-effects.js";import{syncPackages as Qr}from"../core/packages/directory-sync.js";import{startActivationDelivery as Xr}from"../core/model-auth/activations.js";import{createGrantSync as Zr,GRANT_SYNC_INTERVAL_S as Fe}from"../core/grants/sync.js";import{sweepSandboxes as et}from"../core/grants/on-sync.js";import{rebuildCronExecutions as rt}from"./cron/run-socket.js";import{hasSyncedGrants as tt}from"../core/grants/mirror.js";import{readConfig as fe}from"../core/config.js";import{reconcileUndeliveredTickets as nt}from"./human/sweep.js";import{resetHandedOffDeliveries as ot}from"../core/canvas/deliveries.js";import{resetHandedOffDaemonActions as it}from"../core/canvas/daemon-actions.js";import{sweepReviews as at}from"./review/sweep.js";import{pidfilePath as ue}from"./pidfile.js";import{rendererWarning as st}from"../core/runtime/package-health.js";import{DEFAULT_INTERVAL_MS as ct}from"./supervise-cadence.js";import{createResumeDetector as lt}from"./resume-detector.js";import{setFatalFaultAnnouncer as dt}from"../core/canvas/recovery.js";import{BrokerSupervisionReconciler as pt}from"./reconcilers/broker-supervision.js";import{MachineOfflineReconciler as mt}from"./reconcilers/machine-offline.js";import{ControllerDeathReconciler as ft}from"./reconcilers/controller-death.js";import{NodeLifecycleReconciler as ut}from"./reconcilers/node-lifecycle/tick.js";import{NodeDeadlineReconciler as ht}from"./reconcilers/node-deadline.js";import{CronLaneReconciler as wt}from"./reconcilers/cron-lane.js";import{DeliveryLaneReconciler as vt}from"./reconcilers/delivery-lane.js";import{ActionLaneReconciler as gt}from"./reconcilers/action-lane.js";import{endLiveExecution as yt,hasObservedExit as St,latestExecutionForNode as _t,migrateLegacyExecutionIdentities as bt}from"../core/canvas/executions.js";import{revokePriorEpochNodeTokens as kt}from"../core/canvas/node-tokens.js";import{PendingReviewSubmitReconciler as Rt}from"./reconcilers/pending-review-submit.js";import{StorageMaintenanceReconciler as Pt}from"./reconcilers/storage-maintenance.js";import{StorageDueWorkReconciler as Et}from"./reconcilers/storage-due-work.js";import{GroupInviteExpiryReconciler as It}from"./reconcilers/group-invite-expiry.js";import{PurgeDueWorkReconciler as xt}from"./reconcilers/purge-due-work.js";import{assertLedgerEnv as Dt}from"../core/ledger/rates.js";import{LedgerSandboxReconciler as Tt}from"./reconcilers/ledger-sandbox.js";import{LedgerStorageReconciler as Ct}from"./reconcilers/ledger-storage.js";import{LedgerR2Reconciler as Lt}from"./reconcilers/ledger-r2.js";import{importedNodesHeld as he}from"./reconcilers/live-obligation.js";import{ImportLaneReconciler as $t}from"./reconcilers/import-lane.js";import{BashDeadlineReconciler as At}from"./reconcilers/bash-deadline.js";import{FaultRetryBackstopReconciler as Nt}from"./reconcilers/fault-retry-backstop.js";import{StructuredRequestReconciler as Mt}from"./reconcilers/structured-request-lane.js";import{RecipeImageReconciler as Ot,subscribeImageBuilt as Gt}from"./reconcilers/recipe-image.js";import{reconcileStructuredRequestSidecars as Ft}from"./structured-requests/boot.js";import{captureLivenessSnapshot as Be,capturePidCommand as Bt,captureTeardownSnapshot as He,isPidAlive as Ht,isAnyPidAlive as je,killProcessTreePids as ze}from"../core/canvas/pid.js";import{bindFleet as jt,boundFleet as Ue}from"../core/runtime/fleet.js";import{bindDaemonControl as zt,clearDaemonControl as Ut}from"./control.js";import{execDaemon as qt,spawnDaemon as Wt}from"./manage.js";import{reconcileAndMigrateBoot as Jt}from"../core/canvas/boot.js";import{resolveInstallId as Kt}from"../core/canvas/install-id.js";import{setInstallId as Vt}from"../core/runtime/nodes.js";import{claimDaemonOwnership as Yt,daemonOwnershipApplies as Qt,daemonOwnershipClaimed as Xt,releaseDaemonOwnership as qe}from"../core/canvas/daemon-owner.js";import{canvasDatabaseUrl as Zt,closeAllDbs as we,openDb as en,withCanvasWrite as ve}from"../core/canvas/db.js";import{importSqliteCanvasIfPresent as rn}from"../core/canvas/import-sqlite.js";import{ensurePostgres as tn,ensurePostgresHealthy as nn,stopPostgres as on,withPostgresStartLock as an}from"./postgres/index.js";import{brokerSignalBus as M}from"./broker-signals/bus.js";import{brokerSignalStreams as sn}from"./api/handlers/broker-signals.js";import{setRequestsStartRunObservers as cn}from"./api/handlers/broker-ops.js";import{reconcilePackages as ln}from"../core/graph/package-reconcile.js";import{migrateAppInstalls as dn}from"../core/scoped-state/migrate-app-installs.js";import{publish as pn,readBuiltinSnapshot as mn}from"../core/graph/package-publish.js";import{prewarmRecentRecipes as fn,reapStaleSpares as un}from"../core/runtime/warm-pool.js";import{DaemonFleet as hn}from"./fleet.js";import{copyNodeFilesToRows as wn}from"../core/runtime/first-boot-rows.js";import{BOOT_MIGRATIONS as vn}from"./boot-migrations.js";import{emitEvent as p}from"../core/events/emit.js";import{operationIdContext as k}from"../core/events/operation-id.js";import{bindDaemonEventSource as gn}from"../core/events/source.js";import{activateCanvasImport as yn,MigrationBlockedError as Sn,runForcedCanvasImport as _n}from"../migrations/activation.js";import{adoptInstallPerson as bn,convertLegacyScopedStore as kn,personStoresCopied as Rn}from"../core/scoped-state/migrate.js";import{readLegacyUserSnapshot as Pn}from"../core/scoped-state/legacy-profiles.js";import{heldPersons as We,installPreludeSnapshot as En}from"../core/scoped-state/person-store.js";import{loadPersonSettings as ge}from"../core/scoped-state/person-rows.js";import{userScopeRoot as Je}from"../core/scope.js";import{brokerCommandDeclaresCanvasHome as ye}from"../core/runtime/broker-ownership.js";import{brokerCommandDeclaresCanvasHome as la}from"../core/runtime/broker-ownership.js";function Se(e){return/ --epoch (\S+) /.exec(e)?.[1]??null}s(Se,"brokerCommandEpoch");const In=5e3,Ke=150;async function xn(e){const l=Be();if(l===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness"}}),new Error("prior-epoch broker census could not capture the process table");const f=Rr(),m=[];for(const[i,c]of l.processes){const w=c.command;if(c.zombie||!w.includes("broker-cli.js")||!ye(w,f)||Se(w)===e)continue;const b=w.trim().split(/\s+/).at(-1)??"";b===""||b.endsWith("broker-cli.js")||m.push({pid:i,nodeId:b})}let g=0;const o=[];for(const i of m){const c=Bt(i.pid);if(c===null||!c.includes("broker-cli.js")||!ye(c,f)||Se(c)===e||c.trim().split(/\s+/).at(-1)!==i.nodeId)continue;const w=He(i.pid,null);if(!w.reused){try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):process.kill(i.pid,"SIGTERM")}catch{continue}g++,o.push({pid:i.pid,snap:w})}}const h=Date.now()+In;for(;Date.now()<h&&o.some(i=>je(i.snap.tree.length>0?i.snap.tree:[i.pid]));)await new Promise(i=>setTimeout(i,Ke));let y=0;for(const i of o){const c=i.snap.tree.length>0?i.snap.tree:[i.pid];je(c)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:i.pid}):ze(c,"SIGKILL",i.snap.identities),y++)}y>0&&await new Promise(i=>setTimeout(i,Ke));const d=Be();if(d===null)throw p({level:"error",event:"daemon.census.snapshot_failed",fields:{invariant:"prior-epoch brokers are reaped before readiness",stage:"final"}}),new Error("prior-epoch broker census could not capture the final process table");const u=[];for(const[i,c]of d.processes){const w=c.command;c.zombie||!w.includes("broker-cli.js")||ye(w,f)&&Se(w)!==e&&u.push(i)}if(u.length>0)throw new Error(`prior-epoch broker census could not prove termination of pid(s): ${u.join(", ")}`);p({level:"info",event:"daemon.census.completed",fields:{prior_epoch_brokers:m.length,sigtermed:g,sigkilled:y}})}s(xn,"reapPriorEpochBrokers");const Dn=5e3;async function Tn(e){const l=Array.from(e.entries());if(l.length===0)return;for(const[o]of l){const h=(await $r(o))?.status;(h==="active"||h==="idle")&&await Me(o,new Date().toISOString())}const f=l.map(([,o])=>({pid:o.pid,snap:He(o.pid,null),exited:o.handle.exited}));for(const o of f)if(!o.snap.reused)try{process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):process.kill(o.pid,"SIGTERM")}catch{}const m=new Promise(o=>{setTimeout(o,Dn).unref()});await Promise.allSettled(f.map(o=>Promise.race([o.exited.then(()=>{}),m])));const g=[];for(const o of f)Ht(o.pid)&&(process.platform==="linux"&&P(C)?await N({operation:"stop",pid:o.pid}):ze(o.snap.tree.length>0?o.snap.tree:[o.pid],"SIGKILL",o.snap.identities),g.push(o));await Promise.all(g.map(o=>o.exited));for(const[o]of l)await yt(o,{reason:"daemon-teardown"});p({level:"info",event:"daemon.fleet_teardown.completed",fields:{brokers:f.length,sigkilled:g.length}})}s(Tn,"teardownFleet");function Q(...e){xe(gr(ue()),{recursive:!0}),hr(ue(),[process.pid,...e].join(`
|
|
2
2
|
`),"utf8")}s(Q,"writePidfile");function Ve(e){return typeof e=="object"&&e!==null&&e.code==="ENOENT"}s(Ve,"isMissingPathError");function Ye(e){const l=ue();let f;try{f=wr(l,"utf8")}catch(m){if(Ve(m))return;throw m}if(f.split(`
|
|
3
|
-
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{vr(l)}catch(m){if(Ve(m))return;throw m}}s(Ye,"removeOwnedPidfileMirror");const
|
|
4
|
-
`),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),h}s(
|
|
5
|
-
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,m=
|
|
3
|
+
`,1)[0].trim()!==String(e))throw new Error(`daemon readiness mirror does not name this invocation (expected pid ${e})`);try{vr(l)}catch(m){if(Ve(m))return;throw m}}s(Ye,"removeOwnedPidfileMirror");const Cn={acceptsDetachedWork:s(()=>!0,"acceptsDetachedWork"),registerDetached:s(e=>{e.catch(()=>{})},"registerDetached")},X=new pt;dt(e=>X.handleFatalFault(e,!1));const Ln=new ft,$n=new mt,Qe=new ut,An=new ht,Nn=new wt,Mn=new vt,On=new gt,Gn=new Rt,Fn=new Pt,Bn=new Et,Hn=new xt,jn=new It,zn=new Tt,Un=new Ct,qn=new Lt,Wn=new $t,Jn=new At,Kn=new Nt,Vn=new Mt,Yn=new Ot;async function Qn(e=Date.now(),l=Cn){const f=Ue(),m=await X.runFleetPreamble(f);let g,o,h;try{o=await he();const d=(await Ne()).filter(i=>!o.has(i.node_id));g=d.filter(i=>i.status==="active"||i.status==="idle"),h=d.filter(i=>i.status==="done"||i.status==="canceled"||i.status==="dead");const u=new Set(h.map(i=>i.node_id));h.push(...(await Nr()).filter(i=>!u.has(i.node_id)&&!o.has(i.node_id)))}catch(d){p({level:"error",event:"canvas.node_list.failed",error:d});return}await X.run(e,{rows:g,fleet:f,lifecycle:l,held:o}),await Ln.run(e,{rows:g,held:o}),await $n.run(e);const y=await Qe.run(e,{rows:[...g,...h],fleet:f});await An.run(e,o),await Vn.run(e,o),await Yn.run(e,{lifecycle:l}),await Nn.run(e,{lifecycle:l,held:o}),await Mn.run(e,{lifecycle:l}),await On.run(e,{lifecycle:l}),await Gn.run(e,{lifecycle:l}),await Fn.run(e,{lifecycle:l,fleet:f,held:o}),Bn.run(e,{lifecycle:l}),Hn.run(e,{lifecycle:l}),jn.run(e,{lifecycle:l}),zn.run(e,{lifecycle:l}),Un.run(e,{lifecycle:l}),qn.run(e,{lifecycle:l}),Wn.run(e,{lifecycle:l}),await kr(),Kn.run(e,{fleet:f,lifecycle:l}),await Jn.run(e,{rows:g}),X.warnIfSaturated({fleet:f,lifecycle:l,thresholds:m,frozen:y})}s(Qn,"superviseTick");async function Xn(e,l=Date.now()){if((await he()).has(e))return;const f=await _t(e);if(f===null||!St(f))return;const m=await Ar(e);m===null||m.kind==="human"||await Qe.runNode(l,m,Ue())}s(Xn,"exitedNodePass");function Z(e){return e===void 0||e==="reconcile"}s(Z,"roleRunsLanes");function O(e){return e===void 0||e==="api"}s(O,"roleServesRequests");const Zn=66e4;function eo(e){const l=new Or().registerAll(Gr(()=>null).filter(c=>c.pattern==="/healthz")),f=s((c,w)=>{const b=(c.url??"/").split("?")[0];if((c.method??"GET").toUpperCase()==="GET"&&b==="/healthz"){l.handle(c,w,null,{class:"person"});return}w.writeHead(404,{"content-type":"application/json; charset=utf-8"}),w.end(JSON.stringify({error:{code:"not_found",message:"this process serves only /healthz",origin:"runtime"}}))},"handler"),m=$e();P(m)&&De(m);const g=Y(f),o=new Promise((c,w)=>{g.once("error",w),g.listen(m,()=>{g.off("error",w),Te(m,384),c()})});let h,y=null,d=o;const u=e.tcp??Ce()??fe("user").api.tcp;if(u!==void 0&&u!==""){const c=/^(.*):(\d+)$/.exec(u.trim());if(c===null||Number(c[2])>65535)throw new Error(`invalid reconcile probe TCP address: ${u}`);const w=Y(f);w.on("error",b=>p({event:"api.server.failed",level:"error",error:b})),d=o.then(()=>new Promise(b=>{w.once("error",()=>b()),w.listen(Number(c[2]),c[1]===""?"0.0.0.0":c[1],()=>{const E=w.address();y=`${E.address}:${E.port}`,b()})})),h=w}let i=!1;return{ready:d,tcpAddress:s(()=>y,"tcpAddress"),async close(c={}){if(!i){i=!0,await Promise.all([Oe(g,new Set,c.graceMs),h===void 0?Promise.resolve():Oe(h,new Set,c.graceMs)]);try{P(m)&&De(m)}catch{}}}}}s(eo,"createProbeServer");const ro="daemon is draining for shutdown and admits no new work";async function to(e){xe(Ae(),{recursive:!0,mode:493}),process.platform==="linux"&&Te(Ae(),493);const l=$e();if(P(l))throw new Error(`layout refusal cannot bind occupied socket: ${l}`);const f=Y((d,u)=>{if(d.method==="GET"&&d.url==="/healthz"){u.writeHead(200,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({ok:!1,daemon_up:!0,store_accessible:!1,brokers_reconciled:!1,startup_phase:"blocked",startup_blocked:"layout_migration_required"}));return}u.writeHead(503,{"content-type":"application/json; charset=utf-8"}),u.end(JSON.stringify({error:{code:"layout_migration_required",message:"run crtr sys migrate while the runtime is offline",type:"server_error",origin:"runtime",retryable:!1}}))});await new Promise((d,u)=>{f.once("error",u),f.listen(l,()=>{f.off("error",u),d()})});let m;const g=e.tcp??Ce();if(g){const d=/^(.*):(\d+)$/.exec(g);if(!d||Number(d[2])>65535)throw new Error(`invalid refusal TCP address: ${g}`);const u=Y(f.listeners("request")[0]);await new Promise((i,c)=>{u.once("error",c),u.listen(Number(d[2]),d[1],()=>{u.off("error",c),i()})}),m=u}Q();let o;const h=s(()=>(o??=(async()=>{f.closeAllConnections(),m?.closeAllConnections(),await Promise.all([f,m].filter(d=>d!==void 0).map(d=>new Promise((u,i)=>d.close(c=>c?i(c):u())))),Ye(process.pid),process.off("SIGINT",y),process.off("SIGTERM",y)})(),o),"cleanup"),y=s(()=>{h().then(()=>process.exit(0),d=>{process.stderr.write(`[crtrd] layout refusal cleanup failed: ${String(d)}
|
|
4
|
+
`),process.exit(1)})},"onSignal");return process.on("SIGINT",y),process.on("SIGTERM",y),h}s(to,"serveLayoutRefusal");async function no(e={}){if(e.role==="machine")return(await import("./machine-daemon.js")).runMachineDaemon();if(Tr())return to(e);Dr();const l=s(t=>{process.stderr.write(`[crtrd] ${t}
|
|
5
|
+
`)},"logPostgres"),f=!!process.env.CRTR_TEST_PG_URL,m=Qt(e.role);cn(Z(e.role));const g=s(async()=>m?await Yt(Le(16).toString("hex")):{claimed:!0,claim:{pid:process.pid,pid_identity:"",token:Le(16).toString("hex")}},"claimOwnership"),{database:o,ownership:h}=f?{database:{url:await Zt()},ownership:await g()}:await an(async()=>({database:await tn({log:l,startLockHeld:!0}),ownership:await g()}));if(!h.claimed){if(h.reason==="incumbent_alive")process.stderr.write(`[crtrd] already running (pid ${h.incumbentPid??"?"})
|
|
6
6
|
`);else{const t=[h.incumbentPid!==void 0?`pid ${h.incumbentPid}`:void 0,h.verdict!==void 0?`verdict ${h.verdict}`:void 0].filter(v=>v!==void 0),a=t.length>0?` (${t.join(", ")})`:"";process.stderr.write(`[crtrd] claim lost: ${h.reason}${a}
|
|
7
|
-
`),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{m&&await
|
|
7
|
+
`),h.reason==="own_identity_indeterminate"&&process.stderr.write("[crtrd] cannot read its own process identity. crouter needs /proc on Linux, or the `ps` command elsewhere (Debian/Ubuntu: apt-get install procps).\n"),(h.reason==="own_identity_indeterminate"||h.reason==="incumbent_malformed")&&(process.exitCode=1)}return async()=>{}}const y=h.claim;let d=null,u=null,i=null,c=null,w,b="";try{m&&await xn(y.token);for(const r of Lr())process.stderr.write(`[crtrd] ${r}
|
|
8
8
|
`);for(const r of await Cr())process.stderr.write(`[crtrd] ${r}
|
|
9
|
-
`);await
|
|
10
|
-
`)}else{d=await qr(),d!==null&&(Jr(d.id),await ge(d.id));const r=await ve(async n=>(await Ge(n),d===null?null:await
|
|
9
|
+
`);await en(),await rn(o.url,l);const t=e.role===void 0&&!await Rn();let a=null;t&&(kn({kind:"user",root:Je()}),a=Pn(Je())),e.role===void 0&&En(a??{profiles:[],defaults:{},settings:{},state:{},apps:{}}),await M.listen(o.url);const v=s(r=>{ge(r).catch(n=>p({level:"error",event:"daemon.settings.reload_failed",error:n}))},"reloadPerson");if(w=await M.subscribe(r=>{We().includes(r)&&v(r)},{kinds:["settings"],onListenStart:s(()=>{for(const r of We())v(r)},"onListenStart")}),e.role!==void 0&&Ur(),e.role!==void 0){let r;try{r=mn()}catch(_){p({level:"error",event:"daemon.packages.snapshot_failed",error:_})}const n=await ve(async _=>(await Ge(_),r===void 0?void 0:await pn(_,r,"release")));c=await ve(async _=>await dn(_));for(const _ of n?.invalid??[])process.stderr.write(`[crtrd] package file is not a document: ${_.path}: ${_.error}
|
|
10
|
+
`)}else{d=await qr(),d!==null&&(Jr(d.id),await ge(d.id));const r=await ve(async n=>(await Ge(n),d===null?null:await ln(n)));if(r!==null){for(const n of r.conflicts)process.stderr.write(`[crtrd] plugin documents not reconciled: ${n.message}
|
|
11
11
|
`);for(const n of r.invalid)process.stderr.write(`[crtrd] package file is not a document: ${n.path}: ${n.error}
|
|
12
12
|
`);for(const n of r.quarantined)process.stderr.write(`[crtrd] plugin "${n.name}" has a damaged ${n.file} (${n.reason}); ${n.movedTo!==void 0?`moved to ${n.movedTo}`:"left in place and skipped"}
|
|
13
13
|
`);for(const n of r.kinds.refused)process.stderr.write(`[crtrd] plugin "${n.plugin}" kind ${n.kind} not registered: ${n.message}
|
|
14
14
|
`);for(const n of r.kinds.invalid)process.stderr.write(`[crtrd] plugin "${n.plugin}" declares invalid object kinds or scopes; no kinds registered and no app token: ${n.error}
|
|
15
|
-
`)}}if(b=await
|
|
16
|
-
`)}}catch(t){await M.close();try{if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}await we()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,ee,j=Promise.resolve(),re=!1,z,te,ne,oe,ie,L;const U=new Set;let ae=!1,_e=!1,x,I,se,q=!1,W,$,G,F,B,ce,le,de,pe;const Xe=lt();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Ze=null;function er(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(er,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const rr={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function tr(){try{E=!1,
|
|
15
|
+
`)}}if(b=await Kt(),Vt(b),e.role===void 0&&d!==null){if(await bn(d.id),process.platform==="darwin"){const{readConfig:r,updateConfig:n}=await import("../core/config.js");if(r("user").paths?.user_files===void 0){const{homedir:_}=await import("node:os");await n("user",Ie=>{Ie.paths??={},Ie.paths.user_files??=_()})}}u=await Wr(),u.joinedFrom!==null&&await ge(u.person),await dr(),i=await Kr()}if(process.platform==="linux"&&P(C)&&(xr(),await N({operation:"users.sync",users:await Pr()})),m){await kt(y.token);const r=await wn();Object.values(r).some(n=>n>0)&&process.stderr.write(`[crtrd] node files copied into rows: ${JSON.stringify(r)}
|
|
16
|
+
`)}}catch(t){await M.close();try{if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}await we()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}let E=!0,ee,j=Promise.resolve(),re=!1,z,te,ne,oe,ie,L;const U=new Set;let ae=!1,_e=!1,x,I,se,q=!1,W,$,G,F,B,ce,le,de,pe;const Xe=lt();let D,S={phase:"initializing",message:"daemon startup is running the canvas import and normal services are unavailable",blockerPaths:[]},A="initial startup activation",Ze=null;function er(){return S.phase==="ready"?null:{phase:S.phase,message:S.message,blockerPaths:S.blockerPaths}}s(er,"startupBlock");function R(t){U.add(t),t.finally(()=>{U.delete(t)}).catch(()=>{})}s(R,"registerDetached");const rr={acceptsDetachedWork:s(()=>E,"acceptsDetachedWork"),registerDetached:R};async function tr(){try{E=!1,sn.close(),ne?.(),ne=void 0,oe?.(),w?.(),oe=void 0,ie?.(),ie=void 0,de?.(),de=void 0,await M.close(),z!==void 0&&(clearInterval(z),z=void 0),te?.(),te=void 0,G!==void 0&&(clearInterval(G),G=void 0),F!==void 0&&(clearInterval(F),F=void 0),pe?.(),pe=void 0;let t;do t=j,await t;while(t!==j);for(;U.size>0;)await Promise.allSettled([...U]);if(L!==void 0&&(m&&await Tn(L),await L.exitsSettled(),L.dispose()),se!==void 0&&await se.close(),I!==void 0&&!q&&(q=!0,await I.close()),ce?.(),ce=void 0,le?.(),le=void 0,B!==void 0){const a=B;B=void 0,await a.stop()}if($!==void 0){const a=$;$=void 0,await a.close()}if(W!==void 0){const a=W;W=void 0,await a.close()}if(ae||(Ye(process.pid),ae=!0),ae&&!_e){if(m){const{released:a}=await qe(y);if(!a)throw new Error("daemon ownership claim was not released")}_e=!0,await we()}}finally{Ut(),process.off("SIGINT",Re),process.off("SIGTERM",Pe),process.off("exit",Ee)}}s(tr,"cleanupAttempt");const J=1e3;let be=!1;function nr(){if(e.role!==void 0)throw new Error(`a ${e.role} daemon never hands over to a successor: its orchestrator replaces it`);return be?{graceMs:J}:(be=!0,k.fresh(()=>{p({level:"info",event:"daemon.handover.armed",fields:{pid:process.pid,grace_ms:J}})}),setTimeout(()=>{or()},J),{graceMs:J})}s(nr,"requestHandover");async function or(){try{await T()}catch(t){const a=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`[crtrd] handover cleanup failed:
|
|
17
17
|
${a}
|
|
18
|
-
`),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await
|
|
19
|
-
`),process.exit(1)}process.exit(0)}s(or,"performHandover");function T(){if(x!==void 0)return x;const t=tr();return x=t,t.then(()=>{x===t&&(x=void 0)},()=>{x===t&&(x=void 0)}),t}s(T,"requestCleanup");async function ir(){S={phase:"initializing",message:
|
|
18
|
+
`),process.exit(1)}try{process.platform==="linux"&&P(C)&&(await N({operation:"daemon.handover"}),process.exit(0)),process.pid===1&&await qt();const t=await Wt({waitForJoinLock:!0});k.fresh(()=>{p({level:"info",event:"daemon.handover.completed",fields:{predecessor_pid:process.pid,successor_pid:t.pid??t.existing_pid??null,spawned:t.started}})})}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.handover.successor_failed",error:t})});const a=t instanceof Error?t.message:String(t);process.stderr.write(`[crtrd] handover successor failed to start: ${a}
|
|
19
|
+
`),process.exit(1)}process.exit(0)}s(or,"performHandover");function T(){if(x!==void 0)return x;const t=tr();return x=t,t.then(()=>{x===t&&(x=void 0)},()=>{x===t&&(x=void 0)}),t}s(T,"requestCleanup");async function ir(){S={phase:"initializing",message:ro,blockerPaths:[]},I!==void 0&&!q&&(q=!0,await I.close({graceMs:Zn}))}s(ir,"drainApi");async function ke(t){try{t==="SIGTERM"&&e.role==="api"&&await ir(),await T(),await on({claimed:s(async()=>{try{return m&&await Xt()}finally{await we()}},"claimed")}),process.exit(0)}catch(a){process.exitCode=1;const v=a instanceof Error?a.stack??`${a.name}: ${a.message}`:String(a);process.stderr.write(`[crtrd] ${t} cleanup failed:
|
|
20
20
|
${v}
|
|
21
|
-
`),process.exit(1)}}s(ke,"handleSignal");function Re(){ke("SIGINT")}s(Re,"onSigint");function Pe(){ke("SIGTERM")}s(Pe,"onSigterm");function Ee(){T().catch(()=>{})}s(Ee,"onExit");async function K(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(K,"enqueue");async function V(){!E||re||(Xe.check()&&D&&(p({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),re=!0,await K(async()=>{if(re=!1,!!E)try{f||await
|
|
21
|
+
`),process.exit(1)}}s(ke,"handleSignal");function Re(){ke("SIGINT")}s(Re,"onSigint");function Pe(){ke("SIGTERM")}s(Pe,"onSigterm");function Ee(){T().catch(()=>{})}s(Ee,"onExit");async function K(t){E&&(j=j.then(t).then(()=>{},a=>{k.fresh(()=>{p({level:"error",event:"daemon.lane_job.failed",error:a})})}))}s(K,"enqueue");async function V(){!E||re||(Xe.check()&&D&&(p({level:"info",event:"daemon.resume.detected"}),R(D().catch(()=>{}))),re=!0,await K(async()=>{if(re=!1,!!E)try{f||await nn({log:l}),await Qn(Date.now(),rr)}catch(t){k.fresh(()=>{p({level:"error",event:"daemon.tick.failed",error:t})})}}))}s(V,"enqueueTick");let H=null;async function ar(){if(H!==null)throw{status:500,code:"admission_failed",message:`daemon admission previously failed: ${H instanceof Error?H.message:String(H)}`};if(S.phase==="ready")return{admitted:!1,already_admitted:!0,startup_phase:"ready"};if(S.phase!=="prepared"&&S.phase!=="recovering")throw{status:409,code:"not_prepared",message:S.message};const t=S.phase==="prepared";try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},t?{admitted:!0,already_admitted:!1,startup_phase:"ready"}:{admitted:!1,already_admitted:!0,startup_phase:"ready"}}catch(a){throw H=a,{status:500,code:"admission_failed",message:`daemon admission failed: ${a instanceof Error?a.message:String(a)}`}}}s(ar,"admitStartup");async function sr(t){if(A!==null)throw{status:409,code:"migration_in_progress",message:`the canvas import is already running (${A})`};A="repair";try{const a=await _n({dryRun:t.dryRun});if(t.dryRun||a.pending||S.phase!=="blocked")return{result:a,resumed:!1};if(e.prepare)return S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]},{result:a,resumed:!1};try{return await me(),S={phase:"ready",message:"",blockerPaths:[]},{result:a,resumed:!0}}catch(v){const r=v instanceof Error?v.message:String(v);return setTimeout(()=>{T().catch(()=>{})},1e3),{result:a,resumed:!1,resumeError:r}}}finally{A=null}}s(sr,"repairMigrations");async function cr(){ee=e.intervalMs??ct;const t=y.token;L=new hn({epoch:t,enqueue:K}),jt(L),S={phase:"recovering",message:"daemon startup recovery is running and normal services are unavailable",blockerPaths:[]},k.fresh(()=>{p({level:"info",event:"daemon.started",fields:{pid:process.pid,interval_ms:ee}})});const a=b;k.fresh(()=>{p({level:"info",event:"daemon.install_id.resolved",fields:{install_id:a}})});const v=await jr(a);if(k.fresh(()=>{p({level:"info",event:"daemon.environment.registered",fields:{environment_id:v.environmentId,created:v.created}})}),k.fresh(()=>{let r;try{r=st()}catch{return}r!==null&&p({level:"warn",event:"daemon.startup.warning",fields:{stage:"termrender",warning:r.slice(0,2048)}})}),Dt(),e.role!==void 0&&!process.env.CRTR_DIRECTORY_URL)throw new Error("CRTR_DIRECTORY_URL must be set on a cloud role (--role api|reconcile): it names the directory this deployment mints tokens against");if(e.role!==void 0&&zr(),!Z(e.role)){S={phase:"ready",message:"",blockerPaths:[]};return}if(await k.fresh(async()=>{await at(),await nt();const r=e.role!==void 0;await ot(Date.now(),r),await it(Date.now(),r)}),e.role===void 0&&await k.fresh(async()=>{const{reconcile:r,migrated:n}=await Jt(bt);r.changed&&p({level:"info",event:"daemon.boot_change.reconciled",fields:{cleared_count:r.cleared.length,same_boot_proven:r.sameBootProven}}),n.length>0&&p({level:"info",event:"daemon.pid_identity.migrated",fields:{migrated_count:n.length}})}),await k.fresh(async()=>{const r=await he();for(const n of await Ne())r.has(n.node_id)||n.status!=="active"||n.pi_pid!=null||n.frozen_at!=null||n.respawn_not_before!=null||(await Me(n.node_id,new Date().toISOString()),p({level:"warn",event:"daemon.startup.launch_debt_recorded",node_id:n.node_id}))}),await k.fresh(async()=>{await Ft();for(const r of vn){const n=await r.apply();n.changed&&p({level:"info",event:"daemon.boot_migration.applied",fields:{migration:r.id,...n.summary}})}}),R(rt()),D){const r=s(()=>{R(D().catch(()=>{})),R(fr().then(n=>B?.observe(n)).then(()=>{},n=>{p({level:"warn",event:"daemon.peer.status_failed",error:n})}))},"refresh");R(et().then(({completion:n})=>n).catch(n=>{p({level:"error",event:"daemon.grants.sweep_failed",error:n})})),r(),G=setInterval(r,Fe*1e3),G.unref(),pe=mr({joined:!0,register:R})}await K(async()=>{await un(),await fn()}),te=pr(),z=setInterval(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},ee),ne=await Gt(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))}),oe=await M.subscribe(()=>{V().catch(r=>p({level:"error",event:"daemon.tick.failed",error:r}))},{kinds:["spend_limits"]}),ie=await M.subscribe(r=>{K(()=>k.fresh(()=>Xn(r)))},{kinds:["execution_exit"]}),await V(),e.role===void 0&&import("../commands/sys/import/move.js").then(({settleMoveAtDaemonStart:r})=>r(()=>!E,n=>p({level:"warn",event:"daemon.move.settle_failed",error:n}))).catch(r=>p({level:"warn",event:"daemon.move.settle_failed",error:r}))}s(cr,"completeStartup");function me(){return Ze??=cr().catch(t=>{throw S={phase:"initializing",message:"daemon startup recovery failed and normal services are unavailable",blockerPaths:[]},t})}s(me,"resumeStartup");try{process.on("SIGINT",Re),process.on("SIGTERM",Pe),process.on("exit",Ee),gn(),d!==null&&p({level:"info",event:"daemon.person.resolved",fields:{person_id:d.id,source:d.source}}),c!==null&&!c.alreadyDone&&p({level:"info",event:"daemon.packages.install_migration_done",fields:{moved:c.moved,discarded:c.discarded,people:c.people}}),i!==null&&p({level:"info",event:"daemon.permissions.boot",fields:{...i}}),u!==null&&p({level:"info",event:"daemon.person.retired",fields:{person_id:u.person,joined_from:u.joinedFrom,retired:u.retired,columns:u.columns}}),O(e.role)?W=await _r():br(Sr());const t=y.token;zt({epoch:t,requestHandover:nr,registerDetached:R,startupBlock:er,admitStartup:ar,repairMigrations:sr}),Q(),I=O(e.role)?Mr({tcp:e.tcp}):eo(e),await I.ready,Q(I.tcpAddress()??"");const a=yr()??fe("user").document_port;if(O(e.role)){const r=Fr(a,Br());try{await r.ready,se=r}catch(n){p({level:"warn",event:"daemon.document_listener.bind_failed",fields:{port:a,error:n instanceof Error?n.message:String(n)}})}}const v=fe("user").runtime;if(v?.issuer&&(D=Zr(v.issuer,R),v.unsandboxed===!0&&(B=ur({syncGrants:D}))),e.role==="api"){const r=s(()=>R(import("../core/providers/bundles.js").then(_=>_.syncProviderBundles()).catch(_=>{p({level:"error",event:"daemon.providers.bundle_sync_failed",error:_})})),"bundleTick"),n=s(()=>{R(Qr().catch(_=>{p({level:"error",event:"daemon.packages.sync_failed",error:_})})),r()},"packageTick");n(),F=setInterval(n,Fe*1e3),F.unref()}if(O(e.role)&&(ce=await Vr()),Z(e.role)&&(le=Xr()),de=await Yr({serves:O(e.role),runsLanes:Z(e.role)}),v?.unsandboxed===!0&&v.listener!==void 0&&p({level:"warn",event:"daemon.app_listener.refused_unsandboxed",fields:{reason:"runtime.unsandboxed is set; runtime.listener is ignored"}}),O(e.role)&&v!==void 0&&v.listener!==void 0&&v.unsandboxed!==!0&&($=await Hr(v,async()=>await tt(v.issuer.replace(/\/$/,"")),D),await $.ready,Q(I.tcpAddress()??"",`${v.listener.address}:${$.port()}`)),e.role===void 0)try{await yn()}catch(r){if(A=null,r instanceof Sn)return S={phase:"blocked",message:r.message,blockerPaths:r.blockerPaths},T;throw r}process.platform==="linux"&&P(C)&&(Ir(),await Er("app:terminal"));try{e.prepare?S={phase:"prepared",message:"daemon storage is prepared and normal services are unavailable until admission",blockerPaths:[]}:(await me(),S={phase:"ready",message:"",blockerPaths:[]})}finally{A=null}return T}catch(t){try{await T()}catch(a){throw new AggregateError([t,a],"daemon startup failed and cleanup also failed")}throw t}}s(no,"runDaemon");var aa=no;export{Zn as API_DRAIN_GRACE_MS,la as brokerCommandDeclaresCanvasHome,Se as brokerCommandEpoch,aa as default,Xn as exitedNodePass,Z as roleRunsLanes,O as roleServesRequests,no as runDaemon,Qn as superviseTick,Tn as teardownFleet};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Every lane `superviseTick` runs, named as in crtrd.ts. Keep in tick order. */
|
|
2
|
-
export declare const TICK_LANES: readonly ["brokerSupervision", "controllerDeath", "machineOffline", "nodeLifecycle", "nodeDeadline", "structuredRequests", "recipeImage", "cronLane", "deliveryLane", "actionLane", "pendingReviewSubmit", "storageMaintenance", "storageDueWork", "purgeDueWork", "groupInviteExpiry", "pollRunObservers", "faultRetryBackstop", "bashDeadline", "ledgerSandbox", "
|
|
2
|
+
export declare const TICK_LANES: readonly ["brokerSupervision", "controllerDeath", "machineOffline", "nodeLifecycle", "nodeDeadline", "structuredRequests", "recipeImage", "cronLane", "deliveryLane", "actionLane", "pendingReviewSubmit", "storageMaintenance", "storageDueWork", "purgeDueWork", "groupInviteExpiry", "pollRunObservers", "faultRetryBackstop", "bashDeadline", "ledgerSandbox", "ledgerStorage", "ledgerR2", "importLane"];
|
|
3
3
|
export interface DueSource {
|
|
4
4
|
/** Epoch ms of the earliest timed work this lane owes; `now` when work is due already; null when none. */
|
|
5
5
|
nextDue(now: number): Promise<number | null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var t=(e,n)=>p(e,"name",{value:n,configurable:!0});const f=["brokerSupervision","controllerDeath","machineOffline","nodeLifecycle","nodeDeadline","structuredRequests","recipeImage","cronLane","deliveryLane","actionLane","pendingReviewSubmit","storageMaintenance","storageDueWork","purgeDueWork","groupInviteExpiry","pollRunObservers","faultRetryBackstop","bashDeadline","ledgerSandbox","ledgerStorage","ledgerR2","importLane"],u=new Map,a=new Map;function y(e,n){u.set(e,n)}t(y,"registerDueSource");function g(e,n){a.set(e,n)}t(g,"declareBusyOnly");function x(){return[...u.keys()]}t(x,"dueSourceLanes");function D(){return[...a.keys()]}t(D,"busyOnlyLanes");async function b(e,n=()=>{}){let o=null,i=!1;for(const[s,c]of u){let r;try{r=await c.nextDue(e)}catch(l){n(s,l),r=e}r===null||!Number.isFinite(r)||(r<=e&&(i=!0),(o===null||r<o)&&(o=r))}return{dueNow:i,nextDueMs:o}}t(b,"collectDue");export{f as TICK_LANES,D as busyOnlyLanes,b as collectDue,g as declareBusyOnly,x as dueSourceLanes,y as registerDueSource};
|
package/dist/daemon/due.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var
|
|
1
|
+
var D=Object.defineProperty;var a=(n,e)=>D(n,"name",{value:e,configurable:!0});import{openDb as E}from"../core/canvas/db.js";import{isPidPresent as g}from"../core/canvas/pid.js";import{isProfilePaused as p}from"../core/profiles/manifest.js";import{hasUnseenWakeMail as f}from"../core/canvas/deliveries.js";import{listPendingProviderRetries as R}from"../core/canvas/recovery.js";import{listSubmitRequestedRequests as x}from"../core/human/requests.js";import{storageConfig as I}from"../core/storage/client.js";import{emitEvent as h}from"../core/events/emit.js";import{wantsExecution as m}from"./reconcilers/node-lifecycle/wants-execution.js";import{dueAtMs as O}from"./reconcilers/fault-retry-backstop.js";import{UNUSED_UPLOAD_TTL_MS as y}from"./reconcilers/storage-due-work.js";import{IMAGE_BUILD_OWED_SQL as T,IMAGE_DELETE_OWED_SQL as A}from"./reconcilers/recipe-image.js";import{busyOnlyLanes as M,collectDue as b,declareBusyOnly as i,dueSourceLanes as v,registerDueSource as r}from"./due-sources.js";import{filterAsync as k}from"../core/async-array.js";const c=a(async(n,...e)=>await(await E()).prepare(n).all(...e),"rows"),s=a(async n=>await(await E()).prepare(n).get(),"first"),u=a(n=>{if(n==null)return null;const e=Date.parse(n);return Number.isFinite(e)?e:null},"iso"),_=a(n=>{let e=null;for(const t of n)t!==null&&(e===null||t<e)&&(e=t);return e},"earliest"),L="node_id NOT IN (SELECT node_id FROM warm_pool)";let N=!1;async function S(){if(N)return;N=!0,i("brokerSupervision","acts only on live broker processes, which already make busy true"),i("controllerDeath","acts only on live controller processes"),i("machineOffline","control-plane notice about a Mac whose link went quiet: the control plane never sleeps, and the lane must not wake or hold a sleeping runtime"),i("pollRunObservers","follows live pids only"),i("bashDeadline","acts only on running bash jobs, which already make busy true"),i("storageMaintenance","retention and placement housekeeping: never time-critical, and it must not wake or hold a sleeping runtime"),i("purgeDueWork","physical purge of objects soft-deleted over 30 days ago: housekeeping, and a tombstone a live object references stays due forever, so it must not wake or hold a sleeping runtime"),i("groupInviteExpiry","deletes group invites older than 14 days: housekeeping that must not wake or hold a sleeping runtime"),i("ledgerSandbox","bills awake time of executions that are busy or just exited; a sleeping runtime owes nothing until it wakes, and the lane must not wake it"),i("ledgerStorage","monthly storage billing: never time-critical, and it must not wake or hold a sleeping runtime"),i("ledgerR2","moves closed months to R2: housekeeping that must not wake or hold a sleeping runtime"),r("nodeLifecycle",{nextDue:a(async()=>_((await k(await c(`SELECT node_id, status, intent, profile_id, respawn_not_before FROM node_rows
|
|
2
2
|
WHERE status IN ('active', 'idle') AND kind != 'human' AND ${L}
|
|
3
|
-
AND pi_pid IS NULL AND respawn_not_before IS NOT NULL`),async e=>!p(e.profile_id)&&await
|
|
4
|
-
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`)).filter(e=>!p(e.profile_id)).map(e=>u(e.deadline_at))),"nextDue")}),r("structuredRequests",{nextDue:a(async e=>await
|
|
5
|
-
WHERE ${T} OR ${
|
|
3
|
+
AND pi_pid IS NULL AND respawn_not_before IS NOT NULL`),async e=>!p(e.profile_id)&&await m({node_id:e.node_id,status:e.status,intent:e.intent}))).map(e=>u(e.respawn_not_before))),"nextDue")}),r("nodeDeadline",{nextDue:a(async()=>_((await c(`SELECT deadline_at, profile_id FROM node_rows
|
|
4
|
+
WHERE deadline_at IS NOT NULL AND outcome_at IS NULL AND status IN ('active', 'idle') AND kind != 'human'`)).filter(e=>!p(e.profile_id)).map(e=>u(e.deadline_at))),"nextDue")}),r("structuredRequests",{nextDue:a(async e=>await s("SELECT 1 FROM structured_requests WHERE state != 'pending' AND effects_done_at IS NULL LIMIT 1")!==void 0?e:(await s("SELECT MIN(deadline_at) AS at FROM structured_requests WHERE state = 'pending' AND deadline_at IS NOT NULL"))?.at??null,"nextDue")}),r("recipeImage",{nextDue:a(async e=>_((await c(`SELECT image_building_at FROM environments
|
|
5
|
+
WHERE ${T} OR ${A}`)).map(t=>t.image_building_at===null?e:Math.max(e,u(t.image_building_at)??e))),"nextDue")}),r("cronLane",{nextDue:a(async()=>{const e=(await c(`SELECT fire_at, profile FROM crons
|
|
6
6
|
WHERE state = 'active' AND run_state = 'idle'
|
|
7
|
-
AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`)).filter(
|
|
8
|
-
AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(
|
|
7
|
+
AND NOT (held = 1 AND recur IS NULL AND expires_at IS NULL)`)).filter(o=>!p(o.profile)).map(o=>u(o.fire_at)),t=(await c("SELECT expires_at FROM crons WHERE expires_at IS NOT NULL AND run_state = 'idle'")).map(o=>u(o.expires_at));return _([...e,...t])},"nextDue")});const n=a(async e=>async()=>(await s(`SELECT MIN(next_attempt_at) AS at FROM ${e} WHERE state = 'pending' AND canceled_at IS NULL AND next_attempt_at IS NOT NULL`))?.at??null,"attempts");r("deliveryLane",{nextDue:await n("deliveries")}),r("actionLane",{nextDue:await n("daemon_actions")}),r("pendingReviewSubmit",{nextDue:a(async e=>(await x()).length>0?e:null,"nextDue")}),r("storageDueWork",{nextDue:a(async e=>{if(I()===null)return null;if(await s("SELECT 1 FROM uploads WHERE delete_pending_since IS NOT NULL LIMIT 1")!==void 0||await s("SELECT 1 FROM shares WHERE status = 'off' AND object_deleted_at IS NULL LIMIT 1")!==void 0)return e;const t=(await s("SELECT MIN(expires_at) AS at FROM shares WHERE status = 'on' AND expires_at IS NOT NULL"))?.at,o=(await s(`SELECT MIN(created_at) AS at FROM uploads u WHERE delete_pending_since IS NULL
|
|
8
|
+
AND NOT EXISTS (SELECT 1 FROM upload_uses x WHERE x.upload_id = u.upload_id)`))?.at,l=u(o);return _([u(t),l===null?null:l+y])},"nextDue")}),r("importLane",{nextDue:a(async e=>await s(`SELECT 1 FROM import_runs WHERE state IN ('loading', 'committed') AND (claimed_by IS NULL OR lease_expires_at IS NULL OR lease_expires_at <= '${new Date(e).toISOString()}')`)!==void 0?e:null,"nextDue")}),r("faultRetryBackstop",{nextDue:a(async()=>_((await R()).map(e=>O(e))),"nextDue")})}a(S,"installDueSources");const w=12e4;async function W(n){const e=await c(`SELECT n.node_id, n.status, n.intent, n.profile_id, n.pi_pid, n.frozen_at, n.respawn_not_before, n.created, n.launched_at,
|
|
9
9
|
n.turn_open_at, n.turn_closed_at,
|
|
10
10
|
(SELECT x.started_at FROM executions x WHERE x.node_id = n.node_id AND x.state != 'exited') AS exec_started_at
|
|
11
11
|
FROM node_rows n
|
|
12
|
-
WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await
|
|
12
|
+
WHERE n.status IN ('active', 'idle') AND n.kind != 'human' AND n.${L}`);for(const t of e){if(p(t.profile_id)||!await m({node_id:t.node_id,status:t.status,intent:t.intent}))continue;if(t.pi_pid!==null&&g(t.pi_pid)){if(t.turn_open_at!==null&&t.turn_closed_at===null)return!0;const d=u(t.exec_started_at);if(t.turn_open_at===null&&d!==null&&n-d<w||await f(t.node_id))return!0;continue}if(t.respawn_not_before!==null)continue;if(t.pi_pid!==null||t.frozen_at!==null||t.status==="active")return!0;const l=Math.max(...[t.created,t.launched_at,t.exec_started_at].map(d=>u(d)??0));if(l>0&&n-l<w||t.status==="idle"&&await f(t.node_id))return!0}return!1}a(W,"nodesOweWork");async function V(n=Date.now()){await S();const{dueNow:e,nextDueMs:t}=await b(n,(l,d)=>{h({level:"warn",event:"daemon.due.source_failed",error:d,fields:{lane:l}})});return{busy:e||await W(n)||await s("SELECT 1 FROM crons WHERE run_state = 'running' LIMIT 1")!==void 0||await s("SELECT 1 FROM jobs j JOIN objects o ON o.id = j.object WHERE j.status = 'running' AND o.deleted_at IS NULL LIMIT 1")!==void 0,next_due_at:t===null?null:new Date(t).toISOString()}}a(V,"dueReport");async function Y(){return await S(),[...v(),...M()]}a(Y,"coveredLanes");export{w as START_GRACE_MS,Y as coveredLanes,V as dueReport,S as installDueSources};
|
package/dist/daemon/fleet.d.ts
CHANGED
|
@@ -36,7 +36,7 @@ export type DeadNodeRow = Pick<NodeMeta, 'status' | 'intent' | 'pi_session_id' |
|
|
|
36
36
|
* `pendingWake` is the one non-row input (`hasPendingWake`): whether anything
|
|
37
37
|
* would drive a turn if the engine came back. It selects row 4b and defaults
|
|
38
38
|
* to `true`, so an uninformed caller keeps the conservative respawn. */
|
|
39
|
-
export declare function classifyDeadNode(row: DeadNodeRow | null, busy: boolean, pendingWake?: boolean): DeadNodeAction;
|
|
39
|
+
export declare function classifyDeadNode(row: DeadNodeRow | null, busy: boolean, pendingWake?: boolean, admittedTurn?: boolean): DeadNodeAction;
|
|
40
40
|
export interface DaemonFleetOpts {
|
|
41
41
|
/** This daemon's epoch id (randomBytes(8).toString('hex'), minted by
|
|
42
42
|
* runDaemon after the ownership claim). */
|
package/dist/daemon/fleet.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R}from"../core/canvas/index.js";import{revokeExitedNodeToken as T}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as N,endExecution as y,hasLaunchingExecution as S,hasProfilePauseStop as F,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as C,markProfilePauseStop as k,recordExecutionExit as O,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as
|
|
1
|
+
var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R}from"../core/canvas/index.js";import{revokeExitedNodeToken as T}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as N,endExecution as y,hasLaunchingExecution as S,hasProfilePauseStop as F,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as C,markProfilePauseStop as k,recordExecutionExit as O,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as A}from"../core/profiles/manifest.js";import{fullName as p}from"../core/canvas/labels.js";import{isSafeNodeId as o}from"../core/canvas/paths.js";import{hasIdleReleaseIntent as z,transition as v}from"../core/runtime/lifecycle.js";import{publishNotice as L}from"../core/runtime/close.js";import{hasAdmittedTurn as B,readFault as D,readInterruptedTurn as W,readTransportPoisonVerdict as q}from"../core/canvas/recovery.js";import{hasPendingWake as G}from"./reconcilers/live-obligation.js";import{clearRespawnPolicy as h,deferRespawnWhileOffline as H,MAX_RESPAWN_ATTEMPTS as Y,OFFLINE_RESPAWN_RETRY_MS as U,recordRespawnPolicy as V,respawnBackoffMs as j}from"./reconcilers/node-lifecycle/respawn-policy.js";import{probeOnline as K}from"../core/runtime/connectivity.js";import{runnerForExecution as X}from"../core/runtime/runner/index.js";import{reviveNode as J}from"../core/runtime/revive.js";import{isStartRefusal as Q}from"../core/runtime/start-check.js";import{MachineOfflineError as Z}from"../core/runtime/runner/machine/ops.js";import{pushUrgent as m}from"../core/feed/feed.js";import{emitEvent as u}from"../core/events/emit.js";import{brokerThresholdsForDaemon as I}from"../core/runtime/fleet.js";import{isRecoveryHeld as ee}from"../core/runtime/recovery-hold.js";async function E(i,e){const r=await D(i.node_id),t=r===null?"":`The broker reported a ${r.kind} fault on ${r.link} (${r.op}) before it exited: ${r.message}
|
|
2
2
|
|
|
3
3
|
`,s=e===void 0?"The daemon did not observe an exit status.":`The observed exit status was code ${e.code??"null"}, signal ${e.signal??"null"}.`;return`\u26A0 Spawn failed \u2014 \`${i.name}\` (${i.kind}) never started.
|
|
4
4
|
|
|
@@ -8,14 +8,14 @@ Its pi vehicle exited before the session came up (no pi_session_id was ever reco
|
|
|
8
8
|
|
|
9
9
|
If the work still needs doing, re-spawn it.`}l(E,"bootFailureBody");async function $(i,e){await m(i.node_id,await E(i,e),{from:i.node_id})}l($,"surfaceBootFailure");function x(i){return`\u26A0 Out of memory \u2014 \`${i.name}\` (${i.kind}) was killed because its app's processes together passed the app's memory limit.
|
|
10
10
|
|
|
11
|
-
Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function
|
|
11
|
+
Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function te(i){const e=await q(i.node_id),r=e===null?"":`
|
|
12
12
|
|
|
13
13
|
Provider rotation observed ${e.consecutivePasses} consecutive route-queue passes with no HTTP response (tried ${e.routes.join(", ")}). Check network and provider transport before reviving.`,t=`\u26A0 Crash loop \u2014 \`${i.name}\` (${i.kind}) kept dying without settling a turn.
|
|
14
14
|
|
|
15
15
|
Its session started successfully, but six consecutive relaunches made no progress, so the daemon stopped retrying.`+r+`
|
|
16
16
|
|
|
17
|
-
Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(
|
|
17
|
+
Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(te,"surfaceCrashLoop");async function re(i,e){const r=e instanceof Error?e.message:String(e),t=`\u26A0 Recovery failed \u2014 \`${i.name}\` (${i.kind}) could not be relaunched.
|
|
18
18
|
|
|
19
19
|
The daemon refused this recovery before starting a broker: ${r}
|
|
20
20
|
|
|
21
|
-
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(
|
|
21
|
+
The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(re,"surfaceRecoveryFailure");function ie(i){return i?.cycle_pending!==!0}l(ie,"retryResumeMode");function se(i,e,r=!0,t=!1){return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?"forget":i.intent==="refresh"?"respawn-fresh":z(i)?"dormant":i.lifecycle==="resident"&&!e&&!r&&(i.pi_session_id!=null||t)?"release-idle":i.pi_session_id!=null?ie(i)?"respawn-resume":"respawn-cycle":e||t||i.fork_from!=null?"respawn-fresh":"boot-failure"}l(se,"classifyDeadNode");const ae=3e4;class Re{static{l(this,"DaemonFleet")}#a;#n;#r;#o;#e=new Map;#t=new Set;#l=Number.NEGATIVE_INFINITY;constructor(e){this.#a=e.epoch,this.#n=e.enqueue,this.#r=e.now??Date.now,this.#o=e.probeOnline??(()=>K())}epoch(){return this.#a}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}async has(e){return this.#e.has(e)||await b(e)}async isClaimed(e){return this.#e.has(e)||this.#t.has(e)||await b(e)||await S(e,this.#a)}get(e){return this.#e.get(e)}size(){return this.#e.size}async#c(){const e=await C();for(const r of this.#e.keys())e.add(r);for(const r of this.#t)e.add(r);return e}async occupancy(){return(await this.#c()).size}async reserveSlot(e){if(this.#t.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=I(),t=await this.#c();if(this.#t.has(e)||this.#e.has(e))return!0;if(t.delete(e),t.size<r)return this.#t.has(e)||this.#t.add(e),!0;const s=this.#r();return s-this.#l>=ae&&(this.#l=s,u({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:t.size,hard_cap:r}})),!1}releaseReservation(e){this.#t.delete(e)}entries(){return this.#e.entries()}async interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r===void 0){const t=await g(e);if(t===null||t.runner==="process"||t.state!=="running")return;await k(e),(await X(t.runner).stop(t,{reason:_})).confirmed&&await y(t.executionId,{reason:_});return}await k(e);try{process.kill(r,"SIGTERM")}catch{}}async hasProfilePauseInterruption(e){return await F(e)}forget(e){this.#e.delete(e),this.#t.delete(e)}#i=new Set;async exitsSettled(){for(;this.#i.size>0;)await Promise.allSettled([...this.#i])}async onChildExit(e,r,t){const s=this.#u(e,r,t);this.#i.add(s);try{await s}finally{this.#i.delete(s)}}async#u(e,r,t){const s=t??(await g(e))?.executionId;t&&await T(t),this.#e.delete(e),s!==void 0&&(await O(s,r),await y(s,{reason:"exited"})),this.#n(async()=>{const a=await w(e),n=a?.launched_at==null?Number.NaN:Date.parse(a.launched_at),d=Number.isFinite(n)?Math.max(0,this.#r()-n):null,f=a?.respawn_failures??0;this.#f(e,r,d,f)})}async deliverExit(e,r){await this.onChildExit(e,r)}async applyDeadRowPolicy(e){await this.#h(e,await M(e))}async terminalizeIfStillNonTerminal(e,r,t,s,a){const n=await w(e);return n===null||n.status==="done"||n.status==="canceled"||n.status==="dead"?!1:(await this.#s(e,n,{event:r,reason:s,detail:a,wake:`Child crashed \u2014 ${p(n)} (${e}) could not be relaunched and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>re(n,t),"surface")}),!0)}dispose(){}#f(e,r,t,s){u({level:"info",event:"broker.exit.observed",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},code:r.code,signal:r.signal,uptime_ms:t,consecutive_failures:s}})}async#h(e,r){return this.#d(e,r)}async#d(e,r){const t=await w(e);if(t!==null&&A(t.profile_id))return await h(e),"forget";if(await N(e))return await h(e),"forget";if(await ee(e))return"dormant";const s=(await W(e))?.interrupted===!0;if(r?.oomKilled===!0&&t!==null&&t.status!=="done"&&t.status!=="canceled"&&t.status!=="dead")return await h(e),await this.#s(e,t,{event:"broker.out_of_memory",reason:"out_of_memory",detail:{schema:"crtr.node-outcome-detail/v1",message:x(t)},wake:`Child out of memory \u2014 ${p(t)} (${e}) used more memory than its app is allowed and is now dead. It is not restarted automatically. Revive it with \`crtr node lifecycle revive ${e}\` once the work needs less memory or the cap is raised (\`crtr sys limits set\`).`,surface:l(async()=>{await m(e,x(t),{from:e})},"surface")}),"forget";const a=se(t,s,await G(e),await B(e));switch(a){case"forget":await h(e);break;case"dormant":await h(e);break;case"release-idle":await h(e),await v(e,"release"),u({level:"info",event:"broker.recovery.released",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e}}});break;case"boot-failure":await this.#s(e,t,{event:"broker.boot.failed",reason:"boot_failed",detail:{schema:"crtr.node-outcome-detail/v1",message:await E(t,r)},wake:`Child crashed \u2014 ${p(t)} (${e}) exited before its session ever came up and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>$(t,r),"surface")});break;case"respawn-fresh":case"respawn-cycle":case"respawn-resume":await this.#p(e,t,a,s);break}return a}async#p(e,r,t,s){const a=await R(e);if(a===null)return;const n=a.respawn_failures??0;if(!await this.#o()){await H(e,n,this.#r()),u({level:"info",event:"broker.respawn.offline_deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,retry_in_ms:U,consecutive_failures:n}});return}const d=a.respawn_not_before==null,f=d?await V(a,this.#r()):{failures:n,notBefore:a.respawn_not_before,exhausted:n>=Y};if(f.exhausted){const c=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${f.failures} consecutive launches) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await this.#s(e,r,{event:"broker.respawn.exhausted",reason:"crash_looped",detail:{schema:"crtr.node-outcome-detail/v1",message:c,respawn_failures:f.failures},wake:c,...r.pi_session_id!=null?{surface:l(()=>te(r),"surface")}:{}});return}if(d&&f.notBefore!==null){u({level:"info",event:"broker.respawn.deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,backoff_ms:j(f.failures),consecutive_failures:f.failures}});return}u({level:"info",event:"broker.respawn.started",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,consecutive_failures:f.failures}});try{await J(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&s?"runtime-restart-abort":void 0,recovery:!0})}catch(c){if(Q(c)||c instanceof Z){await h(e),await v(e,"release"),u({level:"warn",event:"node.start.refused",node_id:e,error:c,fields:{enact:"respawn"}});return}u({level:"error",event:"broker.respawn.failed",...o(e)?{node_id:e}:{},error:c,fields:{...o(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",c,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:c instanceof Error?c.message:String(c)})}}async#s(e,r,t){u({level:"error",event:t.event,...o(e)?{node_id:e}:{fields:{affected_node_id:e}}}),await v(e,"crash",{reason:t.reason,outcome:{detail:t.detail}});try{await(t.surface??(()=>$(r)))()}catch(s){u({level:"error",event:"broker.boot_failure_surface.failed",...o(e)?{node_id:e}:{fields:{affected_node_id:e}},error:s})}await L(e,"notice.crash",t.wake,{reason:"child-crashed",child:e})}}export{Re as DaemonFleet,se as classifyDeadNode,ie as retryResumeMode,$ as surfaceBootFailure};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var _=Object.defineProperty;var
|
|
2
|
-
`)[0]??"";return n.length>e?`${n.slice(0,e-1)}\u2026`:n}
|
|
1
|
+
var _=Object.defineProperty;var o=(t,e)=>_(t,"name",{value:e,configurable:!0});import{getRequest as y,getRequestByInboxTicket as b,presentationDir as q}from"../../core/human/requests.js";import{buildPageSummary as v}from"../../core/human/summary.js";import{pageAwaitsResponse as $}from"../../core/human/page-schema.js";import{validateFinalPageResponses as j}from"../../core/human/tickets.js";import{composeHumanCompletion as k}from"../../core/human/completion.js";import{describePageAnswer as S}from"../../core/human/answer.js";import{renderAnswerText as T}from"../../core/human/answer-text.js";import{readPageFeedback as A}from"../../core/human/feedback.js";import{pageDocumentSha256 as N}from"../../core/human/feedback-companion.js";import{pagePath as O}from"../../core/human/convention.js";import{retireCompanion as f}from"../companion-retire.js";import{settleHumanRequest as w}from"./settle.js";async function d(t){const e=await y(t)??await b(t);if(e===null||e.kind!=="page")throw new Error(`unknown page request: ${t}`);return e}o(d,"requestForTicket");function c(t){try{const e=JSON.parse(t.specification_json);if(typeof e!="object"||e===null)throw new Error("not an object");return e}catch(e){throw new Error(`corrupt page specification: ${t.request_id}`,{cause:e})}}o(c,"manifest");function u(t,e){if(t.action_json!==null)try{const n=JSON.parse(t.action_json);if(n.schema!=="crtr.human-action-binding/v1"||!Array.isArray(n.argv)||typeof n.cwd!="string")throw new Error("invalid binding");return{adapter:{adapter:"subprocess",argv:n.argv,cwd:n.cwd,node_id:t.requester_node_id,...n.app?{app:n.app}:{}},bodyJson:k({requestId:t.request_id,result:e,binding:n,source:c(t).source??{}})}}catch(n){throw new Error(`corrupt frozen completion action: ${t.request_id}`,{cause:n})}}o(u,"completionAction");function x(t,e=80){const n=t.split(`
|
|
2
|
+
`)[0]??"";return n.length>e?`${n.slice(0,e-1)}\u2026`:n}o(x,"firstLine");function E(t){try{return c(t).title}catch{return}}o(E,"pageTitle");async function h(t){let e;try{const n=await A(t.request_dir);if(n.companionNodeId===void 0)return"";e=[],n.firstCommentedSha256!==void 0&&await N(t.request_dir)!==n.firstCommentedSha256&&e.push(`The page changed during feedback: the person commented on it and its companion conversation (node ${n.companionNodeId}) revised it in place. Reread the final page at ${O(q(t),c(t).dialect)} before interpreting this outcome.`);const r=n.comments.filter(i=>i.status==="open");if(r.length>0){const i=r.map(s=>[...s.quote.split(`
|
|
3
3
|
`).map(a=>`> ${a}`),s.note].join(`
|
|
4
4
|
`));e.push([`Feedback left unresolved at settlement \u2014 the companion conversation (node ${n.companionNodeId}) had not dealt with these items:`,...i].join(`
|
|
5
5
|
|
|
@@ -7,4 +7,4 @@ var _=Object.defineProperty;var r=(t,e)=>_(t,"name",{value:e,configurable:!0});i
|
|
|
7
7
|
|
|
8
8
|
${e.join(`
|
|
9
9
|
|
|
10
|
-
`)}`}
|
|
10
|
+
`)}`}o(h,"feedbackAddendum");async function J(t,e){const n=S(c(t),e.responses,{completedAt:e.completedAt});return T(n)+await h(t)}o(J,"answerBody");async function P(t,e,n){const r=E(t),i=r===void 0?`the human interaction ${t.request_id}`:`\u201C${r}\u201D`,s=n!==void 0&&n!==""?n:"no reason was given";return(e?`The user dismissed ${i} without answering \u2014 a deliberate \u201Cno, I'm not answering this.\u201D Treat it as a rejection: no response will arrive, no partial answer exists, and the same ask must not be raised again.`:`${r===void 0?`The human interaction ${t.request_id}`:`The page \u201C${r}\u201D`} was canceled \u2014 ${s}. No response will arrive, and any partial answers the user had entered were discarded unsent.`)+await h(t)}o(P,"cancelBody");function g(t,e,n,r){if(!(t.requester_node_id===null||!$(c(t))))return{label:x(n),disposition:e,body_json:{body:n,result:r}}}o(g,"notification");function l(t){return t.companion_node_id===null?void 0:{retire:o(async(e,n)=>{await f(e,n)},"retire")}}o(l,"retire");async function V(t,e,n={}){return(await I(t,e,n)).result}o(V,"resolvePageTicket");async function I(t,e,n={}){const r=await d(t),i=c(r),s=j(i,e),a={schema:"crtr.page-response/v1",kind:"page",responses:s,summary:v(i,s),completedAt:n.completedAt??new Date().toISOString(),...n.actor===void 0?{}:{actor:n.actor}},m=await w({request_id:r.request_id,outcome:"answered",result_json:JSON.stringify(a),notification:o(async p=>g(p,"human-answer",await J(p,a),a),"notification"),...u(r,a)===void 0?{}:{completion_action:u(r,a)},...l(r)===void 0?{}:{post_commit:l(r)}});if(m.outcome==="already_settled"){if(m.request.result_json===null)throw new Error(`settled page request lacks a result: ${r.request_id}`);return{outcome:"already_settled",result:JSON.parse(m.request.result_json)}}return{outcome:"settled",result:a}}o(I,"answerPageTicket");async function W(t,e){const n=await d(t),i={schema:"humanloop.cancel/v1",kind:"canceled",canceledAt:new Date().toISOString(),...e.reason===void 0?{}:{reason:e.reason},...e.actor===void 0?{}:{actor:e.actor},...e.disposition===void 0?{}:{disposition:e.disposition}},s=await w({request_id:n.request_id,outcome:e.disposition==="dismissed"?"dismissed":"canceled",result_json:JSON.stringify(i),notification:o(async a=>g(a,"human-canceled",await P(a,e.disposition==="dismissed",e.reason),i),"notification"),...u(n,i)===void 0?{}:{completion_action:u(n,i)},...l(n)===void 0?{}:{post_commit:l(n)}});if(s.outcome==="already_settled"){if(s.request.result_json===null)throw new Error(`settled page request lacks a result: ${n.request_id}`);return{outcome:"already_settled",result:JSON.parse(s.request.result_json)}}return{outcome:"settled",result:i}}o(W,"cancelHumanTicket");async function X(t){return(await d(t)).state==="settled"}o(X,"deliverTerminalResult");async function Y(t,e){const n=await d(t);n.companion_node_id!==null&&await f(n.companion_node_id,e)}o(Y,"settleFeedbackCompanion");export{I as answerPageTicket,W as cancelHumanTicket,X as deliverTerminalResult,V as resolvePageTicket,Y as settleFeedbackCompanion};
|