@north-light/cli 0.3.781 → 0.3.783
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/README.md +9 -19
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/charges.d.ts +3 -3
- package/dist/api/dto/charges.js +1 -1
- package/dist/api/dto/inbox.d.ts +2 -0
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/crouter-concepts/why-a-daemon.md +1 -1
- package/dist/builtin-memory/crouter-sdk/README.md +3 -2
- package/dist/builtin-memory/crouter-sdk/client.md +3 -3
- package/dist/builtin-memory/crouter-sdk/docker.md +6 -10
- package/dist/builtin-memory/crouter-sdk/release-notes.md +25 -3
- package/dist/builtin-memory/crouter-sdk/sourcing.md +94 -0
- package/dist/builtin-memory/insights/capture.md +2 -2
- package/dist/builtin-memory/internal/marketplaces.md +1 -1
- package/dist/builtin-memory/internal/storage-tiers.md +1 -1
- package/dist/builtin-memory/northlight-apps/cli.md +1 -1
- package/dist/builtin-memory/northlight-apps/coding-agents.md +1 -1
- package/dist/builtin-memory/northlight-apps/get-started.md +2 -2
- package/dist/builtin-memory/northlight-apps/guides/watchable-objects.md +1 -1
- package/dist/builtin-memory/northlight-apps/how-it-fits.md +1 -1
- package/dist/builtin-memory/northlight-apps/let-their-ai-use-your-app.md +1 -4
- package/dist/builtin-memory/northlight-apps/quickstart.md +1 -1
- package/dist/cli.js +2 -8
- package/dist/clients/attach/command.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/viewer.js +524 -524
- package/dist/clients/inbox/controller.d.ts +34 -11
- package/dist/clients/inbox/controller.js +1 -1
- package/dist/clients/inbox/dto-adapt.d.ts +1 -0
- package/dist/clients/inbox/dto-adapt.js +1 -1
- package/dist/clients/inbox/surface.js +1 -1
- package/dist/commands/canvas-config.js +2 -2
- package/dist/commands/canvas-use.js +1 -1
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/pkg/account-installs.d.ts +9 -0
- package/dist/commands/pkg/account-installs.js +1 -0
- package/dist/commands/profile/default.js +1 -1
- package/dist/commands/sys/setup-core.d.ts +1 -52
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup-wizard.d.ts +4 -9
- package/dist/commands/sys/setup-wizard.js +2 -1
- package/dist/commands/sys/setup.js +1 -1
- package/dist/commands/sys/signin.d.ts +1 -1
- package/dist/commands/sys/signin.js +6 -3
- package/dist/core/command.d.ts +1 -2
- package/dist/core/command.js +6 -6
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/human/requests.d.ts +2 -0
- package/dist/core/human/requests.js +18 -18
- package/dist/core/ledger/check.d.ts +6 -2
- package/dist/core/ledger/check.js +1 -1
- package/dist/core/llm/run.js +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/broker/cli-relay.d.ts +0 -2
- package/dist/core/runtime/broker/cli-relay.js +1 -1
- package/dist/core/runtime/broker/run-turn-queue.js +1 -1
- package/dist/core/runtime/broker/turn-cause.d.ts +2 -0
- package/dist/core/runtime/broker/turn-cause.js +1 -1
- package/dist/core/runtime/first-run-offer.d.ts +2 -6
- package/dist/core/runtime/first-run-offer.js +2 -10
- package/dist/core/runtime/front-door.js +8 -9
- package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
- package/dist/core/runtime/start-refusal-notice.js +1 -0
- package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
- package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/fleet.js +5 -5
- package/dist/daemon/machine-link/config.d.ts +2 -4
- package/dist/daemon/machine-link/config.js +4 -4
- package/dist/daemon/manage.js +2 -2
- package/dist/daemon/postgres/cluster.d.ts +3 -3
- package/dist/daemon/postgres/cluster.js +5 -5
- package/dist/daemon/postgres/supervisor.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -2
- package/docs/apps/cli.md +1 -1
- package/docs/apps/coding-agents.md +1 -1
- package/docs/apps/get-started.md +2 -2
- package/docs/apps/guides/watchable-objects.md +1 -1
- package/docs/apps/how-it-fits.md +1 -1
- package/docs/apps/let-their-ai-use-your-app.md +1 -4
- package/docs/apps/quickstart.md +1 -1
- package/docs/concepts/why-a-daemon.md +1 -1
- package/docs/sdk/README.md +3 -2
- package/docs/sdk/client.md +3 -3
- package/docs/sdk/docker.md +5 -9
- package/docs/sdk/release-notes.md +25 -3
- package/docs/sdk/sourcing.md +91 -0
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/client.js +2 -2
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/api/dto/charges.js +1 -1
- package/packages/crouter-api/dist/daemon/machine-link/config.js +3 -5
- package/packages/crouter-api/dist/daemon/manage.js +3 -3
- 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 +1 -1
- package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
- package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
- package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
- package/dist/commands/sys/panels/plugins-panel.js +0 -1
- package/dist/core/northlight/previews.d.ts +0 -22
- package/dist/core/northlight/previews.js +0 -1
- package/dist/core/runtime/front-door-login.d.ts +0 -2
- package/dist/core/runtime/front-door-login.js +0 -1
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
var
|
|
2
|
-
`),process.exit(1)
|
|
3
|
-
`),process.exit(1)),
|
|
4
|
-
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=c.node.profile_id,m=c.node.node_id,I(c.node.cwd)&&(d=c.node.cwd))}if(m===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:n}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
|
|
1
|
+
var v=Object.defineProperty;var m=(t,s)=>v(t,"name",{value:s,configurable:!0});import{existsSync as _,statSync as x}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as D}from"../../build-root.js";import{FRONT_DOOR_ENV as F}from"./front-door-env.js";import{frontDoorBootPrompt as E}from"./first-run-offer.js";import{readMachineConfig as C}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as b}from"./node-id-token.js";import{markTourOffered as A,recordSetupCompleted as L,setupCompleted as W,tourOfferPending as $}from"./setup-marker.js";function T(t){try{return _(t)&&x(t).isDirectory()}catch{return!1}}m(T,"isDir");const B=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function M(){let t=!1;const s=m(()=>{t=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:r}=await import("../../commands/sys/setup-wizard.js"),e=await r();if(t){const c=new Error("Interrupted");throw c.name="AbortError",c}await L(e)}finally{process.removeListener("SIGINT",s)}}m(M,"runFirstSetup");function G(t){let s=process.cwd(),r,e,c,l=!1,u,p;const i=[];for(let f=0;f<t.length;f++){const n=t[f];if(n==="--name")r=t[++f];else if(n==="--kind")e=t[++f];else if(n==="--profile")c=t[++f];else if(n==="--pick-profile")l=!0;else if(n==="--continue"||n==="-c")u="continue";else if(n==="--resume"||n==="-r"){u="pick";const w=t[f+1];w!==void 0&&b(w)&&!T(h(w))&&(p=w,f++)}else n.startsWith("--")||i.push(n)}i.length>0&&T(h(i[0]))&&(s=h(i.shift()));const g=i.length>0?i.join(" "):void 0;return{cwd:s,prompt:g,name:r,kind:e,profile:c,pickProfile:l,resume:u,resumeId:p}}m(G,"parseRootArgs");import{FRONT_DOOR_ENV as re}from"./front-door-env.js";async function Q(t){const s=t.slice(2),r=s[0];if(process.env[F]||r==="-h"||r==="--help"||r==="--version"||r==="-v"||r!==void 0&&D.includes(r))return!1;if(r!==void 0){const o=/\s/.test(r),d=!r.startsWith("-")&&T(h(r)),a=B.has(r);if(!o&&!d&&!a)return!1;if(d){const{buildRoot:O}=await import("../../build-root.js");if((await O()).subtrees.some(S=>S.name===r))return!1}}const e=G(s),c=m(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:o}=await import("../profiles/manifest.js");e.profile=o(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await c();const l=process.stdin.isTTY&&process.stdout.isTTY;C()===void 0&&!l&&(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));let u=!1;l&&!W()&&(await M(),u=!0);let p=null,i,g=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:o,noResumeTargetMessage:d}=await import("./resume-root.js"),a=await o(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
|
|
2
|
+
`),process.exit(1)),"none"in a?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
|
|
3
|
+
`),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(p=a.node.profile_id,i=a.node.node_id,T(a.node.cwd)&&(g=a.node.cwd))}if(i===void 0){const{selectProfileForCwd:o,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
|
|
5
4
|
Choose a profile
|
|
6
|
-
`),
|
|
7
|
-
${
|
|
5
|
+
`),p=e.profile??(l?await o(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{inTmux:f}=await import("./placement-tmux.js");if(l&&!f()){const{TMUX_STARTED_ENV:o,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[o]===void 0&&d(s,i!==void 0?null:p,g)}const[{bootRoot:n},{resumeRoot:w},{rendererWarning:R,missingPackageWarning:k,piAgentDir:y}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const o=k(y());o!==null&&process.stderr.write(`
|
|
6
|
+
${o}
|
|
8
7
|
|
|
9
|
-
`);const
|
|
10
|
-
${
|
|
8
|
+
`);const d=R();d!==null&&process.stderr.write(`
|
|
9
|
+
${d}
|
|
11
10
|
|
|
12
|
-
`)}catch{}if(
|
|
11
|
+
`)}catch{}if(i!==void 0){const{resumeNodeById:o}=await import("./resume-root.js");await o(i)}if(e.resume!==void 0&&await w(e.cwd,e.resume==="pick")==="aborted")return!0;const I=l&&(u||await $()),{prompt:P,initialWhip:N}=E({offerTour:I,userPrompt:e.prompt});return I&&f()&&await A(),await n({...e,prompt:P,initialWhip:N,selectedProfileId:p??void 0}),!0}m(Q,"maybeBootRoot");export{re as FRONT_DOOR_ENV,Q as maybeBootRoot,G as parseRootArgs};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Refusal } from '../ledger/index.js';
|
|
2
|
+
/** Report a refused start of `user:<id>` by an app limit or an operator stop; any other refusal is not reported. Never throws. */
|
|
3
|
+
export declare function noticeStartRefusal(refusal: Refusal): Promise<void>;
|
|
4
|
+
/** The same report from the `402 cap_exhausted` a refused revive or respawn threw; any other error is ignored. */
|
|
5
|
+
export declare function noticeStartRefusalError(error: unknown): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{directoryIssuer as f}from"../directory/issuer.js";import{emitEvent as c}from"../events/emit.js";import{describeOutboundFailure as p,outboundFetch as _}from"../events/outbound.js";import{mintDirectoryToken as y}from"../grants/sync.js";import{usageMonth as m}from"../ledger/months.js";import{RunError as g}from"../runs/operations.js";const a=new Set;async function E(e){await u(e.limit)}n(E,"noticeStartRefusal");async function x(e){if(!(e instanceof g)||e.code!=="cap_exhausted")return;const t=e.details?.limit;t!==void 0&&await u({id:t.id,payer:t.payer,source:t.source,grantee:t.filters.grantee})}n(x,"noticeStartRefusalError");async function u(e){const t=f();if(t===null||!e.payer?.startsWith("user:")||e.source!=="grant_sync"&&e.source!=="operator")return;const i=m(),o=`${e.id}|${i}`;if(a.has(o))return;a.add(o);const d=`${t}/v1/runtime/limit-refusals`;try{const r=await y(t),s=await _("limit_refusal_notice",d,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({user_id:e.payer.slice(5),limit_id:e.id,month:i,reason:e.source==="grant_sync"?"app_limit":"operator_stop",app_id:e.source==="grant_sync"&&e.grantee?.startsWith("app:")?e.grantee.slice(4):null}),signal:AbortSignal.timeout(1e4)});if(s.status===400){c({level:"warn",event:"ledger.start_refusal.notice_rejected",fields:{limit_id:e.id}});return}if(!s.ok)throw new Error(`directory answered the limit refusal notice: ${s.status}`)}catch(r){a.delete(o),c({level:"warn",event:"ledger.start_refusal.notice_failed",error:r,fields:{limit_id:e.id,...p(r)}})}}n(u,"notice");export{E as noticeStartRefusal,x as noticeStartRefusalError};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var m=Object.defineProperty;var r=(e,n)=>m(e,"name",{value:n,configurable:!0});import{withCanvasWrite as u}from"../canvas/db.js";import{applyOpsToRows as f,readSnapshotFromRows as O}from"./person-rows.js";import{appRevisionOf as E}from"./person-store.js";const o="app:terminal",p={name:"crouter-official-marketplace",url:"https://github.com/crouton-labs/crouter-official-marketplace.git"},g=["capture"],i=r(e=>`terminal_defaults_seeded:${e}`,"seededKey");async function y(){return await u(async e=>{const n=(await e.prepare("SELECT DISTINCT sub FROM grants WHERE grantee = 'app:terminal' AND status = 'active'").all()).map(a=>a.sub),s=[];for(const a of n){if(await e.prepare("SELECT 1 FROM canvas_meta WHERE key = ?").get(i(a))!==void 0)continue;const t=(await O(e,a)).apps[o];if(t===void 0||Object.keys(t.plugins).length===0&&Object.keys(t.marketplaces).length===0){const c=Object.fromEntries(g.map(l=>[l,{enabled:!0,source_marketplace:p.name}]));await f(e,a,[{op:"app-plugins.replace",app:o,plugins:c,marketplaces:{[p.name]:{url:p.url,ref:"main",installed_at:new Date().toISOString()}},ifRevision:E(t)}]),s.push(a)}await e.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(i(a),new Date().toISOString())}return s})}r(y,"seedTerminalDefaults");export{y as seedTerminalDefaults,i as seededKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var I=Object.defineProperty;var o=(e,t)=>I(e,"name",{value:t,configurable:!0});import{ApiError as i}from"../../../api/index.js";import{inboxPageProjection as b}from"./inbox-page.js";import{getRequestByInboxTicket as v,getRequestsByInboxTickets as x}from"../../../core/human/requests.js";import{collectStepTimings as P,serverTimingHeader as A,timedStep as c}from"../../../core/step-timings.js";import{readableTicketIds as y}from"../router.js";import{readPageManifest as E}from"../../../core/human/page.js";import{scanInbox as R,scanPageHistory as S}from"../../../core/human/scan.js";import{readPageTicket as k,readTicketResult as f,selectedPageDir as O,validatePageTicketResponses as C,writePageProgress as D}from"../../../core/human/tickets.js";import{describePageAnswer as j}from"../../../core/human/answer.js";import{cancelHumanTicket as N,resolvePageTicket as G}from"../../human/finish.js";import{canvasOrigin as T}from"../canvas-host.js";const L="Canceled from the inbox.",$=1e3,H=/^[a-f0-9]{64}$/;async function l(e){const t=await v(e);return t===null?null:{ticketId:t.request_id,dir:t.request_dir,kind:t.kind}}o(l,"resolveTicket");function u(e){const t=e.ticket_id;if(t===void 0||!H.test(t))throw new i(400,"invalid_request","invalid ticket id");return t}o(u,"requireTicketId");function p(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}o(p,"isPlainObject");function _(e,t){for(const r of Object.keys(e))if(!t.includes(r))throw new i(400,"invalid_request",`unexpected field: ${r}`)}o(_,"requireNoExtraKeys");function K(e){if(!p(e))throw new i(400,"invalid_request","respond body is required");if(_(e,["responses"]),!p(e.responses))throw new i(400,"invalid_request","`responses` must be an object");return{responses:e.responses}}o(K,"validateRespondRequest");function M(e){if(!p(e))throw new i(400,"invalid_request","progress body is required");if(_(e,["responses"]),!p(e.responses))throw new i(400,"invalid_request","`responses` must be an object");return{responses:e.responses}}o(M,"validateProgressRequest");function W(e){if(e===void 0)return{};if(!p(e))throw new i(400,"invalid_request","cancel body must be an object");if(_(e,["reason"]),e.reason===void 0)return{};const t=e.reason;if(typeof t!="string")throw new i(400,"invalid_request","`reason` must be a string");if(t.trim()===""||t.length>$)throw new i(400,"invalid_request","`reason` must be nonempty after trim and at most 1000 characters");return{reason:t}}o(W,"validateCancelRequest");const B=[/^slot ".*?" /,/^response names unknown or non-response-bearing slot id/,/^final page response is missing response-bearing slot id/];function g(e){return e instanceof Error&&B.some(t=>t.test(e.message))}o(g,"isSlotValidationError");function q(e){const t={request_id:e.id,request_dir:e.dir,ticket_id:e.inboxTicketId,kind:"page",title:e.title,placement:e.placement,dialect:e.dialect,steps:e.steps,emitted_at:e.emittedAt,source:e.source,slot_kinds:e.slotKinds,inbox:e.inbox,awaits_response:e.awaitsResponse,state:e.state};return e.subtitle!==""&&(t.subtitle=e.subtitle),e.answerDigest!==void 0&&(t.answer_digest=e.answerDigest),e.recommendedOptions.length>0&&(t.recommended_options=e.recommendedOptions.map(r=>({slot_id:r.slotId,option_id:r.optionId,label:r.label}))),e.fastAction!==void 0&&(t.fast_action={kind:e.fastAction.kind,responses:e.fastAction.responses}),t}o(q,"pageSummaryToDTO");async function V(e){const t=await c("scan_inbox",()=>R()),r=await c("readable_ids",()=>y(e.principal,t.map(s=>s.inboxTicketId))),n=t.filter(s=>r.has(s.inboxTicketId)).map(s=>{if(s.kind==="page")return q(s);if(s.kind==="review")return{request_id:s.id,request_dir:s.dir,ticket_id:s.inboxTicketId,kind:"review",title:s.title,subtitle:s.subtitle,blocked_since:s.blockedSince,source:s.source,...T()===void 0?{}:{url:`${T()}/review/${s.id}`}};throw new Error(`unknown ticket kind: ${s.kind}`)}).sort((s,a)=>{const w=o(h=>h.kind==="page"?h.emitted_at:h.blocked_since,"pageTime"),d=Date.parse(w(a))-Date.parse(w(s));return d!==0?d:s.ticket_id.localeCompare(a.ticket_id)});return e.query.get("include")==="page"&&await c("page_bodies",()=>z(n)),{status:200,body:{tickets:n}}}o(V,"listWithinTimings");async function z(e){const t=e.filter(n=>n.kind==="page"),r=new Map((await x(t.map(n=>n.ticket_id))).map(n=>[n.inbox_ticket_id,n]));await Promise.all(t.map(async n=>{const s=r.get(n.ticket_id);if(!(s===void 0||s.kind!=="page"))try{n.page=await b(s)}catch{}}))}o(z,"attachPages");async function m(e){const{value:t,steps:r}=await P(e);return{...t,headers:{"server-timing":A(r)}}}o(m,"withServerTiming");async function F(e){return await m(()=>V(e))}o(F,"handleList");const U=new Set(["pending","resolved","canceled","passive"]);async function X(e){const t=e.query.get("node_id");if(t==="")throw new i(400,"invalid_request","node_id must be nonempty when present");const r=e.query.get("state");if(r!==null&&!U.has(r))throw new i(400,"invalid_request","state must be one of pending, resolved, canceled, passive");const n=await S(t??void 0,r??void 0),s=await y(e.principal,n.map(d=>d.inboxTicketId));return{status:200,body:{tickets:n.filter(d=>s.has(d.inboxTicketId)).map(q)}}}o(X,"handleHistory");async function J(e){return await m(()=>Q(e))}o(J,"handleGetPage");async function Q(e){const t=u(e.params),r=await l(t);if(r===null)throw new i(404,"ticket_not_found","no matching ticket");if(r.kind==="review")throw new i(409,"ticket_kind_unsupported","review tickets have no page read operation");const n=await c("read_request",()=>v(t));if(n===null||n.kind!=="page")throw new i(404,"ticket_not_found","no matching ticket");try{return{status:200,body:await c("project_page",()=>b(n))}}catch{throw new i(500,"internal","the ticket could not be read")}}o(Q,"getPageWithinTimings");async function Y(e){return await m(()=>Z(e))}o(Y,"handleRespond");async function Z(e){const t=u(e.params),r=K(e.body),n=await c("resolve_ticket",()=>l(t));if(n===null)throw new i(404,"ticket_not_found","no matching ticket");if(n.kind==="review")throw new i(409,"ticket_kind_unsupported","review tickets submit through their own path");if((await c("read_ticket",()=>k(n.dir))).state==="passive")throw new i(409,"page_has_no_response_lifecycle","this page has no response lifecycle");const s=await c("read_result",()=>f(n.dir));if(s!==null&&s.kind!=="canceled")throw new i(409,"ticket_already_resolved","ticket was already resolved");if(s?.kind==="canceled")throw new i(409,"ticket_canceled","canceled tickets cannot be answered");try{await c("validate",()=>C(n.dir,r.responses))}catch(a){throw g(a)?new i(400,"invalid_ticket_response",a.message):new i(500,"internal","validation failed")}try{const a=await c("resolve_page",()=>G(n.ticketId,r.responses));if(a.kind!=="page")throw new i(409,"ticket_kind_mismatch","unexpected result kind");return{status:200,body:a}}catch(a){throw a instanceof i?a:g(a)?new i(400,"invalid_ticket_response",a.message):new i(500,"internal","the ticket could not be finalized")}}o(Z,"respondWithinTimings");async function ee(e){const t=u(e.params),r=M(e.body),n=await l(t);if(n===null)throw new i(404,"ticket_not_found","no matching ticket");if(n.kind==="review")throw new i(409,"ticket_kind_unsupported","review tickets do not support progress autosave");if((await k(n.dir)).state==="passive")throw new i(409,"page_has_no_response_lifecycle","this page has no response lifecycle");const s=await f(n.dir);if(s!==null&&s.kind!=="canceled")throw new i(409,"ticket_already_resolved","ticket was already resolved");try{return await D(n.dir,r.responses),{status:200,body:{}}}catch(a){throw g(a)?new i(400,"invalid_ticket_response",a.message):new i(500,"internal","progress could not be saved")}}o(ee,"handleProgress");async function te(e){const t=u(e.params),r=W(e.body),n=await l(t);if(n===null)throw new i(404,"ticket_not_found","no matching ticket");if(n.kind==="review")throw new i(409,"ticket_kind_unsupported","review tickets have their own cancel path");if((await k(n.dir)).state==="passive")throw new i(409,"page_has_no_response_lifecycle","this page has no response lifecycle");try{const s=await N(n.ticketId,{reason:r.reason??L,actor:"human",disposition:"dismissed"});if(s.outcome==="already_settled"||s.result.kind!=="canceled")throw new i(409,"ticket_already_resolved","ticket was already resolved");return{status:200,body:s.result}}catch(s){throw s instanceof i?s:new i(500,"internal","the ticket could not be canceled")}}o(te,"handleCancel");async function ne(e){const t=u(e.params),r=await l(t);if(r===null)throw new i(404,"ticket_not_found","no matching ticket");if(r.kind==="review")throw new i(409,"ticket_kind_unsupported","review tickets fetch responses through their own path");const n=await f(r.dir);if(n===null)throw new i(404,"ticket_pending","ticket has no response yet");if(n.kind==="canceled")throw new i(404,"ticket_canceled","canceled tickets have no response");if(n.kind!=="page")throw new i(409,"ticket_kind_mismatch","unexpected result kind");try{const s=await E(await O(r.dir));return{status:200,body:{...n,answer:j(s,n.responses,{completedAt:n.completedAt})}}}catch{throw new i(500,"internal","the ticket answer could not be read")}}o(ne,"handleGetResponse");const ke=[{method:"GET",pattern:"/v1/human/inbox",handler:F},{method:"GET",pattern:"/v1/human/inbox/history",handler:X},{method:"GET",pattern:"/v1/human/inbox/:ticket_id",handler:J},{method:"GET",pattern:"/v1/human/inbox/:ticket_id/response",handler:ne},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/respond",handler:Y},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/progress",handler:ee},{method:"POST",pattern:"/v1/human/inbox/:ticket_id/cancel",handler:te}];export{ke as inboxRoutes,u as requireTicketId,l as resolveTicket};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var L=Object.defineProperty;var d=(e,t)=>L(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as I}from"../../core/events/emit.js";import{scopeAllowed as m,ScopeDeniedError as F}from"../../core/scopes.js";import{coveredByAny as J}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as M}from"../../core/canvas/person.js";import{activeGrant as p,activeGrantsOfPerson as Y,grantFor as O}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 N,getRequestByInboxTicket as C}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 $(e){return e.class==="broker"||e.class==="cron"}d($,"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 T(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(T,"forwardedGrant");async function U(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 T(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>J(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 p(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(U,"resolvedScopes");function x(e){return"class"in e?k(e):e.grantee}d(x,"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 U(n),o)&&(!$(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(!((!("class"in e)||e.class==="app")&&x(e)===s.grantee&&e.sub===s.sub)&&!await f(e,"read",t))throw new E(404,"not_found","run not found");if(o&&x(e)!==null&&x(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"&&M())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),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 U(t);if(e.scope&&(!m(n,e.scope)||$(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 N(o.request_id):o.ticket_id?await C(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 N(o.request_id):o.ticket_id?await C(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 F("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 He(e){return e.map(t=>({...t,ownerOnly:!0}))}d(He,"ownerOnly");class Ie{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(B){const R=B instanceof D?"payload_too_large":"invalid_request";G(o,R==="payload_too_large"?413:400,R,B.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"){A(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}=H(r);a>=500&&I({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??""}}),A(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 A(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(A,"writeJson");function G(e,t,o,n){A(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(G,"writeError");export{fe as CAUSED_BY_HEADER,Ie as Router,l as actsAsPerson,k as appOf,ie as assertCeiling,$ as boundedByStoredScopes,oe as canReadNode,Ge as canReadRun,he as causedByOf,f as mayOnNode,He as ownerOnly,ce as ownerOnlyError,ze as readableAmong,Pe as readableNodeIds,De as readableTicketIds,Le as requireRun,U as resolvedScopes,x as runCallerApp};
|
|
1
|
+
var L=Object.defineProperty;var d=(e,t)=>L(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as I}from"../../core/events/emit.js";import{scopeAllowed as m,ScopeDeniedError as F}from"../../core/scopes.js";import{coveredByAny as J}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as M}from"../../core/canvas/person.js";import{activeGrant as Y,activeGrantsOfPerson as p,grantFor as O}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 N,getRequestByInboxTicket as C}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 $(e){return e.class==="broker"||e.class==="cron"}d($,"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 T(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(T,"forwardedGrant");async function U(e){if(e.class==="person"&&e.sub!==void 0)return(await p(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 T(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>J(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 Y(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(U,"resolvedScopes");function x(e){return"class"in e?k(e):e.grantee}d(x,"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 U(n),o)&&(!$(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(!((!("class"in e)||e.class==="app"||e.class==="forwarded"&&e.actor.kind==="app")&&x(e)===s.grantee&&e.sub===s.sub)&&!await f(e,"read",t))throw new E(404,"not_found","run not found");if(o&&x(e)!==null&&x(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"&&M())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),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 U(t);if(e.scope&&(!m(n,e.scope)||$(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 N(o.request_id):o.ticket_id?await C(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 N(o.request_id):o.ticket_id?await C(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 F("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 He(e){return e.map(t=>({...t,ownerOnly:!0}))}d(He,"ownerOnly");class Ie{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(B){const R=B instanceof D?"payload_too_large":"invalid_request";G(o,R==="payload_too_large"?413:400,R,B.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"){A(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}=H(r);a>=500&&I({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??""}}),A(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 A(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(A,"writeJson");function G(e,t,o,n){A(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(G,"writeError");export{fe as CAUSED_BY_HEADER,Ie as Router,l as actsAsPerson,k as appOf,ie as assertCeiling,$ as boundedByStoredScopes,oe as canReadNode,Ge as canReadRun,he as causedByOf,f as mayOnNode,He as ownerOnly,ce as ownerOnlyError,ze as readableAmong,Pe as readableNodeIds,De as readableTicketIds,Le as requireRun,U as resolvedScopes,x as runCallerApp};
|
package/dist/daemon/cron-run.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var i=(e,c)=>Y(e,"name",{value:c,configurable:!0});import{randomUUID as X}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as A,formatCronOutputHead as S}from"./cron/capture.js";import{clearLiveRun as
|
|
2
|
-
${q}`.trim().slice(0,A)},lease:"release"}).then(t,a);return}
|
|
1
|
+
var Y=Object.defineProperty;var i=(e,c)=>Y(e,"name",{value:c,configurable:!0});import{randomUUID as X}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as A,formatCronOutputHead as S}from"./cron/capture.js";import{clearLiveRun as w,cronDaemonInstanceId as M,ensureCronOwnerLease as z,registerLiveRun as G}from"./cron/live-runs.js";import{closeCronExecution as J,openCronExecution as K}from"./cron/run-socket.js";import{appProcessSandboxed as Q}from"../core/spaces/process.js";import{nodeAgentDir as V}from"../core/canvas/paths.js";import{uidForApp as W}from"../core/spaces/users.js";import{buildArmedRunContext as Z}from"./cron/armed-context.js";import{asPerson as j}from"./reconcilers/node-lifecycle/node-person.js";import{isProfilePaused as ee}from"../core/profiles/manifest.js";import{ensureCronFolder as ne}from"./cron/folders.js";import{cronEnvironment as re,fireInSandbox as te,fireOnMachine as oe,machineLinkLive as ae}from"./cron/machine-fire.js";import{advanceRecurrence as U}from"./cron/recurrence.js";import{checkCronFire as ie,cronPrincipalOf as se}from"./cron/authority.js";import{refusalError as de}from"../core/ledger/index.js";import{noticeStartRefusal as le}from"../core/runtime/start-refusal-notice.js";import{startRefusal as ue}from"../core/runtime/start-check.js";import{settleClosedRun as fe,settleUnspawnedRun as v}from"./cron/closed.js";import{settleRun as B}from"./cron/settle.js";import{applyOverlapPolicies as me,expireDueCrons as ce}from"./cron/passes.js";import{dueClockCrons as pe,acquireCronRunLease as he,releaseCronRunLease as we,attachCronRunPid as _e,HOSTED_CRON_MAX_FIRES as Ce}from"../core/canvas/crons.js";import{emitEvent as $}from"../core/events/emit.js";import{deliverDueDeadline as ge}from"../core/feed/messages.js";import{runAppCommand as xe}from"../core/runtime/run-command.js";import{CRON_OUTPUT_HEAD_BYTES as We}from"./cron/capture.js";import{cronDaemonInstanceId as je,markSelfCanceledCronRun as en}from"./cron/live-runs.js";import{recoverStaleCronLeases as rn}from"./cron/lease-recovery.js";function Je(e,c){return F(e,c).settled}i(Je,"executeCron");function F(e,c){const{outOfBand:s}=c;let l=i(()=>{},"admit");const u=new Promise(t=>{l=t}),_=new Promise((t,a)=>{let p=!1;const r=X();let I=i(()=>{},"undo");const R=i(d=>{if(I(),!p){a(d);return}p=!1,we(e.cron_id,r).then(()=>a(d),f=>{$({level:"error",event:"cron.lease.release_failed",error:f,fields:{cron_id:e.cron_id}}),a(d)})},"fail");(async()=>{const d=Date.now(),f=new Date(d).toISOString(),C={runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d},D=await re(e),b=D?.kind==="machine"?D.id:null;if(b!==null&&!s&&!await ae(b)){t(null);return}if(await z(),!await he(e.cron_id,M,f,s,r,D?.kind==="blaxel"?Ce:null)){t(null);return}p=!0;let m=await ie(se(e));if(m.allowed){e={...e,scopes:m.scopes};const n=await ue({grantee:e.grantee,sub:e.sub,grant_id:e.grant_id});n!==null&&(m={allowed:!1,reason:"limit_reached",message:de(n).message},await le(n))}if(!m.allowed){try{if(!s&&e.recur!=null){const h=await U(e,d);if(h!==null)throw h}}catch(h){v(e,C,"run could not be armed",h).then(t,a);return}const n=Date.now();B(e,{outOfBand:s,outcome:{kind:"refused",reason:m.reason,message:m.message},record:{runId:r,startedAtIso:f,finishedAtMs:n,durationMs:n-d,exitCode:null,stdoutHead:null,stderrHead:`${m.reason}: ${m.message}`.slice(0,A)},lease:"release"}).then(t,a);return}if(D?.kind==="blaxel"){te(e,C,l).then(t,R);return}if(b!==null){oe(e,{environmentId:b,runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d},l).then(t,R);return}let H;try{if(e.isolated&&ne(e.grantee,e.cron_id),{env:H}=await Z(e,r),!s&&e.recur!=null){const n=await U(e,d);if(n!==null)throw n}}catch(n){v(e,C,"run could not be armed",n).then(t,a);return}let k=null,y=!1;const O={runId:r,replaced:!1,selfCanceled:!1,kill:i(()=>{k!==null?k():y=!0},"kill")};G(e.cron_id,O),I=i(()=>w(e.cron_id,r),"undo"),l();const g=Q()?{executionId:r,kind:"cron",cronId:e.cron_id,fromExec:e.armed_from_exec,grantee:e.grantee,sub:e.sub,grantId:e.grant_id,scopes:e.scopes,originRunId:e.origin_run_id,isolated:e.isolated,anchor:e.anchor_node,uid:await W(e.grantee),rebuilt:!1,refusal:null}:null,x=i(()=>{g!==null&&J(r)},"closeExecution");I=i(()=>{w(e.cron_id,r),x()},"undo"),i(async()=>(g!==null&&await K(g,e.cwd,e.profile),xe({command:e.command,cwd:e.cwd,env:H,app:e.grantee,isolated:e.isolated,principal:{sub:e.sub,grantId:e.grant_id,scopes:e.scopes},...e.isolated?{folder:e.cwd}:{},...g!==null?{cron:{executionId:r,...e.anchor_node===null||e.isolated?{}:{anchorDir:V(e.anchor_node,e.grantee)}}}:e.anchor_node===null||e.isolated?{}:{nodeId:e.anchor_node},timeoutMs:e.run_timeout_s*1e3,headBytes:A})),"launch")().then(async n=>{if(n.pid===null){w(e.cron_id,r),x(),n.completion.then(o=>{v(e,C,"run failed to spawn",o.processError??new Error("bash did not provide a process id")).then(t,a)},a);return}I=i(()=>{w(e.cron_id,r),x(),n.terminate()},"undo");let h=!1;const P=i(()=>{n.completion.then(o=>{const T=O.replaced,N=O.selfCanceled,E=g?.refusal??null;if(w(e.cron_id,r),x(),h){t(null);return}if(E!==null&&!T){const L=Date.now(),q=S(o.stderr,o.stderrTruncated);B(e,{outOfBand:s,outcome:{kind:"refused",reason:E.reason,message:E.message},record:{runId:r,startedAtIso:f,finishedAtMs:L,durationMs:L-d,exitCode:o.exitCode,stdoutHead:S(o.stdout,o.stdoutTruncated)||null,stderrHead:`${E.reason}: ${E.message}
|
|
2
|
+
${q}`.trim().slice(0,A)},lease:"release"}).then(t,a);return}fe(e,{runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d,finishedAtMs:Date.now(),code:o.exitCode,timedOut:o.timedOut,processError:o.processError,stdoutHead:S(o.stdout,o.stdoutTruncated),stderrHead:S(o.stderr,o.stderrTruncated),stdoutSha256:o.stdoutSha256,wasReplaced:T,wasSelfCanceled:N}).then(t,a)},a)},"settleCommand");if(!await _e(e.cron_id,M,f,n.pid)&&!O.selfCanceled){h=!0,n.terminate(),P();return}k=n.terminate,y&&n.terminate(),P()},n=>{w(e.cron_id,r),x(),v(e,C,"run failed to spawn",n).then(t,a)}).catch(R)})().catch(R)});return _.then(l,l),{admitted:u,settled:_}}i(F,"startCron");async function Ke(e,c){const s=new Date(e).toISOString();await ce(s),await me(e,s);const l=[];for(const u of await pe(s)){const _=await j(u.sub,async()=>ee(u.profile)?null:u.deadline_body!==null?await ge(u).then(()=>null):F(u,{outOfBand:!1})).catch(r=>($({level:"error",event:"cron.fire_failed",error:r,fields:{cron_id:u.cron_id}}),null));if(_===null)continue;const{admitted:t,settled:a}=_,p=a.then(()=>{});p.catch(()=>{}),await t,l.push(p),c.register?.(p)}for(const u of l)u.catch(()=>{});return l}i(Ke,"runDueCrons");export{We as CRON_OUTPUT_HEAD_BYTES,je as cronDaemonInstanceId,Je as executeCron,en as markSelfCanceledCronRun,rn as recoverStaleCronLeases,Ke as runDueCrons,F as startCron};
|
package/dist/daemon/fleet.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var P=Object.defineProperty;var
|
|
1
|
+
var P=Object.defineProperty;var c=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R,recordRespawnAttempt as T}from"../core/canvas/index.js";import{revokeExitedNodeToken as N}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as S,endExecution as y,hasLaunchingExecution as F,hasProfilePauseStop as C,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as O,markProfilePauseStop as k,recordExecutionExit as A,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as z}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 B,transition as v}from"../core/runtime/lifecycle.js";import{publishNotice as L}from"../core/runtime/close.js";import{hasAdmittedTurn as D,readFault as W,readInterruptedTurn as q,readTransportPoisonVerdict as G}from"../core/canvas/recovery.js";import{hasPendingWake as H}from"./reconcilers/live-obligation.js";import{clearRespawnPolicy as h,deferRespawnWhileOffline as Y,MAX_RESPAWN_ATTEMPTS as U,OFFLINE_RESPAWN_RETRY_MS as V,recordRespawnPolicy as j,respawnBackoffMs as K}from"./reconcilers/node-lifecycle/respawn-policy.js";import{probeOnline as X}from"../core/runtime/connectivity.js";import{runnerForExecution as J}from"../core/runtime/runner/index.js";import{reviveNode as Q}from"../core/runtime/revive.js";import{noticeStartRefusalError as Z}from"../core/runtime/start-refusal-notice.js";import{isStartRefusal as I}from"../core/runtime/start-check.js";import{MachineOfflineError as ee}from"../core/runtime/runner/machine/ops.js";import{pushUrgent as m}from"../core/feed/feed.js";import{emitEvent as f}from"../core/events/emit.js";import{brokerThresholdsForDaemon as te}from"../core/runtime/fleet.js";import{isRecoveryHeld as re}from"../core/runtime/recovery-hold.js";async function E(i,e){const r=await W(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
|
|
|
@@ -6,16 +6,16 @@ Its pi vehicle exited before the session came up (no pi_session_id was ever reco
|
|
|
6
6
|
|
|
7
7
|
`+t+`Inspect canonical event diagnostics with \`crtr sys logs --node ${i.node_id}\`.
|
|
8
8
|
|
|
9
|
-
If the work still needs doing, re-spawn it.`}
|
|
9
|
+
If the work still needs doing, re-spawn it.`}c(E,"bootFailureBody");async function $(i,e){await m(i.node_id,await E(i,e),{from:i.node_id})}c($,"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.`}
|
|
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.`}c(x,"outOfMemoryBody");async function ie(i){const e=await G(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})}
|
|
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})}c(ie,"surfaceCrashLoop");async function se(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})}
|
|
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})}c(se,"surfaceRecoveryFailure");function ae(i,e,r=!0,t=!1){return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?"forget":i.intent==="refresh"||i.cycle_pending===!0?"respawn-fresh":B(i)?"dormant":i.lifecycle==="resident"&&!e&&!r&&(i.pi_session_id!=null||t)?"release-idle":i.pi_session_id!=null?"respawn-resume":e||t||i.fork_from!=null?"respawn-fresh":"boot-failure"}c(ae,"classifyDeadNode");const ne=3e4;class Ne{static{c(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??(()=>X())}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 F(e,this.#a)}get(e){return this.#e.get(e)}size(){return this.#e.size}async#c(){const e=await O();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}=te(),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>=ne&&(this.#l=s,f({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 J(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 C(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 N(t),this.#e.delete(e),s!==void 0&&(await A(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,u=a?.respawn_failures??0;this.#f(e,r,d,u)})}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:c(()=>se(n,t),"surface")}),!0)}dispose(){}#f(e,r,t,s){f({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&&z(t.profile_id))return await h(e),"forget";if(await S(e))return await h(e),"forget";if(await re(e))return"dormant";const s=(await q(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:c(async()=>{await m(e,x(t),{from:e})},"surface")}),"forget";const a=ae(t,s,await H(e),await D(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"),f({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:c(()=>$(t,r),"surface")});break;case"respawn-fresh":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 Y(e,n,this.#r()),f({level:"info",event:"broker.respawn.offline_deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,retry_in_ms:V,consecutive_failures:n}});return}const d=a.respawn_not_before==null,u=d?await j(a,this.#r()):{failures:n,notBefore:a.respawn_not_before,exhausted:n>=U};if(u.exhausted){await T(e,{failures:u.failures,notBefore:null});const l=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${u.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:l,respawn_failures:u.failures},wake:l,...r.pi_session_id!=null?{surface:c(()=>ie(r),"surface")}:{}});return}if(d&&u.notBefore!==null){f({level:"info",event:"broker.respawn.deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,backoff_ms:K(u.failures),consecutive_failures:u.failures}});return}f({level:"info",event:"broker.respawn.started",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,consecutive_failures:u.failures}});try{await Q(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&s?"runtime-restart-abort":void 0,recovery:!0})}catch(l){if(I(l)||l instanceof ee){await h(e),await v(e,"release"),f({level:"warn",event:"node.start.refused",node_id:e,error:l,fields:{enact:"respawn"}}),await Z(l);return}f({level:"error",event:"broker.respawn.failed",...o(e)?{node_id:e}:{},error:l,fields:{...o(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",l,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:l instanceof Error?l.message:String(l)})}}async#s(e,r,t){f({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){f({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{Ne as DaemonFleet,ae as classifyDeadNode,$ as surfaceBootFailure};
|
|
@@ -22,7 +22,5 @@ export declare function writeMachineCredential(secret: string): void;
|
|
|
22
22
|
/** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
|
|
23
23
|
export declare const installIdPath: () => string;
|
|
24
24
|
export declare function readOrCreateInstallId(): string;
|
|
25
|
-
/**
|
|
26
|
-
export declare const
|
|
27
|
-
/** A computer with no `machine.json`, no local records and no join registration has not been set up: it has no control plane to reach until `crtr sys signin`. */
|
|
28
|
-
export declare const computerIsUnset: () => boolean;
|
|
25
|
+
/** A computer with no `machine.json` and no join registration is not signed in to Northlight: it has no control plane to reach until `crtr sys signin`. */
|
|
26
|
+
export declare const computerIsNotSignedIn: () => boolean;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var m=Object.defineProperty;var t=(r,n)=>m(r,"name",{value:n,configurable:!0});import{chmodSync as l,existsSync as i,mkdirSync as
|
|
2
|
-
`)}t(
|
|
3
|
-
`,{mode:384}),l(n,384)}t(
|
|
4
|
-
`),n}t(
|
|
1
|
+
var m=Object.defineProperty;var t=(r,n)=>m(r,"name",{value:n,configurable:!0});import{chmodSync as l,existsSync as i,mkdirSync as o,readFileSync as c,writeFileSync as d}from"node:fs";import{randomBytes as y}from"node:crypto";import{dirname as a,join as u}from"node:path";import{runtimeRoot as f,secretsDir as h}from"../../core/layout.js";import{joinedIssuer as I}from"../../core/directory/join.js";const s=t(()=>u(f(),"machine.json"),"machineConfigPath"),p=t(()=>u(h(),"machine-credential"),"machineCredentialPath");function g(){const r=s();if(!i(r))return;const n=JSON.parse(c(r,"utf8"));if(typeof n.apiUrl!="string"||typeof n.environmentId!="string"||n.runId!==void 0&&typeof n.runId!="string"||typeof n.directoryUrl!="string")throw new Error(`${r} must hold {apiUrl, environmentId, directoryUrl}`);const e=n.account!==void 0&&typeof n.account?.id=="string"&&typeof n.account.display=="string"?{id:n.account.id,display:n.account.display}:void 0;return{apiUrl:n.apiUrl,environmentId:n.environmentId,...n.runId===void 0?{}:{runId:n.runId},directoryUrl:n.directoryUrl,...e===void 0?{}:{account:e}}}t(g,"readMachineConfig");function $(r){o(a(s()),{recursive:!0}),d(s(),`${JSON.stringify(r,null,2)}
|
|
2
|
+
`)}t($,"writeMachineConfig");function M(){const r=p();if(!i(r))throw new Error(`no machine credential at ${r}`);return c(r,"utf8").trim()}t(M,"readMachineCredential");function N(r){const n=p();o(a(n),{recursive:!0}),d(n,`${r}
|
|
3
|
+
`,{mode:384}),l(n,384)}t(N,"writeMachineCredential");const x=t(()=>u(f(),"install-id"),"installIdPath");function O(){const r=x();if(i(r))return c(r,"utf8").trim();const n=Array.from(y(8),e=>"abcdefghijklmnopqrstuvwxyz0123456789"[e%36]).join("");return o(a(r),{recursive:!0}),d(r,`${n}
|
|
4
|
+
`),n}t(O,"readOrCreateInstallId");const P=t(()=>g()===void 0&&I()===null,"computerIsNotSignedIn");export{P as computerIsNotSignedIn,x as installIdPath,s as machineConfigPath,p as machineCredentialPath,g as readMachineConfig,M as readMachineCredential,O as readOrCreateInstallId,$ as writeMachineConfig,N as writeMachineCredential};
|
package/dist/daemon/manage.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var o=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{spawn as $,execFileSync as J}from"node:child_process";import{createRequire as q}from"node:module";import{dirname as N,join as T}from"node:path";import{fileURLToPath as Q,pathToFileURL as
|
|
1
|
+
var Y=Object.defineProperty;var o=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{spawn as $,execFileSync as J}from"node:child_process";import{createRequire as q}from"node:module";import{dirname as N,join as T}from"node:path";import{fileURLToPath as Q,pathToFileURL as g}from"node:url";import{existsSync as K,lstatSync as Z,mkdirSync as ee,openSync as F,closeSync as H,fstatSync as G,readSync as te}from"node:fs";import{apiSocketPath as re,crtrHome as D}from"../core/canvas/paths.js";import{listProcessTable as ne}from"../core/canvas/pid.js";import{bindDaemonEventSource as oe,eventSource as ae}from"../core/events/source.js";import{hostExecPath as x}from"../core/runtime/branded-host.js";import{isDaemonRunning as ie,readPidfile as w,isPidAlive as p}from"./pidfile.js";import{DAEMON_STARTUP_WINDOW_MS as W}from"./startup-policy.js";import{computerIsNotSignedIn as se,readMachineConfig as ce}from"./machine-link/config.js";import{exclusiveLockOwnerPid as ue}from"../core/exclusive-lock.js";import{onDiskMigrationLockPath as le}from"../core/canvas/paths.js";import{envNoDaemonAutostart as _e}from"../shared/env.js";import{waitForDaemonAvailability as de}from"../api/index.js";import{localClient as Re}from"../api/node-transport.js";const pe=["TMUX","TMUX_PANE","NODE_OPTIONS"],fe=new Set(["CRTR_HOME","CRTR_RUNTIME_HOME","CRTR_PIDFILE","CRTR_RUNTIME","CRTR_INSTALL_ID","CRTR_LOG","CRTR_DEBUG","CRTR_DEBUG_PID_LIVENESS","CRTR_TIMING","CRTR_TIMING_PROC","CRTR_NO_DAEMON_AUTOSTART","CRTR_NO_AUTO_UPDATE","CRTR_NO_AUTO_INIT","CRTR_NO_EXPORTS","CRTR_POSTGRES_HOME","CRTR_DATABASE_URL","CRTR_DATABASE_SCHEMA","CRTR_DATABASE_POOL_MAX","CRTR_SCHEMA_DATABASE_URL","CRTR_DOCUMENT_PORT","CRTR_LAUNCHER_SOCKET","CRTR_API_ADDRESS","CRTR_DIRECTORY_URL","CRTR_PUBLIC_API_URL","CRTR_CANVAS_URL","CRTR_CANVAS_CLIENT_ID","CRTR_CANVAS_JWK_FILE","CRTR_SECRETS_KEY","CRTR_IMPORT_SERVICE_TOKEN","CRTR_PACKAGES_TOKEN","CRTR_FEEDBACK_ENDPOINT","CRTR_FEEDBACK_TOKEN","CRTR_SUPPORT_REPO","CRTR_BRANDED_HOST","CRTR_CODESIGN_IDENTITY","CRTR_PLUGIN_REVALIDATE_TTL_MS","CRTR_IMPORT_BLOB_WORKERS","CRTR_MAX_LIVE_BROKERS","CRTR_WARN_LIVE_BROKERS","CRTR_BROKER_RSS_CAP_MB","CRTR_UNATTENDED_PARK_MS","CRTR_WARM_POOL","CRTR_STREAM_WATCHDOG_MS","CRTR_CONVERSATION_COMMIT_DEADLINE_MS","CRTR_NAME_MODEL","CRTR_MODEL_PROVIDER","CRTR_BROKER_SIGNAL_LONG_PROOF"]),me=["CRTR_DB_","CRTR_BOOT_","CRTR_R2_","CRTR_LEDGER_","CRTR_BASH_","CRTR_WATCHER_","CRTR_RECAP_","CRTR_MODEL_AUTH_","CRTR_TEST_","CRTR_FAULT_"];function he(e){return pe.includes(e)?!1:e.startsWith("CRTR_")?fe.has(e)||me.some(t=>e.startsWith(t)):!0}o(he,"daemonKeepsEnv");function y(){const e={};for(const[t,r]of Object.entries(process.env))he(t)&&(e[t]=r);return e}o(y,"sanitizedDaemonEnv");function Ee(){for(let e=N(Q(import.meta.url));;e=N(e)){if(K(T(e,"bin","runtime-generation-manifest.mjs")))return e;if(N(e)===e)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}o(Ee,"generationRoot");async function I(){const e=Ee(),t=g(T(e,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:r}=await import(t);try{Z(T(r(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",g(q(import.meta.url).resolve("tsx/esm")).href,T(e,"src","daemon","crtrd-cli.ts")]}const n=g(T(e,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:a}=await import(n),s=a("daemon");if(!s.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${s.error}`);return[s.runtime.entryPath]}o(I,"resolveDaemonLaunch");function Te(e,t){return e.includes(` --canvas-home ${t} `)||e.endsWith(` --canvas-home ${t}`)}o(Te,"daemonCommandDeclaresCanvasHome");function we(){const e=ne();if(e===null)return[];const t=D(),r=[];for(const{pid:n,command:a}of e)a.includes("daemon/crtrd")&&Te(a,t)&&n!==process.pid&&r.push(n);return r}o(we,"findDaemonPids");function Se(e){const t=we().filter(n=>n!==e);for(const n of t)try{process.kill(n,"SIGTERM")}catch{}if(t.length===0)return t;const r=Date.now()+2e3;for(;Date.now()<r&&t.some(n=>p(n));)J("sleep",["0.1"]);for(const n of t)if(p(n))try{process.kill(n,"SIGKILL")}catch{}return t}o(Se,"sweepStrayDaemons");async function Qe(){const e=process.execve;if(e===void 0)throw new Error(`this Node.js ${process.version} runtime cannot replace PID 1 with the successor daemon`);const t=x(),r=await I();return e(t,[t,...r,"--canvas-home",D()],y())}o(Qe,"execDaemon");async function Ze(e){const t=await I(),r=$(x(),[...t,...e],{stdio:["ignore","pipe","pipe"],env:y()});let n="",a="";r.stdout.setEncoding("utf8").on("data",c=>{n+=c}),r.stderr.setEncoding("utf8").on("data",c=>{a+=c});const s=await new Promise((c,d)=>{r.once("error",d),r.once("close",f=>c(f))});if(s!==0)throw new Error(a.trim()||`the ${e[0]} process exited with code ${s}`);const u=n.trim().split(`
|
|
2
2
|
`).at(-1)??"";return JSON.parse(u)}o(Ze,"runDaemonEntry");const V=2e4,P=10,L=1e3;async function v(e=L){const t=Math.min(e,L);return Re({autostart:!1,timeoutMs:t,socketPath:re()}).probeHealthz(t)}o(v,"probeDaemonHealth");function De(e){const t=e instanceof Error?e.message:String(e);if(typeof e!="object"||e===null)return t;const r=e.code,n=e.cause,a=typeof r=="string"?r:n?.code;return typeof a=="string"&&!t.includes(a)?`${t}: ${a}`:t}o(De,"probeErrorMessage");async function j(e=L){const t=await v(e);if(t.startup_phase==="blocked"){const r=w()??process.pid;throw new C(r,t.startup_blocked??"daemon startup is blocked")}if(!t.ok)throw new Error(t.startup_blocked??"crtrd health check reported not ready")}o(j,"probeDaemonServing");async function et(){try{return await j(),!0}catch{return!1}}o(et,"isDaemonServing");function b(e){return new Promise(t=>{setTimeout(t,e)})}o(b,"sleepMs");class k extends Error{static{o(this,"DaemonExitedBeforeReadyError")}stderrTail;constructor(t,r){super(r===""?t:`${t}
|
|
3
|
-
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class X extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class U extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ae(e,t=W,r={},n="ready"){const a=r.readPidfile??w,
|
|
3
|
+
${r}`),this.name="DaemonExitedBeforeReadyError",this.stderrTail=r}}class X extends Error{static{o(this,"DaemonLaunchError")}constructor(t){super(t instanceof Error?t.message:String(t),{cause:t}),this.name="DaemonLaunchError"}}class C extends Error{static{o(this,"DaemonStartupBlockedError")}constructor(t,r){super(`daemon ${t} is running but normal startup is blocked: ${r}`),this.name="DaemonStartupBlockedError"}}class U extends Error{static{o(this,"DaemonNotPreparedError")}constructor(t,r){super(r===void 0?`daemon ${t} is serving but did not report the prepared startup phase`:`daemon ${t} reported startup phase ${r}, not prepared`),this.name="DaemonNotPreparedError"}}async function Ae(e,t=W,r={},n="ready"){const a=r.readPidfile??w,s=r.isPidAlive??p,u=r.childExited,c=r.isDaemonServing,d=r.probeDaemonServing??(async h=>{if(c!==void 0){if(await c())return;throw new Error("crtrd health check reported not ready")}await j(h)}),f=r.probeDaemonHealth??v,S=r.sleepMs??b,i=r.now??Date.now;let R=null,l=null;return await de({windowMs:t,pollIntervalMs:P,now:i,sleep:S,retry:o(h=>h!==l,"retry"),probe:o(async h=>{const m=a();if(m===null||!s(m)){const _=u?.();throw _!=null&&(_.signal!==null?l=new k(`daemon ${e} exited before becoming ready (by ${_.signal})`,r.childStderrTail?.()??""):_.code!==0&&(l=new k(`daemon ${e} exited before becoming ready (with exit code ${_.code??"?"})`,r.childStderrTail?.()??"")),l!==null)?l:new Error(`daemon ${e} has no live pidfile owner`)}if(n==="ready"){try{await d(h)}catch(_){throw _ instanceof C&&(l=_),_}R=m;return}const E=await f(h);if(E.startup_phase==="prepared"){R=m;return}throw E.startup_phase==="blocked"?(l=new C(m,E.startup_blocked??"on-disk migration is blocked"),l):E.startup_phase==="ready"?(l=new U(m,E.startup_phase),l):new Error(`daemon ${m} is ${E.startup_phase??"not reporting a startup phase"}; waiting for prepared`)},"probe")}),R===e?null:R}o(Ae,"verifyDaemonStartup");async function Ce(e,t=V,r={}){const n=r.readPidfile??w,a=r.isPidAlive??p,s=r.sleepMs??b,u=r.now??Date.now,c=u()+t;for(;u()<=c;){if(!a(e)&&n()!==e)return;await s(P)}throw new Error(`daemon ${e} did not exit and release its pidfile within ${t}ms`)}o(Ce,"waitForDaemonExit");const Oe=2e3,Me=5e3;async function z(e,t=V,r={}){const n=r.isPidAlive??p,a=r.sleepMs??b,s=r.now??Date.now;try{process.kill(e,"SIGTERM")}catch{}try{return await Ce(e,t,r),"terminated"}catch{}try{process.kill(e,"SIGKILL")}catch{}const u=s()+Oe;for(;s()<=u;){if(!n(e))return"killed";await a(P)}throw new Error(`daemon ${e} survived both SIGTERM and SIGKILL`)}o(z,"stopDaemonProcess");async function tt(){const e=w(),t=e!==null&&p(e),r=t&&await z(e)==="killed",n=Se(null);return{stopped:t||n.length>0,...t?{pid:e}:{},strays_killed:n,force_killed:r}}o(tt,"stopAllDaemons");function Ne(e,t,r=2048){let n;try{n=F(e,"r");const{size:a}=G(n),s=Math.max(t,a-r),u=a-s;if(u<=0)return"";const c=Buffer.alloc(u);return te(n,c,0,u,s),c.toString("utf8").trim()}catch{return""}finally{if(n!==void 0)try{H(n)}catch{}}}o(Ne,"readLogTailFrom");async function ge(e={}){if(process.platform==="linux"&&K("/run/crtr/launcher.sock")&&!p(w()??-1)&&ce()===void 0)throw new Error("crtrd is managed by the root launcher; it cannot self-daemonize");const t=e.targetPhase??"ready",r=w();if(r!==null&&p(r))try{const i=await v();if(t==="prepared"){if(i.startup_phase==="prepared")return{started:!1,existing_pid:r,startup_phase:i.startup_phase};throw new U(r,i.startup_phase)}return i.ok?{started:!1,existing_pid:r,...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}:{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:i.startup_blocked??"crtrd health check reported not ready",...i.startup_phase===void 0?{}:{startup_phase:i.startup_phase}}}catch(i){if(i instanceof U)throw i;return{started:!1,existing_pid:r,running:!0,serving:!1,probe_error:De(i)}}ee(D(),{recursive:!0});const n=await I().catch(i=>{throw new X(i)}),a=T(D(),"crtrd.err"),s=F(a,"a"),u=(()=>{try{return G(s).size}catch{return 0}})();ae()===void 0&&oe();const c=$(x(),[...n,"--canvas-home",D(),...t==="prepared"?["--prepare"]:[]],{detached:!0,stdio:["ignore",s,s],env:y()});H(s);const d=c.pid;if(d===void 0)throw new Error("daemon spawn did not return a pid");let f=null;c.once("exit",(i,R)=>{f={code:i,signal:R}}),c.unref();let S;try{S=await Ae(d,W,{childExited:o(()=>f,"childExited"),childStderrTail:o(()=>Ne(a,u),"childStderrTail")},t)}catch(i){const R=ue(le())===d;if(f===null&&!R&&!(i instanceof C))try{await z(d,Me)}catch{}throw i}return S!==null?{started:!1,existing_pid:S,startup_phase:t}:{started:!0,pid:d,startup_phase:t}}o(ge,"spawnDaemon");function xe(){return _e()||process.argv.includes("--no-autostart")}o(xe,"autostartDisabled");const ye=5e3,Ie=6e4;let B=!1,A,O=0,M=0;function Pe(e){return Math.min(ye*2**(e-1),Ie)}o(Pe,"autostartBackoffMs");function Le(){A=void 0,O=0,M=0}o(Le,"resetDaemonAutostart");function rt(){return A}o(rt,"daemonAutostartStartupFailure");function nt(e={}){const t=e.isDaemonRunning??ie,r=e.spawnDaemon??ge,n=e.now??Date.now;if(!xe()&&!(!e.spawnDaemon&&se())&&!B&&!(n()<M)){if(t()){Le();return}A=void 0,B=!0,r().then(()=>{A=void 0,O=0,M=0},a=>{(a instanceof k||a instanceof X)&&(A=a.message),O+=1,M=n()+Pe(O)}).finally(()=>{B=!1})}}o(nt,"ensureDaemon");export{pe as DAEMON_ENV_STRIP_KEYS,k as DaemonExitedBeforeReadyError,X as DaemonLaunchError,U as DaemonNotPreparedError,C as DaemonStartupBlockedError,xe as autostartDisabled,rt as daemonAutostartStartupFailure,Te as daemonCommandDeclaresCanvasHome,he as daemonKeepsEnv,nt as ensureDaemon,Qe as execDaemon,we as findDaemonPids,et as isDaemonServing,v as probeDaemonHealth,j as probeDaemonServing,De as probeErrorMessage,Le as resetDaemonAutostart,y as sanitizedDaemonEnv,ge as spawnDaemon,tt as stopAllDaemons,z as stopDaemonProcess,Se as sweepStrayDaemons,Ae as verifyDaemonStartup,Ce as waitForDaemonExit};
|
|
@@ -9,7 +9,7 @@ export interface ClusterSettings {
|
|
|
9
9
|
dataDir: string;
|
|
10
10
|
socketDir: string;
|
|
11
11
|
maxConnections: number;
|
|
12
|
-
/** Also listen on this TCP address (scratch clusters
|
|
12
|
+
/** Also listen on this TCP address (scratch test clusters). */
|
|
13
13
|
tcp?: {
|
|
14
14
|
host: string;
|
|
15
15
|
port: number;
|
|
@@ -27,8 +27,8 @@ export declare function tcpUrl(user: string, host: string, port: number): string
|
|
|
27
27
|
export declare function assertNotRoot(what: string): void;
|
|
28
28
|
export declare function clusterInitialized(dataDir: string): boolean;
|
|
29
29
|
export declare function postmasterPid(dataDir: string): number | null;
|
|
30
|
-
/** `initdb` a new cluster.
|
|
31
|
-
export declare function initCluster(bins: PostgresBinaries, settings: ClusterSettings, user: string
|
|
30
|
+
/** `initdb` a new cluster. Throwaway test clusters only; trust authentication. */
|
|
31
|
+
export declare function initCluster(bins: PostgresBinaries, settings: ClusterSettings, user: string): void;
|
|
32
32
|
/** Open a connection, run `SELECT 1`, close. Resolves to the failure message when the server does not answer. */
|
|
33
33
|
export declare function probe(url: string, timeoutMs?: number): Promise<string | null>;
|
|
34
34
|
/** Start `postgres` detached in its own process group and wait until `url` answers `SELECT 1`. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var S=Object.defineProperty;var
|
|
2
|
-
`,1)[0]);return Number.isSafeInteger(t)&&t>0?t:null}catch{return null}}
|
|
1
|
+
var S=Object.defineProperty;var n=(r,t)=>S(r,"name",{value:t,configurable:!0});import{spawn as _,spawnSync as l}from"node:child_process";import{closeSync as y,existsSync as C,openSync as T,readFileSync as f}from"node:fs";import{join as m}from"node:path";const I=103,b=5432,w="postgres",D=15e3;function v(r,t,o){return`postgresql://${encodeURIComponent(r)}@/${w}?host=${encodeURIComponent(t)}${o===void 0?"":`&port=${o}`}`}n(v,"socketUrl");function N(r,t,o){return`postgresql://${encodeURIComponent(r)}@${t}:${o}/${w}`}n(N,"tcpUrl");function O(r){if(typeof process.getuid=="function"&&process.getuid()===0)throw new Error(`${r}: Postgres refuses to run as root, and this process is root. Run crtrd as a non-root user (the hosted guest launches it as the crtrd user through setpriv), or set CRTR_DATABASE_URL to an existing Postgres.`)}n(O,"assertNotRoot");function M(r){return C(m(r,"PG_VERSION"))}n(M,"clusterInitialized");function h(r){try{const t=Number(f(m(r,"postmaster.pid"),"utf8").split(`
|
|
2
|
+
`,1)[0]);return Number.isSafeInteger(t)&&t>0?t:null}catch{return null}}n(h,"postmasterPid");function d(r){return r.asUser?{uid:r.asUser.uid,gid:r.asUser.gid}:{}}n(d,"identity");function k(r,t,o){const s=["-D",t.dataDir,"-U",o,"--encoding=UTF8","--locale=C","--no-instructions","--auth=trust"],e=l(r.initdb,s,{encoding:"utf8",...d(t),env:{...process.env,LC_ALL:"C"}});if(e.status!==0)throw new Error(`initdb failed (${e.status??e.error?.message}): ${(e.stderr||e.stdout).trim()}`)}n(k,"initCluster");function $(r){try{return f(r,"utf8").trim().split(`
|
|
3
3
|
`).slice(-12).join(`
|
|
4
|
-
`)}catch{return"(no log)"}}
|
|
5
|
-
${
|
|
6
|
-
${
|
|
4
|
+
`)}catch{return"(no log)"}}n($,"logTail");async function A(r,t=1e3){const{default:o}=await import("pg"),s=new o.Client({connectionString:r,connectionTimeoutMillis:t});s.on("error",()=>{});try{return await s.connect(),await s.query("SELECT 1"),null}catch(e){return e instanceof Error?e.message:String(e)}finally{await s.end().catch(()=>{})}}n(A,"probe");async function q(r,t,o,s,e=D){const x=["-D",t.dataDir,"-c",`listen_addresses=${t.tcp?t.tcp.host:""}`,...t.tcp?["-c",`port=${t.tcp.port}`]:[],"-c",`unix_socket_directories=${t.socketDir}`,"-c",`max_connections=${t.maxConnections}`,"-c","fsync=on"],u=T(s,"a",384);let c=null;try{const a=_(r.postgres,x,{detached:!0,stdio:["ignore",u,u],env:{...process.env,LC_ALL:"C"},...d(t)});a.on("exit",(i,E)=>{c=`exited with ${i??E}`}),a.on("error",i=>{c=i.message}),a.unref();const g=Date.now()+e;let p="not tried";for(;Date.now()<g;){if(c!==null)throw new Error(`postgres ${c} before answering:
|
|
5
|
+
${$(s)}`);if(p=await A(o,500),p===null){a.removeAllListeners();return}await new Promise(i=>setTimeout(i,50))}throw new Error(`postgres did not answer SELECT 1 within ${e/1e3} s (${p}):
|
|
6
|
+
${$(s)}`)}finally{y(u)}}n(q,"startPostmaster");function B(r,t){if(h(t.dataDir)===null)return;const o=l(r.pgCtl,["stop","-D",t.dataDir,"-m","fast","-w","-t","60"],{encoding:"utf8",...d(t)});if(o.status!==0&&h(t.dataDir)!==null)throw new Error(`pg_ctl stop failed (${o.status??o.error?.message}): ${(o.stderr||o.stdout).trim()}`)}n(B,"stopPostmaster");export{w as DATABASE_NAME,I as MAX_SOCKET_PATH_BYTES,b as POSTGRES_PORT,D as READY_TIMEOUT_MS,O as assertNotRoot,M as clusterInitialized,k as initCluster,h as postmasterPid,A as probe,v as socketUrl,q as startPostmaster,B as stopPostmaster,N as tcpUrl};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var d=Object.defineProperty;var e=(r,t)=>d(r,"name",{value:t,configurable:!0});import{chownSync as u,chmodSync as f,lstatSync as l,mkdirSync as m,rmSync as g}from"node:fs";import{join as a}from"node:path";import{ensurePostgresBinaries as y}from"./binary.js";import{MAX_SOCKET_PATH_BYTES as h,POSTGRES_PORT as S,assertNotRoot as U,initCluster as w,socketUrl as P,startPostmaster as E,stopPostmaster as n,tcpUrl as T}from"./cluster.js";const k=e(()=>{},"noLog");function x(){return process.env.CRTR_DATABASE_URL||null}e(x,"externalDatabaseUrl");function C(r){m(r,{recursive:!0,mode:448});const t=l(r);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`${r} is not a directory`);if(typeof process.getuid=="function"&&t.uid!==process.getuid())throw new Error(`${r} is owned by uid ${t.uid}, not this process; refusing to put the Postgres socket there`);(t.mode&63)!==0&&f(r,448)}e(C,"ensurePrivateDir");async function A(r){const t=r.log??k;r.asUser===void 0&&U("a scratch Postgres cluster");const c=await y(t);if(C(r.dir),r.asUser&&u(r.dir,r.asUser.uid,r.asUser.gid),Buffer.byteLength(a(r.dir,`.s.PGSQL.${r.tcp?.port??S}`))>h)throw new Error(`scratch directory ${r.dir} is too long for a Postgres socket path`);const s={dataDir:a(r.dir,"data"),socketDir:r.dir,maxConnections:r.maxConnections??100,...r.tcp?{tcp:r.tcp}:{},...r.asUser?{asUser:r.asUser}:{}},o=P("crtr",r.dir,r.tcp?.port);try{w(c,s,"crtr"),await E(c,s,o,a(r.dir,"postgres.log"))}catch(i){try{n(c,s)}catch{}throw i}return{url:o,tcpUrl:r.tcp?T("crtr",r.tcp.host,r.tcp.port):null,dir:r.dir,stop:e(async(i={})=>{n(c,s),i.remove!==!1&&g(r.dir,{recursive:!0,force:!0})},"stop")}}e(A,"startScratchCluster");export{x as externalDatabaseUrl,A as startScratchCluster};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var s=(i,t)=>N(i,"name",{value:t,configurable:!0});import{clearFrozen as w,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as T}from"../../../core/canvas/labels.js";import{isSafeNodeId as l}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as z}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as C}from"../../../core/canvas/deliveries.js";import{publishNotice as L}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as h}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as
|
|
1
|
+
var N=Object.defineProperty;var s=(i,t)=>N(i,"name",{value:t,configurable:!0});import{clearFrozen as w,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as T}from"../../../core/canvas/labels.js";import{isSafeNodeId as l}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as z}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as C}from"../../../core/canvas/deliveries.js";import{publishNotice as L}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{noticeStartRefusalError as M}from"../../../core/runtime/start-refusal-notice.js";import{isStartRefusal as h}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as b}from"./node-person.js";import{MachineOfflineError as m}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as E}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as O}from"../../../core/canvas/recovery.js";import{mapAsync as P}from"../../../core/async-array.js";const R=6,U=10*6e4,x=2e4;async function H(i){const t=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(t?.idle_release_attempts??0),acknowledgedCount:Number(t?.idle_release_acked_count??0),lastAttempt:t?.idle_release_last_attempt_at==null?void 0:Date.parse(t.idle_release_last_attempt_at)}}s(H,"readEpisode");async function F(i,t,a,e,r){const o=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),e,i,t);return Number(o.changes)===1}s(F,"claimAttempt");async function W(i,t){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(t.attempts,t.lastAttempt===void 0?null:new Date(t.lastAttempt).toISOString(),t.acknowledgedCount,i)}s(W,"writeEpisode");function $(i,t){if(t)return 2;const a=i.launched_at;if(a==null)return 1;const e=i.last_settled_at;return e==null?2:Date.parse(e)>Date.parse(a)?1:2}s($,"thawTier");function B(i,t){const a=i.row.frozen_at,e=t.row.frozen_at;return a==null?e==null?0:1:e==null?-1:Date.parse(a)-Date.parse(e)}s(B,"compareThaw");const X=16;class _e{static{s(this,"FreezeLaneReconciler")}async endEpisode(t){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(t)}async run(t,a){const e=await P(a.candidates,async n=>({...n,tier:$(n.row,await k(n.row.node_id))}));e.sort(B);const r={stalled:0,waitingOnMail:0};let o=0;const d=s(async()=>{for(;o<e.length;){const n=e[o++];await z.fresh(()=>b(n.row,()=>this.enact(t,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1)}},"worker");return await Promise.all(Array.from({length:Math.min(X,e.length)},d)),r}async enact(t,a,e){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(t,a.row):(await e.applyDeadRowPolicy(r),await e.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(o){return u({level:"error",event:"node.lifecycle.enact_failed",...l(r)?{node_id:r}:{},error:o,fields:{...l(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(t){await I(t.node_id);try{return(await E(t.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(h(a)||a instanceof A||a instanceof m)return await this.settleRefusedStart(t.node_id,a,"reopen");throw a}}async settleRefusedStart(t,a,e){return a instanceof m&&a.sent||await p(t,"release"),await w(t),u({level:"warn",event:"node.start.refused",node_id:t,error:a,fields:{enact:e}}),await M(a),"skipped"}async enactThaw(t){const a=(await O(t.node_id))?.interrupted===!0;if(!a&&t.lifecycle==="resident"&&(await y(t.node_id))?.pi_session_id!=null&&!await k(t.node_id))return await p(t.node_id,"release"),await w(t.node_id),"skipped";try{return(await E(t.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(e){if(h(e)||e instanceof A||e instanceof m)return await this.settleRefusedStart(t.node_id,e,"thaw");const r=await y(t.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await p(t.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}),await w(t.node_id)),e}}async enactIdleRelease(t,a){const e=a.node_id,r=await C(e),o=await H(e),d=o.attempts===0||o.acknowledgedCount!==r,n=d?0:o.attempts;if(n>=R)return await this.endEpisode(e),u({level:"warn",event:"broker.idle_release.exhausted",...l(e)?{node_id:e}:{},fields:{...l(e)?{}:{affected_node_id:e},attempts:n,max_attempts:R}}),await p(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:n}}}),await L(e,"notice.crash",`Child crashed \u2014 ${T(a)} (${e}) failed to relaunch after ${n} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e}),"skipped";const f=d?void 0:o.lastAttempt,S=Math.min(x*2**n,U);if(f!==void 0&&t-f<S||!await F(e,o.attempts,n+1,r,t))return"skipped";const g=s(()=>W(e,{attempts:d?0:n,lastAttempt:d?void 0:o.lastAttempt,acknowledgedCount:r}),"giveBack");let v;try{v=await E(e,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof m||h(c)))throw c;return await g(),await this.settleRefusedStart(e,c,"idle-release")}return v.outcome==="frozen"?(await g(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...l(e)?{node_id:e}:{},attempt:n+1,fields:{...l(e)?{}:{affected_node_id:e},attempts:n+1,max_attempts:R}}),"launched")}}export{_e as FreezeLaneReconciler,B as compareThaw,$ as thawTier};
|