@north-light/cli 0.3.735 → 0.3.737

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.
@@ -3,5 +3,10 @@ import { type SignInPrompt } from '../../core/directory/person-credential.js';
3
3
  export declare function showSignIn(prompt: SignInPrompt & {
4
4
  complete: string;
5
5
  }): void;
6
+ /** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
7
+ * The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
8
+ export declare function registerFreshComputer(directoryUrl: string): Promise<{
9
+ account: string;
10
+ }>;
6
11
  export declare const sysSigninLeaf: import("../../core/command.js").LeafDef;
7
12
  export declare const sysSignoutLeaf: import("../../core/command.js").LeafDef;
@@ -1,2 +1,2 @@
1
- var y=Object.defineProperty;var r=(e,n)=>y(e,"name",{value:n,configurable:!0});import{spawn as c}from"node:child_process";import{mkdirSync as k,openSync as _}from"node:fs";import{dirname as d,join as b}from"node:path";import{defineLeaf as h}from"../../core/command.js";import{CrtrError as u}from"../../core/errors.js";import{signIn as m,signOut as T}from"../../core/directory/person-credential.js";import{moveRecordPath as N,readMachineConfig as l}from"../../daemon/machine-link/config.js";import{sanitizedDaemonEnv as U,spawnDaemon as p,stopAllDaemons as g}from"../../daemon/manage.js";import{northlightUnreachable as S}from"../../core/directory/reach.js";import{envNodeId as A}from"../../shared/env.js";import{ExitCode as f}from"../../types.js";import{insideBroker as v}from"./join.js";import{cliClient as C}from"../api-client.js";import{defaultDirectoryUrl as O,finishMove as $,registerThisMac as P,runMove as R,settleEarlierMove as E}from"./import/move.js";import{WAIT_FOR_PID_ENV as I}from"./import/start.js";function x(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{c(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}r(x,"openBrowser");function a(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
- `),x(e.complete)}r(a,"showSignIn");function D(e){return async n=>{let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(o){return S(o,e.apiUrl)}if(!t.ok)return t.status===404?new u("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,f.USAGE):new u("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,f.GENERAL,{next:"Retry `crtr sys signin`."})}}r(D,"sameAccountOnly");function w(e){const n=b(d(N()),"move.log");k(d(n),{recursive:!0});const t=_(n,"a",384),o=U();for(const s of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete o[s];o[I]=String(process.pid);const i=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];c(process.execPath,i,{detached:!0,stdio:["ignore",t,t],env:o}).unref()}r(w,"startDetachedMove");const M=r(e=>`Signed in as ${e}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`,"MOVING"),te=h({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",whenToUse:"the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, move this computer's records into it, and register it with the directory",guide:"Prints a code and opens the directory's confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account's move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account's machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,constraint:"Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails."}],outputKind:"object",effects:["Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.","On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account's result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.","On a moved computer: restarts the daemon so it reconnects to Northlight.","Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity."]},run:r(async e=>{const n=e.directoryUrl===void 0?O():String(e.directoryUrl),t=await E(a);if(t!==void 0)return v()?(w(void 0),{account:t.account.display,moving:!0}):(await $(t),{account:t.account.display,moved:!0});const o=l();if(o!==void 0){const{account:s}=await m(n,a,{accept:D(o)});return await P(n),await g(),await p(),{account:s}}const{account:i}=await m(n,a);return v()?(w(A()),{account:i,moving:!0}):(await R({directoryUrl:n,notify:null}),{account:i,moved:!0})},"run"),render:r(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${M(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function q(){return await g(),await p(),(await C({local:!0}).healthz()).signed_in===!1}r(q,"stopMovedComputer");const ne=h({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["Calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:r(async()=>{const{signedOut:e,revoked:n}=await T(),t=l()===void 0?!1:await q();return{signed_out:e,revoked:n,stopped:t}},"run"),render:r(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{a as showSignIn,te as sysSigninLeaf,ne as sysSignoutLeaf};
1
+ var A=Object.defineProperty;var i=(e,n)=>A(e,"name",{value:n,configurable:!0});import{spawn as f}from"node:child_process";import{mkdirSync as O,openSync as R}from"node:fs";import{dirname as w,join as P}from"node:path";import{defineLeaf as v}from"../../core/command.js";import{CrtrError as a}from"../../core/errors.js";import{controlPlaneUrl as U,personAccount as y,personBearer as k,readPersonCredential as _,signIn as u,signOut as C}from"../../core/directory/person-credential.js";import{hasLocalCanvas as x,moveRecordPath as I,readMachineConfig as b,readOrCreateInstallId as L,writeMachineConfig as D,writeMachineCredential as M}from"../../daemon/machine-link/config.js";import{probeDaemonHealth as j,sanitizedDaemonEnv as q,spawnDaemon as m,stopAllDaemons as l}from"../../daemon/manage.js";import{hostname as G}from"node:os";import{northlightUnreachable as g}from"../../core/directory/reach.js";import{envNodeId as B}from"../../shared/env.js";import{ExitCode as c}from"../../types.js";import{insideBroker as T}from"./join.js";import{defaultDirectoryUrl as F,finishMove as z,registerThisMac as N,runMove as H,settleEarlierMove as K}from"./import/move.js";import{WAIT_FOR_PID_ENV as J}from"./import/start.js";function V(e){const[n,t]=process.platform==="darwin"?["open",[e]]:["xdg-open",[e]];try{f(n,t,{stdio:"ignore",detached:!0}).on("error",()=>{}).unref()}catch{}}i(V,"openBrowser");function h(e){process.stderr.write(`Confirm this code at ${e.verificationUri}: ${e.userCode}
2
+ `),V(e.complete)}i(h,"showSignIn");function W(e){return async n=>{if(e.runId===void 0)return e.account===void 0||e.account.id===n.account.id?void 0:new a("signin_other_account",`This computer belongs to the Northlight account ${e.account.display}. Sign in to that account.`,c.USAGE);let t;try{t=await fetch(new URL(`/v1/imports/${e.runId}`,e.apiUrl),{headers:{authorization:`Bearer ${n.bearer}`},signal:AbortSignal.timeout(3e4)})}catch(r){return g(r,e.apiUrl)}if(!t.ok)return t.status===404?new a("signin_other_account",`This computer's crtr belongs to the Northlight account ${e.account?.display??"it was moved into"}. Sign in to that account.`,c.USAGE):new a("signin_unchecked",`the control plane did not say which account owns this computer (HTTP ${t.status}); nothing was written.`,c.GENERAL,{next:"Retry `crtr sys signin`."})}}i(W,"sameAccountOnly");function E(e){const n=P(w(I()),"move.log");O(w(n),{recursive:!0});const t=R(n,"a",384),r=q();for(const o of["CRTR_API_SOCKET","CRTR_API_TOKEN","CRTR_API_URL"])delete r[o];r[J]=String(process.pid);const s=[...process.execArgv,process.argv[1],"sys","import","start","--kind","machine",...e===void 0?[]:["--notify",e]];f(process.execPath,s,{detached:!0,stdio:["ignore",t,t],env:r}).unref()}i(E,"startDetachedMove");async function Q(e){const n=_()===void 0?(await u(e,h),await y(e)):await y(e),t=await U(e),r=await k(e),s=i(async S=>{try{return await fetch(new URL(`/v1/machines${S?"?rotate=1":""}`,t),{method:"POST",headers:{authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({install_id:L(),name:G().slice(0,64)}),signal:AbortSignal.timeout(3e4)})}catch($){throw g($,t)}},"post");let o=await s(!1);o.status===409&&(await o.clone().text()).includes("credential_exists")&&(o=await s(!0));const p=await o.text();if(!o.ok)throw new a("machine_registration_failed",`Northlight refused to register this computer (HTTP ${o.status}): ${p.slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signin` again."});const d=JSON.parse(p);if(typeof d.credential!="string"||typeof d.environment_id!="string")throw new a("machine_registration_failed","Northlight answered without a credential",c.GENERAL);return M(d.credential),D({apiUrl:t,environmentId:d.environment_id,directoryUrl:e,account:n}),await N(e),await l(),await m(),{account:n.display}}i(Q,"registerFreshComputer");const X=i(e=>`Signed in as ${e}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`,"MOVING"),fe=v({name:"signin",description:"sign this computer's crtr in to the person's Northlight account and register it as one of their machines",whenToUse:"the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in` or `move_unfinished`",help:{name:"sys signin",summary:"pair this computer with the person's Northlight account in the browser, move this computer's records into it, and register it with the directory",guide:"Prints a code and opens the directory's confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. On a computer whose records are still local it then moves them into the account: run from a terminal it prints each step and returns when done; run from inside a node it returns at once and the node is messaged when the move finishes or fails. A computer already moved accepts only the account it moved into. For an unfinished move (`move_unfinished`), it checks the account's move result and finishes the switch-over if the records arrived. If the stored sign-in is missing or revoked, it first pairs only the account recorded for that move. Until the result is known, agents remain paused. Once the records are in the account the computer is also registered as one of the account's machines: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.",params:[{kind:"flag",name:"directory-url",type:"string",required:!1,constraint:"Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in's, else Northlight's."}],output:[{name:"account",type:"string",required:!0,constraint:"The account this computer is now signed in as."},{name:"moved",type:"boolean",required:!1,constraint:"Present when this command moved the records, or finished an earlier move's switch-over."},{name:"moving",type:"boolean",required:!1,constraint:"Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails."}],outputKind:"object",effects:["Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.","On a computer whose records are local: the move of `crtr sys import start --kind machine` (drains the daemon, uploads, restarts it in machine role); a move confirmed failed before the account holds the records ends the drain and signs this computer out again. If the account's result is unknown, the move record and drain remain for recovery. From inside a node it runs as a detached process logging to `runtime/import/move.log`.","On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.","On a moved computer: restarts the daemon so it reconnects to Northlight.","Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity."]},run:i(async e=>{const n=e.directoryUrl===void 0?F():String(e.directoryUrl),t=await K(h);if(t!==void 0)return T()?(E(void 0),{account:t.account.display,moving:!0}):(await z(t),{account:t.account.display,moved:!0});const r=b();if(r!==void 0){const{account:o}=await u(n,h,{accept:W(r)});return await N(n),await l(),await m(),{account:o}}if(!x())return await Q(n);const{account:s}=await u(n,h);return T()?(E(B()),{account:s,moving:!0}):(await H({directoryUrl:n,notify:null}),{account:s,moved:!0})},"run"),render:i(e=>e.moving===!0?`<signin account="${e.account}" moving="true">${X(String(e.account))}</signin>`:`<signin account="${e.account}"${e.moved===!0?' moved="true"':""}/>`,"render")});async function Y(){return await l(),await m(),(await j()).signed_in===!1}i(Y,"stopMovedComputer");async function Z(e){if(_()===void 0)return;const n=await k(e.directoryUrl);let t;try{t=await fetch(new URL(`/v1/machines/${e.environmentId}`,e.apiUrl),{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:AbortSignal.timeout(3e4)})}catch(r){throw g(r,e.apiUrl)}if(!t.ok&&t.status!==404)throw new a("machine_revoke_failed",`Northlight refused to revoke this computer's machine credential (HTTP ${t.status}): ${(await t.text()).slice(0,300)}`,c.GENERAL,{next:"Run `crtr sys signout` again."})}i(Z,"revokeMachine");const we=v({name:"signout",description:"sign this computer's crtr out, revoke its credential, and stop its agents",whenToUse:"this computer should stop acting as the person on Northlight, or its stored sign-in may have leaked",help:{name:"sys signout",summary:"revoke the stored credential, delete it from this computer, and on a moved computer stop every agent and cron here",params:[],output:[{name:"signed_out",type:"boolean",required:!0,constraint:"False when no sign-in was stored."},{name:"revoked",type:"boolean",required:!0,constraint:"True when the directory ended the credential now; false when it was already ended or none was stored."},{name:"stopped",type:"boolean",required:!0,constraint:"True when this computer's records are in Northlight and its agents and running crons have stopped; false on a computer whose records are local, where nothing else is tied to the sign-in."}],outputKind:"object",effects:["On a fleet machine first calls `DELETE /v1/machines/<environment>` with the stored sign-in, which ends the machine credential (no running daemon needed). Then calls `POST /v1/developer/token/revoke` with the stored secret, then deletes `runtime/secrets/person-credential` and `person-bearer.json`. A bearer already issued stays valid for at most 5 minutes.","On a computer whose records are in Northlight: restarts the daemon, which stops every agent and running cron here and takes no new work until `crtr sys signin`; agents keep their mail on Northlight and wake after it. Commands answer `not_signed_in`."]},run:i(async()=>{const e=b();e!==void 0&&await Z(e);const{signedOut:n,revoked:t}=await C(),r=e===void 0?!1:await Y();return{signed_out:n,revoked:t,stopped:r}},"run"),render:i(e=>`<signout signed_out="${e.signed_out}" revoked="${e.revoked}" stopped="${e.stopped}"/>`,"render")});export{Q as registerFreshComputer,h as showSignIn,fe as sysSigninLeaf,we as sysSignoutLeaf};
@@ -111,6 +111,8 @@ export declare function grantsOfPerson(person: string): Promise<Array<Pick<Grant
111
111
  export declare function grantExpired(grant: Pick<GrantRecord, 'expires_at'>): boolean;
112
112
  /** The active form of a grant record read earlier, or null when it is not active, is past `expires_at`, or is unparsable. */
113
113
  export declare function activeRecord(grant: GrantRecord): ActiveGrant | null;
114
+ /** JSON with every object's keys sorted, at every depth, and arrays kept in order. */
115
+ export declare function canonicalJson(value: unknown): string;
114
116
  /** `grant.get`'s `version`: an opaque string that changes exactly when what an app
115
117
  * reads from its grant changes — `rev`, `resolved_scopes` (order kept), `spend_cap`,
116
118
  * `payer`, `inference_endpoint`, `dependencies`. `synced_at` and the token's claims are left out, so a
@@ -1,11 +1,11 @@
1
- var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";const $=["not_started","pending","ready","failed","unavailable"],F=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}t(v,"runtimeScope");async function i(e,r,n=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...n,...s.args)}t(i,"grantRows");async function u(e,r,n=[]){return(await i(e,r,n))[0]}t(u,"grantRow");function k(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}t(k,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!k(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}t(l,"entries");function U(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:n,next:s,step:o}=e;return typeof r!="string"||!$.includes(r)||n!==void 0&&typeof n!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...n===void 0?{}:{message:n},next:s,...o===void 0?{}:{step:o}}}t(U,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[n,s]of Object.entries(e)){const o=U(s);o&&(r[n]=o)}return r}t(O,"dependenciesOf");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:n}=e;if(typeof r!="string"||!r||!n||typeof n!="object"||Array.isArray(n))return null;const s={};for(const o of F){const a=n[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}t(G,"inferenceEndpointOf");function A(e,r,n,s){return r===e&&n&&s}t(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?G(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}t(f,"record");function d(e){if(!e||e.status!=="active")return null;try{return q(f(e))}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}t(_,"mirrorOnly");async function ne(){return(await J()).filter(e=>!_(e))}t(ne,"localGrants");async function te(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}t(te,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",H=new RegExp(`^(${y}):(${y})$`);function W(e){const r=new Set;for(const n of e)if(n.status==="active")for(const{scope:s}of n.resolved_scopes){const o=H.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}t(W,"providerIdsFromGrants");async function se(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
1
+ var R=Object.defineProperty;var n=(e,r)=>R(e,"name",{value:r,configurable:!0});import{createHash as D}from"node:crypto";import{parseScope as L}from"@north-light/identity";import{openDb as p,withCanvasWrite as T}from"../canvas/db.js";import{isUnsandboxedMachine as N}from"../runtime/unsandboxed.js";import{replaceWrittenBy as I,userSubject as C}from"../permissions/facts.js";import{GROUP_TYPE as M}from"../permissions/builtin.js";import{shadowCheck as $}from"./shadow.js";const F=["not_started","pending","ready","failed","unavailable"],k=["ultra","strong","medium","light"];function v(){const e=process.env.CRTR_RUNTIME;return e?{sql:" AND runtime = ?",args:[e]}:{sql:"",args:[]}}n(v,"runtimeScope");async function i(e,r,t=[]){const s=v();return await(await p()).prepare(`SELECT ${e} FROM grants WHERE (${r})${s.sql}`).all(...t,...s.args)}n(i,"grantRows");async function u(e,r,t=[]){return(await i(e,r,t))[0]}n(u,"grantRow");function U(e){return!/\u0000|[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/.test(e)}n(U,"jsonbSafe");function l(e){if(!Array.isArray(e))throw new TypeError("grant scopes must be a list");return e.map(r=>{if(!r||typeof r!="object"||typeof r.scope!="string"||!U(r.scope)||!["always","ask"].includes(r.mode))throw new TypeError("invalid grant scope entry");return{scope:r.scope,mode:r.mode}})}n(l,"entries");function G(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{state:r,message:t,next:s,step:o}=e;return typeof r!="string"||!F.includes(r)||t!==void 0&&typeof t!="string"||o!==void 0&&typeof o!="string"||typeof s!="string"||!s?null:{state:r,...t===void 0?{}:{message:t},next:s,...o===void 0?{}:{step:o}}}n(G,"dependencyOf");function O(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const r={};for(const[t,s]of Object.entries(e)){const o=G(s);o&&(r[t]=o)}return r}n(O,"dependenciesOf");function H(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const{base_url:r,rungs:t}=e;if(typeof r!="string"||!r||!t||typeof t!="object"||Array.isArray(t))return null;const s={};for(const o of k){const a=t[o];typeof a=="string"&&a&&(s[o]=a)}return Object.keys(s).length?{base_url:r.replace(/\/+$/,""),rungs:s}:null}n(H,"inferenceEndpointOf");function A(e,r,t,s){return r===e&&t&&s}n(A,"computedFor");function f(e){if(!A(e.rev,e.computed_rev,e.scopes_json!==null,e.resolved_scopes_json!==null))throw new TypeError("grant columns are not computed for this revision");return{id:e.id,runtime:e.runtime,sub:e.sub,grantee:e.grantee,rev:e.rev,scopes:l(JSON.parse(e.scopes_json)),resolved_scopes:l(JSON.parse(e.resolved_scopes_json)),spend_cap:e.spend_cap,expires_at:e.expires_at,status:e.status,revoked_at:e.revoked_at,approved_at:e.approved_at,payer:e.payer,dependencies:O(JSON.parse(e.dependencies_json??"{}")),run_notice_url:e.run_notice_url??null,inference_endpoint:e.inference_endpoint_json?H(JSON.parse(e.inference_endpoint_json)):null,synced_at:e.synced_at??""}}n(f,"record");function d(e){if(!e||e.status!=="active")return null;try{const r=B(f(e));return r!==null&&$(r),r}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(d,"active");function _(e){return e.grantee!=="app:terminal"&&N()}n(_,"mirrorOnly");async function se(){return(await V()).filter(e=>!_(e))}n(se,"localGrants");async function ae(e,r){return!_({grantee:e})&&await u("1","grantee = ? AND sub <> ? AND status <> 'removed'",[e,r])!==void 0}n(ae,"otherLiveGrantOfApp");const y="[A-Za-z0-9_-]{1,64}",W=new RegExp(`^(${y}):(${y})$`);function P(e){const r=new Set;for(const t of e)if(t.status==="active")for(const{scope:s}of t.resolved_scopes){const o=W.exec(s);o&&o[1]!=="crtr"&&r.add(o[1])}return[...r].sort()}n(P,"providerIdsFromGrants");async function oe(){const e=v();return(await(await p()).prepare(`SELECT DISTINCT m[1] AS id FROM (
2
2
  SELECT DISTINCT e->>'scope' AS scope FROM (
3
3
  SELECT t::jsonb AS j FROM (SELECT DISTINCT resolved_scopes_json AS t FROM grants WHERE ${m}${x()}${e.sql}) d OFFSET 0) p
4
4
  CROSS JOIN LATERAL jsonb_array_elements(CASE WHEN jsonb_typeof(p.j) = 'array' THEN p.j ELSE '[]' END) e) s
5
5
  CROSS JOIN LATERAL regexp_match(s.scope, '^(${y}):${y}$') m
6
- WHERE m[1] <> 'crtr'`).all(...e.args)).map(n=>n.id).sort()}t(se,"activeProviderIds");async function ae(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}t(ae,"anyActiveGrant");async function oe(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
6
+ WHERE m[1] <> 'crtr'`).all(...e.args)).map(t=>t.id).sort()}n(oe,"activeProviderIds");async function ce(){const e=v();return await(await p()).prepare(`SELECT 1 FROM grants WHERE ${m}${x()}${e.sql} LIMIT 1`).get(...e.args)!==void 0}n(ce,"anyActiveGrant");async function ie(e,r){return await u("1",`sub = ? AND ${m}${x()} AND EXISTS (
7
7
  SELECT 1 FROM jsonb_array_elements(CASE WHEN jsonb_typeof(resolved_scopes_json::jsonb) = 'array' THEN resolved_scopes_json::jsonb ELSE '[]' END) e
8
- WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}t(oe,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",P="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}t(x,"localOnly");async function ce(){return(await i("DISTINCT sub",P)).map(e=>e.sub)}t(ce,"grantSubs");async function ie(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}t(ie,"activeGrants");async function ue(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(W(r.flatMap(n=>{try{return[f(n)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}t(ue,"grantedProviderIds");function pe(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}t(pe,"isProviderBundleRow");async function de(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(n=>{const s=d(n);return s===null?[]:[s]})}t(de,"activeGrantsOfPerson");async function J(){return j(await i("*","true"))}t(J,"allGrants");async function le(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(n=>{if(!A(n.rev,n.computed_rev,n.has_scopes,n.resolved_scopes_json!==null))return[];try{return[{sub:n.sub,status:n.status,resolved_scopes:l(JSON.parse(n.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}t(le,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return[];throw n}})}t(j,"records");function V(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}t(V,"grantExpired");function q(e){if(e.status!=="active"||V(e))return null;try{const r=e.resolved_scopes.map(({scope:n})=>L(n));return{...e,resolved:e.resolved_scopes.flatMap(({mode:n},s)=>n==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}t(q,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}t(S,"canonicalJson");function fe(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}t(fe,"grantVersion");async function _e(e){return!!await u("1","id = ?",[e])}t(_e,"hasGrant");async function ye(e){return await u("rev, status","id = ?",[e])??null}t(ye,"grantSyncState");async function Ee(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}t(Ee,"grantSyncStateFor");async function B(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(n){if(n instanceof TypeError||n instanceof SyntaxError)return null;throw n}}t(B,"grantRecord");async function ge(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const n={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...n,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...n,standing:"lagging",record:null};const s=d(r);return s===null?{...n,standing:"inactive",record:null}:{...n,standing:"active",record:s}}t(ge,"grantStanding");async function ve(e){return(await i("id",e)).map(r=>r.id)}t(ve,"grantIdsWhere");async function me(e){return(e?(await B(e))?.payer:null)??"user"}t(me,"payerOfGrant");async function X(e){return d(await u("*","id = ?",[e]))}t(X,"activeGrant");async function xe(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}t(xe,"grantFor");async function Se(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}t(Se,"activeGrantForApp");async function Te(e){const r=await X(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}t(Te,"runNoticeTarget");async function Ne(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}t(Ne,"terminalGrant");async function Oe(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}t(Oe,"grantsSource");async function Ae(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}t(Ae,"hasSyncedGrants");async function je(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}t(je,"dropLocalGrantMirror");async function we(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}t(we,"backfillComputedRev");function be(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const n of e){const{team:s,members:o}=n??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}t(be,"teamsOf");async function he(e,r,n,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
8
+ WHERE starts_with(e->>'scope', ?))`,[e,`${r}:`])!==void 0}n(ie,"activeGrantNamesApp");const m="status = 'active' AND computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL",J="computed_rev = rev AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL";function x(){return N()?" AND grantee = 'app:terminal'":""}n(x,"localOnly");async function ue(){return(await i("DISTINCT sub",J)).map(e=>e.sub)}n(ue,"grantSubs");async function pe(e){return j(e===void 0?await i("*","status = 'active'"):await i("*","sub = ? AND status = 'active'",[e]))}n(pe,"activeGrants");async function de(e){const r=await i("*","sub = ? AND status = 'active'",[e]);return new Set(P(r.flatMap(t=>{try{return[f(t)]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})))}n(de,"grantedProviderIds");function le(e,r){return e.source_marketplace===null&&e.source_path===null&&r.has(e.name)}n(le,"isProviderBundleRow");async function fe(e){return(await i("*","sub = ? AND status = 'active'",[e])).flatMap(t=>{const s=d(t);return s===null?[]:[s]})}n(fe,"activeGrantsOfPerson");async function V(){return j(await i("*","true"))}n(V,"allGrants");async function _e(e){return(await i("sub, status, rev, computed_rev, resolved_scopes_json, scopes_json IS NOT NULL AS has_scopes","sub = ?",[e])).flatMap(t=>{if(!A(t.rev,t.computed_rev,t.has_scopes,t.resolved_scopes_json!==null))return[];try{return[{sub:t.sub,status:t.status,resolved_scopes:l(JSON.parse(t.resolved_scopes_json))}]}catch(s){if(s instanceof TypeError||s instanceof SyntaxError)return[];throw s}})}n(_e,"grantsOfPerson");function j(e){return e.flatMap(r=>{try{return[f(r)]}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return[];throw t}})}n(j,"records");function q(e){return e.expires_at!==null&&!(Date.parse(e.expires_at)>Date.now())}n(q,"grantExpired");function B(e){if(e.status!=="active"||q(e))return null;try{const r=e.resolved_scopes.map(({scope:t})=>L(t));return{...e,resolved:e.resolved_scopes.flatMap(({mode:t},s)=>t==="always"?[r[s]]:[])}}catch(r){if(r instanceof TypeError||r instanceof SyntaxError)return null;throw r}}n(B,"activeRecord");function S(e){return Array.isArray(e)?`[${e.map(S).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().filter(r=>e[r]!==void 0).map(r=>`${JSON.stringify(r)}:${S(e[r])}`).join(",")}}`:JSON.stringify(e)??"null"}n(S,"canonicalJson");function ye(e){const r={rev:e.rev,resolved_scopes:e.resolved_scopes,spend_cap:e.spend_cap,payer:e.payer,dependencies:e.dependencies??{},...e.inference_endpoint?{inference_endpoint:e.inference_endpoint}:{}};return D("sha256").update(S(r)).digest("base64url").slice(0,22)}n(ye,"grantVersion");async function Ee(e){return!!await u("1","id = ?",[e])}n(Ee,"hasGrant");async function ge(e){return await u("rev, status","id = ?",[e])??null}n(ge,"grantSyncState");async function ve(e,r){return await u("rev, status","grantee = ? AND sub = ?",[e,r])??null}n(ve,"grantSyncStateFor");async function X(e){const r=await u("*","id = ?",[e]);if(!r)return null;try{return f(r)}catch(t){if(t instanceof TypeError||t instanceof SyntaxError)return null;throw t}}n(X,"grantRecord");async function me(e){const r=await u("*","id = ?",[e]);if(!r)return{standing:"inactive",rev:null,sub:null,grantee:null,status:null,removal_done_at:null,record:null};const t={rev:r.rev,sub:r.sub,grantee:r.grantee,status:r.status,removal_done_at:r.removal_done_at??null};if(r.status!=="active")return{...t,standing:"inactive",record:null};if(r.computed_rev!==r.rev)return{...t,standing:"lagging",record:null};const s=d(r);return s===null?{...t,standing:"inactive",record:null}:{...t,standing:"active",record:s}}n(me,"grantStanding");async function xe(e){return(await i("id",e)).map(r=>r.id)}n(xe,"grantIdsWhere");async function Se(e){return(e?(await X(e))?.payer:null)??"user"}n(Se,"payerOfGrant");async function z(e){return d(await u("*","id = ?",[e]))}n(z,"activeGrant");async function Te(e,r){return d(await u("*","grantee = ? AND sub = ?",[e,r]))}n(Te,"grantFor");async function Ne(e){if(_({grantee:e}))return null;const r=await i("*","grantee = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active grants for ${e}`);return d(r[0])}n(Ne,"activeGrantForApp");async function Oe(e){const r=await z(e);return r&&r.run_notice_url&&!_(r)?{url:r.run_notice_url,sub:r.sub,grantee:r.grantee}:null}n(Oe,"runNoticeTarget");async function Ae(e){const r=await i("*","grantee = 'app:terminal' AND sub = ? AND status = 'active'",[e]);if(r.length>1)throw new Error(`multiple active terminal grants for ${e}`);return d(r[0])}n(Ae,"terminalGrant");async function je(){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value??null}n(je,"grantsSource");async function we(e){return(await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value===e}n(we,"hasSyncedGrants");async function be(e){return(await e.prepare("SELECT value FROM runtime_state WHERE key = 'grants_source'").get())?.value!=="local"?0:(await e.prepare("DELETE FROM runtime_state WHERE key = 'grants_source'").run(),Number((await e.prepare("DELETE FROM grants").run()).changes))}n(be,"dropLocalGrantMirror");async function he(){return await T(async e=>Number((await e.prepare("UPDATE grants SET computed_rev = rev WHERE computed_rev IS NULL AND scopes_json IS NOT NULL AND resolved_scopes_json IS NOT NULL").run()).changes))}n(he,"backfillComputedRev");function Re(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("invalid grant sync response");const r=[];for(const t of e){const{team:s,members:o}=t??{};if(!(typeof s!="string"||!/^team:\S+$/.test(s))){if(!Array.isArray(o)||o.some(a=>typeof a!="string"||!/^user:[^\s*]+$/.test(a)))throw new TypeError("invalid grant sync response");r.push({team:s,members:o})}}return r}n(Re,"teamsOf");async function De(e,r,t,s=[]){const o=new Set;for(const a of e){if(o.has(a.id)||!a.id||!a.runtime||!a.sub||!a.grantee||!Number.isInteger(a.rev)||!["active","revoked","removed"].includes(a.status))throw new TypeError("invalid grant sync response");o.add(a.id),l(a.scopes),l(a.resolved_scopes)}await T(async a=>{let E=0;const g=[...o];E+=Number((await(g.length?a.prepareUncached(`DELETE FROM grants WHERE id NOT IN (${g.map(()=>"?").join(",")})`).run(...g):a.prepareUncached("DELETE FROM grants").run())).changes);const w=a.prepare(`INSERT INTO grants
9
9
  (id, runtime, sub, grantee, rev, scopes_json, resolved_scopes_json, spend_cap, expires_at,
10
10
  status, revoked_at, approved_at, payer, dependencies_json, run_notice_url, inference_endpoint_json, synced_at, computed_rev)
11
11
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -19,4 +19,4 @@ var R=Object.defineProperty;var t=(e,r)=>R(e,"name",{value:r,configurable:!0});i
19
19
  grants.run_notice_url, grants.inference_endpoint_json, grants.computed_rev)
20
20
  IS DISTINCT FROM (excluded.runtime, excluded.sub, excluded.grantee, excluded.rev, excluded.scopes_json, excluded.resolved_scopes_json,
21
21
  excluded.spend_cap, excluded.expires_at, excluded.status, excluded.revoked_at, excluded.approved_at, excluded.payer,
22
- excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(n),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}t(he,"replaceGrants");async function Re(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}t(Re,"grantsGeneration");export{X as activeGrant,Se as activeGrantForApp,oe as activeGrantNamesApp,ie as activeGrants,de as activeGrantsOfPerson,se as activeProviderIds,q as activeRecord,J as allGrants,ae as anyActiveGrant,we as backfillComputedRev,O as dependenciesOf,je as dropLocalGrantMirror,V as grantExpired,xe as grantFor,ve as grantIdsWhere,B as grantRecord,ge as grantStanding,ce as grantSubs,ye as grantSyncState,Ee as grantSyncStateFor,fe as grantVersion,ue as grantedProviderIds,Re as grantsGeneration,le as grantsOfPerson,Oe as grantsSource,_e as hasGrant,Ae as hasSyncedGrants,G as inferenceEndpointOf,pe as isProviderBundleRow,ne as localGrants,_ as mirrorOnly,te as otherLiveGrantOfApp,me as payerOfGrant,W as providerIdsFromGrants,he as replaceGrants,Te as runNoticeTarget,v as runtimeScope,be as teamsOf,Ne as terminalGrant};
22
+ excluded.dependencies_json, excluded.run_notice_url, excluded.inference_endpoint_json, excluded.computed_rev)`);for(const c of e)E+=Number((await w.run(c.id,c.runtime,c.sub,c.grantee,c.rev,JSON.stringify(c.scopes),JSON.stringify(c.resolved_scopes),c.spend_cap,c.expires_at,c.status,c.revoked_at,c.approved_at,c.payer,JSON.stringify(O(c.dependencies)),c.run_notice_url??null,c.inference_endpoint?JSON.stringify(c.inference_endpoint):null,c.synced_at,c.rev)).changes);await I(a,"directory",M,"member",s.flatMap(({team:c,members:b})=>b.map(h=>({resourceId:c,subject:C(h)})))),await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_source', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t),E>0&&await a.prepare("INSERT INTO runtime_state (key, value) VALUES ('grants_generation', '1') ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(runtime_state.value AS INTEGER) + 1 AS TEXT)").run()})}n(De,"replaceGrants");async function Le(){const e=await(await p()).prepare("SELECT value FROM runtime_state WHERE key = 'grants_generation'").get();return e?Number(e.value):0}n(Le,"grantsGeneration");export{z as activeGrant,Ne as activeGrantForApp,ie as activeGrantNamesApp,pe as activeGrants,fe as activeGrantsOfPerson,oe as activeProviderIds,B as activeRecord,V as allGrants,ce as anyActiveGrant,he as backfillComputedRev,S as canonicalJson,O as dependenciesOf,be as dropLocalGrantMirror,q as grantExpired,Te as grantFor,xe as grantIdsWhere,X as grantRecord,me as grantStanding,ue as grantSubs,ge as grantSyncState,ve as grantSyncStateFor,ye as grantVersion,de as grantedProviderIds,Le as grantsGeneration,_e as grantsOfPerson,je as grantsSource,Ee as hasGrant,we as hasSyncedGrants,H as inferenceEndpointOf,le as isProviderBundleRow,se as localGrants,_ as mirrorOnly,ae as otherLiveGrantOfApp,Se as payerOfGrant,P as providerIdsFromGrants,De as replaceGrants,Oe as runNoticeTarget,v as runtimeScope,Re as teamsOf,Ae as terminalGrant};
@@ -0,0 +1,15 @@
1
+ import { type GrantRecord } from './mirror.js';
2
+ /** Test hook: how long a cached answer is used before its epochs are re-checked. */
3
+ export declare function setShadowTtl(ms: number): void;
4
+ /** Test hook: forget every cached answer. */
5
+ export declare function resetShadowCache(): void;
6
+ /** How many checks agreed, disagreed (live answer differs at the same rev), lagged (live rev differs: a sync has not landed) or failed since this process started. */
7
+ export declare const shadowCounts: {
8
+ agree: number;
9
+ disagree: number;
10
+ lagging: number;
11
+ error: number;
12
+ };
13
+ export declare function shadowIdle(): Promise<void>;
14
+ /** Compare one stored grant with the directory's live answer, in the background, on the fleet only. Never throws and never delays the caller. */
15
+ export declare function shadowCheck(stored: GrantRecord): void;
@@ -0,0 +1 @@
1
+ var S=Object.defineProperty;var a=(e,r)=>S(e,"name",{value:r,configurable:!0});import{directoryIssuer as $}from"../directory/issuer.js";import{outboundFetch as v}from"../events/outbound.js";import{warn as u}from"../output.js";import{canonicalJson as m}from"./mirror.js";let _=5e3;function O(e){_=e}a(O,"setShadowTtl");const k=512,A=["status","scopes","resolved_scopes","spend_cap","payer","dependencies","run_notice_url","inference_endpoint"];function R(){i.clear()}a(R,"resetShadowCache");const i=new Map,f=new Map,t={agree:0,disagree:0,lagging:0,error:0};async function M(e,r,n){const{mintDirectoryToken:s}=await import("./sync.js"),o=await s(e),g=n?`&epochs=${n.epochs.global},${n.epochs.sub}`:"",y=`${e}/v1/runtime/grant-answers?sub=${encodeURIComponent(r)}${g}`,d=await v("grant_shadow",y,{headers:{Authorization:`Bearer ${o.access_token}`},signal:AbortSignal.timeout(1e4)});if(!d.ok)throw new Error(`grant-answers ${d.status}`);const l=await d.json();if(l.unchanged){if(!n)throw new Error("grant-answers said unchanged to a caller holding nothing");return{...n,epochs:l.epochs,checkedAt:Date.now()}}return{epochs:l.epochs,grants:new Map((l.grants??[]).map(w=>[String(w.id),w])),checkedAt:Date.now()}}a(M,"fetchAnswer");async function x(e,r){const n=i.get(r);if(n&&Date.now()-n.checkedAt<_)return n;const s=f.get(r);if(s)return s;const o=M(e,r,n).then(g=>(i.delete(r),i.set(r,g),i.size>k&&i.delete(i.keys().next().value),g)).finally(()=>f.delete(r));return f.set(r,o),o}a(x,"answerFor");const h=new Set;async function T(){await Promise.all([...h])}a(T,"shadowIdle");async function C(e){const r=$();if(r===null)return;const n=(await x(r,e.sub)).grants.get(e.id);if(!n){t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,fields:["missing"]})}`);return}if(n.rev!==e.rev){t.lagging++;return}const s=A.filter(o=>m(n[o]??null)!==m(e[o]??null));if(s.length===0){t.agree++;return}t.disagree++,u(`grant_shadow disagree ${JSON.stringify({grant:e.id,sub:e.sub,rev:e.rev,fields:s})}`)}a(C,"compare");let p,c={agree:0,disagree:0,lagging:0,error:0};function b(){p||(p=setInterval(()=>{const e={agree:t.agree-c.agree,disagree:t.disagree-c.disagree,lagging:t.lagging-c.lagging,error:t.error-c.error};c={...t},e.agree+e.disagree+e.lagging+e.error>0&&u(`grant_shadow_summary ${JSON.stringify({window_s:60,...e})}`)},6e4),p.unref())}a(b,"startSummary");function U(e){if(!process.env.CRTR_RUNTIME)return;b();const r=C(e).catch(n=>{t.error++,u(`grant_shadow error ${JSON.stringify({grant:e.id,message:n instanceof Error?n.message:String(n)})}`)}).finally(()=>h.delete(r));h.add(r)}a(U,"shadowCheck");export{R as resetShadowCache,O as setShadowTtl,U as shadowCheck,t as shadowCounts,T as shadowIdle};
@@ -186,8 +186,8 @@ export declare const chartDataRowsSchema: z.ZodArray<z.ZodRecord<z.ZodString, z.
186
186
  export declare const chartConfigSchema: z.ZodObject<{
187
187
  kind: z.ZodEnum<{
188
188
  line: "line";
189
- bar: "bar";
190
189
  area: "area";
190
+ bar: "bar";
191
191
  }>;
192
192
  x: z.ZodString;
193
193
  y: z.ZodArray<z.ZodObject<{
@@ -1,3 +1,3 @@
1
- var V=Object.defineProperty;var l=(e,s)=>V(e,"name",{value:s,configurable:!0});import{zstdCompressSync as X}from"node:zlib";import{blobStore as Z}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as x}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as M,decodeRows as ne,rowKeys as N,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as L,encodeKeys as B}from"./copy.js";import{pruneStaged as re,precheck as oe,renameClashingLegacyCharges as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,dropRefusedMessages as _e,checkSourcePerson as we,checkStagedBlobKeys as ge,checkStagedPersons as be,checkStagedReferences as he,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Se,deleteRunPrefix as ve,moveRunBlobs as Re}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Te,renameClashingRepos as je,rewriteIds as ke,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as W,ImportLaneError as g,stage as De,stagingSchema as Me,targetSchema as Ne}from"./stage.js";import{verifyRun as Le}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as We}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ke,recordImportedActivations as Ue,writeStores as Fe}from"./stores.js";import{openImportGrants as Je}from"./open-grants.js";import{publishImportedPlugins as Ge}from"./publish-plugins.js";import{COPIED_TABLES as qe}from"../bundle/layout.js";import{emitEvent as $e}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const ze=10*6e4,Qe=30*6e4,R=l(()=>new Date().toISOString(),"now"),H=l(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Ve(e,s){const a=await e.get(M.source(s));if(a===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(a.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}l(Ve,"readSource");async function Xe(e,s,a,n,i,p,d){const o=[];for(const t of N(a.run_id,"grants",n)){const u=await e.get(t);if(u===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(u))}if(o.length===0)return;const w=o.map(t=>({sub:me(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const f=[];for(const t of w)await Oe(s,i,p,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Pe(f)}l(Xe,"ensureGrants");async function It(e,s,a={}){const n=a.blobs??await Z(),i=await v(),p=Me(e.run_id);let d="start";const o=l(async t=>{d=t,await s.assertOwned(),await H(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Ve(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const u=await Ne(i),I=[...qe],b=await ie(i,u,[...I,"grants"]);if(!w){const m={},P=[],T=[],j=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await we(i,u,t.person,e.person),await o("open-grants"),await Xe(n,i,e,t,u,j,a.openGrants??Je),await o("publish-plugins");const U=await Ke(n,e.run_id),E=await x(e.person,()=>Ge(U));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=ze)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await H(e.run_id,"waiting_for_directory");return}T.push(...E.refused),await o("stage");const F=await De(i,e.run_id,t.counts,r=>N(e.run_id,r,t),r=>n.get(r));for(const[r,c]of Object.entries(F))m[r]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:u,catalog:b,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,c]of Object.entries(await be(_)))h(m,r,c);for(const[r,c]of Object.entries(await ge(_)))h(m,r,c);await o("rewrite-person"),await Ce(_),await Ae(_),await o("prune");const J=await re(i,p,b,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(i,p,S),await ue(i,p,S,n,e.run_id),await le(i,p),await ye(_);const G=await Te(_);await pe(i,p,u,t.installId,e.person),await o("rewrite-ids");const k=await ke(_,G);await o("drop");const q=await fe(i,p,u),$=await Ie(_);for(const[r,c]of Object.entries({...J}))h(m,r,c);for(const[r,c]of Object.entries($))h(m,r,c);for(const[r,c]of Object.entries(await _e(_,{installId:t.installId,person:e.person,runId:e.run_id})))h(m,r,c);await he(_,{installId:t.installId,person:e.person,runId:e.run_id}),await je(_),await de(i,p,u,t.installId),await o("pre-check");const Y=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,u,b,I,new Set,Y),await o("blobs"),await Re(i,p,u,e.person,n,e.run_id,f),await o("copy"),await D(async r=>{await s.assertOwned({extendLeaseMs:Qe});const c=await se({db:r,runId:e.run_id,schema:p,target:u,catalog:b,source:t,person:e.person,idMap:k,pathMap:S}),C=await et(r,e.run_id,q);C>0&&(c.inserted.revisions=(c.inserted.revisions??0)+C),await We(r,p,e.run_id,t);const A=await Fe({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[z,Q]of Object.entries(A.inserted))c.inserted[z]=Q.length;return P.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...xe(m,c),unresolved_plugins:P,refused_plugins:T}),R(),e.run_id),c}),w=!0,await a.atStep?.("committed")}await o("verify");const y=await Le(i,e.run_id,p,u,b,t.installId);if(await i.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=M.manifest(e.run_id);await n.put(O,await tt(e.run_id)),await W(i,e.run_id);for(const m of He(e.run_id))await n.delete(m);await Se(n,e.run_id),await D(async m=>{await Ue(m,e.run_id,e.person),await m.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof Ye)throw t;const u=Ze(t,d);$e({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:u.step,code:u.code}}),await W(i,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await ve(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}l(It,"processRun");function Ze(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}l(Ze,"failureOf");function h(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}l(h,"addDropped");function xe(e,s){for(const[a,n]of Object.entries(s.inserted))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[a,n]of Object.entries(s.mapped))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}l(xe,"withInserted");async function et(e,s,a){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(a.map(d=>d.rev_id)))).map(d=>d.rev_id)),i=a.filter(d=>!n.has(d.rev_id)),p=new Map;for(const d of a)p.set(d.document,[...p.get(d.document)??[],d]);for(const[d,o]of p){const w=await te(e,d);w!==null&&await ee(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await K(e,s,"revisions",i.map(d=>[d.rev_id])),await K(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}l(et,"arrive");async function K(e,s,a,n){if(n.length===0)return;const i=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,a);i===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,a,B(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(B([...L(i.inserted_keys),...n]),s,a)}l(K,"appendManifest");async function tt(e){const a=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return X(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:L(n.inserted_keys)})).join(`
1
+ var X=Object.defineProperty;var l=(e,s)=>X(e,"name",{value:s,configurable:!0});import{zstdCompressSync as Z}from"node:zlib";import{blobStore as x}from"../../blobs/index.js";import{openDb as v,withCanvasWrite as D}from"../../canvas/db.js";import{runAsPerson as M}from"../../canvas/person.js";import{insertImportedRevisions as ee}from"../../graph/documents.js";import{getById as te}from"../../graph/objects.js";import{bundleKeys as N,decodeRows as ne,rowKeys as L,SEQ_TABLES as ae}from"../bundle/layout.js";import{readCatalog as ie}from"./catalog.js";import{copyRows as se,decodeKeys as B,encodeKeys as W}from"./copy.js";import{pruneStaged as re,precheck as oe,renameClashingLegacyCharges as de,renameClashingProfiles as pe,rewriteConversationHeaders as ue,rewritePaths as ce,rewriteRequestPaths as le,takeRepoSyncedDocuments as fe}from"./prepare.js";import{boundSub as me,dropRefusedMessages as _e,checkSourcePerson as we,checkStagedBlobKeys as ge,checkStagedPersons as be,checkStagedReferences as he,checkStagedRequestKeys as ye}from"./bind.js";import{deleteBlobs as Ee,deleteRunBlobs as Se,deleteRunPrefix as ve,moveRunBlobs as Re}from"./blobs.js";import{dropStubRows as Ie,findFleetGrant as Oe,grantMissing as Pe,mapProfileIds as Te,renameClashingRepos as je,rewriteIds as ke,rewritePerson as Ce,scopeRepoIdentities as Ae}from"./rewrite.js";import{dropStaging as H,ImportLaneError as g,stage as De,stagingSchema as Me,targetSchema as Ne}from"./stage.js";import{verifyRun as Le}from"./verify.js";import{sandboxPathMap as Be,writeNodeFiles as We}from"./path-map.js";import{allStoreKeys as He,readPluginsStore as Ke,recordImportedActivations as Ue,writeStores as Fe}from"./stores.js";import{openImportGrants as Je}from"./open-grants.js";import{publishImportedPlugins as Ge}from"./publish-plugins.js";import{COPIED_TABLES as qe}from"../bundle/layout.js";import{emitEvent as $e}from"../../events/emit.js";import{ClaimLostError as Ye}from"../../../daemon/reconcilers/row-claim.js";const ze=10*6e4,Qe=30*6e4,R=l(()=>new Date().toISOString(),"now"),K=l(async(e,s)=>{await(await v()).prepare("UPDATE import_runs SET step = ? WHERE run_id = ?").run(s,e)},"setStep");async function Ve(e,s){const a=await e.get(N.source(s));if(a===null)throw new g("stage","bundle_invalid","source.json is missing");const n=JSON.parse(a.toString("utf8"));if(typeof n.rowParts!="object"||n.rowParts===null)throw new g("stage","bundle_invalid","source.json names no row parts");return n}l(Ve,"readSource");async function Xe(e,s,a,n,i,p,d){const o=[];for(const t of L(a.run_id,"grants",n)){const u=await e.get(t);if(u===null)throw new g("stage","bundle_invalid",`row file ${t} is missing`);o.push(...ne(u))}if(o.length===0)return;const w=o.map(t=>({sub:me(t.sub,n.person,a.person,"grants.sub"),grantee:t.grantee}));await d(a.run_id);const f=[];for(const t of w)await Oe(s,i,p,t.sub,t.grantee)===void 0&&f.push(t.grantee);if(f.length>0)throw Pe(f)}l(Xe,"ensureGrants");async function It(e,s,a={}){const n=a.blobs??await x(),i=await v(),p=Me(e.run_id);let d="start";const o=l(async t=>{d=t,await s.assertOwned(),await K(e.run_id,t),await a.atStep?.(t)},"at");let w=e.state==="committed";const f=[];try{const t=await Ve(n,e.run_id);if(e.source_kind==="machine"&&t.installId!==e.source_install_id)throw new g("stage","bundle_invalid",`source.json names install ${t.installId}, the run is for ${e.source_install_id}`);t.installId=e.source_install_id;const u=await Ne(i),I=[...qe],b=await ie(i,u,[...I,"grants"]);if(!w){const m={},P=[],T=[],j=a.fleetRuntime??process.env.CRTR_RUNTIME??null;await we(i,u,t.person,e.person),await o("open-grants"),await Xe(n,i,e,t,u,j,a.openGrants??Je),await o("publish-plugins");const F=await Ke(n,e.run_id),E=await M(e.person,()=>Ge(F));if(E.unavailable.length>0){if(e.loaded_at===void 0||e.loaded_at===null)throw new g("publish-plugins","import_failed","a loading run has no loaded_at");if(Date.now()-Date.parse(e.loaded_at)>=ze)throw new g("publish-plugins","directory_unavailable",`the directory did not answer for: ${E.unavailable.slice(0,10).join(", ")}; rerun the import once it is reachable`,{plugins:E.unavailable});await s.assertOwned(),await K(e.run_id,"waiting_for_directory");return}T.push(...E.refused),await o("stage");const J=await De(i,e.run_id,t.counts,r=>L(e.run_id,r,t),r=>n.get(r));for(const[r,c]of Object.entries(J))m[r]={staged:c,inserted:0,mapped:0,dropped:0};const _={db:i,schema:p,target:u,catalog:b,sourcePerson:t.person,targetPerson:e.person,fleetRuntime:j,shippedBodies:t.shippedBodies??{}};await o("bind-staged");for(const[r,c]of Object.entries(await be(_)))h(m,r,c);for(const[r,c]of Object.entries(await ge(_)))h(m,r,c);await o("rewrite-person"),await Ce(_),await Ae(_),await o("prune");const G=await re(i,p,b,t),S=t.kind==="hosted"?Be(t.pathPrefixes??[]):[];await o("rewrite-paths"),await ce(i,p,S),await ue(i,p,S,n,e.run_id),await le(i,p),await ye(_);const q=await Te(_);await pe(i,p,u,t.installId,e.person),await o("rewrite-ids");const k=await ke(_,q);await o("drop");const $=await fe(i,p,u),Y=await Ie(_);for(const[r,c]of Object.entries({...G}))h(m,r,c);for(const[r,c]of Object.entries(Y))h(m,r,c);for(const[r,c]of Object.entries(await _e(_,{installId:t.installId,person:e.person,runId:e.run_id})))h(m,r,c);await he(_,{installId:t.installId,person:e.person,runId:e.run_id}),await je(_),await de(i,p,u,t.installId),await o("pre-check");const z=new Map([["messages",["seq"]],...ae.map(r=>[r,["seq"]])]);await oe(i,p,u,b,I,new Set,z),await o("blobs"),await Re(i,p,u,e.person,n,e.run_id,f),await o("copy"),await M(e.person,()=>D(async r=>{await s.assertOwned({extendLeaseMs:Qe});const c=await se({db:r,runId:e.run_id,schema:p,target:u,catalog:b,source:t,person:e.person,idMap:k,pathMap:S}),C=await et(r,e.run_id,$);C>0&&(c.inserted.revisions=(c.inserted.revisions??0)+C),await We(r,p,e.run_id,t);const A=await Fe({db:r,blobs:n,runId:e.run_id,person:e.person,objectMap:k.object});for(const[Q,V]of Object.entries(A.inserted))c.inserted[Q]=V.length;return P.push(...A.unresolvedPlugins),await r.prepare("UPDATE import_runs SET counts_json = ?, loaded_at = COALESCE(loaded_at, ?) WHERE run_id = ?").run(JSON.stringify({...xe(m,c),unresolved_plugins:P,refused_plugins:T}),R(),e.run_id),c})),w=!0,await a.atStep?.("committed")}await o("verify");const y=await Le(i,e.run_id,p,u,b,t.installId);if(await i.prepare("UPDATE import_runs SET verify_json = ? WHERE run_id = ?").run(JSON.stringify(y),e.run_id),!y.ok)throw new g("verify","verify_failed","the committed rows differ from the staged rows or an invariant failed",{differences:y.differences,invariants:y.invariants});await o("manifest");const O=N.manifest(e.run_id);await n.put(O,await tt(e.run_id)),await H(i,e.run_id);for(const m of He(e.run_id))await n.delete(m);await Se(n,e.run_id),await D(async m=>{await Ue(m,e.run_id,e.person),await m.prepare("UPDATE import_runs SET state = 'done', step = 'done', manifest_key = ?, finished_at = ? WHERE run_id = ?").run(O,R(),e.run_id)})}catch(t){if(t instanceof Ye)throw t;const u=Ze(t,d);$e({level:"error",event:"import.run.failed",error:t,fields:{run_id:e.run_id,step:u.step,code:u.code}}),await H(i,e.run_id).catch(()=>{}),w||await Ee(n,f,!0),await i.prepare("UPDATE import_runs SET state = 'failed', failure_json = ?, finished_at = ? WHERE run_id = ?").run(JSON.stringify(u),R(),e.run_id),await ve(n,e.run_id,{keepNodeFiles:w,bestEffort:!0})}}l(It,"processRun");function Ze(e,s){if(e instanceof g)return{step:e.step,code:e.code,message:e.message,...e.detail===void 0?{}:{detail:e.detail}};const a=e.code;return{step:s,code:typeof a=="string"?a:"import_failed",message:e instanceof Error?e.message:String(e)}}l(Ze,"failureOf");function h(e,s,a){(e[s]??={staged:0,inserted:0,mapped:0,dropped:0}).dropped+=a}l(h,"addDropped");function xe(e,s){for(const[a,n]of Object.entries(s.inserted))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).inserted=n;for(const[a,n]of Object.entries(s.mapped))(e[a]??={staged:0,inserted:0,mapped:0,dropped:0}).mapped=n;return e}l(xe,"withInserted");async function et(e,s,a){const n=new Set((await e.prepareUncached("SELECT rev_id FROM revisions WHERE rev_id IN (SELECT jsonb_array_elements_text(?::jsonb))").all(JSON.stringify(a.map(d=>d.rev_id)))).map(d=>d.rev_id)),i=a.filter(d=>!n.has(d.rev_id)),p=new Map;for(const d of a)p.set(d.document,[...p.get(d.document)??[],d]);for(const[d,o]of p){const w=await te(e,d);w!==null&&await ee(e,w,o.map(f=>({rev_id:f.rev_id,parents:f.parents,body_hash:f.body_hash,rationale:f.rationale,created_at:f.created_at})))}return await U(e,s,"revisions",i.map(d=>[d.rev_id])),await U(e,s,"revision_parents",i.flatMap(d=>d.parents.map(o=>[d.rev_id,o]))),i.length}l(et,"arrive");async function U(e,s,a,n){if(n.length===0)return;const i=await e.prepare("SELECT inserted_keys FROM import_manifest WHERE run_id = ? AND table_name = ?").get(s,a);i===void 0?await e.prepare("INSERT INTO import_manifest (run_id, table_name, inserted_keys) VALUES (?, ?, ?)").run(s,a,W(n)):await e.prepare("UPDATE import_manifest SET inserted_keys = ? WHERE run_id = ? AND table_name = ?").run(W([...B(i.inserted_keys),...n]),s,a)}l(U,"appendManifest");async function tt(e){const a=await(await v()).prepare("SELECT table_name, inserted_keys FROM import_manifest WHERE run_id = ? ORDER BY table_name").all(e);return Z(Buffer.from(a.map(n=>JSON.stringify({table:n.table_name,keys:B(n.inserted_keys)})).join(`
2
2
  `)+`
3
3
  `))}l(tt,"manifestFile");export{Qe as COPY_LEASE_MS,ze as GRANT_WAIT_MS,It as processRun};
@@ -1,11 +1,13 @@
1
- var E=Object.defineProperty;var p=(i,s)=>E(i,"name",{value:s,configurable:!0});import{existsSync as x,statSync as b}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as A}from"../../build-root.js";import{FRONT_DOOR_ENV as L}from"./front-door-env.js";import{frontDoorBootPrompt as M}from"./first-run-offer.js";import{readMachineConfig as W}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as $}from"./node-id-token.js";import{markTourOffered as B,recordSetupCompleted as G,setupCompleted as V,tourOfferPending as U}from"./setup-marker.js";function I(i){try{return x(i)&&b(i).isDirectory()}catch{return!1}}p(I,"isDir");const Y=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function j(){let i=!1;const s=p(()=>{i=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const c=new Error("Interrupted");throw c.name="AbortError",c}await G(e)}finally{process.removeListener("SIGINT",s)}}p(j,"runFirstSetup");function J(i){let s=process.cwd(),t,e,c,u=!1,m,a;const n=[];for(let f=0;f<i.length;f++){const o=i[f];if(o==="--name")t=i[++f];else if(o==="--kind")e=i[++f];else if(o==="--profile")c=i[++f];else if(o==="--pick-profile")u=!0;else if(o==="--continue"||o==="-c")m="continue";else if(o==="--resume"||o==="-r"){m="pick";const w=i[f+1];w!==void 0&&$(w)&&!I(h(w))&&(a=w,f++)}else o.startsWith("--")||n.push(o)}n.length>0&&I(h(n[0]))&&(s=h(n.shift()));const g=n.length>0?n.join(" "):void 0;return{cwd:s,prompt:g,name:t,kind:e,profile:c,pickProfile:u,resume:m,resumeId:a}}p(J,"parseRootArgs");import{FRONT_DOOR_ENV as se}from"./front-door-env.js";async function ie(i){const s=i.slice(2),t=s[0];if(process.env[L]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&A.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),d=!t.startsWith("-")&&I(h(t)),l=Y.has(t);if(!r&&!d&&!l)return!1;if(d){const{buildRoot:C}=await import("../../build-root.js");if((await C()).subtrees.some(D=>D.name===t))return!1}}const e=J(s),c=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await c();const u=process.stdin.isTTY&&process.stdout.isTTY;let m=!1;u&&!V()&&(await j(),m=!0);let a=null,n,g=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:d}=await import("./resume-root.js"),l=await r(e.resumeId);"error"in l&&(process.stderr.write(`${l.error}
2
- `),process.exit(1)),"none"in l?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
3
- `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(a=l.node.profile_id,n=l.node.node_id,I(l.node.cwd)&&(g=l.node.cwd))}if(n===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");m&&e.profile===void 0&&process.stdout.write(`
1
+ var A=Object.defineProperty;var u=(i,d)=>A(i,"name",{value:d,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as g}from"node:path";import{SUBTREE_NAMES as $}from"../../build-root.js";import{FRONT_DOOR_ENV as W}from"./front-door-env.js";import{frontDoorBootPrompt as B}from"./first-run-offer.js";import{readMachineConfig as R}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as G}from"./node-id-token.js";import{markTourOffered as V,recordSetupCompleted as U,setupCompleted as P,tourOfferPending as Y}from"./setup-marker.js";function T(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}u(T,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const d=u(()=>{i=!0},"onSigint");process.once("SIGINT",d);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",d)}}u(J,"runFirstSetup");function X(i){let d=process.cwd(),t,e,l,f=!1,p,h;const o=[];for(let c=0;c<i.length;c++){const n=i[c];if(n==="--name")t=i[++c];else if(n==="--kind")e=i[++c];else if(n==="--profile")l=i[++c];else if(n==="--pick-profile")f=!0;else if(n==="--continue"||n==="-c")p="continue";else if(n==="--resume"||n==="-r"){p="pick";const w=i[c+1];w!==void 0&&G(w)&&!T(g(w))&&(h=w,c++)}else n.startsWith("--")||o.push(n)}o.length>0&&T(g(o[0]))&&(d=g(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:d,prompt:m,name:t,kind:e,profile:l,pickProfile:f,resume:p,resumeId:h}}u(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const d=i.slice(2),t=d[0];if(process.env[W]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&$.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),s=!t.startsWith("-")&&T(g(t)),a=j.has(t);if(!r&&!s&&!a)return!1;if(s){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(L=>L.name===t))return!1}}const e=X(d),l=u(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(R()===void 0){f||(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));const{hasLocalCanvas:r}=await import("../../daemon/machine-link/config.js");r()&&process.stderr.write(`This computer's crtr keeps its records locally. Local installs are ending; sign in to Northlight to move them into your account.
2
+ `);const{sysSigninLeaf:s}=await import("../../commands/sys/signin.js");try{await s.run({},{})}catch(a){process.stderr.write(`${a instanceof Error?a.message:String(a)}
3
+ `),process.exit(1)}}let p=!1;const h=f&&!P()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!P()&&!h&&(await J(),p=!0);let o=null,m,c=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:s}=await import("./resume-root.js"),a=await r(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
4
+ `),process.exit(1)),"none"in a?(e.resumeId.includes("-")&&(process.stderr.write(`${s(e.resumeId)}
5
+ `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=a.node.profile_id,m=a.node.node_id,T(a.node.cwd)&&(c=a.node.cwd))}if(m===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:s}=await import("../profiles/select.js");p&&e.profile===void 0&&process.stdout.write(`
4
6
  Choose a profile
5
- `),a=e.profile??(u?await r(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{cliClient:f}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:o,hasConfiguredProviderCredential:w},R]=await Promise.all([import("./provider-credential-gate.js"),a===null?[]:f().listProfileEnv(a).then(r=>r.names)]),k=p(async()=>{const r=await f().getModelAuthReadiness({cwd:e.cwd,...a===null?{}:{profile:a}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await w(R)&&!await k()){u||o();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||o()}const{inTmux:P}=await import("./placement-tmux.js");if(u&&!P()){const{TMUX_STARTED_ENV:r,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[r]===void 0&&d(s,n!==void 0?null:a,g)}const[{bootRoot:v},{resumeRoot:y},{rendererWarning:N,missingPackageWarning:O,piAgentDir:S}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=O(S());r!==null&&process.stderr.write(`
7
+ `),o=e.profile??(f?await r(e.cwd,void 0,e.pickProfile,!1):s(e.cwd))}const{cliClient:n}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:w,hasConfiguredProviderCredential:k},v]=await Promise.all([import("./provider-credential-gate.js"),o===null?[]:n().listProfileEnv(o).then(r=>r.names)]),N=u(async()=>{const r=await n().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await k(v)&&!await N()){f||w();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||w()}const{inTmux:y}=await import("./placement-tmux.js");if(f&&!y()){const{TMUX_STARTED_ENV:r,handoffToTmux:s}=await import("./tmux-handoff.js");process.env[r]===void 0&&s(d,m!==void 0?null:o,c)}const[{bootRoot:S},{resumeRoot:C},{rendererWarning:O,missingPackageWarning:_,piAgentDir:x}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=_(x());r!==null&&process.stderr.write(`
6
8
  ${r}
7
9
 
8
- `);const d=N();d!==null&&process.stderr.write(`
9
- ${d}
10
+ `);const s=O();s!==null&&process.stderr.write(`
11
+ ${s}
10
12
 
11
- `)}catch{}if(n!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(n)}if(e.resume!==void 0&&await y(e.cwd,e.resume==="pick")==="aborted")return!0;const T=u&&(m||await U()),{prompt:F,initialWhip:_}=M({offerTour:T,signedIn:T&&W()!==void 0,userPrompt:e.prompt});return T&&P()&&await B(),await v({...e,prompt:F,initialWhip:_,selectedProfileId:a??void 0}),!0}p(ie,"maybeBootRoot");export{se as FRONT_DOOR_ENV,ie as maybeBootRoot,J as parseRootArgs};
13
+ `)}catch{}if(m!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(m)}if(e.resume!==void 0&&await C(e.cwd,e.resume==="pick")==="aborted")return!0;const I=f&&(p||await Y()),{prompt:E,initialWhip:F}=B({offerTour:I,signedIn:I&&R()!==void 0,userPrompt:e.prompt});return I&&y()&&await V(),await S({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}u(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
@@ -1 +1 @@
1
- var h=Object.defineProperty;var w=(t,o)=>h(t,"name",{value:o,configurable:!0});import{ApiError as a}from"../../../api/errors.js";import{withCanvasWrite as _}from"../../../core/canvas/db.js";import{createObject as v,ownerForGrantee as E}from"../../../core/graph/objects.js";import{OBJECT_TYPE as y}from"../../../core/permissions/builtin.js";import{listFacts as g,userSubject as b,writeActsFor as j}from"../../../core/permissions/facts.js";import{hasMachineCredential as S,mintMachineCredential as T}from"../../machine-link/credential.js";async function R(t){if(t.principal.class!=="person"||t.principal.sub===void 0)throw new a(403,"person_only","a machine is registered by a signed-in person");const o=b(t.principal.sub).id,e=t.body??{},p=t.query.get("rotate")==="1",i=typeof e.environment_id=="string"&&p?e.environment_id:void 0;if(i===void 0&&(typeof e.install_id!="string"||e.install_id.trim()===""))throw new a(400,"invalid_request","install_id is required");const s=typeof e.install_id=="string"?e.install_id.trim():"",u=typeof e.name=="string"&&e.name.trim()!==""?e.name.trim():s,l=new Date().toISOString(),c=await _(async n=>{const r=i===void 0?await n.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(s):await n.prepare("SELECT object FROM environments WHERE object = ? AND kind = 'machine'").get(i);if(r===void 0&&i!==void 0)throw new a(404,"environment_not_found",`no machine environment ${i}`);if(r!==void 0){if(!(await g(n,y,r.object)).some(m=>m.relation==="acts_for"&&m.subject_type==="user"&&m.subject_id===o))throw new a(409,"install_id_taken","this install id is registered to another person");return await n.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(l,r.object),r.object}const f=await E(n,"app:terminal"),d=await v(n,{type:"environment",kind:"machine",owner:f.id,privacy:"public",name:s,preview:u});return await j(n,d.id,o),await n.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(d.id,s,l),d.id});if(!p&&await S(c))throw new a(409,"credential_exists","the machine credential was already issued; rotate it");return{status:200,body:{environment_id:c,credential:await T(c)}}}w(R,"handleRegister");const N=[{method:"POST",pattern:"/v1/machines",handler:R}];export{N as machineRoutes};
1
+ var y=Object.defineProperty;var u=(n,r)=>y(n,"name",{value:r,configurable:!0});import{ApiError as t}from"../../../api/errors.js";import{withCanvasWrite as h}from"../../../core/canvas/db.js";import{createObject as b,ownerForGrantee as g}from"../../../core/graph/objects.js";import{OBJECT_TYPE as _}from"../../../core/permissions/builtin.js";import{listFacts as f,userSubject as v,writeActsFor as j}from"../../../core/permissions/facts.js";import{hasMachineCredential as R,mintMachineCredential as T,revokeMachineCredential as S}from"../../machine-link/credential.js";async function k(n){if(n.principal.class!=="person"||n.principal.sub===void 0)throw new t(403,"person_only","a machine is registered by a signed-in person");const r=v(n.principal.sub).id,e=n.body??{},o=n.query.get("rotate")==="1",a=typeof e.environment_id=="string"&&o?e.environment_id:void 0;if(a===void 0&&(typeof e.install_id!="string"||e.install_id.trim()===""))throw new t(400,"invalid_request","install_id is required");const s=typeof e.install_id=="string"?e.install_id.trim():"",c=typeof e.name=="string"&&e.name.trim()!==""?e.name.trim():s,w=new Date().toISOString(),m=await h(async i=>{const d=a===void 0?await i.prepare("SELECT object FROM environments WHERE machine_id = ? AND kind = 'machine'").get(s):await i.prepare("SELECT object FROM environments WHERE object = ? AND kind = 'machine'").get(a);if(d===void 0&&a!==void 0)throw new t(404,"environment_not_found",`no machine environment ${a}`);if(d!==void 0){if(!(await f(i,_,d.object)).some(l=>l.relation==="acts_for"&&l.subject_type==="user"&&l.subject_id===r))throw new t(409,"install_id_taken","this install id is registered to another person");return await i.prepare("UPDATE environments SET last_seen_at = ? WHERE object = ?").run(w,d.object),d.object}const E=await g(i,"app:terminal"),p=await b(i,{type:"environment",kind:"machine",owner:E.id,privacy:"public",name:s,preview:c});return await j(i,p.id,r),await i.prepare("INSERT INTO environments (object, kind, machine_id, last_seen_at) VALUES (?, 'machine', ?, ?)").run(p.id,s,w),p.id});if(!o&&await R(m))throw new t(409,"credential_exists","the machine credential was already issued; rotate it");return{status:200,body:{environment_id:m,credential:await T(m)}}}u(k,"handleRegister");async function A(n){if(n.principal.class!=="person"||n.principal.sub===void 0)throw new t(403,"person_only","a machine is revoked by a signed-in person");const r=v(n.principal.sub).id,e=n.params.environment_id??"";return await h(async o=>{if(!(await o.prepare("SELECT object FROM environments WHERE object = ? AND kind = 'machine'").get(e)===void 0?[]:await f(o,_,e)).some(c=>c.relation==="acts_for"&&c.subject_type==="user"&&c.subject_id===r))throw new t(404,"environment_not_found",`no machine environment ${e}`)}),await S(e),{status:200,body:{environment_id:e}}}u(A,"handleRevoke");const W=[{method:"POST",pattern:"/v1/machines",handler:k},{method:"DELETE",pattern:"/v1/machines/:environment_id",handler:A}];export{W as machineRoutes};