@north-light/cli 0.3.781 → 0.3.782
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 +1 -1
- 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 +19 -3
- package/dist/builtin-memory/crouter-sdk/sourcing.md +94 -0
- package/dist/builtin-memory/insights/capture.md +2 -2
- 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 -2
- package/dist/clients/attach/command.js +1 -1
- package/dist/clients/attach/input/capabilities.js +1 -1
- package/dist/clients/attach/viewer.js +459 -459
- 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/profile/default.js +1 -1
- package/dist/commands/sys/signin.d.ts +1 -1
- package/dist/commands/sys/signin.js +3 -3
- package/dist/core/command.d.ts +1 -2
- package/dist/core/command.js +6 -6
- package/dist/core/human/requests.d.ts +2 -0
- package/dist/core/human/requests.js +18 -18
- 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/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/router.js +1 -1
- 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/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 +19 -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/core/northlight/previews.d.ts +0 -22
- package/dist/core/northlight/previews.js +0 -1
|
@@ -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};
|
|
@@ -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,2 +1,2 @@
|
|
|
1
|
-
var
|
|
2
|
-
`):""}h(Ee,"messageText");function W(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}h(W,"isSessionShutdownReason");function Ie(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}h(Ie,"disposalReasonForShutdown");function ke(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}h(ke,"boundedRuntimeReason");class xe{static{h(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=L();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=h((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(o=>o.awaitingDequeue!==void 0))return;const n=C(Ee(i.content)),s=this.pendingHandoffs.find(o=>o.awaitingDequeue===n);s!==void 0&&delete s.awaitingDequeue}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=W(i)?Ie(i):"reload";W(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:ke(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=N();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const o of this.signalUnsubscribers.splice(0))o();const s=n;{const o=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const a of o)R(a,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=N().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),V()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ye,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<ge)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;D(n,{op:"record",input:{link:"daemon\u2192node",op:H,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&te(t).then(e=>e.fault?.op===H?D(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&me())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new B(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof B)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(re()){this.waitingForStartup||(this.waitingForStartup=!0,se(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),P()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await Z(t,"wake",this.reportBodies)}catch(a){throw S(a)&&(this.replayUnseenInherited=!0),a}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(a=>a.entry.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));for(const a of s)this.claims.delete(a.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>n.has(a.entry_id))),s.length>0){const a=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof a=="function"&&a(s.map(f=>f.entry_id),process.hrtime.bigint())}let o=!1;for(const a of e.deliveries){const f=a.entry.entry_id;this.claims.has(f)||(a.entry=ne(a.entry,t),this.claims.set(f,a),a.handoff==="inherited"&&!i?y.fresh(d=>{this.pendingHandoffs.push({...x([a.entry],"visible"),operationId:d,settleAtAgentSettled:!0})}):(this.buffer.push(a.entry),this.lastArrival=Date.now(),o=!0))}return o&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||q()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),o=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),a=this.isIdle()&&o.length>0&&o.every(l=>l.tier==="deferred"),f=this.visibleRoute(i)==="critical",d=!a&&!f&&e.length>0,c=!a&&!f&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:a,sendCount:Number(d)+Number(c)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await ee(t)).situational_card}catch(o){this.raiseSituationalFatal(n,o)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...K(n));return i}digest(t,e){try{return Y(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let o;try{o=x(e,t)}catch(d){this.raiseReadFatal(n,d)}let a;try{y.fresh(d=>{a=d,E({level:"info",event:"inbox.delivery.started",operation_id:d,fields:b(o)}),i()})}catch(d){return a===void 0&&this.raiseReadFatal(n,d),M(a,o,"send",d),"failed"}a===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const f={operationId:a,...o,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(f),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(f,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,o){const a=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",f=a===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{this.runNode&&s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(d=>d.entry_id)}),i.forEach((d,c)=>{const l=s&&c===i.length-1;this.pi.sendMessage({customType:F,content:d,display:!0,details:{nodeId:t}},a!==void 0?{deliverAs:a}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},o,f)}sendVisible(t,e,i,n,s,o){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const a of e)this.pi.sendMessage({customType:F,content:a,display:!0},s==="idle"?{}:{deliverAs:s});if(de(i,n),s==="idle"){const a=ce();if(a===void 0)throw new Error("broker idle-turn admission is unavailable");a(i,this.runNode?t.map(f=>f.entry_id):[])}else this.pi.sendUserMessage(i,{deliverAs:s})},o,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(o=>e.has(o.entry_id)),n=new Set(i.map(o=>o.entry_id)),s=this.buffer.filter(o=>!n.has(o.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const d of e.visibleEntries)n.add(d.entry_id);for(const d of e.hiddenEntries)n.add(d.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(d=>d.entry_id))};if(this.runNode&&s==="steer"){let d=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(d=p)});const c=e.visibleEntries.slice(0,d+1);if(e.hiddenEntries.length>0||c.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(c,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const $=new Set(c.map(u=>u.entry_id));for(const u of e.visibleEntries)$.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const o=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[a,...f]=o;for(const d of f)for(const c of d.entries)n.add(c.entry_id);if(e.hiddenEntries.length>0){const d=await this.contextCards(t,e.hiddenEntries),c=this.sendContext(t,e.hiddenEntries,d,s,a===void 0,i);if(c==="inactive")return{inactive:!0,requeueEntryIds:n};if(c==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(a!==void 0){const d=this.sendVisible(a.entries,a.cards,a.text,we(a),s,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const c of a.entries)n.add(c.entry_id);else a.kind==="human"&&(await le(t,a.text).catch(()=>{}),fe(t,a.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||q())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.runNode&&this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(o=>o.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const o of i)await this.sendPromptJoinDelivery(t,"visible",o.entries,[...o.cards,o.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(f){this.raiseReadFatal("poll",f)}let o;try{await y.fresh(async f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(s)});for(const d of n)await t.sendCustomMessage({customType:F,content:d,display:!0})})}catch(f){throw o===void 0&&this.raiseReadFatal("poll",f),M(o,s,"send",f),f}o===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const a={operationId:o,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(a,this.disposalReason);return}this.pendingHandoffs.push(a)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await Q(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const o of e.receipts){const a=s.results.find(f=>f.delivery_id===o.delivery_id);if(a?.outcome!==o.disposition&&a?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(o=>o.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const o of e.handoffs)M(o.operationId,o,"receipt_commit",s);return O({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ie(t,s),P()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(o=>!s.has(o.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(o=>!this.claims.has(o)));for(const s of n)i&&_e(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=ae(),o=new Set(this.buffer.map(l=>l.entry_id)),a=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),f=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!a.has(m))),d=new Set(f.flatMap(l=>[...l.entryIds])),c=[...this.claims.keys()].filter(l=>s||d.has(l)&&!o.has(l));return c.length===0?"settled":(this.pendingCommit={handoffs:f,entryIds:c,receipts:c.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Se(r,t){v?.dispose("reload",!1);const e=new xe(r,t,++be);v=e;const i=h(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[pe]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}h(Se,"installWatcher");function Ce(r){const t=Se(r,ve());return()=>t.dispose("shutdown",!1)}h(Ce,"registerCanvasInboxWatcher");var Ge=Ce;export{Ge as default,Ce as registerCanvasInboxWatcher};
|
|
1
|
+
var L=Object.defineProperty;var c=(r,t)=>L(r,"name",{value:t,configurable:!0});import{envInboxBetweenTurns as G,envNodeId as X,envProfileId as j,envWatcherDebounceMs as z,envWatcherTickMs as V,envWatcherBackstopMs as Y}from"../shared/env.js";import{coalesceBrokerInbox as K,entryCards as Q}from"../core/runtime/broker/inbox.js";import{consumedTurnInputIds as Z}from"../core/runtime/broker/turn-cause.js";import{acknowledgeBrokerMail as D,claimBrokerMail as ee,brokerExtensionState as te,brokerRecovery as ie,mutateBrokerFault as N,recordConversationWriteFault as ne}from"../core/runtime/broker/daemon-ops.js";import{materializeSpilledBody as se}from"../core/runtime/broker/spilled-body.js";import{brokerSignalClient as O}from"../core/runtime/broker/signal-stream.js";import{afterStartupClaimsReleased as re,startupClaimsHeld as ae}from"../core/runtime/broker/boot-state.js";import{wasTurnRefused as de}from"../core/runtime/broker/extension-abort.js";import{isTokenRevokedApiError as oe,isTransientDaemonApiError as S}from"../api/errors.js";import{announceMessageOrigin as le,messageSignature as C}from"../core/runtime/stamp/channel.js";import{captureGoalIfAbsent as fe,generateAndCommitInitialName as he}from"./broker-local.js";import{emitEvent as P}from"../core/events/emit.js";import{errorClassFromError as ce}from"../core/events/errors.js";import{operationIdContext as y}from"../core/events/operation-id.js";import{SITUATIONAL_CONTEXT_CUSTOM_TYPE as F}from"../shared/generated-context.js";import{isProfilePaused as ue}from"../core/profiles/manifest.js";import{brokerDisposeAndExit as H,brokerIdleTurnStart as me,brokerRunTurnBusy as pe,brokerRunSteer as I,HELD_DEFERRED_INBOX_PROMPT_JOIN as ye}from"../core/runtime/broker/held-deferred-inbox.js";const k=64,ge=3e4,be=5*6e4,U="inbox daemon unreachable",B=16;let v,ve=0;class q extends Error{static{c(this,"WatcherFatalError")}constructor(t,e){super(t,{cause:e}),this.name="WatcherFatalError"}}function we(){return{tickMs:V(),debounceMs:z()}}c(we,"resolveCadence");function w(){const r=X();return r===void 0||r.trim()===""?void 0:r}c(w,"currentNodeId");function W(){const r=j();return r!==void 0&&r!==""&&ue(r)}c(W,"profilePaused");function _(r){try{return ce(r)}catch{return{class:"unknown"}}}c(_,"safeErrorClass");function E(r){try{P(r)}catch{}}c(E,"emitBestEffort");function g(r){try{y.fresh(t=>{E({...r,operation_id:t})})}catch{}}c(g,"emitFreshBestEffort");function M(r,t){try{y.run(r,()=>{E({...t,operation_id:r})})}catch{}}c(M,"emitStoredBestEffort");function _e(r){return r.kind==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:r.entries.map(t=>({...t.from===null?{}:{from:t.from},...t.from_name===void 0?{}:{fromName:t.from_name},kind:t.kind,tier:t.tier,...t.ref===void 0?{}:{ref:t.ref}}))}}c(_e,"deliveryOrigin");function x(r,t){if(r.length===0)throw new Error(`cannot create an empty ${t} delivery`);const e=[...new Set(r.map(n=>n.operation_id))].sort(),i=e.length-B;return{channel:t,entryIds:r.map(n=>n.entry_id),throughEntryId:r.at(-1).entry_id,sourceOperationIds:e.slice(0,B),...i>0?{sourceOperationIdsOmitted:i}:{}}}c(x,"deliveryFacts");function b(r){return{channel:r.channel,entry_ids:r.entryIds,through_entry_id:r.throughEntryId,source_operation_ids:r.sourceOperationIds,...r.sourceOperationIdsOmitted===void 0?{}:{source_operation_ids_omitted:r.sourceOperationIdsOmitted}}}c(b,"deliveryFields");function Ee(r){M(r.operationId,{level:"info",event:"inbox.delivery.completed",outcome:"succeeded",fields:b(r)})}c(Ee,"emitDeliveryCompleted");function T(r,t,e,i){M(r,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:e,...b(t)}})}c(T,"emitDeliveryFailure");function R(r,t){M(r.operationId,{level:"error",event:"inbox.delivery.failed",outcome:"failed",error_class:{class:"unknown"},fields:{stage:"abandoned",reason:t,...b(r)}})}c(R,"emitDeliveryAbandoned");function Ie(r){return typeof r=="string"?r:Array.isArray(r)?r.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string").map(t=>t.text).join(`
|
|
2
|
+
`):""}c(Ie,"messageText");function $(r){return r==="quit"||r==="reload"||r==="new"||r==="resume"||r==="fork"}c($,"isSessionShutdownReason");function ke(r){switch(r){case"quit":return"shutdown";case"reload":case"new":case"resume":case"fork":return"reload";default:return r}}c(ke,"disposalReasonForShutdown");function xe(r){return typeof r=="string"?r.slice(0,128):r===null?"null":r===void 0?"undefined":typeof r=="number"||typeof r=="boolean"||typeof r=="bigint"?String(r).slice(0,128):typeof r}c(xe,"boundedRuntimeReason");class Se{static{c(this,"CanvasInboxWatcher")}pi;cadence;generation;timer;backstop;debounceTimer;signalUnsubscribers=[];rerun=!1;retryNeeded=!1;failingSince;failureCount=0;nextRetryAt=0;stallFaultRecorded=!1;tickFailed=!1;waitingForStartup=!1;armed=!1;lastCtx;streaming=!1;runNode=G();nodeId;claims=new Map;reportBodies=new Map;tickInFlight;buffer=[];lastArrival=0;pendingHandoffs=[];pendingCommit;promptJoinInFlight=!1;replayUnseenInherited=!1;seeded=!1;disposed=!1;disposalReason;fatalError;fatalEscaped=!1;constructor(t,e,i){this.pi=t,this.cadence=e,this.generation=i}start(){const t=c((e,i)=>{this.canMutate()&&this.captureCtx(e,i)},"capture");this.pi.on("session_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.arm())}),this.pi.on("turn_end",t),this.pi.on("agent_start",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!0)}),this.pi.on("agent_end",(e,i)=>{this.canMutate()&&(this.captureCtx(e,i),this.streaming=!1)}),this.pi.on("message_end",e=>{if(!this.canMutate())return;const i=e?.message;if(i?.role!=="user"&&i?.role!=="custom"||!this.pendingHandoffs.some(a=>a.awaitingDequeue!==void 0))return;const n=C(Ie(i.content)),s=this.pendingHandoffs.find(a=>a.awaitingDequeue===n);s!==void 0&&(delete s.awaitingDequeue,this.pi.appendEntry("crtr-turn-input",{message_ids:[...s.entryIds]}))}),this.pi.on("agent_settled",async(e,i)=>{if(!this.canMutate())return;this.captureCtx(e,i);const n=w();if(n!==void 0)try{this.assertNodeOwnership(n,"settle"),await this.tickInFlight,this.seeded||await this.claimMail(n),this.returnUnconsumedSteers();const s=await this.settle(n,i,!1,!0);s==="refresh_held"&&this.dispose("refresh",!1),this.runNode&&s==="settled"&&this.canMutate()&&this.buffer.length>0&&await this.flushOrdinary(n),this.syncTimers()}catch(s){this.dispose("shutdown",!1,void 0,{error:s,stage:"settle"})}}),this.pi.on("session_shutdown",async e=>{if(!this.canMutate())return;let i;try{i=e?.reason}catch{i=void 0}const n=$(i)?ke(i):"reload";$(i)||g({level:"warn",event:"inbox.lifecycle.unknown_shutdown_reason",outcome:"failed",fields:{reason:xe(i)}});try{await this.disposeAtSettlement(n,this.lastCtx)}catch(s){this.dispose(n,!1,void 0,{error:s,stage:"settle"})}})}arm(){if(this.armed)return;this.armed=!0;const t=O();this.signalUnsubscribers.push(t.subscribe("state",()=>this.syncTimers()),t.subscribe("mail",()=>this.runTick("schedule")),t.subscribe("resync",()=>this.runTick("schedule"))),this.syncTimers(),t.state!=="connected"&&this.runTick("schedule")}async disposeAtSettlement(t,e){const i=w();if(i===void 0){this.dispose(t,!1);return}try{this.assertNodeOwnership(i,"settle"),this.returnUnconsumedSteers();const n=await this.settle(i,e,t!=="refresh");this.dispose(n==="refresh_held"?"refresh":t,!1)}catch(n){this.dispose(t,!1,void 0,{error:n,stage:"settle"})}}dispose(t,e,i,n){if(this.disposed)return;this.disposed=!0,this.disposalReason=t,this.clearTimer();for(const a of this.signalUnsubscribers.splice(0))a();const s=n;{const a=[...new Set([...this.pendingCommit?.handoffs??[],...this.pendingHandoffs.splice(0)])];this.buffer.length=0,this.claims.clear(),this.reportBodies.clear(),this.pendingCommit=void 0,this.promptJoinInFlight=!1,this.replayUnseenInherited=!1,this.nodeId=void 0,this.lastCtx=void 0,this.lastArrival=0,this.streaming=!1,this.seeded=!1,this.ownsCurrentGeneration()&&(v=void 0);for(const o of a)R(o,t)}if(s!==void 0){this.scheduleHandlerFatal(s.error,s.stage);return}}ownsCurrentGeneration(){return v===this&&v.generation===this.generation}canMutate(){return this.ownsCurrentGeneration()&&!this.disposed&&this.fatalError===void 0}captureCtx(t,e){e!==void 0&&(this.lastCtx=e)}clearTimer(){this.timer!==void 0&&clearInterval(this.timer),this.backstop!==void 0&&clearInterval(this.backstop),this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer),this.timer=this.backstop=this.debounceTimer=void 0}syncTimers(){if(!this.armed||!this.canMutate())return;const t=O().state,e=t==="connected",i=t!=="stopped"&&(t!=="connected"||this.buffer.length>0||this.pendingCommit!==void 0||this.retryNeeded);i&&this.timer===void 0?(this.timer=setInterval(()=>this.runTick("schedule"),this.cadence.tickMs),this.timer.unref?.()):!i&&this.timer!==void 0&&(clearInterval(this.timer),this.timer=void 0),e&&this.backstop===void 0?(this.backstop=setInterval(()=>this.runTick("schedule"),Y()),this.backstop.unref?.()):!e&&this.backstop!==void 0&&(clearInterval(this.backstop),this.backstop=void 0),this.buffer.length===0&&this.debounceTimer!==void 0&&(clearTimeout(this.debounceTimer),this.debounceTimer=void 0)}noteDaemonFailure(t){const e=Date.now();this.tickFailed=!0,this.failingSince??=e,this.failureCount+=1;const i=Math.min(ge,this.cadence.tickMs*2**Math.min(this.failureCount-1,16));this.nextRetryAt=e+i;const n=this.nodeId??w();if(this.stallFaultRecorded||n===void 0||e-this.failingSince<be)return;const s=`inbox has not reached the daemon for ${Math.round((e-this.failingSince)/6e4)} min: ${t instanceof Error?t.message:String(t)}`;N(n,{op:"record",input:{link:"daemon\u2192node",op:U,kind:"connection",retry:{disposition:"auto",nextAt:new Date(this.nextRetryAt).toISOString()},message:s}}).then(()=>{this.stallFaultRecorded=!0},()=>{})}noteDaemonSuccess(){if(this.failingSince===void 0||(this.failingSince=void 0,this.failureCount=0,this.nextRetryAt=0,!this.stallFaultRecorded))return;this.stallFaultRecorded=!1;const t=this.nodeId??w();t!==void 0&&ie(t).then(e=>e.fault?.op===U?N(t,{op:"clear",link:"daemon\u2192node"}):void 0).catch(e=>{g({level:"warn",event:"inbox.stall_fault.clear_failed",outcome:"failed",error:e,error_class:_(e),fields:{stage:"poll"}})})}armDebounce(){this.debounceTimer!==void 0&&clearTimeout(this.debounceTimer);const t=Math.max(0,this.lastArrival+this.cadence.debounceMs-Date.now());this.debounceTimer=setTimeout(()=>{this.debounceTimer=void 0,this.runTick("schedule")},t),this.debounceTimer.unref?.()}isIdle(){if(this.runNode&&pe())return!1;try{if(typeof this.lastCtx?.isIdle=="function")return this.lastCtx.isIdle()===!0}catch{}return!this.streaming}assertNodeOwnership(t,e){!this.seeded||this.nodeId===void 0||this.nodeId===t||this.raiseReadFatal(e,new Error(`watcher node changed from ${this.nodeId} to ${t}`))}raiseFatal(t,e,i,n){throw this.fatalError===void 0&&(this.fatalError=new q(e,i),this.clearTimer(),g({level:"error",event:t,outcome:"failed",error:i,error_class:_(i),fields:n})),this.fatalError}raiseReadFatal(t,e){return this.raiseFatal("inbox.read.failed",`inbox ${t} state is corrupt`,e,{stage:t})}raiseSituationalFatal(t,e){return this.raiseFatal("inbox.situational_context.missing","situational context marker has no readable sidecar",e,{entry_id:t})}escapeFatal(t,e){if(!this.fatalEscaped){if(this.fatalEscaped=!0,e==="throw")throw t;queueMicrotask(()=>{throw t})}}scheduleHandlerFatal(t,e){let i;if(t instanceof q)i=t;else try{this.raiseReadFatal(e,t)}catch(n){i=n}this.escapeFatal(i,"schedule")}runTick(t="throw"){if(!this.canMutate())return;if(ae()){this.waitingForStartup||(this.waitingForStartup=!0,re(()=>{this.waitingForStartup=!1,this.runTick("schedule")}));return}if(this.tickInFlight!==void 0){this.rerun=!0;return}if(this.failingSince!==void 0&&Date.now()<this.nextRetryAt)return;this.tickFailed=!1;const e=this.tick().then(()=>{this.retryNeeded=!1,this.tickFailed||this.noteDaemonSuccess()}).catch(i=>{if(this.canMutate()){if(S(i)){this.retryNeeded=!0,this.noteDaemonFailure(i),g({level:"warn",event:"inbox.read.failed",outcome:"failed",error:i,error_class:_(i),fields:{stage:"poll"}});return}if(oe(i)){this.clearTimer(),g({level:"info",event:"inbox.poll.token_revoked",outcome:"succeeded",fields:{stage:"poll"}}),H()?.("token-revoked");return}this.scheduleHandlerFatal(i,"poll")}}).finally(()=>{this.tickInFlight===e&&(this.tickInFlight=void 0),this.syncTimers(),this.rerun&&this.canMutate()&&(this.rerun=!1,this.runTick("schedule"))});this.tickInFlight=e}async claimMail(t){this.assertNodeOwnership(t,"poll");let e;try{e=await ee(t,"wake",this.reportBodies)}catch(d){throw S(d)&&(this.replayUnseenInherited=!0),d}if(!this.canMutate()||e.action==="hold")return!1;const i=this.replayUnseenInherited;this.replayUnseenInherited=!1,this.nodeId=t,this.seeded=!0;const n=new Set(e.deliveries.map(d=>d.entry.entry_id)),s=this.buffer.filter(d=>!n.has(d.entry_id));for(const d of s)this.claims.delete(d.entry_id);if(this.buffer.splice(0,this.buffer.length,...this.buffer.filter(d=>n.has(d.entry_id))),s.length>0){const d=globalThis[Symbol.for("@crouton-kit/crtr:watcher-cancel-probe")];typeof d=="function"&&d(s.map(l=>l.entry_id),process.hrtime.bigint())}let a=!1;const o=e.deliveries.filter(d=>!this.claims.has(d.entry.entry_id));let h=new Set;if(o.length>0){const d=this.lastCtx?.sessionManager;if(d===void 0)throw new Error("inbox watcher cannot read the conversation to check reclaimed mail");h=Z(d.getBranch())}const f=o.filter(d=>h.has(d.entry.entry_id));if(f.length>0&&((await D(t,f.map(l=>({delivery_id:l.delivery_id,attempts:l.attempts,disposition:"acknowledged"})))).action==="hold"||!this.canMutate()))return!1;for(const d of e.deliveries){const l=d.entry.entry_id;this.claims.has(l)||f.includes(d)||(d.entry=se(d.entry,t),this.claims.set(l,d),d.handoff==="inherited"&&!i?y.fresh(m=>{this.pendingHandoffs.push({...x([d.entry],"visible"),operationId:m,settleAtAgentSettled:!0})}):(this.buffer.push(d.entry),this.lastArrival=Date.now(),a=!0))}return a&&this.armDebounce(),this.syncTimers(),!0}async tick(){const t=w();if(t!==void 0){if(this.pendingCommit!==void 0){await this.retryPendingCommit(t)==="refresh_held"&&this.canMutate()&&this.dispose("refresh",!1);return}this.promptJoinInFlight||W()||this.pendingHandoffs.length>=k||await this.claimMail(t)&&this.buffer.length>0&&(!this.runNode||this.isIdle()||this.buffer.some(e=>e.tier==="critical")||this.buffer.some(e=>this.isRunSteer(e))&&I()?.steerable())&&Date.now()-this.lastArrival>=this.cadence.debounceMs&&await this.flushOrdinary(t)}}missingChannelEntries(t){const e=t.filter(s=>this.claims.has(s.entry_id)),i=this.coveredEntryIds("hidden"),n=this.coveredEntryIds("visible");return{hiddenEntries:e.filter(s=>(s.data?.situational===!0||s.data?.situationalOnly===!0)&&!i.has(s.entry_id)),visibleEntries:e.filter(s=>s.data?.situationalOnly!==!0&&!n.has(s.entry_id))}}isRunSteer(t){return this.runNode&&t.kind==="message"&&(t.from??"system")==="human"&&t.data?.steer===!0}returnUnconsumedSteers(){const t=I()?.takeUnconsumed()??[];if(t.length===0)return;const e=new Set(t.flatMap(n=>n.messageIds));this.detachPending(n=>n.settlesThroughBridge===!0&&n.entryIds.every(s=>e.has(s)));const i=[...e].map(n=>this.claims.get(n)?.entry).filter(n=>n!==void 0);this.requeueFromBatch(i,e)}visibleRoute(t){return t.length===0?"none":this.isIdle()?"idle":this.runNode?t.some(e=>e.tier==="critical")?"critical":t.some(e=>this.isRunSteer(e))&&I()?.steerable()?"steer":"none":t.some(e=>e.tier==="critical")?"critical":t.some(e=>e.tier==="urgent"||e.kind==="final")?"steer":"followUp"}buildPlan(t){const{hiddenEntries:e,visibleEntries:i}=this.missingChannelEntries(t),n=new Set(e.map(l=>l.entry_id)),s=new Set(i.map(l=>l.entry_id)),a=t.filter(l=>n.has(l.entry_id)||s.has(l.entry_id)),o=this.isIdle()&&a.length>0&&a.every(l=>l.tier==="deferred"),h=this.visibleRoute(i)==="critical",f=!o&&!h&&e.length>0,d=!o&&!h&&i.length>0;return{hiddenEntries:e,visibleEntries:i,deferredHold:o,sendCount:Number(f)+Number(d)}}ordinaryPlan(){return this.buildPlan(this.buffer)}async contextCards(t,e){const i=[];if(e.some(n=>n.data?.situational===!0)){const n=e.at(-1).entry_id;let s;try{s=(await te(t)).situational_card}catch(a){this.raiseSituationalFatal(n,a)}s===null&&this.raiseSituationalFatal(n,new Error(`missing situational context for entry ${n}`)),i.push(s)}for(const n of e)n.data?.situationalOnly===!0&&i.push(...Q(n));return i}digest(t,e){try{return K(t)}catch(i){this.raiseReadFatal(e,i)}}sendDelivery(t,e,i,n,s){this.pendingHandoffs.length>=k&&this.raiseReadFatal(n,new Error(`pending handoff capacity exceeded before ${t} send`));let a;try{a=x(e,t)}catch(f){this.raiseReadFatal(n,f)}let o;try{y.fresh(f=>{o=f,E({level:"info",event:"inbox.delivery.started",operation_id:f,fields:b(a)}),i()})}catch(f){return o===void 0&&this.raiseReadFatal(n,f),T(o,a,"send",f),"failed"}o===void 0&&this.raiseReadFatal(n,new Error(`${t} delivery returned without an operation id`));const h={operationId:o,...a,...s===void 0?{}:{awaitingDequeue:s}};return this.canMutate()?(this.pendingHandoffs.push(h),"handed-off"):(this.disposed&&this.disposalReason!==void 0&&R(h,this.disposalReason),"inactive")}sendContext(t,e,i,n,s,a){const o=n==="steer"||n==="followUp"?n:this.isIdle()?void 0:"followUp",h=o===void 0||i.length===0?void 0:C(i.at(-1));return this.sendDelivery("hidden",e,()=>{s&&this.pi.appendEntry("crtr-turn-input",{message_ids:e.map(f=>f.entry_id)}),i.forEach((f,d)=>{const l=s&&d===i.length-1;this.pi.sendMessage({customType:F,content:f,display:!0,details:{nodeId:t}},o!==void 0?{deliverAs:o}:l?{deliverAs:"followUp",triggerTurn:!0}:{})})},a,h)}sendVisible(t,e,i,n,s,a){return this.sendDelivery("visible",t,()=>{if(s!=="idle"&&s!=="steer"&&s!=="followUp")throw new Error(`visible send requested for non-send route ${s}`);for(const o of e)this.pi.sendMessage({customType:F,content:o,display:!0},s==="idle"?{}:{deliverAs:s});if(le(i,n),s==="idle"){const o=me();if(o===void 0)throw new Error("broker idle-turn admission is unavailable");o(i,t.map(h=>h.entry_id))}else this.pi.sendUserMessage(i,{deliverAs:s})},a,s==="steer"||s==="followUp"?C(i):void 0)}abortCritical(){try{this.lastCtx?.abort?.()}catch{}}requeueFromBatch(t,e){if(e.size===0)return;const i=t.filter(a=>e.has(a.entry_id)),n=new Set(i.map(a=>a.entry_id)),s=this.buffer.filter(a=>!n.has(a.entry_id));this.buffer.splice(0,this.buffer.length,...i,...s)}async executePlan(t,e,i){const n=new Set,s=this.visibleRoute(e.visibleEntries);if(s==="critical"){if(this.abortCritical(),!this.canMutate())return{inactive:!0,requeueEntryIds:n};for(const f of e.visibleEntries)n.add(f.entry_id);for(const f of e.hiddenEntries)n.add(f.entry_id);return{inactive:!1,requeueEntryIds:n}}if(this.runNode&&s==="none")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(f=>f.entry_id))};if(this.runNode&&s==="steer"){let f=-1;e.visibleEntries.forEach((u,p)=>{this.isRunSteer(u)&&(f=p)});const d=e.visibleEntries.slice(0,f+1);if(e.hiddenEntries.length>0||d.some(u=>u.kind!=="message"||u.tier==="deferred"||(u.from??"system")!=="human"))return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};const l=this.digest(d,i),m=l.map(u=>({text:u.text,messageIds:u.entries.map(p=>p.entry_id),cards:u.cards}));if(I()?.accept(m)!=="accepted")return{inactive:!1,requeueEntryIds:new Set([...e.hiddenEntries,...e.visibleEntries].map(u=>u.entry_id))};for(const u of l){const p=x(u.entries,"visible");y.fresh(A=>{E({level:"info",event:"inbox.delivery.started",operation_id:A,fields:b(p)}),this.pendingHandoffs.push({...p,operationId:A,settlesThroughBridge:!0})})}const J=new Set(d.map(u=>u.entry_id));for(const u of e.visibleEntries)J.has(u.entry_id)||n.add(u.entry_id);for(const u of e.hiddenEntries)n.add(u.entry_id);return{inactive:!1,requeueEntryIds:n}}const a=e.visibleEntries.length>0?this.digest(e.visibleEntries,i):[],[o,...h]=a;for(const f of h)for(const d of f.entries)n.add(d.entry_id);if(e.hiddenEntries.length>0){const f=await this.contextCards(t,e.hiddenEntries),d=this.sendContext(t,e.hiddenEntries,f,s,o===void 0,i);if(d==="inactive")return{inactive:!0,requeueEntryIds:n};if(d==="failed")for(const l of e.hiddenEntries)n.add(l.entry_id)}if(!this.canMutate())return{inactive:!0,requeueEntryIds:n};if(o!==void 0){const f=this.sendVisible(o.entries,o.cards,o.text,_e(o),s,i);if(f==="inactive")return{inactive:!0,requeueEntryIds:n};if(f==="failed")for(const d of o.entries)n.add(d.entry_id);else o.kind==="human"&&(await fe(t,o.text).catch(()=>{}),he(t,o.text))}return{inactive:!1,requeueEntryIds:n}}async flushOrdinary(t){if(this.buffer.length===0)return"empty";const e=this.ordinaryPlan();if(e.deferredHold)return"held";if(this.pendingHandoffs.length+e.sendCount>k)return"capacity-blocked";const i=[...this.buffer],n=await this.executePlan(t,e,"poll");return n.inactive||(this.buffer.splice(0,i.length),this.requeueFromBatch(i,n.requeueEntryIds)),"attempted"}async prependHeldDeferredInbox(t){if(!this.canMutate()||this.nodeId===void 0||W())return;const e=this.ordinaryPlan();if(!e.deferredHold)return;const i=e.visibleEntries.length===0?[]:this.digest(e.visibleEntries,"poll"),n=+(e.hiddenEntries.length>0)+i.length;if(this.pendingHandoffs.length+n>k)return;const s=[...this.buffer];this.promptJoinInFlight=!0;try{this.pi.appendEntry("crtr-turn-input",{message_ids:[...e.hiddenEntries,...e.visibleEntries].map(a=>a.entry_id)}),e.hiddenEntries.length>0&&await this.sendPromptJoinDelivery(t,"hidden",e.hiddenEntries,await this.contextCards(this.nodeId,e.hiddenEntries));for(const a of i)await this.sendPromptJoinDelivery(t,"visible",a.entries,[...a.cards,a.text]);if(!this.canMutate())return;this.buffer.splice(0,s.length)}finally{this.promptJoinInFlight=!1}}async sendPromptJoinDelivery(t,e,i,n){let s;try{s=x(i,e)}catch(h){this.raiseReadFatal("poll",h)}let a;try{await y.fresh(async h=>{a=h,E({level:"info",event:"inbox.delivery.started",operation_id:h,fields:b(s)});for(const f of n)await t.sendCustomMessage({customType:F,content:f,display:!0})})}catch(h){throw a===void 0&&this.raiseReadFatal("poll",h),T(a,s,"send",h),h}a===void 0&&this.raiseReadFatal("poll",new Error(`${e} prompt-join delivery returned without an operation id`));const o={operationId:a,...s,settleAtAgentSettled:!0};if(!this.canMutate()){this.disposed&&this.disposalReason!==void 0&&R(o,this.disposalReason);return}this.pendingHandoffs.push(o)}coveredEntryIds(t){const e=new Set;for(const i of this.pendingHandoffs)if(i.channel===t)for(const n of i.entryIds)e.add(n);return e}retryPendingCommit(t){const e=this.pendingCommit;if(e===void 0)return Promise.resolve("settled");if(e.attempt!==void 0)return e.attempt;const i=this.attemptPendingCommit(t,e).finally(()=>{e.attempt===i&&(e.attempt=void 0)});return e.attempt=i,i}async attemptPendingCommit(t,e){let i=!1;try{const s=await D(t,e.receipts);if(s.action==="hold")return"refresh_held";for(const a of e.receipts){const o=s.results.find(h=>h.delivery_id===a.delivery_id);if(o?.outcome!==a.disposition&&o?.outcome!=="stale")throw new Error("daemon returned no terminal mail settlement outcome")}i=s.results.every(a=>a.outcome==="acknowledged")}catch(s){if(S(s)&&this.pendingCommit===e&&this.canMutate())return this.retryNeeded=!0,this.noteDaemonFailure(s),g({level:"warn",event:"inbox.receipt_commit.retrying",outcome:"failed",error:s,error_class:_(s),fields:{stage:"settle"}}),this.syncTimers(),"held";if(this.pendingCommit===e)for(const a of e.handoffs)T(a.operationId,a,"receipt_commit",s);return P({level:"error",event:"broker.exited",node_id:t,error:s,fields:{fault:"receipt_commit_failed"}}),this.dispose("shutdown",!1),String(s?.message).startsWith("conversation_write_failed")&&await ne(t,s),H()?.("receipt_commit_failed",1),"held"}if(this.pendingCommit!==e)return"settled";for(const s of e.entryIds)this.claims.delete(s);if(e.receipts.some(s=>s.disposition==="released")){const s=new Set(e.entryIds);this.buffer.splice(0,this.buffer.length,...this.buffer.filter(a=>!s.has(a.entry_id)))}this.pendingCommit=void 0;const n=this.detachPending(s=>s.entryIds.every(a=>!this.claims.has(a)));for(const s of n)i&&Ee(s);return"settled"}async settle(t,e,i,n=!1){if(i)try{if(e?.hasPendingMessages?.()===!0)return"held"}catch{}if(this.pendingCommit!==void 0)return this.retryPendingCommit(t);const s=de(),a=new Set(this.buffer.map(l=>l.entry_id)),o=new Set(s?[]:this.pendingHandoffs.filter(l=>l.awaitingDequeue!==void 0).flatMap(l=>[...l.entryIds])),h=this.pendingHandoffs.filter(l=>(n||l.settleAtAgentSettled!==!0)&&l.entryIds.every(m=>!o.has(m))),f=new Set(h.flatMap(l=>[...l.entryIds])),d=[...this.claims.keys()].filter(l=>s||f.has(l)&&!a.has(l));return d.length===0?"settled":(this.pendingCommit={handoffs:h,entryIds:d,receipts:d.map(l=>{const m=this.claims.get(l);return{delivery_id:m.delivery_id,attempts:m.attempts,disposition:s?"released":"acknowledged"}})},this.retryPendingCommit(t))}detachPending(t){const e=[];for(let i=this.pendingHandoffs.length-1;i>=0;i-=1){const n=this.pendingHandoffs[i];t(n)&&e.push(...this.pendingHandoffs.splice(i,1))}return e.reverse(),e}}function Ce(r,t){v?.dispose("reload",!1);const e=new Se(r,t,++ve);v=e;const i=c(n=>e.prependHeldDeferredInbox(n),"promptJoin");globalThis[ye]=i;try{e.start()}catch(n){throw e.dispose("reload",!1),n}return e}c(Ce,"installWatcher");function Fe(r){const t=Ce(r,we());return()=>t.dispose("shutdown",!1)}c(Fe,"registerCanvasInboxWatcher");var je=Fe;export{je as default,Fe as registerCanvasInboxWatcher};
|
package/docs/apps/cli.md
CHANGED
|
@@ -21,7 +21,7 @@ With no dependencies installed, `npx` downloads the newest published release of
|
|
|
21
21
|
| `npx @north-light/sdk register [--name <text>] [--scope <scope>]... [--logo <url>] [--justification <text>] [--redirect-uri <uri>]... [--issuer <url>]` | Run in a project made by `init`, after `login`: registers the app with the public key from `local/app-key.json`, adds each `--scope` beyond `crtr:llm crtr:act`, and writes `CROUTER_CLIENT_ID` and `CROUTER_ISSUER` to `local/app.env`. | No |
|
|
22
22
|
| `npx @north-light/sdk apps <leaf> [--app <client id>] [--issuer <url>] [leaf flags] [--json]` | Call one app-management leaf with the login and print its answer as JSON. Leaves: `mine`, `get`, `update`, `set-logo --file <path>`, `set-brand-color --color <#rrggbb|none>`, `set-redirect-uris`, `asks`, `set-scopes`, `set-requires`, `set-run-notice-url`, `keys list\|add\|retire\|delete\|set-jwks-uri\|remove-jwks-uri`, `testers list\|add\|remove`. `--app` defaults to `CROUTER_CLIENT_ID` in `local/app.env`; `keys add` takes `--key-file <path>` and sends only the public half. Deleting an app, its marketplace listing, monthly spend cap, sharing and provider role are console-only: those leaves exit 1 and name the console page, with no request. | No |
|
|
23
23
|
|
|
24
|
-
`keygen` and `env` are the only commands that can call `crtr`, and only with `--app`. The rest of this site never uses `--app`, so crtr is optional
|
|
24
|
+
`keygen` and `env` are the only commands that can call `crtr`, and only with `--app`. The rest of this site never uses `--app`, so crtr is optional. `login`, `logout`, `whoami`, `register` and `apps` call only the Northlight directory.
|
|
25
25
|
|
|
26
26
|
## Details
|
|
27
27
|
|
|
@@ -5,7 +5,7 @@ description: What npx @north-light/sdk init and skill install for Claude Code, C
|
|
|
5
5
|
|
|
6
6
|
# Use your coding agent
|
|
7
7
|
|
|
8
|
-
The `northlight` skill teaches a coding agent the whole path in the [quick setup](/docs/quickstart): the commands, the code patterns and the rules. With it, your agent signs you up, logs in, registers the app and runs it, and you choose **Allow** twice in your browser: once on the login page, once on the app's consent page. `npx @north-light/sdk init` installs it into your project. The skill needs no account to install, and works
|
|
8
|
+
The `northlight` skill teaches a coding agent the whole path in the [quick setup](/docs/quickstart): the commands, the code patterns and the rules. With it, your agent signs you up, logs in, registers the app and runs it, and you choose **Allow** twice in your browser: once on the login page, once on the app's consent page. `npx @north-light/sdk init` installs it into your project. The skill needs no account to install, and works on any machine.
|
|
9
9
|
|
|
10
10
|
## Install it
|
|
11
11
|
|
package/docs/apps/get-started.md
CHANGED
|
@@ -36,7 +36,7 @@ Then pick what your app does from the sections in the sidebar: [use our AI](/doc
|
|
|
36
36
|
|
|
37
37
|
## Run `crtr cloud apps` yourself
|
|
38
38
|
|
|
39
|
-
Everything on this site works with the SDK's own commands and the web console.
|
|
39
|
+
Everything on this site works with the SDK's own commands and the web console. You can also sign your Mac in to your Northlight account with the `crtr` CLI and manage your apps with `crtr cloud apps`. The agents that run commands there run on Northlight; your Mac is a machine they can use.
|
|
40
40
|
|
|
41
41
|
```bash
|
|
42
42
|
npm i -g @north-light/cli@latest
|
|
@@ -44,4 +44,4 @@ crtr sys signin
|
|
|
44
44
|
crtr cloud apps mine
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
`crtr sys signin` asks you to approve once in your browser. The
|
|
47
|
+
`crtr sys signin` asks you to approve once in your browser. The CLI is [`@north-light/cli`](https://www.npmjs.com/package/@north-light/cli) on npm.
|
|
@@ -7,7 +7,7 @@ description: Give each person a canvas object per thing in your app, let their a
|
|
|
7
7
|
|
|
8
8
|
`PostgresObjectStore` from `@north-light/sdk/stores/postgres` keeps one canvas object per person for each thing in your app (a problem, a ticket, a workspace), links the person's nodes to it, and delivers events to it from a database outbox. An agent that runs `crtr <your-plugin> thing watch T-12` then receives the events you publish for T-12.
|
|
9
9
|
|
|
10
|
-
Your app declares the object kinds and their events in its plugin with `definePlugin({objectKinds})
|
|
10
|
+
Your app declares the object kinds and their events in its plugin with `definePlugin({objectKinds})`. The store registers objects of those kinds. Install `pg` in your app.
|
|
11
11
|
|
|
12
12
|
## Create the tables
|
|
13
13
|
|
package/docs/apps/how-it-fits.md
CHANGED
|
@@ -41,6 +41,6 @@ The person's AI subscription pays for model calls, and what your app may do on t
|
|
|
41
41
|
|
|
42
42
|
## What you operate
|
|
43
43
|
|
|
44
|
-
You operate your server, its sessions, its database and its `ConnectionStore`. You register the app in the console and keep its key pair. Northlight operates the directory and the runtimes; you do not run either, and there is no local Northlight to start.
|
|
44
|
+
You operate your server, its sessions, its database and its `ConnectionStore`. You register the app in the console and keep its key pair. Northlight operates the directory and the runtimes; you do not run either, and there is no local Northlight to start.
|
|
45
45
|
|
|
46
46
|
The directory's discovery document at `https://account.northlight.ai/.well-known/openid-configuration` lists the endpoints, the `S256` PKCE method and `private_key_jwt` as the only token authentication method.
|
|
@@ -53,11 +53,8 @@ A group's `who` says who may be granted it: `own` (only your own app), `user` (t
|
|
|
53
53
|
|
|
54
54
|
## Guides
|
|
55
55
|
|
|
56
|
-
|
|
56
|
+
The plugin kit `@north-light/plugin` adds commands to the Northlight runtime.
|
|
57
57
|
|
|
58
58
|
| Page | What it covers |
|
|
59
59
|
|---|---|
|
|
60
|
-
| [Plugin docs](https://crouter.docs.northlight.ai/docs/plugin) | What `@north-light/plugin` does and how a plugin is installed |
|
|
61
|
-
| [Commands](https://crouter.docs.northlight.ai/docs/plugin/commands) | Branches, leaves, parameters, outputs, groups and `who` |
|
|
62
|
-
| [Deploying](https://crouter.docs.northlight.ai/docs/plugin/deploying) | `auth: {issuer, audience, providerId}`, `ctx.caller`, versions and breaking changes |
|
|
63
60
|
| [Manage your app](/docs/guides/manage-your-app) | The console's **Provider** tab beside the others |
|
package/docs/apps/quickstart.md
CHANGED
|
@@ -9,7 +9,7 @@ description: From no account to a running app that signs a person in with Northl
|
|
|
9
9
|
npx @north-light/sdk@latest init my-app
|
|
10
10
|
```
|
|
11
11
|
|
|
12
|
-
This command creates a small Node server, a signing key and an env file. About ten minutes later you have an app on your laptop that signs you in with Northlight, starts an agent run on your own Northlight runtime, and texts your phone. The app runs on your machine and talks to Northlight's production directory at `https://account.northlight.ai`. There is no local Northlight stack to run.
|
|
12
|
+
This command creates a small Node server, a signing key and an env file. About ten minutes later you have an app on your laptop that signs you in with Northlight, starts an agent run on your own Northlight runtime, and texts your phone. The app runs on your machine and talks to Northlight's production directory at `https://account.northlight.ai`. There is no local Northlight stack to run.
|
|
13
13
|
|
|
14
14
|
You need Node.js 20.6 or later (the start command uses `--env-file`) and a phone that can receive iMessage. The server was run on Node 20.6, 20.20, 22.14, 22.22 and 26.12.
|
|
15
15
|
|
|
@@ -5,7 +5,7 @@ description: When deciding how an application should host or reconnect to an age
|
|
|
5
5
|
|
|
6
6
|
# Why a daemon
|
|
7
7
|
|
|
8
|
-
A terminal is not an agent host. A broker is the detached process that hosts one node’s agent engine and session; a viewer is only a terminal presentation attached to that broker. The daemon, `crtrd
|
|
8
|
+
A terminal is not an agent host. A broker is the detached process that hosts one node’s agent engine and session; a viewer is only a terminal presentation attached to that broker. The daemon, `crtrd` (in production the Northlight control plane at `api-fleet.northlight.ai`), owns the durable canvas and starts, stops, and recovers brokers. This separation lets a node continue after the terminal that created or displayed it has gone away.
|
|
9
9
|
|
|
10
10
|
```mermaid
|
|
11
11
|
flowchart LR
|
package/docs/sdk/README.md
CHANGED
|
@@ -25,11 +25,12 @@ const node = await crtr.createNode({ prompt: 'List the top-level directories her
|
|
|
25
25
|
|
|
26
26
|
| Page | Covers |
|
|
27
27
|
|---|---|
|
|
28
|
-
| [Getting started](./getting-started.md) | Install, `new Crouter()` on
|
|
28
|
+
| [Getting started](./getting-started.md) | Install, `new Crouter()` on a signed-in machine's socket, `CRTRD_TOKEN` for a browser or remote app, Chrome's local-network prompt |
|
|
29
29
|
| [Client construction](./client.md) | Every constructor option and its environment-variable fallback; per-request options |
|
|
30
|
+
| [Sourcing reads](./sourcing.md) | `sourcing.read`: Mac first, then hosted search; the route table, the routing rule, `SourcingUnavailableError`, `SOURCING_RUN_RULE` |
|
|
30
31
|
| [Resource map](./resources.md) | Every namespace with its routes, and the `client.request()` escape hatch |
|
|
31
32
|
| [Errors](./errors.md) | The daemon's scoped-token and wire errors, and identifier validation |
|
|
32
|
-
| [Docker environment](./docker.md) |
|
|
33
|
+
| [Docker environment](./docker.md) | Northlight-internal: `@north-light/env-docker`, the CI image helper used by pr-review |
|
|
33
34
|
| [Release notes](https://sdk.docs.northlight.ai/docs/release-notes) | Behavior changes an existing app must act on, newest first |
|
|
34
35
|
|
|
35
36
|
## Where the agents read this
|
package/docs/sdk/client.md
CHANGED
|
@@ -22,14 +22,14 @@ An app that signs people in with Northlight uses `OAuth2Client` and `oauth.clien
|
|
|
22
22
|
| Option | Type | Default | Meaning |
|
|
23
23
|
|---|---|---|---|
|
|
24
24
|
| `baseURL` | `string` | `CRTR_BASE_URL`, else unset | `http(s)://host:port` of a daemon TCP listener. |
|
|
25
|
-
| `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket. Node only; throws in a browser. |
|
|
25
|
+
| `socketPath` | `string` | `CRTR_SOCKET`, else `CRTR_API_SOCKET`, else `api.sock` in the runtime root (`${CRTR_HOME:-~/.crouter}/runtime/api.sock` on macOS, `/run/crtr/api.sock` on Linux) | Unix socket of a signed-in machine's own daemon. Node only; throws in a browser. |
|
|
26
26
|
| `token` | `string` | `CRTRD_TOKEN` | Sent as `Authorization: Bearer <token>`. The token the daemon was started with (`CRTRD_TOKEN`); a scoped token's ceiling is enforced per request (see [Getting started](./getting-started.md#a-token-that-holds-less-than-the-owner)). Ignored by a unix-socket daemon, which authenticates by filesystem permission. |
|
|
27
27
|
| `timeout` | `number` (ms) | `30_000` | Per-request wall clock. Does not apply to a stream. |
|
|
28
28
|
| `maxRetries` | `number` | `2` | Transient-failure retries. Never applied to `POST` or `PATCH` — see [Errors](./errors.md). |
|
|
29
29
|
| `defaultHeaders` | `Record<string, string>` | `{}` | Merged into every request. |
|
|
30
30
|
| `headers` | `Record<string, string>` | unset | Merged after `defaultHeaders`; a matching name wins unless `token` is set, in which case the generated `Authorization` header wins at construction. |
|
|
31
31
|
| `fetch` | `typeof fetch` | global `fetch`, or the socket implementation when `socketPath` is used | Transport override, for proxies and instrumentation. |
|
|
32
|
-
| `autostart` | `boolean` | `true` for a socket, `false` for `baseURL` |
|
|
32
|
+
| `autostart` | `boolean` | `true` for a socket, `false` for `baseURL` | For a signed-in machine's own daemon socket: on a cold socket, run `crtr sys daemon start` and retry once. Node only. |
|
|
33
33
|
|
|
34
34
|
### Environment-variable fallbacks
|
|
35
35
|
|
|
@@ -52,7 +52,7 @@ There is one request path. The client issues every request through the Web `fetc
|
|
|
52
52
|
|
|
53
53
|
## Autostart
|
|
54
54
|
|
|
55
|
-
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once.
|
|
55
|
+
With `autostart` on (the default for a socket), a request that finds a cold socket runs `crtr sys daemon start`, waits for the daemon to serve, and retries the request once.
|
|
56
56
|
|
|
57
57
|
Autostart is Node-only and applies only to the socket transport. A `baseURL` client cannot start a daemon it may not even share a machine with, so `autostart` defaults to `false` there; setting it to `true` on a `baseURL` client throws `CrouterError` (`autostart is only valid for the local socket transport`).
|
|
58
58
|
|
package/docs/sdk/docker.md
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Docker environment
|
|
3
|
-
description:
|
|
3
|
+
description: Northlight-internal helper that runs the crtrd CI image for the pr-review workflow.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Docker environment
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`@north-light/env-docker` runs a crouter daemon in a container and tells you how to reach it. It is a separate package because container lifecycle is real work the SDK does not otherwise do — and it **has no dependencies**, including on the SDK itself.
|
|
8
|
+
`@north-light/env-docker` is Northlight-internal: `Northlight-Systems/shared`'s pr-review workflow uses it to run the `crtrd` CI image (`ghcr.io/northlight-systems/crtrd`) in a container. It is not a way to run or self-host crtr; production is the Northlight control plane at `api-fleet.northlight.ai`. It has no dependencies, including on the SDK itself.
|
|
11
9
|
|
|
12
10
|
```bash
|
|
13
11
|
npm i @north-light/env-docker
|
|
@@ -19,11 +17,9 @@ npm i @north-light/env-docker
|
|
|
19
17
|
import { start } from '@north-light/env-docker';
|
|
20
18
|
import Crouter from '@north-light/sdk';
|
|
21
19
|
|
|
22
|
-
const env = await start({ volume: '
|
|
20
|
+
const env = await start({ volume: 'ci-home' });
|
|
23
21
|
const client = new Crouter(env.connection());
|
|
24
22
|
|
|
25
|
-
await client.runs.start({ prompt: 'Do the thing.' });
|
|
26
|
-
|
|
27
23
|
await env.stop();
|
|
28
24
|
```
|
|
29
25
|
|
|
@@ -63,6 +59,6 @@ const client = new Crouter(env.connection());
|
|
|
63
59
|
|
|
64
60
|
`connection()` is typed structurally — `{ baseURL: string; headers?: Record<string, string> }` — which is how the package stays dependency-free while producing something the SDK accepts directly.
|
|
65
61
|
|
|
66
|
-
## The volume
|
|
62
|
+
## The volume
|
|
67
63
|
|
|
68
|
-
The `volume` you pass is the container's canvas home
|
|
64
|
+
The `volume` you pass is the container's canvas home. Reuse it across `start` calls to keep state; use a fresh one to start from nothing. `start()` mounts an existing named volume unchanged.
|