@north-light/cli 0.3.603 → 0.3.605
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clients/attach/viewer.js +433 -433
- package/dist/commands/api-client.d.ts +4 -0
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/daemon-generation.d.ts +1 -1
- package/dist/commands/daemon-generation.js +1 -1
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/core/canvas/canvas.js +20 -20
- package/dist/core/canvas/schema-pg/005-fleet-blobs.sql +1 -1
- package/dist/core/import/export/cloud.d.ts +8 -3
- package/dist/core/import/export/cloud.js +1 -1
- package/dist/core/import/export/files.d.ts +1 -0
- package/dist/core/import/export/files.js +1 -1
- package/dist/core/providers/bundles.js +2 -2
- package/dist/core/runs/operations.js +6 -6
- package/dist/core/runtime/runner/blaxel/runner.d.ts +1 -1
- package/dist/core/runtime/runner/blaxel/runner.js +3 -3
- package/dist/core/runtime/runner/delete-sandboxes.d.ts +3 -0
- package/dist/core/runtime/runner/delete-sandboxes.js +1 -0
- package/dist/core/runtime/runner/machine/executor.d.ts +14 -1
- package/dist/core/runtime/runner/machine/executor.js +1 -1
- package/dist/core/runtime/runner/machine/machine-executor.test.js +3 -3
- package/dist/core/storage/attachments.d.ts +1 -1
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/api/server.d.ts +1 -2
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/crtrd.js +13 -13
- package/dist/daemon/due.js +4 -4
- package/dist/daemon/reconcilers/recipe-image.d.ts +15 -1
- package/dist/daemon/reconcilers/recipe-image.js +5 -6
- package/dist/daemon/reconcilers/storage-due-work.d.ts +3 -4
- package/dist/daemon/reconcilers/storage-due-work.js +3 -2
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var le=Object.defineProperty;var o=(e,n)=>le(e,"name",{value:n,configurable:!0});import{existsSync as b,readdirSync as z,readFileSync as _,rmSync as g,statSync as D}from"node:fs";import{join as d}from"node:path";import{validateCommandManifest as pe}from"../../api/command-manifest/manifest.js";import{crtrHome as L}from"../canvas/paths.js";import{isCloudRole as h}from"../canvas/person-state.js";import{withCanvasWrite as me}from"../canvas/db.js";import{bundleVersion as ve,isInstalledGeneration as ge,recordCheckedGeneration as he}from"../command-plugins/bundle.js";import{readState as we,updateConfig as $e,updateState as ye}from"../config.js";import{directoryIssuer as q}from"../directory/issuer.js";import{emitEvent as p}from"../events/emit.js";import{describeOutboundFailure as be,outboundFetch as _e,outboundRefusal as
|
|
2
|
-
`),g(d(e,"bundle.tar"),{force:!0}),g(d(e,"etag"),{force:!0})}o(Ne,"retire");function ce(e,n){return new c("provider_version_retired",`provider "${e}" major ${n} is retired`,{param:"version"})}o(ce,"retiredError");async function
|
|
1
|
+
var le=Object.defineProperty;var o=(e,n)=>le(e,"name",{value:n,configurable:!0});import{existsSync as b,readdirSync as z,readFileSync as _,rmSync as g,statSync as D}from"node:fs";import{join as d}from"node:path";import{validateCommandManifest as pe}from"../../api/command-manifest/manifest.js";import{crtrHome as L}from"../canvas/paths.js";import{isCloudRole as h}from"../canvas/person-state.js";import{withCanvasWrite as me}from"../canvas/db.js";import{bundleVersion as ve,isInstalledGeneration as ge,recordCheckedGeneration as he}from"../command-plugins/bundle.js";import{readState as we,updateConfig as $e,updateState as ye}from"../config.js";import{directoryIssuer as q}from"../directory/issuer.js";import{emitEvent as p}from"../events/emit.js";import{describeOutboundFailure as be,outboundFetch as _e,outboundRefusal as K,OutboundError as Me}from"../events/outbound.js";import{withExclusiveDirectoryLockAsync as Z}from"../exclusive-lock.js";import{atomicWriteText as T,ensureDir as N,pathExists as V}from"../fs-utils.js";import{reconcilePackages as Se}from"../graph/package-reconcile.js";import{readPluginManifest as I}from"../manifest.js";import{bundleSwapLockPath as J}from"../plugin-swap-lock.js";import{pluginsDir as X,userScopeRoot as Q}from"../scope.js";import{installedProviderPlugins as Pe}from"./roots.js";import{allGrants as Ee,localGrants as Te,providerIdsFromGrants as Y}from"../grants/mirror.js";import{ProviderError as c}from"./errors.js";const Ie="[A-Za-z0-9_-]{1,64}",ee=new RegExp(`^${Ie}$`),ke=3e4,ne=3e4;function $(e){return d(X("user"),e)}o($,"pluginRoot");function M(e){return d(X("user"),`.${e}.etag`)}o(M,"etagFile");function Ae(e){if(!h())return we("user").plugins[e]?.etag;try{return _(M(e),"utf8")}catch(n){if(n.code==="ENOENT")return;throw n}}o(Ae,"storedEtag");async function re(e,n){if(!h())return he("user",e,n,{swapped:!1});n===void 0?g(M(e),{force:!0}):T(M(e),n)}o(re,"recordEtag");async function te(e){if(!h())try{await me(async n=>await Se(n))}catch(n){p({level:"error",event:"daemon.providers.docs_reconcile_failed",fields:{provider:e},error:n})}}o(te,"reconcileProviderDocs");function xe(e,n,r){return h()?I(n)?.version===r&&V(d(n,"commands.json")):ge(e,"user",n,r)}o(xe,"installedGeneration");function R(){return d(L(),"providers")}o(R,"providersRoot");function oe(e,n){return d(R(),e,`v${n}`)}o(oe,"majorDir");function B(e){if(!ee.test(e))throw new c("not_found",`"${e}" is not a provider id`,{param:"provider"})}o(B,"assertId");function k(){const e=q();if(!e)throw new c("not_found","provider bundles need a directory-connected runtime");return e}o(k,"directoryBase");async function ae(e,n){const r=`${k()}/providers/${encodeURIComponent(e)}/plugin${n.version!==void 0?`?version=${n.version}`:""}`;let t;try{t=await _e("bundle_fetch",r,{headers:{Accept:"application/x-tar",...n.ifNoneMatch!==void 0?{"If-None-Match":n.ifNoneMatch}:{}},signal:AbortSignal.timeout(ke)})}catch(i){return{status:"failed",message:`could not reach ${r}: ${i instanceof Error?i.message:String(i)}`,cause:i}}if(t.status===304){if(n.ifNoneMatch===void 0){const i=`HTTP 304 from ${r} without a conditional request`;return{status:"failed",message:i,cause:K("bundle_fetch",r,i)}}return{status:304}}if(t.status===404||t.status===410)return await t.body?.cancel().catch(()=>{}),{status:t.status===404?404:410,message:`HTTP ${t.status} from ${r}`};if(t.status<200||t.status>=300){await t.body?.cancel().catch(()=>{});{const i=`HTTP ${t.status} from ${r}`;return{status:"failed",message:i,cause:K("bundle_fetch",r,i)}}}let a;try{a=new Uint8Array(await t.arrayBuffer())}catch(i){return{status:"failed",message:`reading ${r} failed: ${i instanceof Error?i.message:String(i)}`,cause:new Me("bundle_fetch",r,i)}}const u=t.headers.get("etag");return{status:200,raw:a,...u!==null?{etag:u}:{}}}o(ae,"fetchProviderBundle");const A=new WeakSet;class x extends Error{static{o(this,"BundleInvalid")}issues;constructor(n,r){super(n),this.issues=r}}function ie(e,n,r){if(r.provider===void 0)return"the archive carries no provider block";if(r.provider.id!==e)return`the archive is provider "${r.provider.id}", not "${e}"`;if(n!==void 0&&r.provider.major!==n)return`the archive is major ${r.provider.major}, not ${n}`;const t=["hooks","kinds","page_components","memory_extensions"].filter(a=>r[a]!==void 0);if(t.length>0)return`a provider bundle may not carry ${t.join(", ")}`}o(ie,"wrongBundle");function O(e,n,r){p({level:"error",event:"daemon.providers.bundle_invalid",fields:{provider:e,...n!==void 0?{major:n}:{},...r instanceof x?{issues:r.issues}:{}},error:r})}o(O,"logInvalid");function C(e,n,r,t,a){p({level:"info",event:"daemon.providers.bundle_checked",fields:{provider:e,...n!==void 0?{major:n}:{},status:r,...t!==void 0?{etag:t}:{},outcome:a}})}o(C,"logChecked");function se(e,n,r){p({level:"warn",event:"daemon.providers.bundle_fetch_failed",fields:{provider:e,...n!==void 0?{major:n}:{},message:r instanceof Error?r.message:String(r),...be(r instanceof Error?r.cause:void 0)}})}o(se,"logFailure");async function ue(){return import("../../commands/pkg/plugin-manage.js")}o(ue,"pluginManage");const S=new Map,P=o(e=>`${L()}\0${e}`,"installKey");function Ce(e){const n=e,r=n?.code??n?.cause?.code;return typeof r=="string"&&/^[A-Z][A-Z0-9_]{1,30}$/.test(r)?`${r} on provider install directory`:e instanceof c&&e.message.includes("HTTP 404")?"directory returned HTTP 404":e instanceof c&&e.message.includes("HTTP 410")?"directory returned HTTP 410":"provider bundle could not be installed"}o(Ce,"publicInstallCause");function je(e){if(m(e)===void 0)return S.get(P(e))??{status:"installing"}}o(je,"providerInstallState");function De(e){return new c("provider_unavailable",`provider "${e}" unavailable: ${je(e)?.error??"bundle installation pending"}`)}o(De,"unavailableProviderError");function m(e){const n=I($(e));if(!(n?.provider===void 0||n.transport?.kind!=="http"&&n.transport?.kind!=="machine")&&V(d($(e),"commands.json"))){try{if(D(d($(e),"commands.json")).size===0)return}catch{return}return{provider:n.provider,transport:n.transport.kind==="machine"?{kind:"machine"}:{kind:"http",endpoint:n.transport.endpoint}}}}o(m,"installedManifest");async function G(e,n,r=!1){const t=Q();m(e)===void 0&&S.set(P(e),{status:"installing"});try{return N(d(t,"tmp")),await Z(J(t,e),async()=>{const a=$(e),u=I(a);if(u!==null&&u.provider===void 0)throw new c("provider_unavailable",`plugin "${e}" is installed and is not the directory's provider bundle`);const i=m(e)!==void 0;if(i&&r)return"unchanged";const f=i&&n?Ae(e):void 0,s=await ae(e,f!==void 0?{ifNoneMatch:f}:{});if(s.status===304)return C(e,m(e)?.provider.major,304,f,"unchanged"),"unchanged";if(s.status===404||s.status===410)throw new c("not_found",`the directory serves no provider "${e}" (${s.message})`,{param:"provider"});if(s.status==="failed")throw new c("provider_unavailable",`provider "${e}" bundle fetch failed: ${s.message}`,{cause:s.cause});const l=ve(s.raw);if(i&&xe(e,a,l))return await re(e,s.etag),C(e,m(e)?.provider.major,200,s.etag,"unchanged"),"unchanged";const{installPluginArchive:w}=await ue();h()&&g(M(e),{force:!0});try{await w(e,s.raw,{scope:"user",scopeRootPath:t,root:a,version:l,etag:s.etag,enable:!i,bundle:{endpoint:`${k()}/providers/${encodeURIComponent(e)}/plugin`},transport:{kind:"http",endpoint:k()},accept:o(v=>ie(e,void 0,v),"accept"),record:!h()})}catch(v){O(e,void 0,v);const W=new c("not_found",`provider "${e}" served an invalid bundle: ${v instanceof Error?v.message:String(v)}`,{param:"provider"});throw A.add(W),W}return h()&&await re(e,s.etag),await te(e),p({level:"info",event:"daemon.providers.bundle_installed",fields:{provider:e,major:m(e)?.provider.major,version:l,replaced:i,...s.etag!==void 0?{etag:s.etag}:{}}}),S.delete(P(e)),i?"updated":"installed"},{timeoutMs:ne,timeoutError:o(()=>new c("provider_unavailable",`timed out waiting for another process replacing plugin "${e}"`),"timeoutError")})}catch(a){throw m(e)===void 0&&S.set(P(e),{status:"install_failed",error:Ce(a)}),a instanceof c?a:(p({level:"error",event:"daemon.providers.bundle_install_failed",fields:{provider:e},error:a}),De(e))}}o(G,"refreshInstalled");async function mn(e){B(e),m(e)===void 0&&await G(e,!1,!0)}o(mn,"ensureProviderBundle");async function vn(e,n){return B(e),n.version!==void 0&&m(e)?.provider.major!==n.version?H(e,n.version,n.conditional):G(e,n.conditional)}o(vn,"refreshProviderBundle");async function de(e,n,r){const{validatePluginArchive:t}=await ue(),a=await t(r);if(a.bundle===void 0)throw new x(`provider "${e}" major ${n} bundle is invalid: ${a.issues.map(i=>i.message).join("; ")}`,a.issues);const u=ie(e,n,a.bundle);if(u!==void 0)throw new x(`provider "${e}" major ${n} bundle is invalid: ${u}`,[]);if(a.bundle.transport===void 0)throw new x(`provider "${e}" major ${n} bundle declares no transport`,[]);return a.bundle}o(de,"validateArchive");function Ne(e){N(e),T(d(e,"retired"),`${new Date().toISOString()}
|
|
2
|
+
`),g(d(e,"bundle.tar"),{force:!0}),g(d(e,"etag"),{force:!0})}o(Ne,"retire");function ce(e,n){return new c("provider_version_retired",`provider "${e}" major ${n} is retired`,{param:"version"})}o(ce,"retiredError");async function H(e,n,r){const t=oe(e,n),a=d(t,"bundle.tar"),u=b(a),i=u&&r&&b(d(t,"etag"))?_(d(t,"etag"),"utf8"):void 0,f=await ae(e,{version:n,...i!==void 0?{ifNoneMatch:i}:{}});if(f.status===304)return C(e,n,304,i,"unchanged"),"unchanged";if(f.status===410)throw Ne(t),p({level:"info",event:"daemon.providers.major_retired",fields:{provider:e,major:n}}),ce(e,n);if(f.status===404)throw new c("not_found",`provider "${e}" never served major ${n}`,{param:"version"});if(f.status==="failed")throw new c("provider_unavailable",`provider "${e}" major ${n} bundle fetch failed: ${f.message}`,{cause:f.cause});try{await de(e,n,f.raw)}catch(w){O(e,n,w);const v=new c(u?"provider_unavailable":"not_found",w instanceof Error?w.message:String(w),{param:"version"});throw A.add(v),v}N(t),g(d(t,"retired"),{force:!0});const s=u&&Buffer.from(f.raw).equals(_(a));s||T(a,f.raw),f.etag!==void 0?T(d(t,"etag"),f.etag):g(d(t,"etag"),{force:!0});const l=s?"unchanged":u?"updated":"installed";return C(e,n,200,f.etag,l),l}o(H,"refreshPinned");function Re(){const e=[],n=R();if(!b(n))return e;for(const r of z(n)){if(!ee.test(r))continue;let t;try{t=z(d(n,r))}catch{continue}for(const a of t){const u=/^v([1-9][0-9]*)$/.exec(a);u&&b(d(n,r,a,"bundle.tar"))&&e.push([r,Number(u[1])])}}return e}o(Re,"cachedMajors");function Be(e){const n=pe(e,{transport:"http",reservedCoreNames:new Set});if(n.manifest===void 0)throw new c("not_found","the provider bundle's commands.json no longer validates");return n.manifest}o(Be,"readCommands");const E=new Map,F=new Map;function Oe(e,n){const r=D(n),t=`${r.ino}:${r.mtimeMs}:${r.size}`,a=F.get(e);if(a?.stamp===t)return a.commands;const u=Be(JSON.parse(_(n,"utf8")));return F.set(e,{stamp:t,commands:u}),u}o(Oe,"installedCommands");async function gn(e,n){B(e);const r=m(e);if(n===void 0||r?.provider.major===n){if(r===void 0)throw new c("not_found",`provider "${e}" has no installed bundle`,{param:"provider"});const l=$(e),w=Oe(e,d(l,"commands.json"));return{id:e,major:r.provider.major,provider:r.provider,commands:w,transport:r.transport,source:"installed",root:l}}if(!Number.isInteger(n)||n<1)throw new c("invalid_request","version must be an integer of at least 1",{param:"version"});const t=oe(e,n);if(b(d(t,"retired")))throw ce(e,n);const a=d(t,"bundle.tar");b(a)||await H(e,n,!1);const u=`${e}/${n}`,i=D(a),f=`${i.mtimeMs}:${i.size}`;let s=E.get(u)?.stamp===f?E.get(u).bundle:void 0;if(s===void 0){try{s=await de(e,n,new Uint8Array(_(a)))}catch(l){throw O(e,n,l),new c("not_found",`provider "${e}" has no valid bundle for major ${n}`,{param:"version"})}E.set(u,{stamp:f,bundle:s})}return{id:e,major:n,provider:s.provider,commands:s.commands,transport:s.transport.kind==="machine"?{kind:"machine"}:{kind:"http",endpoint:s.transport.endpoint},source:"pinned"}}o(gn,"resolveProviderBundle");let y=null;const Ge=4*6e4,He=1e3,Fe=2e3;function j(e,n){e.stage=n,e.stageAgeMs=0}o(j,"enter");function Ue(e,n){return e?.provider?.id===n&&e.bundle?.endpoint===`${k()}/providers/${encodeURIComponent(n)}/plugin`}o(Ue,"isDirectoryBundle");async function U(){return h()?Ee():Te()}o(U,"bundleGrants");async function fe(e){return Y(await U()).includes(e)}o(fe,"grantNames");async function We(e){await Z(J(Q(),e),async()=>{if(!(await fe(e)||!Ue(I($(e)),e))){g($(e),{recursive:!0,force:!0}),h()?g(M(e),{force:!0}):(await $e("user",n=>{delete n.plugins[e]}),await ye("user",n=>{delete n.plugins[e]})),g(d(R(),e),{recursive:!0,force:!0}),F.delete(e),S.delete(P(e));for(const n of[...E.keys()])n.startsWith(`${e}/`)&&E.delete(n);await te(e),p({level:"info",event:"daemon.providers.bundle_uninstalled",fields:{provider:e}})}},{timeoutMs:ne,timeoutError:o(()=>new c("provider_unavailable",`timed out waiting for another process replacing plugin "${e}"`),"timeoutError")})}o(We,"uninstallProvider");async function ze(){if(!(await U()).every(e=>e.status!=="active")){for(const e of Pe())if(!(e.manifest.provider===void 0||await fe(e.name)))try{await We(e.name)}catch(n){p({level:"error",event:"daemon.providers.bundle_uninstall_failed",fields:{provider:e.name},error:n})}}}o(ze,"uninstallDisconnected");async function Le(e){if(!q())return;j(e,"reading grants");const n=Y(await U());for(const r of n){j(e,`refreshing installed bundle ${r}`);try{await G(r,!0)}catch(t){t instanceof Object&&A.has(t)||se(r,void 0,t)}}j(e,"uninstalling disconnected bundles"),await ze();for(const[r,t]of Re()){j(e,`refreshing pinned bundle ${r} v${t}`);try{await H(r,t,!0)}catch(a){if(a instanceof c&&a.code==="provider_version_retired"||a instanceof Object&&A.has(a))continue;se(r,t,a)}}}o(Le,"syncOnce");function hn(){if(y!==null){y.rerun=!0;const t=y.stageAgeMs;return t>=Ge&&p({level:"error",event:"daemon.providers.sync_stalled",fields:{stage:y.stage,stalled_ms:t}}),y.promise}const e={promise:Promise.resolve(),stage:"starting",stageAgeMs:0,rerun:!1};y=e;let n=Date.now();const r=setInterval(()=>{const t=Date.now();e.stageAgeMs+=Math.min(Math.max(t-n,0),Fe),n=t},He);return r.unref(),e.promise=(async()=>{try{do e.rerun=!1,await Le(e);while(e.rerun)}finally{clearInterval(r),y=null}})(),e.promise}o(hn,"syncProviderBundles");export{mn as ensureProviderBundle,je as providerInstallState,vn as refreshProviderBundle,gn as resolveProviderBundle,hn as syncProviderBundles,De as unavailableProviderError};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
var Me=Object.defineProperty;var c=(e,t)=>Me(e,"name",{value:t,configurable:!0});import{coveredByAny as
|
|
1
|
+
var Me=Object.defineProperty;var c=(e,t)=>Me(e,"name",{value:t,configurable:!0});import{coveredByAny as Ae}from"../../shared/env.js";import{createHash as Q}from"node:crypto";import{ApiError as Ie}from"../../api/errors.js";import{CrtrError as Te}from"../errors.js";import{isCloudRole as Le}from"../canvas/person.js";import{isAbsolute as V,relative as Ce,resolve as ke,sep as xe,join as We}from"node:path";import{SessionManager as Fe}from"@earendil-works/pi-coding-agent";import{covers as P}from"@north-light/identity";import{openDb as B,withCanvasWrite as F}from"../canvas/db.js";import{deleteNodeWithOwned as qe}from"../graph/deletion.js";import{getById as He}from"../graph/objects.js";import{repairRunConversations as Z}from"../canvas/sessions.js";import{getNode as v,nodeFiles as Ue,removeNodeFiles as $e,updateNode as Pe}from"../canvas/canvas.js";import{fullName as Be}from"../canvas/labels.js";import{renameWindow as je}from"../runtime/placement.js";import{liveExecutionForNode as K}from"../canvas/executions.js";import{conversationStore as ee,isConversationNotFound as Je}from"../conversation-store/index.js";import{PARKED_RESIDENT_SQL as Ye}from"../canvas/canvas.js";import{WAKE_MAIL_SQL as Ge}from"../canvas/deliveries.js";import{readNodeRecap as Xe}from"../canvas/node-recap.js";import{enqueueNodeMail as ze}from"../feed/messages.js";import{recordInitialInput as Qe}from"./initial-input.js";import{newestReportBody as Ve}from"../feed/reports.js";import{ensureAppProfile as te,loadExactProfileManifest as ne}from"../profiles/manifest.js";import{stopNodeSandboxes as ae}from"../spaces/stop.js";import{deleteNodeSandboxes as Ze}from"../runtime/runner/delete-sandboxes.js";import{BrokerUnreachableError as Ke}from"../runtime/broker-request.js";import{interruptLive as et}from"../runtime/interactive-deliver.js";import{isBrokerLive as se}from"../runtime/model-swap.js";import{newNodeId as tt}from"../runtime/nodes.js";import{reviveNode as j}from"../runtime/revive.js";import{spawnChildPrepared as nt}from"../runtime/spawn.js";import{isPortableModelToken as at}from"../runtime/launch.js";import{parseDurationMs as st}from"../wake.js";import{expandModelCandidates as it,parseModelSpec as rt}from"../model-routes.js";import{payerOfGrant as J}from"../grants/mirror.js";import{isolatedBrokerLauncherAvailable as ot}from"../runtime/host.js";import{blaxelEnvironmentOf as dt}from"../runtime/blaxel-environment.js";import{resolveRunKind as ct,resolveRunModel as ut}from"../runtime/launch-target.js";import{cycleAwareMessages as mt}from"../runtime/session-cycles.js";import{originFor as ie}from"../runtime/stamp/protocol.js";import{readOutputRequest as lt,readOutputResult as re}from"../runtime/output-result.js";import{admitLegacyStructuredOutput as oe}from"../../daemon/structured-requests/sidecar.js";import{runSchemaRepromptPending as ft}from"../runtime/stop-guard.js";import{toRunOutcomeDTO as pt}from"../../daemon/api/map.js";import{openAssistantMessageStartSequence as _t}from"../../daemon/runs/observer.js";import{closeNode as de}from"../runtime/close.js";import{parseScope as wt}from"@north-light/identity";import{appendRunEvent as ce,lockRunRoot as gt,subscribeRunEvents as Et}from"./events.js";import{runActivity as yt}from"./activity.js";import{cancelOpenQuestions as ue,openNoticeIds as ht,openQuestionIds as me}from"./questions.js";import{appSpace as Y}from"../layout.js";import{ensureAppSpace as Rt}from"../spaces/space.js";import{assertUploadsUsable as le,resolveStorageUrls as St}from"../storage/attachments.js";import{storageClient as Nt,storageConfig as vt}from"../storage/client.js";import{deleteUploadRow as bt,insertUploadUses as fe,releaseRunUploads as Ot,runUsesPath as Dt}from"../storage/tables.js";import{abortProviderCalls as pe}from"../providers/inflight.js";import{filterAsync as _e,mapAsync as x}from"../async-array.js";import{blobStore as Mt}from"../blobs/index.js";import{emitEvent as At}from"../events/emit.js";const we=c((e,t,a,n)=>St(t,e,a,n?{taken:n}:{}),"defaultResolver"),It=3e3;class R extends Error{static{c(this,"RunError")}status;code;param;details;scope;retryable;constructor(t,a,n,d,_,i,s=t===503){super(n),this.status=t,this.code=a,this.param=d,this.details=_,this.scope=i,this.retryable=s}}const S=c((e,t)=>new R(400,"invalid_request",e,t),"invalid"),G=c(()=>new R(404,"not_found","run not found"),"missing"),X=c(()=>({input_tokens:0,output_tokens:0,cache_read_tokens:0,cache_write_tokens:0,cost_usd:0}),"usage"),M=c(async()=>await B(),"db");async function q(e,t,a=!1){const n=await v(e);if(!n||n.parent!==null||n.run_id!==e||n.grantee!==t||!a&&n.deleting_at)throw G();return n}c(q,"ownedRun");const ge=["waiting_on_user","idle","settled"];async function C(e){if(e.status==="canceled"||e.status==="dead"||e.status==="done"&&e.intent!=="parked")return"settled";const t=await(await M()).prepare(`SELECT 1 FROM node_rows n WHERE n.run_id = ? AND n.status = 'active' AND
|
|
2
2
|
(n.last_settled_at IS NULL OR EXISTS (
|
|
3
3
|
SELECT 1 FROM run_events e WHERE e.run_id = ? AND e.node_id = n.node_id AND e.type = 'node.turn.started'
|
|
4
4
|
AND e.sequence_number > COALESCE((SELECT MAX(c.sequence_number) FROM run_events c
|
|
5
5
|
WHERE c.run_id = e.run_id AND c.node_id = e.node_id AND c.type = 'node.turn.completed'), 0)
|
|
6
|
-
)) LIMIT 1`).get(e.node_id,e.node_id),
|
|
6
|
+
)) LIMIT 1`).get(e.node_id,e.node_id),a=!e.last_settled_at&&e.status!=="done";return t||a||await ft(e)?"running":(await me(e.node_id)).length?"waiting_on_user":await(await M()).prepare(`SELECT 1 FROM deliveries d JOIN nodes n ON n.node_id = d.destination_id
|
|
7
7
|
WHERE n.run_id = ? AND ${Ge("d","'armed', 'pending', 'handed_off'")}
|
|
8
|
-
AND (n.status IN ('active', 'idle') OR ${Ye("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function
|
|
8
|
+
AND (n.status IN ('active', 'idle') OR ${Ye("n")}) LIMIT 1`).get(e.node_id)?"running":"idle"}c(C,"runStatus");async function Jn(e){const t=await v(e);return t!==null&&await C(t)==="running"}c(Jn,"runIsRunning");async function W(e){await Z(e.node_id),e=await v(e.node_id)??e;const t=await C(e),a=t==="settled"?[]:await me(e.node_id),n=await Ve(e.node_id)||void 0,d=t==="settled"?await pt(e):null,_=d?.kind==="result"?await re(e.node_id):void 0,i=Xe(e.node_id);return{run_id:e.node_id,name:e.name,status:t,...d?{outcome:d}:{},..._===void 0?{}:{result:_},...n!==void 0?{last_report:n}:{},...i?{recap:i}:{},pending_question_ids:a,open_notice_ids:t==="settled"?[]:await ht(e.node_id),...e.last_turn_error_json?{last_turn_error:JSON.parse(e.last_turn_error_json)}:{},usage:JSON.parse(e.usage_json??JSON.stringify(X())),payer:await J(e.grant_id),scopes:e.scopes,metadata:e.metadata_json?JSON.parse(e.metadata_json):{},created_at:e.created,...t==="settled"&&e.outcome_at?{settled_at:e.outcome_at}:{},latest_sequence:(e.event_cursor??1)-1,last_activity_at:e.last_activity_at,activity:await yt(e.node_id,t)}}c(W,"runObject");const z=864e5,Ee=255;function Yn(e){if(e!==void 0){if(typeof e!="string"||!e.length||e.length>Ee)throw S(`Idempotency-Key must be 1-${Ee} characters`);return e}}c(Yn,"idempotencyKeyOf");function Tt(e){if(Le()){if(!e)throw new R(403,"permission_error","a cloud role serves this call only for a token that names a person");return e}}c(Tt,"cloudPersonScope");function k(e,t){const a=Tt(e);return a===void 0?t:`${a}:${t}`}c(k,"personKey");async function H(e,t,a,n){n&&await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`idempotency:${e}:${t}`),n??=await B();const d=await n.prepare("SELECT body_hash, run_id, response_json, created_at FROM idempotency_keys WHERE grantee = ? AND key = ?").get(e,t);if(!(!d||Date.now()-Date.parse(d.created_at)>=z)){if(d.body_hash!==a)throw new R(409,"idempotency_conflict","key used with a different request");return{run_id:d.run_id,response:JSON.parse(d.response_json)}}}c(H,"findIdempotent");async function ye(e,t,a,n,d,_,i){await e.prepare("DELETE FROM idempotency_keys WHERE grantee = ? AND key = ? AND created_at <= ?").run(t,a,new Date(Date.now()-z).toISOString()),await e.prepare("INSERT INTO idempotency_keys (grantee, key, body_hash, run_id, response_json, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(t,a,n,d,JSON.stringify(_),i)}c(ye,"recordIdempotent");async function Gn(e=Date.now()){return Number((await(await B()).prepare("DELETE FROM idempotency_keys WHERE created_at <= ?").run(new Date(e-z).toISOString())).changes)}c(Gn,"pruneExpiredIdempotencyKeys");async function he(e,t,a,n,d,_=!1){const i=n.text;let s=0;return{messageId:(await ze(t,{kind:"message",label:i.slice(0,120),senderNodeId:"human",senderName:a,bodyJson:d?{body:i,..._?{steer:!0}:{}}:{body:i,start_turn:!1},urgency:d?"normal":"deferred",wake:d?1:0,withinEnqueue:c(async(l,h)=>{n.uses.length&&(await le(a,n.uses,l),await fe(n.uses.map(({upload_id:o,path:f,blob_key:r})=>({upload_id:o,path:f,blob_key:r,run_id:t})),l)),s=(await ce(l,t,t,"node.message.accepted",{message_id:h,start_turn:d})).sequence_number},"withinEnqueue")})).messageId,sequence:s}}c(he,"acceptRunMessage");class Re extends Error{static{c(this,"IdempotentReplay")}winner;constructor(t){super("idempotent replay"),this.winner=t}}const Lt=1440*60*1e3;function Se(e){const t=typeof e=="string"?st(e):null;if(t===null||!Number.isSafeInteger(t))throw S(`deadline '${String(e)}' is not a duration; use one or more <int>[smhd] parts such as 10m or 1h30m`,"deadline");if(t<=0)throw S("deadline must be greater than zero","deadline");if(t>Lt)throw S("deadline must be at most 24h","deadline");return t}c(Se,"parseRunDeadlineMs");async function Xn(e,t,a,n=we){if(t.isolated&&!ot()&&await dt((t.profile===void 0?await te(e.grantee):ne(t.profile)).profileId)===null)throw new R(503,"isolated_unavailable","isolated runs require the Linux root launcher","isolated");t.deadline!==void 0&&Se(t.deadline);const{causedBy:d,..._}=t,i=Q("sha256").update(JSON.stringify(_)).digest("hex");if(a){const o=await H(e.grantee,k(e.sub,a),i);if(o){const f=await q(o.run_id,e.grantee);return!f.pi_pid&&await C(f)==="running"&&(t.output_schema!==void 0&&!f.outcome_at&&await lt(f.node_id)===null&&await re(f.node_id)===void 0&&await oe(f.node_id,"terminal",t.output_schema),await j(f.node_id,{resume:!0,capacity:"freeze"})),o.response}}await Rt(e.grantee);const s=t.profile===void 0?await te(e.grantee):ne(t.profile),m=s.manifest.grantee??"app:terminal";if(m!==e.grantee){const o=`crtr:memory:rw:${m}:profile:${s.profileId}`;if(!e.resolved.some(f=>P(f,o))||t.scopes!==null&&!t.scopes.some(f=>P(f,o)))throw new R(403,"scope_missing",`missing scope ${o}`,"profile",void 0,o)}if(t.model!==void 0){const o=t.model;if(at(o)){if(o.includes("/")&&await J(e.grant)!=="app"){const f=o.lastIndexOf("/"),r=o.slice(0,f),p=o.slice(f+1);if(["ultra","strong","medium","light"].includes(p)&&(await it({kind:"logical",family:r,strength:p,spec:o},Y(e.grantee).files,s.profileId)).every(y=>y.family!==r))throw S(`model '${o}' names a model family that is not configured in this daemon`,"model")}}else if(rt(o)===void 0)throw S(`model '${o}' is not a strength (ultra, strong, medium, light), a family/strength, or a provider/model id`,"model")}const l=await tt(),h=We(Y(e.grantee).nodes,l);if(t.isolated&&t.cwd!==void 0){const o=Ce(h,ke(t.cwd));if(!V(t.cwd)||o===".."||o.startsWith(`..${xe}`)||V(o))throw S("cwd must be inside the isolated root node folder","cwd")}try{const o=await n(l,e.grantee,t.prompt),f=o.text,r=t.message===void 0?void 0:await n(l,e.grantee,t.message,o.uses.map(u=>u.path)),p=await J(e.grant);let y;try{const u=ut(s,t.model);await nt({kind:ct(s),mode:"base",root:!0,rootLifecycle:"resident",readiness:"launch",cwd:t.isolated?t.cwd??h:Y(e.grantee).files,profile:s.profileId,prompt:f,nodeId:l,isolated:t.isolated??!1,...t.causedBy===void 0?{}:{causedBy:t.causedBy},...u===void 0?{}:{model:u},...t.deadline===void 0?{}:{deadlineAt:new Date(Date.now()+Se(t.deadline)).toISOString()},...t.scopes===null?{}:{scopes:t.scopes},run:{grantee:e.grantee,sub:e.sub,grant_id:e.grant,client_id:e.client_id,metadata_json:JSON.stringify(t.metadata),run_id:l,event_cursor:1,usage_json:JSON.stringify(X())},withinCreate:c(async(E,A)=>{if(a){const N=await H(e.grantee,k(e.sub,a),i,E);if(N)throw new Re(N)}const D=o.uses;if(D.length&&(await le(e.grantee,D,E),await fe(D.map(({upload_id:N,path:I,blob_key:U})=>({upload_id:N,path:I,blob_key:U,run_id:l})),E)),y={run_id:l,node_id:l,grantee:e.grantee,grant:e.grant,rev:e.rev,scopes:t.scopes,payer:p,status:"running",created_at:A.created,metadata:t.metadata,sequence_number:0},await ce(E,l,l,"run.started",{scopes:t.scopes,payer:p,usage:X()}),r){const N=await he(E,l,e.grantee,r,!1);y.message={run_id:l,message_id:N.messageId,sequence_number:N.sequence}}else await Qe(l,e.grantee,f);a&&await ye(E,e.grantee,k(e.sub,a),i,l,y,A.created)},"withinCreate")},t.output_schema===void 0?void 0:async E=>{await oe(E,"terminal",t.output_schema)})}catch(u){if(u instanceof Re)return u.winner.response;if(t.model!==void 0&&u instanceof Te&&u.code==="usage")throw S(u.message,"model");if(u instanceof Ie&&(u.code==="isolated_run"||u.code==="invalid_request")){const E=u.details&&typeof u.details=="object"&&"param"in u.details&&typeof u.details.param=="string"?u.details.param:void 0;throw new R(u.status,u.code,u.message,E)}throw u}if(!y)throw new Error("run creation did not commit");return y}finally{await Ct(l)}}c(Xn,"startRun");async function Ct(e){try{if(await v(e)!==null)return;const t=await Mt();for(const a of await t.list(`attachments/${e}/`))await t.delete(a)}catch(t){At({level:"warn",event:"runs.start_attachment_cleanup_failed",error:t,fields:{run_id:e}})}}c(Ct,"discardUncommittedAttachments");async function zn(e,t){let a;if(t.after)try{const s=JSON.parse(Buffer.from(t.after,"base64url").toString());if(!s||typeof s!="object"||!("activity"in s)||typeof s.activity!="string"||!("id"in s)||typeof s.id!="string")throw new Error("invalid cursor");a={activity:s.activity,id:s.id}}catch{throw S("invalid list cursor","after")}const n=await(await M()).prepareUncached(`SELECT node_id, COALESCE(last_activity_at, created) AS activity FROM node_rows
|
|
9
9
|
WHERE run_id = node_id AND deleting_at IS NULL ${e===null?"":"AND grantee = ?"}${t.sub===void 0?"":" AND sub = ?"}
|
|
10
|
-
ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await _e(await x((await _e(n,async({node_id:
|
|
10
|
+
ORDER BY activity DESC, node_id DESC`).all(...e===null?[]:[e],...t.sub===void 0?[]:[t.sub]),d=await _e(await x((await _e(n,async({node_id:s})=>!t.visible||await t.visible(s))).filter(({activity:s,node_id:m})=>!a||s<a.activity||s===a.activity&&m<a.id),async s=>({root:await v(s.node_id),activity:s.activity})),async({root:s})=>!t.status||await C(s)===t.status),_=d.slice(0,t.limit),i=_.at(-1);return{runs:await x(_,async({root:s})=>await W(s)),next:d.length>t.limit&&i?Buffer.from(JSON.stringify({activity:i.activity,id:i.root.node_id})).toString("base64url"):null}}c(zn,"listRuns");async function Qn(e,t,a){const n=await q(e,t),d=c(async()=>await W(await q(e,t)),"read");return!a||ge.includes(await C(n))?await d():new Promise((_,i)=>{let s=c(()=>{},"unsubscribe");const m=c(()=>{clearTimeout(r),clearInterval(f),s()},"settle"),l=c(async()=>{m();try{_(await d())}catch(p){i(p)}},"finish"),h=c(async()=>{ge.includes(String((await d()).status))&&await l()},"check"),o=c(()=>{h().catch(p=>{m(),i(p)})},"run"),f=setInterval(o,250),r=setTimeout(()=>{l()},a*1e3);Et(e,o).then(p=>{s=p},p=>{m(),i(p)})})}c(Qn,"waitRun");const kt=5;async function Vn(e,t,a=we,n=!0,d,_=!0){const i=e.status==="canceled"||e.outcome_reason==="closed",s=e.grantee??"app:terminal",m=Q("sha256").update(JSON.stringify(["run.message",e.node_id,t,n,...n&&!_?["steer:false"]:[]])).digest("hex"),l=c(async o=>{const f=await v(e.node_id),r=await(await M()).prepare("SELECT 1 FROM deliveries WHERE message_id = ? AND state = 'pending' AND canceled_at IS NULL").get(String(o.message_id));return f&&!i&&n&&!f.pi_pid&&r&&await j(e.node_id,{resume:!0,capacity:"freeze"}),o},"replay");if(d){const o=await H(s,k(e.sub,d),m);if(o)return l(o.response)}if(i)throw new R(409,"run_settled","canceled run cannot receive a message");const h=n&&e.final_report&&!e.pi_pid?(await import("../runtime/reopen.js")).commitReopenResident:void 0;for(let o=1;;o++){const f=await a(e.node_id,s,t),r=await F(async p=>{if(d){const E=await H(s,k(e.sub,d),m,p);if(E)return{replayed:E.response}}if(f.uses.length){await gt(p,e.node_id);for(const E of f.uses)if(await Dt(e.node_id,E.path,p))return"path_taken"}await h?.(e.node_id);const y=await he(p,e.node_id,s,f,n,n&&_),u={run_id:e.node_id,message_id:y.messageId,sequence_number:y.sequence};return d&&await ye(p,s,k(e.sub,d),m,e.node_id,u,new Date().toISOString()),{result:u}});if(r==="path_taken"){if(o>=kt)throw new R(503,"service_unavailable","attachments of concurrent messages kept taking each other's file names; retry");continue}return"replayed"in r?l(r.replayed):(n&&!e.pi_pid&&await j(e.node_id,{resume:!0,capacity:"freeze"}),r.result)}}c(Vn,"messageRun");async function xt(e){const t=c(()=>new R(503,"service_unavailable",`node ${e} broker was unavailable before the interrupt reached it`),"unavailable");for(let a=0;a<2;a++){const n=await v(e);if(!n)throw G();if(!se(n)){if(n.streaming)throw t();return}const d=(await K(e))?.executionId;try{await et(e)==="turn"&&pe({nodes:[e]});return}catch(_){if(!(_ instanceof Ke))throw _;const i=await v(e);if(!i)throw G();if(!i.streaming)return;if(a===0&&se(i)&&(await K(e))?.executionId!==d)continue;throw t()}}throw t()}c(xt,"interruptNode");async function Zn(e,t="stop"){const a=t==="stop"?(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ?").all(e.node_id)).map(({node_id:n})=>n):[e.node_id];return await Promise.all(a.map(n=>xt(n))),await W(await v(e.node_id)??e)}c(Zn,"interruptRun");async function Kn(e,t={}){const a=(await(await M()).prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(i=>i.node_id);pe({run:e.node_id});const n=[];if(await C(e)!=="settled")n.push(...(await de(e.node_id,{preserveEmpty:!0,stopReason:"run_canceled"})).closed);else for(const i of a){if(i===e.node_id)continue;const s=await v(i);s&&s.status!=="done"&&s.status!=="canceled"&&s.status!=="dead"&&n.push(...(await de(i,{preserveEmpty:!0,stopReason:"run_canceled"})).closed)}if(await ue({run_id:e.node_id},"the run was canceled"),(await Promise.all([...new Set([e.node_id,...n])].map(i=>ae(i,"run_canceled")))).some(i=>!i.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);const _=await v(e.node_id);return await W(_??e)}c(Kn,"cancelRun");const Ne=200;async function ea(e,t){if(typeof t!="string"||!t.trim())throw S("name is required","name");const a=t.trim();if(a.length>Ne)throw S(`name exceeds ${Ne} characters`,"name");const n=await Pe(e.node_id,{name:a});return n.window&&je(n.window,Be(n)),await W(n)}c(ea,"renameRun");async function ta(e,t={config:vt,client:Nt}){await ue({run_id:e.node_id},"the run was deleted");const a=await F(async m=>(await m.prepare("UPDATE nodes SET deleting_at = COALESCE(deleting_at, ?) WHERE node_id = ?").run(new Date().toISOString(),e.node_id),(await m.prepare("SELECT node_id FROM nodes WHERE run_id = ? ORDER BY created DESC").all(e.node_id)).map(l=>l.node_id)));if((await Promise.all(a.map(m=>ae(m,"run_deleted",{deleting:!0})))).some(m=>!m.confirmed))throw new R(500,"server_error","run process teardown could not be confirmed",void 0,void 0,void 0,!0);if((await Ze(a)).length>0)throw new R(500,"server_error","run sandbox deletion could not be confirmed",void 0,void 0,void 0,!0);const d=await x(a,async m=>{const l=await Ue(m);if(l.app===null)throw new Error(`run node missing during deletion: ${m}`);return l}),_=await(await M()).prepare("SELECT DISTINCT session_id FROM sessions WHERE session_id IS NOT NULL AND node_id IN (SELECT node_id FROM nodes WHERE run_id = ?)").all(e.node_id);for(const{session_id:m}of _)try{await ee().delete(m)}catch(l){if(!Je(l))throw l}const i=await F(async m=>{for(const f of a){const r=await He(m,f);r!==null&&r.deleted_at===null&&await qe(m,r)}const l=await Ot([e.node_id],m);await m.prepare("DELETE FROM run_events WHERE run_id = ?").run(e.node_id),await m.prepare("DELETE FROM idempotency_keys WHERE run_id = ?").run(e.node_id);const h=a.map(()=>"?").join(","),o=await m.prepareUncached(`SELECT message_id FROM messages WHERE sender_node_id IN (${h}) UNION SELECT message_id FROM deliveries WHERE destination_id IN (${h})`).all(...a,...a);await m.prepareUncached(`DELETE FROM deliveries WHERE destination_id IN (${h})`).run(...a);for(const{message_id:f}of o)await m.prepare("DELETE FROM messages WHERE message_id = ? AND NOT EXISTS (SELECT 1 FROM deliveries WHERE message_id = ?)").run(f,f);return l});for(const m of d)await $e(m);const{notifyRunDeleted:s}=await import("./events.js");return s(e.node_id),{uploads_pending:await Wt(i,t)}}c(ta,"deleteRun");async function Wt(e,t){if(!e.length||!t.config())return e.length;let a;try{a=t.client()}catch{return e.length}const n=new Set,d=e.map(i=>a.deleteUpload(i).then(async()=>{await bt(i),n.add(i)},()=>{}));let _;return await Promise.race([Promise.all(d),new Promise(i=>{_=setTimeout(i,t.budgetMs??It),_.unref?.()})]),clearTimeout(_),e.length-n.size}c(Wt,"deleteReleasedUploads");async function na(e,t,a){await q(e,t),await Z(e);const n=await F(async r=>{const p=await r.prepare("SELECT node_id, parent FROM nodes WHERE run_id = ? ORDER BY CASE WHEN node_id = ? THEN 0 ELSE 1 END, created, node_id").all(e,e),y=new Map;for(const N of p)y.set(N.node_id,(await r.prepare("SELECT session_id FROM sessions WHERE node_id = ? GROUP BY session_id ORDER BY min(created_at)").all(N.node_id)).map(I=>I.session_id));const E=(await r.prepare("SELECT event_cursor FROM nodes WHERE node_id = ?").get(e)).event_cursor-1,A=await r.prepare(`SELECT node_id, sequence_number FROM run_events
|
|
11
11
|
WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.done', 'node.output_text.done', 'usage')
|
|
12
|
-
ORDER BY sequence_number`).all(e,
|
|
12
|
+
ORDER BY sequence_number`).all(e,E),D=await r.prepare(`SELECT node_id, sequence_number, type, body_json FROM run_events
|
|
13
13
|
WHERE run_id = ? AND sequence_number <= ? AND type IN ('node.thinking.delta', 'node.output_text.delta')
|
|
14
|
-
ORDER BY sequence_number`).all(e,
|
|
14
|
+
ORDER BY sequence_number`).all(e,E);return{nodes:p,sessionIds:y,latestSequence:E,completed:A,deltas:D}}),{nodes:d,sessionIds:_,latestSequence:i,completed:s,deltas:m}=n,l=await x(d,async r=>({node_id:r.node_id,parent_node_id:r.parent,conversations:await x(_.get(r.node_id)??[],async p=>{const{header:y,entries:u}=await ee().read(p);if(a==="entries")return{conversation_id:p,header:y,entries:u};const E=Fe.inMemory(y.cwd,void 0,[y,...u]),A=mt(E)??[],D=new Map(u.map((g,b)=>[g.id,b])),N=u.filter(g=>g.type==="custom"&&g.customType==="crtr-system-prompt").map(g=>({id:g.id,message:{role:"custom",customType:"crtr-system-prompt",data:"data"in g?g.data:void 0,timestamp:g.timestamp}})),I=u.filter(g=>g.type==="custom_message"&&g.customType==="app_message").map(g=>({id:g.id,message:{role:"custom",customType:"app_message",content:"content"in g?g.content:"",timestamp:g.timestamp}})),U=r.node_id===e?u.find(g=>{if(g.type!=="message"||g.message.role!=="user")return!1;const b=ie(u,g.message.timestamp);return b?.type==="runtime"&&b.kind==="kickoff"})?.id:void 0,ve=[...A.filter(({id:g})=>!I.some(b=>b.id===g)),...N,...I].sort((g,b)=>(D.get(g.id)??Number.MAX_SAFE_INTEGER)-(D.get(b.id)??Number.MAX_SAFE_INTEGER)).map(({id:g,message:b})=>{const w=b,T=w.usage,$=w.role==="user"?ie(u,Number(w.timestamp)):null,be=$?.type==="human"||g===U,L=w.role==="toolResult"?"tool_result":w.role==="bashExecution"?"bash_execution":w.role==="compactionSummary"?"compaction_summary":w.role==="branchSummary"?"branch_summary":w.role==="custom"&&w.customType==="crtr-system-prompt"?"system":w.role==="user"?be?"user":"custom":w.role,Oe=L==="custom"?w.role==="custom"?w.customType:$?.type==="runtime"?$.kind:"unknown":void 0,De=L==="system"&&w.customType==="crtr-system-prompt"?[{type:"text",text:w.data?.text??""}]:typeof w.content=="string"?[{type:"text",text:w.content}]:Array.isArray(w.content)?w.content.map(O=>O.type==="toolCall"?{type:"tool_call",tool_call_id:O.id,name:O.name,arguments:O.arguments}:O.type==="image"?{type:"image",mime_type:O.mimeType}:O.type==="thinking"?{type:"thinking",text:O.thinking}:O):[];return{entry_id:g,role:L,...L==="custom"?{custom_type:Oe}:{},time:typeof w.timestamp=="string"?w.timestamp:new Date(Number(w.timestamp??Date.now())).toISOString(),content:De,...L==="assistant"?{model:w.model,provider:w.provider,stop_reason:w.stopReason,...w.errorMessage?{error_message:w.errorMessage}:{},...T?{usage:{input_tokens:T.input??0,output_tokens:T.output??0,cache_read_tokens:T.cacheRead??0,cache_write_tokens:T.cacheWrite??0,cost_usd:T.cost?.total??0}}:{}}:{},...L==="tool_result"?{tool_call_id:w.toolCallId,tool_name:w.toolName,is_error:w.isError}:{}}})??[];return{conversation_id:p,messages:ve}})})),h=new Map(await Promise.all(l.map(async r=>[r.node_id,await _t(r.node_id)])));for(const r of s){const p=h.get(r.node_id);p!=null&&r.sequence_number>=p&&h.set(r.node_id,null)}const o=new Map;for(const r of m){const p=h.get(r.node_id);if(p==null||r.sequence_number<p)continue;const y=JSON.parse(r.body_json),u=o.get(r.node_id)??{thinking:"",text:""};r.type==="node.thinking.delta"?u.thinking+=y.delta:u.text+=y.delta,o.set(r.node_id,u)}const f=l.map(r=>({...r,in_progress_message:h.get(r.node_id)==null?null:o.get(r.node_id)??{thinking:"",text:""}}));return{run_id:e,latest_sequence:i,nodes:f}}c(na,"traceRun");function aa(e,t,a){if(t===void 0){if(!e.some(n=>P(n,"crtr:llm")))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return null}if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw S("scopes must be a list of scope strings","scopes");for(const n of t){try{wt(n)}catch{throw S(`invalid scope ${n}`,"scopes")}if(/^crtr:files:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))throw S(`own-app files cannot narrow a run: ${n}`,"scopes");if(!(/^crtr:memory:(?:read|rw):app:/.test(n)&&n.split(":")[4]===a.slice(4))&&!Ae(e,n))throw new R(403,"scope_missing",`missing scope ${n}`,void 0,void 0,n)}if(!t.includes("crtr:llm"))throw new R(403,"scope_missing","missing scope crtr:llm",void 0,void 0,"crtr:llm");return t}c(aa,"requestedScopes");export{z as IDEMPOTENCY_WINDOW_MS,Lt as RUN_DEADLINE_MAX_MS,It as RUN_DELETE_STORAGE_BUDGET_MS,Ne as RUN_NAME_MAX,R as RunError,Kn as cancelRun,Tt as cloudPersonScope,ta as deleteRun,Yn as idempotencyKeyOf,Zn as interruptRun,zn as listRuns,Vn as messageRun,q as ownedRun,Se as parseRunDeadlineMs,Gn as pruneExpiredIdempotencyKeys,ea as renameRun,aa as requestedScopes,Jn as runIsRunning,W as runObject,Xn as startRun,na as traceRun,Qn as waitRun};
|
|
@@ -30,7 +30,7 @@ export interface BlaxelRunnerDeps {
|
|
|
30
30
|
mintToken?(input: RunnerStartInput): Promise<string>;
|
|
31
31
|
/** The bootstrap script text passed as the process command (`scripts/sandbox-bootstrap.sh`). */
|
|
32
32
|
bootstrap(): string;
|
|
33
|
-
/** Sandbox names that belong to a node, for `delete`. Default: the node
|
|
33
|
+
/** Sandbox names that belong to a node, for `delete`. Default: one per execution of the node (`sandboxNameFor`). */
|
|
34
34
|
sandboxNamesForNode?(nodeId: string): Promise<string[]>;
|
|
35
35
|
/** Seconds `stop` waits after SIGTERM before the kill. */
|
|
36
36
|
stopGraceS?: number;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var $=Object.defineProperty;var i=(
|
|
2
|
-
${
|
|
3
|
-
${
|
|
1
|
+
var $=Object.defineProperty;var i=(n,a)=>$(n,"name",{value:a,configurable:!0});import{openDb as k}from"../../../canvas/db.js";import{mintExecutionToken as I}from"../../../canvas/node-tokens.js";import{BlaxelApiError as S,isWorkloadUnavailable as f}from"./client.js";const m=4180,u="view",T="node /opt/crtr/current/scripts/sandbox-start.mjs --wake",y=3,C=/^crtr-sandbox-start: failed (\S+)/m,p=i(n=>`broker-${n}`,"brokerProcessName"),w=i(n=>n.sandboxName??`${n.nodeId}-${n.attempt}`,"sandboxNameFor");async function h(n){const a=await(await k()).prepare("SELECT execution_id, attempt, sandbox_name FROM executions WHERE node_id = ? AND runner = 'blaxel'").all(n);return[...new Set(a.map(c=>w({executionId:c.execution_id,nodeId:n,attempt:Number(c.attempt),sandboxName:c.sandbox_name})))]}i(h,"defaultSandboxNames");function N(n){const a=`${n.logs}
|
|
2
|
+
${n.stderr}
|
|
3
|
+
${n.stdout}`;return{state:"failed",reason:C.exec(a)?.[1]??"start_failed",code:n.exitCode}}i(N,"failureOf");function O(n){const{client:a}=n,c=(n.stopGraceS??10)*1e3,E=new Map;async function d(t){return await a.getSandbox(w(t))}i(d,"sandboxOf");async function _(t,r){if(!/^[A-Za-z0-9_-]+$/.test(r))throw new Error(`execution id ${JSON.stringify(r)} is not safe to name in a command`);const e=Math.max(1,Math.ceil(c/1e3)),o=`p='[b]roker-cli\\.js .*--epoch ${r}( |$)'; pkill -TERM -f "$p"; i=0; while pgrep -f "$p" >/dev/null && [ $i -lt ${e*5} ]; do sleep 0.2; i=$((i+1)); done; pkill -KILL -f "$p"; sleep 0.3; ! pgrep -f "$p"`;return(await a.exec(t,`stop-${r}-${Date.now()}`,o,e+20)).exitCode===0}return i(_,"brokerGone"),{kind:"blaxel",async start(t){const r=await n.launchContext(t),e=w(t),o=await a.createSandbox({name:e,image:r.image,memoryMb:r.memoryMb,ports:[{name:u,target:m}]}),s=p(t.executionId);if((await a.getProcess(o,s))?.status==="running")return{pid:null,exited:null};await a.ensurePreview(e,u,m);const x=await(n.mintToken??(b=>I(b.executionId,b.nodeId)))(t),R={...r.secrets,CRTR_API_URL:r.apiUrl,CRTR_EXECUTION_ID:t.executionId,CRTR_NODE_TOKEN:x,CRTR_RELEASE:t.release,CRTR_RELEASE_URL:r.releaseUrl,CRTR_RELEASE_SHA256:r.releaseSha256};return await a.startProcess(o,{name:s,command:n.bootstrap(),env:R,waitForCompletion:!1}),{pid:null,exited:null}},async wake(t){const r=await d(t);if(r===null)return"no_broker";try{const e=await a.exec(r,`wake-${t.executionId}-${Date.now()}`,`${T} ${t.executionId}`,30);if(e.exitCode===0)return"signalled";if(e.exitCode===y)return"no_broker";throw new Error(`wake of ${t.executionId} failed (exit ${e.exitCode}): ${(e.stderr||e.logs).slice(0,300)}`)}catch(e){if(f(e))return"no_broker";throw e}},async stop(t,r){try{const e=await d(t);if(e===null)return{confirmed:!0};const o=p(t.executionId),s=i(async()=>(await a.getProcess(e,o))?.status==="running","running");if(await s()){await a.stopProcess(e,o);const l=Date.now()+c;for(;Date.now()<l&&await s();)await new Promise(x=>setTimeout(x,250));if(await s()&&await a.killProcess(e,o),await s())return{confirmed:!1}}return{confirmed:await _(e,t.executionId)}}catch(e){return f(e)?{confirmed:!0}:{confirmed:!1,error:e instanceof Error?e:new Error(String(e))}}},async status(t,r){try{const e=await d(t);if(e===null)return{state:"gone"};if(r?.idle===!0)return{state:"running",pid:null};const o=await a.getProcess(e,p(t.executionId));return o===null?{state:"gone"}:o.status==="running"?{state:"running",pid:null}:o.status==="failed"||o.status==="completed"&&o.exitCode!==0?N(o):{state:"gone"}}catch(e){return f(e)?{state:"gone"}:{state:"unknown",error:e instanceof Error?e.message:String(e)}}},async delete(t){for(const r of await(n.sandboxNamesForNode??h)(t))await a.deleteSandbox(r)},async viewerAddress(t){const r=w(t),e=E.get(r);if(e&&e.expiresAt-Date.now()>5*6e4)return g(e.url,e.token);const o=await a.ensurePreview(r,u,m),s=new Date(Date.now()+60*6e4),{token:l}=await a.createPreviewToken(r,u,s);return E.set(r,{url:o,token:l,expiresAt:s.getTime()}),g(o,l)},async sandboxState(t){return(await d(t))?.state??null}}}i(O,"createBlaxelRunner");function g(n,a){return{kind:"wss",url:`${n.replace(/^https:/,"wss:")}/view`,headers:{"x-blaxel-preview-token":a}}}i(g,"viewer");export{m as BROKER_VIEW_PORT,S as BlaxelApiError,y as EXIT_NO_BROKER,C as FAILURE_LINE,T as WAKE_COMMAND,p as brokerProcessName,O as createBlaxelRunner,w as sandboxNameFor};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Delete the sandboxes of the nodes that ran in one. Returns the ids whose sandboxes could not all be deleted: the caller keeps
|
|
2
|
+
* those nodes' rows, which are what the next removal sweep or retention pass finds them by. A repeat is harmless. */
|
|
3
|
+
export declare function deleteNodeSandboxes(nodeIds: readonly string[]): Promise<string[]>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{openDb as c}from"../../canvas/db.js";import{emitEvent as d}from"../../events/emit.js";async function u(e){if(e.length===0)return[];const t=e.map(()=>"?").join(","),a=await(await c()).prepare(`SELECT DISTINCT node_id FROM executions WHERE runner = 'blaxel' AND node_id IN (${t})`).all(...e),r=[];for(const{node_id:o}of a)try{await(await import("./index.js")).runnerForExecution("blaxel").delete(o)}catch(i){r.push(o),d({level:"error",event:"canvas.node_sandbox.delete_failed",node_id:o,error:i})}return r}n(u,"deleteNodeSandboxes");export{u as deleteNodeSandboxes};
|
|
@@ -16,9 +16,22 @@ export declare function findBrokers(): Array<{
|
|
|
16
16
|
node: string;
|
|
17
17
|
command: string;
|
|
18
18
|
}>;
|
|
19
|
+
/** Reads the start bundle. A transient failure (connection error, timeout, 502/503/504) is asked again with doubling backoff until the budget above is spent, so a brief
|
|
20
|
+
* control-plane restart does not end the launch; any other non-2xx answer is permanent and fails at once with its status. The link dropping (`signal`) ends the wait. */
|
|
21
|
+
export declare function fetchBundle(apiUrl: string, executionId: string, token: string, signal?: AbortSignal): Promise<StartBundleDTO>;
|
|
22
|
+
/** The recipe's `-e` extension paths name files of the control plane's install (`/opt/crouter/runtime/generations/...`), and its release may ship a different
|
|
23
|
+
* set of canvas extensions than this install. So the mandatory canvas extensions are this install's complete list (`mergeCanvasExtensions`), whatever the recipe
|
|
24
|
+
* carried of them; the recipe's own extensions are kept and must exist on this machine, or the launch is refused. Every other argument is the recipe's. */
|
|
25
|
+
export declare function localExtensionArgv(argv: readonly string[]): string[];
|
|
26
|
+
/** The recipe this machine's broker reads from `broker-launch.json` (the broker merges its `env` into `process.env` and loads its `argv` extensions):
|
|
27
|
+
* the control plane's recipe with the machine-local paths above. */
|
|
28
|
+
export declare function machineLaunchRecipe(launchJson: string, node: {
|
|
29
|
+
id: string;
|
|
30
|
+
app: string;
|
|
31
|
+
}): string;
|
|
19
32
|
/** The env a machine's broker starts with: what the process runner's `buildBrokerEnv` builds for the same node. The environment's secret rows come from the
|
|
20
33
|
* control plane in the start bundle with the profile's metadata (this role has no database and no profiles, so the profile is never looked up here); the operational base, the profile's metadata, the app's pi dir and the launch recipe's env
|
|
21
|
-
* go over them in `buildBrokerEnv`'s order, and the link's own settings are pinned last. */
|
|
34
|
+
* go over them in `buildBrokerEnv`'s order, and the link's own settings are pinned last. The recipe's path-shaped keys are this machine's (`localLaunchEnv`). */
|
|
22
35
|
export declare function machineBrokerEnv(bundle: StartBundleDTO, deps: Pick<MachineExecutorDeps, 'apiUrl' | 'environmentId'>, executionId: string): NodeJS.ProcessEnv;
|
|
23
36
|
/** Stop every broker of this crtr home (a machine daemon starting with no sign-in, design-crtr-northlight-signin component 5). A broker of another
|
|
24
37
|
* home on the same computer (its `--canvas-home` differs) is not touched. Rejects when the process table cannot be read or a broker's tree survives
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P=Object.defineProperty;var s=(o,n)=>P(o,"name",{value:n,configurable:!0});import{spawn as U}from"node:child_process";import{closeSync as $,existsSync as R,mkdirSync as _,openSync as B,statSync as G}from"node:fs";import{rm as H}from"node:fs/promises";import{basename as S,dirname as I,join as w}from"node:path";import{fileURLToPath as F}from"node:url";import{contextDir as j,jobDir as K,nodeRunDir as k,crtrHome as b,viewSocketPath as X}from"../../../canvas/paths.js";import{captureTeardownSnapshot as J,isAnyPidAlive as V,killProcessTreePids as v,listProcessTable as Y}from"../../../canvas/pid.js";import{scopesFilePath as y}from"../../../canvas/paths.js";import{writeFileBeneath as x}from"../../../spaces/open-beneath.js";import{FRONT_DOOR_ENV as W}from"../../front-door-env.js";import{brokerCommandDeclaresCanvasHome as z}from"../../broker-ownership.js";import{isShippedCanvasExtension as Q}from"../../../canvas/extensions.js";import{CANVAS_EXTENSIONS as q,mergeCanvasExtensions as Z}from"../../canvas-extensions.js";import{layoutRoot as g,runtimeRoot as ee}from"../../../layout.js";import{composeAppProcessEnv as oe,overlayBrokerEnv as te}from"../../spawn-env.js";const T=s(()=>w(I(F(import.meta.url)),"..","..","broker-cli.js"),"brokerEntry"),C=s(o=>{if(o!==void 0)try{process.kill(-o,"SIGKILL")}catch{}},"killGroup"),re=s(o=>new Promise(n=>setTimeout(n,o)),"sleep");function N(){const o=[],n=Y();if(n===null)throw new Error("the process table could not be read, so which brokers are running is unknown");for(const{pid:r,command:e}of n){const t=/broker-cli\.js .*--epoch (\S+) (\S+)\s*$/.exec(e);t!==null&&o.push({pid:r,execution:t[1],node:t[2],command:e})}return o}s(N,"findBrokers");const ne=new Set([502,503,504]),ie=1e3,ce=3e4,se=3e4,O=9e4;async function ae(o,n,r,e){const t=Date.now()+O;for(let c=ie;;c=Math.min(c*2,ce)){e?.throwIfAborted();const i=AbortSignal.timeout(Math.min(se,Math.max(1,t-Date.now())));let a,d;try{a=await fetch(`${o.replace(/\/$/,"")}/v1/executions/${n}/start`,{headers:{authorization:`Bearer ${r}`},signal:e===void 0?i:AbortSignal.any([i,e])}),d=`the control plane answered ${a.status} for the start bundle of ${n}`}catch(u){e?.throwIfAborted(),d=`the control plane could not be reached for the start bundle of ${n}: ${u instanceof Error?u.message:String(u)}`}if(a?.ok)return await a.json();if(a!==void 0&&!ne.has(a.status))throw new Error(d);if(Date.now()+c>=t)throw new Error(`${d} (gave up after ${O/1e3} seconds of retries)`);e?.throwIfAborted(),await new Promise(u=>{const m=setTimeout(l,c);function l(){clearTimeout(m),e?.removeEventListener("abort",l),u()}s(l,"done"),e?.addEventListener("abort",l,{once:!0})})}}s(ae,"fetchBundle");const de=["CRTR_HOME","CRTR_RUNTIME_HOME"];function A(o,n){const r={...o};for(const e of de)delete r[e];return r.CRTR_CONTEXT_DIR!==void 0&&(r.CRTR_CONTEXT_DIR=j(n.id,r.CRTR_GRANTEE??n.app)),r.CRTR_SCOPES_FILE!==void 0&&(r.CRTR_SCOPES_FILE=y(n.id)),r}s(A,"localLaunchEnv");function ue(o){const n=s(i=>S(i).replace(/\.[jt]s$/,""),"stem"),r=new Set(q.map(n)),e=s(i=>Q(i)||S(I(i))==="pi-extensions"&&(r.has(n(i))||n(i).startsWith("canvas-")&&!R(i)),"shipped"),t=[],c=[];for(let i=0;i<o.length;i++)if(o[i]==="-e"&&o[i+1]!==void 0){const a=o[++i];if(e(a))continue;if(!R(a))throw new Error(`extension ${a} does not exist on this machine`);c.push(a)}else t.push(o[i]);return[...Z(c).flatMap(i=>["-e",i]),...t]}s(ue,"localExtensionArgv");function fe(o,n){const r=JSON.parse(o);return JSON.stringify({...r,argv:ue(r.argv),env:A(r.env??{},n)})}s(fe,"machineLaunchRecipe");function le(o,n,r){const e=o.launch,t=te({argv:[],env:A(e.env??{},o.node)},oe(o.node.cwd,null,o.node.app,o.machine_env??{},{}));return Object.assign(t,{CRTR_HOME:g(),CRTR_RUNTIME_HOME:process.env.CRTR_RUNTIME_HOME??ee(),CRTR_API_URL:n.apiUrl,CRTR_EXECUTION_ID:r,CRTR_ENVIRONMENT_ID:n.environmentId,CRTR_VIEW_WSS:"0",[W]:"1"})}s(le,"machineBrokerEnv");async function M(o,n,r){const{tree:e,identities:t}=J(o,null,r);if(t===null)return{confirmed:!1,error:`the process tree of broker ${o} could not be read, so shutdown cannot be confirmed`};const c=s(async(i,a)=>{for(let d=0;V(i);d+=100){if(d>=a)return!1;await re(100)}return!0},"waitUntilDead");try{process.kill(o,"SIGTERM")}catch{}return await c([o],n),v(e,"SIGTERM",t),await c(e,2e3)?{confirmed:!0}:(v(e,"SIGKILL",t),await c(e,5e3)?{confirmed:!0}:{confirmed:!1,error:`broker process tree of ${o} survived SIGKILL`})}s(M,"stopBroker");async function Ne(o=1e4){const r=(await Promise.all(N().filter(e=>z(e.command,b())).map(e=>M(e.pid,o)))).filter(e=>!e.confirmed);if(r.length>0)throw new Error(r.map(e=>e.error??"a broker did not stop").join("; "))}s(Ne,"stopAllBrokers");function Oe(o){const n=(o.stopGraceS??10)*1e3,r=s(e=>N().find(t=>t.execution===e),"brokerOf");return{async start(e,t){const c=r(e.executionId);if(c!==void 0)return{pid:c.pid};if(t?.throwIfAborted(),!R(e.cwd)||!G(e.cwd).isDirectory())throw new Error(`the node's cwd ${e.cwd} is not a directory on this machine`);if(!R(T()))throw new Error(`the broker entry ${T()} does not exist`);const i=await ae(o.apiUrl,e.executionId,e.nodeToken,t);t?.throwIfAborted();const a=i.launch,d=k(e.nodeId);_(d,{recursive:!0}),x(d,w(d,"broker-launch.json"),fe(e.launchJson,i.node),{atomic:!0}),a.env?.CRTR_SCOPES_FILE!==void 0&&x(d,y(e.nodeId),JSON.stringify(a.scopes??[]),{atomic:!0});const u=K(e.nodeId);_(u,{recursive:!0});const m=B(w(u,"broker.log"),"a"),l=le(i,o,e.executionId);delete l.CRTR_NODE_TOKEN;try{t?.throwIfAborted();const f=U(process.execPath,[T(),"--canvas-home",b(),"--epoch",e.executionId,e.nodeId],{cwd:e.cwd,detached:!0,stdio:["ignore",m,m,"pipe"],env:l}),p=f.stdio[3];if(p==null||!("end"in p))throw C(f.pid),new Error("broker token pipe did not open");const D=await new Promise((L,h)=>{f.once("error",h),f.once("spawn",()=>{f.off("error",h),p.once("error",E=>{C(f.pid),h(E)}),p.end(e.nodeToken,E=>{E?h(E):L(f.pid)})})});return f.unref(),{pid:D}}finally{$(m)}},async wake({execution:e}){const t=r(e.executionId);if(t===void 0)return"no_broker";try{return process.kill(t.pid,"SIGUSR1"),"signalled"}catch(c){if(c.code==="ESRCH")return"no_broker";throw c}},async stop({execution:e,options:t}){const c=r(e.executionId);return c===void 0?{confirmed:!0}:await M(c.pid,n,t.excludePid)},async status({execution:e}){const t=r(e.executionId);return t===void 0?{state:"gone"}:{state:"running",pid:t.pid}},async delete({nodeId:e}){return await H(k(e),{recursive:!0,force:!0}),null},async viewer({execution:e}){return{kind:"unix",path:X(e.nodeId)}}}}s(Oe,"createMachineExecutor");export{Oe as createMachineExecutor,ae as fetchBundle,N as findBrokers,ue as localExtensionArgv,le as machineBrokerEnv,fe as machineLaunchRecipe,Ne as stopAllBrokers};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var N=Object.defineProperty;var m=(n,o)=>N(n,"name",{value:o,configurable:!0});import{after as q,before as x,test as c}from"node:test";import e from"node:assert/strict";import{spawn as P}from"node:child_process";import{mkdirSync as R,mkdtempSync as E,readFileSync as A,rmSync as v,writeFileSync as _}from"node:fs";import{tmpdir as w}from"node:os";import{join as l}from"node:path";import{EventEmitter as k}from"node:events";import{Readable as D}from"node:stream";import{createServer as H}from"node:http";import{createNode as M}from"../../../canvas/canvas.js";import{closeDb as L,openDb as T}from"../../../canvas/db.js";import{isPidAlive as u}from"../../../canvas/pid.js";import{bindPerson as F,installTerminalGrant as j,useEmptyPersonSettings as U}from"../../../__tests__/helpers/person.js";import{setAppEnvVar as O}from"../../../profiles/app-env-store.js";import{setProfileEnvVar as g}from"../../../profiles/env-store.js";import{createProfile as V}from"../../../profiles/manifest.js";import{putEnvRow as G}from"../../../secrets/env-rows.js";import{appSpace as J}from"../../../layout.js";import{executionStartRoutes as $}from"../../../../daemon/api/handlers/execution-start.js";import{Router as X}from"../../../../daemon/api/router.js";import{contextDir as S,scopesFilePath as C}from"../../../canvas/paths.js";import{layoutRoot as B,runtimeRoot as K}from"../../../layout.js";import{CANVAS_EXTENSIONS as d}from"../../canvas-extensions.js";import{createMachineExecutor as Y,fetchBundle as I,localExtensionArgv as z,machineBrokerEnv as h,machineLaunchRecipe as b}from"./executor.js";let p;const Q={HOME:process.env.HOME,CRTR_HOME:process.env.CRTR_HOME};x(()=>{process.env.HOME=p=E(l(w(),"crtr-machine-exec-")),process.env.CRTR_HOME=l(p,".crouter"),R(process.env.CRTR_HOME,{recursive:!0})}),q(async()=>{await L(),v(p,{recursive:!0,force:!0});for(const[n,o]of Object.entries(Q))o===void 0?delete process.env[n]:process.env[n]=o});async function W(n,o){const a=new X().registerAll($),i=Object.assign(D.from([]),{method:"GET",url:`/v1/executions/${o}/start`,headers:{}});let r="";const t=Object.assign(new k,{headersSent:!1,writableEnded:!1,writableFinished:!1});return t.setHeader=()=>t,t.writeHead=()=>(t.headersSent=!0,t),t.end=s=>(s&&(r+=s),t.writableEnded=!0,t.writableFinished=!0,t),await a.handle(i,t,null,n),JSON.parse(r)}m(W,"bundleFor"),c("a machine broker gets the profile, app and deployment rows, the app pi dir and the launch env, with the process runner's precedence",async()=>{await U(),await T();const n=await j(),o=(await V("machine-env")).profileId;await O("app:terminal","SHARED","from-app",n),await O("app:terminal","APP_SECRET","app-secret",n),await g(o,"SHARED","from-profile",n),await g(o,"PROFILE_VAR","profile-value",n),await G({person:null,kind:"deployment",id:"_deployment"},"DEPLOY_VAR","deploy-value");const a=l(p,"work");R(a,{recursive:!0}),await M({node_id:"m1",name:"m1",created:new Date().toISOString(),cwd:a,kind:"general",mode:"base",lifecycle:"resident",status:"active",parent:null,profile_id:o,grantee:"app:terminal"}),await(await T()).prepare("INSERT INTO executions (execution_id, node_id, state, started_at, launch_json, runner) VALUES ('em1', 'm1', 'launching', 't', ?, 'machine')").run(JSON.stringify({argv:["x"],env:{LAUNCH_VAR:"launch",CRTR_NODE_ID:"m1"}}));const i={class:"broker",app:"app:terminal",node:"m1",run:null,uid:process.getuid?.()??0,sub:await F(),grant:null,client_id:null,scopes:null},r=await W(i,"em1");e.equal(r.machine_env?.APP_SECRET,"app-secret");const t=h(r,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1");e.equal(t.APP_SECRET,"app-secret"),e.equal(t.PROFILE_VAR,"profile-value"),e.equal(t.DEPLOY_VAR,"deploy-value"),e.equal(t.SHARED,"from-profile","the profile's row wins over the app's"),e.equal(t.LAUNCH_VAR,"launch"),e.equal(t.PI_CODING_AGENT_DIR,l(J("app:terminal").home,".pi","agent")),e.equal(t.CRTR_API_URL,"http://cloud.invalid"),e.equal(t.CRTR_EXECUTION_ID,"em1"),e.doesNotThrow(()=>h({...r,node:{...r.node,profile:"profile-the-mac-does-not-hold"}},{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em1")),e.equal(t.GITHUB_TOKEN,void 0)}),c("stop ends the broker and the detached command it left behind, and confirms both gone",async()=>{const n=E(l(w(),"crtr-machine-stop-")),o=l(n,"child.pid"),a=l(n,"broker-cli.js");_(a,`const { spawn } = require('node:child_process');
|
|
2
2
|
const c = spawn('sleep', ['300'], { detached: true, stdio: 'ignore' }); c.unref();
|
|
3
|
-
require('node:fs').writeFileSync(${JSON.stringify(
|
|
4
|
-
setInterval(() => {}, 1000);`);const
|
|
3
|
+
require('node:fs').writeFileSync(${JSON.stringify(o)}, String(c.pid));
|
|
4
|
+
setInterval(() => {}, 1000);`);const i=P(process.execPath,[a,"--canvas-home",n,"--epoch","exec-stop-1","node-stop-1"],{detached:!0,stdio:"ignore"});i.unref();try{let r=0;for(let f=0;f<100&&r===0;f++)try{r=Number(A(o,"utf8"))}catch{await new Promise(y=>setTimeout(y,50))}e.ok(r>0&&u(r),"the detached child is running");const s=await Y({apiUrl:"http://cloud.invalid",environmentId:"env1",stopGraceS:3}).stop({execution:{executionId:"exec-stop-1",nodeId:"node-stop-1"},options:{reason:"test"}});e.deepEqual(s,{confirmed:!0}),e.equal(u(i.pid),!1,"the broker is gone"),e.equal(u(r),!1,"the detached child is gone")}finally{try{process.kill(-i.pid,"SIGKILL")}catch{}v(n,{recursive:!0,force:!0})}}),c("a bundle the control plane built on its Linux layout starts a broker on this machine's own home, runtime, context, scopes and extension paths",()=>{const n={CRTR_HOME:"/work/crtr",CRTR_RUNTIME_HOME:"/opt/crouter/runtime",CRTR_CONTEXT_DIR:"/work/crtr/apps/terminal/nodes/m2/context",CRTR_SCOPES_FILE:"/work/crtr/runtime/nodes/m2/run/scopes.json",CRTR_NODE_ID:"m2",CRTR_KIND:"general",CRTR_GRANTEE:"app:terminal",CRTR_PROFILE_ID:"p-1"},a={launch:{argv:[...d.flatMap(t=>["-e",`/opt/crouter/runtime/generations/96276ec4/dist/pi-extensions/${t.split("/").pop()}`]),"-n","m2"],env:n,scopes:["a:b"]},node:{id:"m2",app:"app:terminal",cwd:p,profile:null},machine_env:{APP_SECRET:"s"}},i=h(a,{apiUrl:"http://cloud.invalid",environmentId:"env1"},"em2");e.equal(i.CRTR_HOME,B()),e.equal(i.CRTR_RUNTIME_HOME,process.env.CRTR_RUNTIME_HOME??K()),e.equal(i.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(i.CRTR_SCOPES_FILE,C("m2")),e.equal(i.CRTR_NODE_ID,"m2"),e.equal(i.CRTR_PROFILE_ID,"p-1"),e.equal(i.APP_SECRET,"s");for(const[t,s]of Object.entries(i))e.ok(!/\/work\/crtr|\/opt\/crouter/.test(s??""),`${t} names a control plane path: ${s}`);const r=JSON.parse(b(JSON.stringify(a.launch),a.node));e.deepEqual(r.argv.filter((t,s)=>r.argv[s-1]==="-e"),d),e.equal(r.argv.at(-1),"m2"),e.equal(r.env.CRTR_HOME,void 0),e.equal(r.env.CRTR_CONTEXT_DIR,S("m2","app:terminal")),e.equal(r.env.CRTR_SCOPES_FILE,C("m2")),e.deepEqual(r.scopes,["a:b"]),e.ok(!/\/work\/crtr|\/opt\/crouter/.test(JSON.stringify(r))),e.throws(()=>b(JSON.stringify({argv:["-e","/opt/crouter/runtime/generations/x/custom.js"],env:{}}),{id:"m2",app:"app:terminal"}),/does not exist on this machine/)}),c("the broker's mandatory extensions are this install's complete list, whatever set the control plane's release shipped",()=>{const n=m(t=>["-e",`/opt/crouter/runtime/generations/old/dist/pi-extensions/${t}.js`],"server"),o=l(p,"custom-ext.js");_(o,"");const a=[...d,o].flatMap(t=>["-e",t]),r=[...d.map(t=>t.split("/").pop().replace(/\.[jt]s$/,"")).slice(1).flatMap(n),...n("canvas-retired-hook"),"-e",o,"-n","label","prompt text"];e.deepEqual(z(r),[...a,"-n","label","prompt text"])}),c("a control plane that answers 502 and then 200 still gives the start bundle, while a 404 fails at once with its status",async()=>{const n=[502,200],o=H((a,i)=>{const r=a.url?.includes("/gone/")?404:n.shift()??200;i.writeHead(r,{"content-type":"application/json"}),i.end(JSON.stringify(r===200?{launch:{argv:[]},node:{id:"n"}}:{error:"x"}))});await new Promise(a=>o.listen(0,"127.0.0.1",a));try{const a=`http://127.0.0.1:${o.address().port}`;e.deepEqual((await I(a,"exec-502","token")).node,{id:"n"}),e.deepEqual(n,[],"the 502 was asked again"),await e.rejects(I(a,"gone","token"),/answered 404/)}finally{o.close()}});
|
|
@@ -32,5 +32,5 @@ export declare function assertUploadsUsable(grantee: string, uses: readonly Atta
|
|
|
32
32
|
/** Fetch every upload a storage URL in `text` names into the blob store at `attachments/<rootId>/<sha256>` and replace
|
|
33
33
|
* exactly each URL's span with the path the node's broker downloads that file to (`<app space>/nodes/<rootId>/attachments/<name>`).
|
|
34
34
|
* The control plane writes no file there. Without configured storage the text passes through unchanged. A failure leaves
|
|
35
|
-
* at most content-keyed blobs, which are harmless and are deleted with the node
|
|
35
|
+
* at most content-keyed blobs, which are harmless and are deleted with the node. */
|
|
36
36
|
export declare function resolveStorageUrls(grantee: string, rootId: string, text: string, options?: ResolveOptions): Promise<ResolvedAttachments>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.defineProperty;var d=(e,t)=>j(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as D}from"../../core/events/emit.js";import{scopeAllowed as _,ScopeDeniedError as I}from"../../core/scopes.js";import{coveredByAny as L}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{activeGrant as F,activeGrantsOfPerson as J,grantFor as S}from"../../core/grants/mirror.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as M,RunError as b}from"../../core/runs/operations.js";import{openDb as x}from"../../core/canvas/db.js";import{check as Y,permits as Z}from"../../core/permissions/evaluator.js";import{readerFor as R}from"./reader.js";import{checkCronFire as V}from"../cron/authority.js";import{operationFor as X}from"./operations.js";import{CONTROL_BODY_MAX_BYTES as K}from"../../core/llm/body-limits.js";import{getRequest as A,getRequestByInboxTicket as O}from"../../core/human/requests.js";import{requireVisibleReview as g}from"../../core/review/store.js";import{getComment as v}from"../../core/review/comments.js";import{getStructuredRequest as Q}from"../../core/canvas/structured-requests.js";async function ee(e,t,o,n,s){const r=e.path,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};if(r==="/v1/human/requests"||r==="/v1/human/reviews"){const i=r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id,c=r==="/v1/human/requests"&&i==null;if(i!==t.node&&!c)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const h=a.source;if(h&&typeof h=="object"&&"nodeId"in h&&h.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 v(o.comment_id))throw new u(404,"not_found","comment not found")}d(ee,"authorizeHumanBody");function C(e){return e.class==="broker"||e.class==="cron"}d(C,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function y(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(y,"actsAsPerson");async function $(e){const t=await S(e.actor.app,e.sub);if(!t)throw new u(403,"app_not_granted",`${e.actor.app} holds no active grant for ${e.sub} on this machine`);return t}d($,"forwardedGrant");async function p(e){if(e.class==="person"&&e.sub!==void 0)return(await J(e.sub)).flatMap(o=>o.resolved);if(e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import")return[];if(e.class==="forwarded"){if(e.actor.kind==="person")return[];const{resolved:o}=await $(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>L(o,s))}if(e.class==="app")return e.scopes;if(e.class==="cron"){const o=await V({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 F(e.grant):await S(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(p,"resolvedScopes");function N(e){return"class"in e?k(e):e.grantee}d(N,"runCallerApp");function T(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(T,"asRequestPrincipal");async function f(e,t,o){const n=T(e);if(y(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await x();return await Y(s,await R(s,{principal:n}),t,o)}d(f,"mayOnNode");async function We(e){if(y(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await x(),o=await Z(t,await R(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(We,"readableNodeIds");async function W(e,t,o){const n=T(e);return y(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:_(await p(n),o)&&(!C(n)||_(n.scopes,o))}d(W,"mayReadApp");async function ze(e,t,o){return o===void 0?await W(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(ze,"canReadRun");async function Ge(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 b(404,"not_found","run not found");if(!await f(e,"read",t))throw new b(404,"not_found","run not found");if(o&&N(e)!==null&&N(e)!==s.grantee)throw new b(403,"other_app_run","cannot change another app's run");return await M(t,s.grantee,n)}d(Ge,"requireRun");async function te(e,t,o){return o===void 0?await W(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(te,"canReadNode");const z=new Set(["messages.post.58","messages.post.59"]);async function oe(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(t.class==="forwarded"&&t.actor.kind==="app"&&await $(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||y(t))return;if(t.class==="person")return await ne(e,t,o);const n=await p(t);if(e.scope&&(!_(n,e.scope)||C(t)&&!_(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 de(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=z.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(oe,"authorizeOperation");async function ne(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 re(e,t,o);if(o.request_id!==void 0&&e.path.startsWith("/v1/structured-requests/"))return await se(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,z.has(e.name)?"message":"read",n))throw new u(404,"not_found","node not found")}d(ne,"authorizePersonNode");async function re(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 A(o.request_id):o.ticket_id?await O(o.ticket_id):null,r=o.comment_id?await v(o.comment_id):null,a=o.review_id?await g(o.review_id).catch(()=>null):r?await g(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(re,"authorizePersonHuman");async function se(e,t,o){const n=await Q(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(se,"authorizePersonStructuredRequest");async function ae(e,t,o){const n=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=e.path;if(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(ae,"authorizePersonBody");async function de(e,t,o,n){if(e.resource==="daemon-bash"&&(!_(n,"crtr:files:rw:user:.")||!_(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 A(o.request_id):o.ticket_id?await O(o.ticket_id):null,c=o.comment_id?await v(o.comment_id):null,h=o.review_id?await g(o.review_id):c?await g(c.review_id):null,m=i?.requester_node_id??h?.origin_node_id;if(m!=null){const l=await w(m);if(l&&(a?!await te(t,l.grantee??"app:terminal",m):l.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(l&&!a&&!await f(t,"read",m))throw new u(404,"not_found","human request not found")}else if(i||h)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(de,"authorizeBrokerOnly");function ue(e,t){if(!_(e,t))throw new I("the bearer token",t)}d(ue,"assertCeiling");function ie(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ie,"ownerOnlyError");const ce="Crtr-Caused-By",fe=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function he(e){const t=e[ce.toLowerCase()];return typeof t=="string"&&fe.test(t)?t:void 0}d(he,"causedByOf");function Ue(e){return e.map(t=>({...t,ownerOnly:!0}))}d(Ue,"ownerOnly");class Pe{static{d(this,"Router")}routes=[];register(t){const o=X(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:G(t.pattern),handler:t.handler,maxBodyBytes:t.maxBodyBytes??K}),this}registerAll(t){for(const o of t)this.register(o);return this}match(t,o){const n=t.toUpperCase(),s=G(o);for(const r of this.routes){if(r.method!==n)continue;const a=we(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){P(o,404,"not_found",`no route for ${a} ${r.pathname}`);return}if(await oe(i.operation,s,i.params),n!==null){if(i.operation.classes.length===1&&i.operation.classes[0]==="person")throw ie();i.operation.scope&&ue(n,i.operation.scope)}let c;try{c=await me(t,i.maxBodyBytes)}catch(E){const B=E instanceof U?"payload_too_large":"invalid_request";P(o,B==="payload_too_large"?413:400,B,E.message);return}s.class==="person"&&s.sub!==void 0&&await ae(i.operation,s,c),s.class==="broker"&&i.operation.resource==="human"&&await ee(i.operation,s,i.params,r.searchParams,c);const h=he(t.headers),m={...h===void 0?{}:{causedBy:h},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},l=await i.handler(m);o.writableEnded||_e(o,l)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){q(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&&D({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??""}}),q(o,a,i)}}}function G(e){return e.split("/").filter(t=>t.length>0)}d(G,"splitPath");function we(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(we,"matchSegments");class U extends Error{static{d(this,"BodyTooLargeError")}}async function me(e,t){const o=[];let n=0;for await(const r of e){const a=r;if(n+=a.length,n>t)throw new U(`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(me,"readJsonBody");function _e(e,t){if(e.headersSent)return;const o={...t.headers??{}};if(t.rawBody!==void 0){e.writeHead(t.status,o),e.end(t.rawBody);return}if(t.status===204||t.body===void 0){e.writeHead(t.status,o),e.end();return}o["content-type"]===void 0&&(o["content-type"]="application/json; charset=utf-8"),e.writeHead(t.status,o),e.end(JSON.stringify(t.body))}d(_e,"writeResult");function q(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(q,"writeJson");function P(e,t,o,n){q(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(P,"writeError");export{ce as CAUSED_BY_HEADER,Pe as Router,y as actsAsPerson,k as appOf,ue as assertCeiling,te as canReadNode,ze as canReadRun,he as causedByOf,f as mayOnNode,Ue as ownerOnly,ie as ownerOnlyError,We as readableNodeIds,Ge as requireRun,p as resolvedScopes,N as runCallerApp};
|
|
1
|
+
var j=Object.defineProperty;var d=(e,t)=>j(e,"name",{value:t,configurable:!0});import{toErrorBody as H}from"./map.js";import{emitEvent as D}from"../../core/events/emit.js";import{scopeAllowed as _,ScopeDeniedError as I}from"../../core/scopes.js";import{coveredByAny as L}from"../../shared/env.js";import{ApiError as u}from"../../api/errors.js";import{isCloudRole as F}from"../../core/canvas/person.js";import{activeGrant as J,activeGrantsOfPerson as M,grantFor as S}from"../../core/grants/mirror.js";import{getNode as w}from"../../core/canvas/canvas.js";import{ownedRun as Y,RunError as b}from"../../core/runs/operations.js";import{openDb as x}from"../../core/canvas/db.js";import{check as Z,permits as V}from"../../core/permissions/evaluator.js";import{readerFor as R}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 A,getRequestByInboxTicket as O}from"../../core/human/requests.js";import{requireVisibleReview as g}from"../../core/review/store.js";import{getComment as v}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(r==="/v1/human/requests"||r==="/v1/human/reviews"){const i=r.endsWith("/reviews")?a.origin_node_id:a.requester_node_id,c=r==="/v1/human/requests"&&i==null;if(i!==t.node&&!c)throw new u(403,"other_app_run","a broker may create a human request only for its own node");const h=a.source;if(h&&typeof h=="object"&&"nodeId"in h&&h.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 v(o.comment_id))throw new u(404,"not_found","comment not found")}d(te,"authorizeHumanBody");function C(e){return e.class==="broker"||e.class==="cron"}d(C,"boundedByStoredScopes");function k(e){return e.class==="person"||e.class==="anonymous"||e.class==="machine"||e.class==="import"?null:e.class==="forwarded"?e.actor.kind==="app"?e.actor.app:null:e.app}d(k,"appOf");function y(e){return e.class==="person"&&e.sub===void 0||e.class==="forwarded"&&e.actor.kind==="person"}d(y,"actsAsPerson");async function p(e){const t=await S(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(p,"forwardedGrant");async function $(e){if(e.class==="person"&&e.sub!==void 0)return(await M(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 p(e),n=e.actor.node_scopes;return n===null?o:n.filter(s=>L(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 J(e.grant):await S(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($,"resolvedScopes");function N(e){return"class"in e?k(e):e.grantee}d(N,"runCallerApp");function T(e){return"class"in e?e:{class:"app",app:e.grantee,scopes:e.resolved,sub:e.sub}}d(T,"asRequestPrincipal");async function f(e,t,o){const n=T(e);if(y(n))return!0;if(n.class==="anonymous"||n.class==="machine"||n.class==="import")return!1;const s=await x();return await Z(s,await R(s,{principal:n}),t,o)}d(f,"mayOnNode");async function Ge(e){if(y(e))return null;if(e.class==="anonymous"||e.class==="machine"||e.class==="import")return new Set;const t=await x(),o=await V(t,await R(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(Ge,"readableNodeIds");async function W(e,t,o){const n=T(e);return y(n)?!0:n.class==="anonymous"||n.class==="machine"||n.class==="import"?!1:k(n)===t?!0:_(await $(n),o)&&(!C(n)||_(n.scopes,o))}d(W,"mayReadApp");async function Ue(e,t,o){return o===void 0?await W(e,t,`crtr:conversations:read:${t}`):await f(e,"read",o)}d(Ue,"canReadRun");async function Pe(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 b(404,"not_found","run not found");if(!await f(e,"read",t))throw new b(404,"not_found","run not found");if(o&&N(e)!==null&&N(e)!==s.grantee)throw new b(403,"other_app_run","cannot change another app's run");return await Y(t,s.grantee,n)}d(Pe,"requireRun");async function oe(e,t,o){return o===void 0?await W(e,t,`crtr:objects:read:${t}`):await f(e,"read",o)}d(oe,"canReadNode");const z=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"&&F())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 p(t),t.class==="anonymous"||t.class==="machine"||t.class==="import"||y(t))return;if(t.class==="person")return await re(e,t,o);const n=await $(t);if(e.scope&&(!_(n,e.scope)||C(t)&&!_(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=z.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,z.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 A(o.request_id):o.ticket_id?await O(o.ticket_id):null,r=o.comment_id?await v(o.comment_id):null,a=o.review_id?await g(o.review_id).catch(()=>null):r?await g(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(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"&&(!_(n,"crtr:files:rw:user:.")||!_(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 A(o.request_id):o.ticket_id?await O(o.ticket_id):null,c=o.comment_id?await v(o.comment_id):null,h=o.review_id?await g(o.review_id):c?await g(c.review_id):null,m=i?.requester_node_id??h?.origin_node_id;if(m!=null){const l=await w(m);if(l&&(a?!await oe(t,l.grantee??"app:terminal",m):l.grantee!==t.app))throw new u(a?404:403,a?"not_found":"other_app_run","human request belongs to another app");if(l&&!a&&!await f(t,"read",m))throw new u(404,"not_found","human request not found")}else if(i||h)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(!_(e,t))throw new I("the bearer token",t)}d(ie,"assertCeiling");function ce(){return new u(403,"owner_only","this operation is owner-only; a scoped token does not reach it")}d(ce,"ownerOnlyError");const fe="Crtr-Caused-By",he=/^(?:message|request|cron_run):[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;function we(e){const t=e[fe.toLowerCase()];return typeof t=="string"&&he.test(t)?t:void 0}d(we,"causedByOf");function je(e){return e.map(t=>({...t,ownerOnly:!0}))}d(je,"ownerOnly");class He{static{d(this,"Router")}routes=[];register(t){const o=K(t.method,t.pattern);if(!o)throw new Error(`route has no operation row: ${t.method} ${t.pattern}`);if(this.routes.some(n=>n.method===t.method.toUpperCase()&&n.operation.path===t.pattern))throw new Error(`duplicate route: ${t.method} ${t.pattern}`);return this.routes.push({operation:o,method:t.method.toUpperCase(),segments:G(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=G(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){P(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(E){const B=E instanceof U?"payload_too_large":"invalid_request";P(o,B==="payload_too_large"?413:400,B,E.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 h=we(t.headers),m={...h===void 0?{}:{causedBy:h},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},l=await i.handler(m);o.writableEnded||le(o,l)}catch(r){if(r instanceof Error&&r.code==="person_unresolved"){q(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&&D({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??""}}),q(o,a,i)}}}function G(e){return e.split("/").filter(t=>t.length>0)}d(G,"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 U 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 U(`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 q(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(q,"writeJson");function P(e,t,o,n){q(e,t,{error:{code:o,message:n,origin:"runtime"}})}d(P,"writeError");export{fe as CAUSED_BY_HEADER,He as Router,y as actsAsPerson,k as appOf,ie as assertCeiling,oe as canReadNode,Ue as canReadRun,we as causedByOf,f as mayOnNode,je as ownerOnly,ce as ownerOnlyError,Ge as readableNodeIds,Pe as requireRun,$ as resolvedScopes,N as runCallerApp};
|
|
@@ -29,8 +29,7 @@ export interface ApiServer {
|
|
|
29
29
|
export declare function buildRouter(tcpAddress: () => string | null): Router;
|
|
30
30
|
export type SocketPrincipal = RequestPrincipal;
|
|
31
31
|
export declare function socketPrincipal(req: IncomingMessage): SocketPrincipal | undefined;
|
|
32
|
-
/** Close one http.Server. Without `graceMs` every connection drops at once. With it, new connections are refused,
|
|
33
|
-
* (attach) sockets close with 1001 at once, idle keep-alives are dropped as they appear, and in-flight requests run until
|
|
32
|
+
/** Close one http.Server. Every upgraded socket is destroyed at once, with or without `graceMs`. Without `graceMs` every other connection drops at once. With it, new connections are refused, idle keep-alives are dropped as they appear, and in-flight requests run until
|
|
34
33
|
* they end or `graceMs` passes; then every remaining connection is dropped. */
|
|
35
34
|
export declare function closeServer(server: HttpServer | HttpsServer, upgraded: ReadonlySet<Duplex>, graceMs?: number): Promise<void>;
|
|
36
35
|
/** Create and start the crtrd API server. Returns immediately with a `close()`
|