@north-light/cli 0.3.671 → 0.3.673
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/execution-start.d.ts +1 -1
- package/dist/api/dto/nodes.d.ts +2 -0
- package/dist/core/pool-credential-store.d.ts +4 -0
- package/dist/core/pool-credential-store.js +1 -1
- package/dist/core/runtime/provider-credential-gate.d.ts +2 -2
- package/dist/core/runtime/provider-credential-gate.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +5 -5
- package/dist/core/runtime/runner/machine/call.d.ts +5 -0
- package/dist/core/runtime/runner/machine/call.js +2 -2
- package/dist/core/runtime/runner/machine/ops.d.ts +2 -1
- package/dist/core/runtime/spawn.d.ts +2 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/subscription-state.d.ts +2 -0
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.d.ts +12 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/execution-start.d.ts +9 -1
- package/dist/daemon/api/handlers/execution-start.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/machine-link/holder.js +4 -4
- package/package.json +3 -3
- package/packages/crouter-api/dist/api/contract.js +1 -1
- package/packages/crouter-api/dist/core/pool-credential-store.js +44 -25
- package/packages/crouter-api/dist/core/review/document.js +143 -0
- package/packages/crouter-api/dist/core/review/project.js +45 -0
- package/packages/crouter-api/dist/core/runtime/launch-recipe.js +45 -0
- package/packages/crouter-api/dist/core/runtime/provider-credential-gate.js +4 -4
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +13 -5
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +96 -0
- package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +170 -0
- package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +11 -2
- package/packages/crouter-api/dist/core/runtime/spawn.js +88 -3
- package/packages/crouter-api/dist/core/runtime/stop-signals.js +46 -0
- package/packages/crouter-api/dist/core/secrets/blaxel-launch.js +104 -0
- package/packages/crouter-api/dist/core/subscription-state.js +18 -2
- package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +701 -0
- package/packages/crouter-api/dist/daemon/api/handlers/execution-start.js +120 -0
- package/packages/crouter-api/dist/daemon/api/handlers/node-records.js +113 -0
- package/packages/crouter-api/dist/daemon/api/handlers/telemetry-record.js +34 -0
- package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
- package/packages/crouter-api/dist/daemon/review/companion.js +29 -0
- package/packages/crouter-api/dist/daemon/review/deliver.js +13 -0
- package/packages/crouter-api/dist/daemon/review/finish.js +170 -0
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/scripts/sandbox-start.mjs +8 -1
package/dist/api/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
2
|
-
export declare const CONTRACT_LEVEL = "1.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.60";
|
|
3
3
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
4
4
|
export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
|
|
5
5
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.60",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
|
|
@@ -60,7 +60,7 @@ export interface StartBundleDTO {
|
|
|
60
60
|
plugins: StartBundlePluginDTO[];
|
|
61
61
|
/** Null when the node has no `import_node_files` row, or its archive was deleted (30 days after the first unpack). Named on every start while the archive exists: a sandbox unpacks it only when it holds no marker of its own. */
|
|
62
62
|
import_node_files: StartBundleImportFilesDTO | null;
|
|
63
|
-
/** Present only for an execution on a machine environment (the Mac, which holds no database): the node's profile metadata (`CRTR_PROFILE_META_*`) and the secrets of its environment (the app's rows, the owning profile's rows, the deployment rows), merged in the process runner's order. Secret values:
|
|
63
|
+
/** Present only for an execution on a machine environment (the Mac, which holds no database): the node's profile metadata (`CRTR_PROFILE_META_*`) and the secrets of its environment (the app's rows, the owning profile's rows, the deployment rows), merged in the process runner's order. Secret values: a sandbox reads them with the execution's node token; for a machine the control plane carries them in the `start` call's link frame, where they sit in `machine_calls.args_json` only while the call is in flight (erased when the call finishes). */
|
|
64
64
|
machine_env?: Record<string, string>;
|
|
65
65
|
/** The start data for a broker that reads it with the bundle instead of asking `cycle-start` (cloud-hosted and local launches carry it this way). */
|
|
66
66
|
start?: StartDataDTO;
|
package/dist/api/dto/nodes.d.ts
CHANGED
|
@@ -49,6 +49,8 @@ export interface CreateNodeRequest {
|
|
|
49
49
|
/** Sticky isolation; a child cannot turn off an isolated run. */
|
|
50
50
|
isolated?: boolean;
|
|
51
51
|
root?: boolean;
|
|
52
|
+
/** Launch the node in the create itself when its profile's environment is a machine reached over a link, instead of leaving it dormant for a first attach to revive. */
|
|
53
|
+
start?: boolean;
|
|
52
54
|
/** Lifecycle of the new node. Roots default to `resident`; managed children
|
|
53
55
|
* default to `terminal`. Use `resident` for a child that remains wakeable
|
|
54
56
|
* without owing a final, or `terminal` for a bounded worker that must
|
|
@@ -29,3 +29,7 @@ export declare class PoolCredentialStore implements CredentialStore {
|
|
|
29
29
|
modify(providerId: string, fn: (current: Credential | undefined) => Promise<Credential | undefined>): Promise<Credential | undefined>;
|
|
30
30
|
delete(providerId: string): Promise<void>;
|
|
31
31
|
}
|
|
32
|
+
/** A read-only view of what `PoolCredentialStore` would serve, built from one read per table (model_api_keys, model_accounts,
|
|
33
|
+
* model_account_cooldowns) instead of one per provider. Same rules as `read`/`list`: a managed provider is its elected pool account,
|
|
34
|
+
* else a stored api_key (never a stored oauth record). */
|
|
35
|
+
export declare function snapshotCredentialStore(): Promise<CredentialStore>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var y=Object.defineProperty;var s=(t,e)=>y(t,"name",{value:e,configurable:!0});import{CrouterCredentialStore as p,readAuthCredentials as g}from"./auth-file.js";import{MANAGED_PROVIDER_IDS as l,getProviderLabel as x,isManagedProvider as o,modifyElectedSubscription as C,readAllSubscriptionPools as P,readSubscriptionPool as h,removeManagedAccount as S}from"./subscription-state.js";import{registerGateCredentialStore as b}from"./runtime/provider-credential-gate.js";async function u(t,e=Date.now()){return d(await h(t),e)}s(u,"electPoolCredential");function d(t,e=Date.now()){return t.find(n=>!n.authFailure&&(!n.rateLimitedUntil||n.rateLimitedUntil<=e))??t[0]}s(d,"electFrom");function f(t){return{type:"oauth",refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}s(f,"toCredential");function w(t,e){return t!==void 0?f(t):e?.type==="oauth"?void 0:e}s(w,"servedManaged");function m(t,e){const n=t.filter(i=>!(o(i.providerId)&&i.type==="oauth"));for(const i of l)!n.some(a=>a.providerId===i)&&e(i)>0&&n.push({providerId:i,type:"oauth"});return n}s(m,"listedCredentials");class F{static{s(this,"PoolCredentialStore")}auth=new p;async read(e){if(!o(e))return this.auth.read(e);const n=await u(e);return w(n,n===void 0?await this.auth.read(e):void 0)}async list(){const e=await this.auth.list(),n=new Map;for(const i of l)e.some(a=>a.providerId===i&&a.type!=="oauth")||n.set(i,(await h(i)).length);return m(e,i=>n.get(i)??0)}async modify(e,n){if(!o(e))return this.auth.modify(e,n);if(await u(e)===void 0){if(await this.read(e)!==void 0)return this.auth.modify(e,n);throw new Error(`${x(e)} has no account to update \u2014 add one with \`crtr sys settings\` or \`/provider-sub ${e} add\`.`)}const i=await C(e,a=>d(a),async a=>{const r=await n(f(a));if(r===void 0||r.type!=="oauth")return;const c=r.clientId;return{refresh:r.refresh,access:r.access,expires:r.expires,...typeof c=="string"&&c?{clientId:c}:{}}});return i===void 0?void 0:f(i)}async delete(e){if(!o(e))return this.auth.delete(e);const n=await u(e);n!==void 0&&await S(e,n.label),await this.auth.read(e)!==void 0&&await this.auth.delete(e)}}async function A(){const[t,e]=await Promise.all([g(),P()]),n=s(a=>o(a)?w(d(e.get(a)??[]),t[a]):t[a],"read"),i=s(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:s(async a=>n(a),"read"),list:s(async()=>m(Object.entries(t).map(([a,r])=>({providerId:a,type:r.type})),a=>e.get(a)?.length??0),"list"),modify:i,delete:i}}s(A,"snapshotCredentialStore"),b(A);export{F as PoolCredentialStore,u as electPoolCredential,A as snapshotCredentialStore};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { CredentialStore } from '@earendil-works/pi-ai';
|
|
2
|
-
/** The daemon, which owns the rows, registers its row-backed
|
|
3
|
-
export declare function registerGateCredentialStore(
|
|
2
|
+
/** The daemon, which owns the rows, registers a builder of its row-backed read-only view (one read per table); every other process asks the daemon over /v1/model-auth. */
|
|
3
|
+
export declare function registerGateCredentialStore(snapshot: () => Promise<CredentialStore>): void;
|
|
4
4
|
export declare const NO_PROVIDER_CREDENTIAL_MESSAGE = "crtr: no provider credential; run `crtr sys setup` to log in.";
|
|
5
5
|
/** Check the setup catalog before a path creates a broker-backed node. `profileEnvNames` are the names stored on the
|
|
6
6
|
* launching profile (values are never needed: a stored value is never empty). */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var d=Object.defineProperty;var t=(e,o)=>d(e,"name",{value:o,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as p}from"../model-auth/api-credential-store.js";import{cliClient as f}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as
|
|
2
|
-
`),process.exit(1)}t(_,"exitForMissingProviderCredential");export{
|
|
1
|
+
var d=Object.defineProperty;var t=(e,o)=>d(e,"name",{value:o,configurable:!0});import{ModelRegistry as c,ModelRuntime as l}from"@earendil-works/pi-coding-agent";import{join as m}from"node:path";import{ApiCredentialStore as p}from"../model-auth/api-credential-store.js";import{cliClient as f}from"../../commands/api-client.js";import{hasProviderCredential as u}from"../provider-credential.js";import{piAgentDir as E}from"./package-health.js";import{PROVIDER_ENV_KEYS as w}from"./spawn-env.js";let a;function D(e){a=e}t(D,"registerGateCredentialStore");function g(e){const o=new Map;let n;const i=t(()=>{throw new Error("the provider credential check is read-only")},"refuse");return{read:t(r=>{let s=o.get(r);return s===void 0&&o.set(r,s=e.read(r)),s},"read"),list:t(()=>n??=e.list(),"list"),modify:i,delete:i}}t(g,"readOnceStore");const h="crtr: no provider credential; run `crtr sys setup` to log in.";async function M(e){const o=Object.fromEntries(e.map(r=>[r,"stored"]));if(Object.values(w).some(r=>(o[r]??process.env[r])?.trim()))return!0;const n=E(),i=await l.create({credentials:a===void 0?g(new p(()=>f(),!0)):await a(),modelsPath:m(n,"models.json")});return await u(i,new c(i))}t(M,"hasConfiguredProviderCredential");function _(){process.stderr.write(`${h}
|
|
2
|
+
`),process.exit(1)}t(_,"exitForMissingProviderCredential");export{h as NO_PROVIDER_CREDENTIAL_MESSAGE,_ as exitForMissingProviderCredential,M as hasConfiguredProviderCredential,D as registerGateCredentialStore};
|
|
@@ -19,6 +19,9 @@ export declare const RUN_USER = "crtr";
|
|
|
19
19
|
export declare const RECIPE_PI_AGENT_DIR = "/var/lib/crtr/recipe-pi-agent";
|
|
20
20
|
export declare const SETUP_SCRIPT_FILE = "recipe-setup.sh";
|
|
21
21
|
export declare const REPOS_DIR = "repos";
|
|
22
|
+
/** Where the image keeps the setup script's output, and its exit status when it failed. `sandbox-start.mjs` reads both (it derives them from `/work/.crtr`). */
|
|
23
|
+
export declare const SETUP_LOG_FILE = "/work/.crtr/setup.log";
|
|
24
|
+
export declare const SETUP_FAILED_FILE = "/work/.crtr/setup-failed";
|
|
22
25
|
/** The Dockerfile for a recipe revision. Pure. It clones and fetches nothing: the repositories arrive by `COPY`, so a git token cannot appear here.
|
|
23
26
|
* Two stages: `build` runs the setup script as root; the final image copies only the installed trees out of it, never `/root`. With `packagesToken`
|
|
24
27
|
* the build stage declares `ARG NODE_AUTH_TOKEN` (its value comes from `.env.build` in the upload), so the token is in no layer of the final image. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).map(
|
|
3
|
-
`)}l(
|
|
4
|
-
`,{mode:384}),e.recipe.setup_script!==null&&e.recipe.setup_script.trim()!==""&&
|
|
1
|
+
var F=Object.defineProperty;var l=(e,t)=>F(e,"name",{value:t,configurable:!0});import{spawn as M}from"node:child_process";import{constants as N,lstatSync as K,mkdirSync as Y,readFileSync as j,readdirSync as z,readlinkSync as q,rmSync as H,writeFileSync as U}from"node:fs";import{join as g,relative as J}from"node:path";import{crc32 as W,deflateRawSync as V}from"node:zlib";import{BlaxelApiError as Z}from"./client.js";const Q="public.ecr.aws/docker/library/node:24-alpine",X="ghcr.io/blaxel-ai/sandbox:latest",m="crtr",S="/var/lib/crtr/recipe-pi-agent",ee="1.1.0",$="recipe-setup.sh",_="repos",v="/work/.crtr/setup.log",A="/work/.crtr/setup-failed",D=l(e=>`'${e.replace(/'/g,"'\\''")}'`,"shellQuote"),te=l(e=>(e??"").split(`
|
|
2
|
+
`).map(t=>t.trim()).filter(t=>t!==""),"lines"),I=l((e,t)=>`RUN { ${t}; } >> ${v} 2>&1 || echo ${D(e)} "exited $?" >> ${A}`,"guarded");function re(e,t,a=!1){const o=te(e.pi_packages),i=e.setup_script!==null&&e.setup_script.trim()!=="",n=[`FROM ${Q}`,"RUN apk add --no-cache bash git curl ripgrep",`COPY --from=${X} /sandbox-api /usr/local/bin/sandbox-api`,`RUN adduser -D -h /home/${m} -s /bin/sh ${m} && mkdir -p /work/.crtr ${S} && chown -R ${m} /work /var/lib/crtr`],r=[`${n[0]} AS build`,...a?["ARG NODE_AUTH_TOKEN"]:[],...n.slice(1),`RUN rm -f ${A} ${v}`,I("npm install -g pnpm","npm install -g pnpm && mkdir -p /var/lib/postgresql")];e.repositories.length>0&&r.push(`COPY --chown=${m} ${_}/ /work/`),o.length>0&&r.push(I("npm install pi",`npm install -g @earendil-works/pi-coding-agent@${ee}`)),i&&r.push(`COPY ${$} /tmp/${$}`),r.push("WORKDIR /work");for(const s of o)r.push(I(`pi install ${s}`,`HOME=/var/lib/crtr PI_CODING_AGENT_DIR=${S} pi install ${D(s)}`));i&&r.push(I("setup script",`bash /tmp/${$}`)),r.push(I("finalize",`echo ${Math.trunc(t)} > /work/.crtr/recipe-revision && chown -R ${m} /work /home/${m} /var/lib/crtr`)),r.push("",...n);for(const s of["/work",`/home/${m}`,"/usr/local","/var/lib/crtr","/usr","/etc","/lib"])r.push(`COPY --from=build ${s} ${s}`);return r.push("COPY --from=build /var/lib/postgresql /var/lib/postgresql"),a&&r.push(`RUN rm -f /work/.npmrc /home/${m}/.npmrc`),r.push("WORKDIR /work",'ENTRYPOINT ["/usr/local/bin/sandbox-api"]',""),r.join(`
|
|
3
|
+
`)}l(re,"recipeDockerfile");const ne=l((e,t,a)=>new Promise((o,i)=>{const n=M("git",e,{cwd:a,env:{...process.env,...t,GIT_TERMINAL_PROMPT:"0"},stdio:["ignore","ignore","pipe"]});let r="";n.stderr.on("data",s=>{r+=s.toString()}),n.on("error",i),n.on("close",s=>{s===0?o():i(new Error(`git ${e[0]} failed (${s}): ${r.slice(0,300)}`))})}),"runGit");async function ue(e){const t=e.git??ne,a=e.packagesToken??null,o=e.cloneUrl??(n=>`https://github.com/${n}.git`);Y(g(e.dir,_),{recursive:!0});const i=e.token===null?{}:{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"http.https://github.com/.extraheader",GIT_CONFIG_VALUE_0:`AUTHORIZATION: basic ${Buffer.from(`x-access-token:${e.token}`).toString("base64")}`};for(const n of e.recipe.repositories){if(!/^[A-Za-z0-9._-]+$/.test(n.name)||n.name==="."||n.name==="..")throw new Error(`repository name ${JSON.stringify(n.name)} is not a plain directory name`);await t(["clone","--quiet","--branch",n.default_branch,o(n.github_full_name),g(_,n.name)],i,e.dir)}U(g(e.dir,"Dockerfile"),re(e.recipe,e.revision,a!==null)),a!==null&&U(g(e.dir,".env.build"),`NODE_AUTH_TOKEN=${a}
|
|
4
|
+
`,{mode:384}),e.recipe.setup_script!==null&&e.recipe.setup_script.trim()!==""&&U(g(e.dir,$),e.recipe.setup_script.endsWith(`
|
|
5
5
|
`)?e.recipe.setup_script:`${e.recipe.setup_script}
|
|
6
|
-
`)}l(
|
|
6
|
+
`)}l(ue,"prepareBuildDir");function P(e,t,a){for(const o of z(t).sort()){const i=g(t,o),n=K(i),r=J(e,i).split("\\").join("/");n.isDirectory()?P(e,i,a):n.isSymbolicLink()?a.push({name:r,data:Buffer.from(q(i)),mode:N.S_IFLNK|511}):n.isFile()&&a.push({name:r,data:j(i),mode:N.S_IFREG|n.mode&511})}}l(P,"walk");function se(e){const t=[];P(e,e,t);const a=[],o=[];let i=0;for(const s of t){const u=Buffer.from(s.name),h=V(s.data),b=W(s.data),p=Buffer.alloc(30);p.writeUInt32LE(67324752,0),p.writeUInt16LE(20,4),p.writeUInt16LE(2048,6),p.writeUInt16LE(8,8),p.writeUInt32LE(33,12),p.writeUInt32LE(b,14),p.writeUInt32LE(h.length,18),p.writeUInt32LE(s.data.length,22),p.writeUInt16LE(u.length,26),a.push(p,u,h);const c=Buffer.alloc(46);c.writeUInt32LE(33639248,0),c.writeUInt16LE(788,4),c.writeUInt16LE(20,6),c.writeUInt16LE(2048,8),c.writeUInt16LE(8,10),c.writeUInt32LE(33,14),c.writeUInt32LE(b,16),c.writeUInt32LE(h.length,20),c.writeUInt32LE(s.data.length,24),c.writeUInt16LE(u.length,28),c.writeUInt32LE(s.mode<<16>>>0,38),c.writeUInt32LE(i,42),o.push(c,u),i+=p.length+u.length+h.length}const n=Buffer.concat(o),r=Buffer.alloc(22);return r.writeUInt32LE(101010256,0),r.writeUInt16LE(t.length,8),r.writeUInt16LE(t.length,10),r.writeUInt32LE(n.length,12),r.writeUInt32LE(i,16),Buffer.concat([...a,n,r])}l(se,"zipDirectory");async function x(e,t,a,o,i=[]){const n=`${e.controlUrl??"https://api.blaxel.ai/v0"}${a}`,r=await(e.fetch??fetch)(n,{method:t,headers:{authorization:`Bearer ${e.apiKey}`,"x-blaxel-workspace":e.workspace,"content-type":"application/json"},...o===void 0?{}:{body:JSON.stringify(o)}}),s=await r.text();let u=null;if(s!=="")try{u=JSON.parse(s)}catch{u={raw:s}}if(!r.ok&&!i.includes(r.status))throw new Z(r.status,null,`Blaxel ${t} ${n} failed (${r.status}): ${s.slice(0,300)}`);return{status:r.status,headers:r.headers,json:u}}l(x,"api");async function B(e,t){const{status:a,json:o}=await x(e,"GET",`/images/sandbox/${encodeURIComponent(t)}`,void 0,[404]);return a===404?null:o}l(B,"getImage");async function fe(e,t){await x(e,"DELETE",`/images/sandbox/${encodeURIComponent(t)}`,void 0,[404])}l(fe,"deleteImage");async function me(e,t,a,o={}){const i=o.sleep??(f=>new Promise(w=>setTimeout(w,f))),n=o.now??Date.now,r=n(),s=await B(e,t),u=new Set((s?.spec?.tags??[]).map(f=>f.name)),h=s?.metadata?.events?.length??0,p=(await x(e,"POST","/images",{resourceType:"sandbox",name:t})).headers.get("x-blaxel-upload-url");if(p===null)throw new Error(`Blaxel gave no upload URL for image ${t}`);const c=await(e.fetch??fetch)(p,{method:"PUT",headers:{"content-type":"application/zip"},body:new Uint8Array(se(a))});if(!c.ok)throw new Error(`uploading the build context of image ${t} failed (${c.status}): ${(await c.text()).slice(0,300)}`);const G=r+(o.timeoutMs??20*6e4);let L=null;for(;;){const f=await B(e,t),w=f?.metadata?.status;if(w==="BUILT"&&(f?.metadata?.events?.length??0)>=h+2){L??=n();const E=(f?.spec?.tags??[]).filter(d=>d.name!==void 0),k=(f?.metadata?.events??[]).slice(h).map(d=>d.time??"").filter(d=>d!=="").sort()[0],O=l(d=>k!==void 0&&Date.parse(d??"")>=Date.parse(k),"touchedSince"),R=E.filter(d=>!u.has(d.name)||O(d.createdAt)||O(d.updatedAt)),T=n()-L>=(o.tagGraceMs??6e4),y=(R.length>0?R:T?E:[]).sort((d,C)=>(C.updatedAt??"").localeCompare(d.updatedAt??""))[0]?.name;if(y!==void 0)return{ref:`sandbox/${t}:${y}`,buildMs:n()-r};if(T)throw new Error(`Blaxel built image ${t} but no tag appeared`)}if(w==="FAILED"||w==="TERMINATED"){const E=f?.metadata?.events??[];throw new Error(`building image ${t} ${w.toLowerCase()}: ${E[E.length-1]?.message??"no message"}`)}if(n()>G)throw new Error(`building image ${t} did not finish within ${o.timeoutMs??20*6e4} ms (last status ${w??"none"})`);await i(o.pollMs??3e3)}}l(me,"buildImage");const he=l(e=>`env-${e}`,"environmentImageName");function we(e){H(e,{recursive:!0,force:!0})}l(we,"removeBuildDir");export{Q as NODE_BASE_IMAGE,S as RECIPE_PI_AGENT_DIR,_ as REPOS_DIR,m as RUN_USER,X as SANDBOX_API_IMAGE,A as SETUP_FAILED_FILE,v as SETUP_LOG_FILE,$ as SETUP_SCRIPT_FILE,me as buildImage,fe as deleteImage,he as environmentImageName,B as getImage,ue as prepareBuildDir,re as recipeDockerfile,we as removeBuildDir,se as zipDirectory};
|
|
@@ -6,4 +6,9 @@ export interface CallMachineOptions {
|
|
|
6
6
|
timeoutMs?: number;
|
|
7
7
|
rereadMs?: number;
|
|
8
8
|
}
|
|
9
|
+
/** Write the `pending` call row and notify the link's holder, in the caller's transaction when it has one (the notification is delivered at its commit,
|
|
10
|
+
* so a call queued by a transaction that rolls back is never sent). No live link → MachineOfflineError, nothing written. Returns the call id for `awaitMachineCall`. */
|
|
11
|
+
export declare function enqueueMachineCall<O extends MachineOp>(environmentId: string, op: O, args: MachineOpTable[O]['args']): Promise<string>;
|
|
9
12
|
export declare function callMachine<O extends MachineOp>(environmentId: string, op: O, args: MachineOpTable[O]['args'], options?: CallMachineOptions): Promise<MachineOpTable[O]['result']>;
|
|
13
|
+
/** Wait for the holder's answer to a queued call. */
|
|
14
|
+
export declare function awaitMachineCall<O extends MachineOp>(environmentId: string, op: O, callId: string, options?: CallMachineOptions): Promise<MachineOpTable[O]['result']>;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var s=(e,n)=>p(e,"name",{value:n,configurable:!0});import{randomUUID as E}from"node:crypto";import{openDb as _,withCanvasWrite as m}from"../../../canvas/db.js";import{brokerSignalBus as g}from"../../../../daemon/broker-signals/bus.js";import{MachineCallFailedError as S,MachineLostError as c,MachineOfflineError as w}from"./ops.js";const N={start:60,wake:15,stop:15,status:15,"status.all":15,delete:15,viewer:15,"cron.run":15,"cron.cancel":15,"job.stop":15,"worktree.create":60,"worktree.rollback":60,"worktree.close":60,"worktree.abandon":60,"worktree.finalize":60,"repo.identify":15},k=1e3;async function M(e,n,t){const r=E(),l=new Date().toISOString();if(!await m(async a=>await a.prepare("SELECT 1 AS live FROM machine_links WHERE environment = ? AND lease_expires_at > ?").get(e,l)===void 0?!1:(await a.prepare("INSERT INTO machine_calls (call_id, environment, op, args_json, created_at) VALUES (?, ?, ?, ?, ?)").run(r,e,n,JSON.stringify(t),l),await a.prepare("SELECT pg_notify(?, ?)").get("crtr_signal",`machine:${e}`),!0)))throw new w(e,"no live link");return r}s(M,"enqueueMachineCall");async function R(e,n,t,r={}){return await O(e,n,await M(e,n,t),r)}s(R,"callMachine");async function O(e,n,t,r={}){const l=Date.now()+(r.timeoutMs??N[n]*1e3);let o,a=!1;const i=await g.subscribe(u=>{u===t&&(a=!0,o?.())},{kinds:["machine_call"]});try{return await y(e,n,t,l,r.rereadMs??k,u=>new Promise(f=>{if(a){a=!1,f();return}const h=setTimeout(()=>{o=void 0,f()},u);o=s(()=>{clearTimeout(h),o=void 0,a=!1,f()},"wake")}))}finally{i()}}s(O,"awaitMachineCall");async function y(e,n,t,r,l,o){for(;;){const a=await(await _()).prepare("SELECT state, result_json, lease_expires_at, claimed_generation FROM machine_calls WHERE call_id = ?").get(t);if(a===void 0)throw new c(e,t);if(a.state==="done")return a.result_json===null?null:JSON.parse(a.result_json);if(a.state==="failed"){const i=a.result_json===null?{}:JSON.parse(a.result_json);throw i.code==="machine_offline"?new w(e,i.message,i.sent===!0):i.code==="machine_lost"?new c(e,t):new S(e,n,i.message??"unknown")}if(a.claimed_generation!==null&&a.lease_expires_at!==null&&a.lease_expires_at<=new Date().toISOString()){if(await d(t,"lease expired")===void 0)continue;throw new c(e,t)}if(Date.now()>=r){const i=await d(t,"timed out");if(i===void 0)continue;throw i===null?new w(e,"no holder claimed the call"):new c(e,t)}await o(Math.min(l,Math.max(0,r-Date.now())))}}s(y,"waitForCall");async function d(e,n){const t=await(await _()).prepare(`UPDATE machine_calls SET state = 'failed', finished_at = ?, args_json = '{}',
|
|
2
2
|
result_json = CASE WHEN claimed_generation IS NULL THEN ? ELSE ? END
|
|
3
|
-
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return t===void 0?void 0:t.claimed_generation===null?null:Number(t.claimed_generation)}s(
|
|
3
|
+
WHERE call_id = ? AND state IN ('pending', 'sent') RETURNING claimed_generation`).get(new Date().toISOString(),JSON.stringify({code:"machine_offline",message:n,sent:!1}),JSON.stringify({code:"machine_lost",message:n}),e);return t===void 0?void 0:t.claimed_generation===null?null:Number(t.claimed_generation)}s(d,"failOpenCall");export{N as MACHINE_CALL_TIMEOUT_S,O as awaitMachineCall,R as callMachine,M as enqueueMachineCall};
|
|
@@ -8,7 +8,8 @@ import type { RunnerExecution, RunnerStartInput, RunnerStatus, RunnerStopOptions
|
|
|
8
8
|
export declare const MACHINE_OPS: readonly ["start", "wake", "stop", "status", "status.all", "delete", "viewer", "cron.run", "cron.cancel", "job.stop", "worktree.create", "worktree.rollback", "worktree.close", "worktree.abandon", "worktree.finalize", "repo.identify"];
|
|
9
9
|
export type MachineOp = (typeof MACHINE_OPS)[number];
|
|
10
10
|
/** A `start` call carries the whole start input and the node token the control plane minted: the Mac has no database, so it cannot mint one.
|
|
11
|
-
* The
|
|
11
|
+
* The bundle includes `machine_env`, the environment's secrets. The token and the bundle sit in `machine_calls.args_json` only while the call is in flight:
|
|
12
|
+
* the UPDATE that finishes any call (answered, failed, lost or offline) sets `args_json` to '{}', and a requeue from `sent` to `pending` keeps it. A row nothing finishes (its awaiter died and no link ever claims it) keeps its arguments: no code deletes `machine_calls` rows. */
|
|
12
13
|
export type MachineStartArgs = RunnerStartInput & {
|
|
13
14
|
nodeToken: string;
|
|
14
15
|
/** The start bundle, when the control plane carries it: the Mac then does not fetch it. */
|
|
@@ -27,6 +27,8 @@ export interface SpawnChildOpts {
|
|
|
27
27
|
* bounded worker that must finalize. For roots, terminal keeps the
|
|
28
28
|
* unattended no-viewer behavior. */
|
|
29
29
|
rootLifecycle?: Lifecycle;
|
|
30
|
+
/** Start the node on its remote machine in the create itself (a machine environment on a cloud role) instead of leaving it dormant. */
|
|
31
|
+
start?: boolean;
|
|
30
32
|
/** Direct root creation waits until the broker accepts viewers before it
|
|
31
33
|
* returns. Cron-launched births use `launch`: the daemon must never wait in
|
|
32
34
|
* its supervision loop. */
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var ke=Object.defineProperty;var d=(e,r)=>ke(e,"name",{value:r,configurable:!0});import{accessSync as _e,constants as ve}from"node:fs";import{isAbsolute as ge,resolve as ye,join as be}from"node:path";import{appSpace as xe}from"../layout.js";import{ApiError as oe}from"../../api/errors.js";import{spawnNode as Ce,forkSourceNode as $e,currentNodeContext as Se,rootOfSpine as Ee,newNodeId as te,preflightNodeId as Oe}from"./nodes.js";import{resolveProfileOperand as Re}from"../profiles/manifest.js";import{selectProfileForCwd as Ie,selectProfileForCwdReadOnly as Fe}from"../profiles/select.js";import{buildLaunchSpecAsync as ie,buildPiArgv as Me}from"./launch.js";import{devEnvironmentCwd as Be,runsOnBlaxel as Pe,sandboxWorktreeRequest as De}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as Ne,rollbackManagedWorktreeAsync as Le}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as Te,rollbackManagedWorktreeOnMachine as Ae,worktreeMachineOf as We}from"../worktree-machine.js";import{usage as h,brokerLaunchFailed as L}from"../errors.js";import{writeGoal as je}from"./kickoff.js";import{appendSituationalContext as ze,formatSituationalProse as He}from"./situational-context.js";import{ensureRoadmap as Ke}from"./roadmap.js";import{buildWakeBearings as Ge}from"./bearings.js";import{encodeKickoffOrigin as Ue,KICKOFF_ORIGIN_ENV as Ve}from"./stamp/protocol.js";import{carryInitialInput as Xe}from"../runs/initial-input.js";import{ExecutionCapReached as qe,beginExecution as Ye,crtrHome as Je,getNode as u,fullName as ae,jobDir as Qe,recordExecutionPid as Ze,abortExecution as H,setFrozen as K}from"../canvas/index.js";import{contextDir as G,nodeAgentDir as U}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as en}from"../spaces/open-beneath.js";import{conversationIdFromPath as T,conversationStore as S}from"../conversation-store/index.js";import{appMemoryTooSmall as nn,boundFleet as rn,brokerThresholdsForDaemon as de}from"./fleet.js";import{admitBrokerMemory as on}from"./memory-admission.js";import{emitEvent as A}from"../events/emit.js";import{remoteEnvironmentOf as tn}from"./blaxel-environment.js";import{openViewerWindow as an,focusOf as dn,windowOfPane as sn}from"./placement.js";import{awaitBrokerViewSocket as ln}from"./view-socket.js";import{readLogSnapshot as cn}from"../events/read.js";import{transition as g}from"./lifecycle.js";import{beginBootFaultAttempt as un}from"../canvas/recovery.js";import{headlessBrokerHost as V}from"./host.js";import{ensureDaemon as fn}from"../../daemon/manage.js";import{readConfig as wn}from"../config.js";import{modelRequestFromConfig as mn,unregisteredConcreteModel as hn,unroutableConcreteModel as pn}from"../model-routes.js";import{openModelRegistry as kn}from"./model-registry.js";import{MODEL_SPEC_NEXT as _n}from"./model-selection.js";import{forkNodeLedger as vn}from"./ledger.js";import{appRungForGrant as gn}from"../llm/app-rungs.js";import{APP_FAMILY as X}from"../model-routes.js";import{discoverLifecycleHookRegistry as yn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as bn}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as xn}from"../async-array.js";import{checkStart as Cn}from"./start-check.js";function y(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}d(y,"launchFailureOutcome");async function $n(e,r,a){try{return await V.launch(e,r,a)}catch(o){try{await g(e,"crash",{reason:"launch_failed",outcome:y(o)})}catch{}const t=o.message;throw L(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}d($n,"launchBrokerOrCrash");function Sn(e){return cn({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}d(Sn,"lastStartupStep");function En(e,r){const a=Sn(e),o=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(r.reason==="exited"){const{code:t,signal:s}=r.status;return{text:`exited (code ${t??"null"}, signal ${s??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:t,signal:s,last_startup_step:a}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:a}}}d(En,"notReadyDescription");async function On(e,r){try{await g(e,"crash",{reason:"launch_failed",outcome:y(r)})}catch{}try{V.teardown(e)}catch{}}d(On,"crashAndTearDown");async function Rn(e){const r=(await S().list()).map(({conversation_id:t,path:s})=>({id:t,path:s})),a=r.filter(t=>t.id===e),o=a.length>0?a:r.filter(t=>t.id.startsWith(e));if(o.length===0)throw h(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(o.length>1)throw h(`--fork-from '${e}': ambiguous \u2014 ${o.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return o[0].path}d(Rn,"resolveSessionUuid");async function se(e){const r=e.trim();if(r==="")throw h("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=T(ge(r)?r:ye(process.cwd(),r));if(o===null)throw h(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await S().header(o)).path}const a=await u(r);if(a!==null){const o=a.pi_session_file;if(o==null||o==="")throw h(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=T(o);if(t===null)throw h(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await S().header(t)).path}return await Rn(r)}d(se,"resolveForkSource");async function In(e,r,a,o={}){return e===null?null:e!==void 0&&e!==""?Re(e).profileId:r!==null?(await u(r))?.profile_id??null:o.readOnlySelection===!0?Fe(a):Ie(a)}d(In,"resolveProfileId");function le(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return mn(e.model,r,e.modelExact===!0)}d(le,"requestFromLaunch");async function ce(e,r,a){const o=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await gn(r,o,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:s,...l}=e.env??{};return{...e,model:t.model,modelIntent:{family:X,strength:t.strength},modelExact:void 0,env:{...l,CRTR_MODEL_INTENT:`${X}/${t.strength}`}}}d(ce,"appPaidLaunch");async function ue(e,r,a){if(e===void 0||e.kind==="logical"&&e.family!==X)return;const o=await hn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await kn(),r);if(o!==void 0)throw h(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:_n});const t=await pn(e,r);if(t!==void 0)throw h(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}d(ue,"assertLaunchModelRegistered");function Fn(e,r,a){const o=e??r??null;if(!a&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}d(Fn,"resolveSpawner");async function fe(e,r,a){try{fn()}catch{}const o=Se(),t=e.root===!0,s=Fn(e.parent,o.nodeId??null,t),l=e.mode??"base",b=e.rootLifecycle??(t?"resident":"terminal"),we=t&&b==="resident",I=s===null?null:await u(s),q=e.creator===void 0||e.creator===null?null:await u(e.creator);e.nodeId!==void 0&&await Oe(e.nodeId);const x=e.forkFrom!==void 0?await se(e.forkFrom):void 0,W=x===void 0?null:await $e(x),j=await xn([I,q,W],async f=>f?.isolated===!0||f?.run_id!=null&&(await u(f.run_id))?.isolated===!0);if(j&&e.isolated===!1)throw new oe(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const E=j||e.isolated===!0;if(E&&e.worktree===!0)throw new oe(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let w=E||e.worktree===!0?e.nodeId??await te():e.nodeId,C=E?e.run!==void 0&&t&&!j?e.cwd:be(xe(e.run?.grantee??I?.grantee??"app:terminal").nodes,w):e.cwd;const m=await In(e.profile,s,C),F=E?null:await Be(m,e.worktreeCwd??C);F!==null&&(C=F,w??=await te());const O=e.worktree===!0||F!==null,Y=e.run?.grant_id??I?.grant_id??null,R=e.run??q??I??W,J=await ce((await ie(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:C,profileId:m,app:R?.grantee??"app:terminal"})).launch,Y,e.model);await ue(le(J),{cwd:C,profileId:m}),await Cn({grantee:R?.grantee??"app:terminal",sub:R?.sub,grant_id:R?.grant_id});const Q=W?.node_id??null;let p,M=C;const B=O&&await Pe(m)?await De(m,F??e.worktreeCwd??e.cwd,w,e.worktreeBase):void 0,P=O&&B===void 0?await We(m):null;try{O&&B===void 0&&(p=P!==null?await Te(P,e.worktreeCwd??e.cwd,w,e.worktreeBase):await Ne(e.worktreeCwd??e.cwd,w,e.worktreeBase),M=p.path);const f=O?await ce((await ie(e.kind,l,{lifecycle:b,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:M,profileId:m,app:R?.grantee??"app:terminal"})).launch,Y,e.model):J;B!==void 0&&(f.worktree=B),O&&await ue(le(f),{cwd:M,profileId:m});const n=await Ce({kind:e.kind,mode:l,lifecycle:b,cwd:M,name:e.name??e.kind,description:e.description,parent:t?null:s,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:Q,spawnedBy:t?s??void 0:void 0,profile_id:m,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:E,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:x,modelOverride:e.model===void 0?void 0:f.model,...p!==void 0?{managedWorktree:p}:{},...w!==void 0?{nodeId:w}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await vn(n.node_id,Q??null)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}if(await je(n.node_id,e.prompt),e.situationalContext!==void 0&&await ze(n.node_id,He(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await g(n.node_id,"crash",{reason:"launch_failed",outcome:y(i)}),i}const z=e.prompt!=="",me=`${z&&e.wakeOrigin!==void 0?`${Ge(e.wakeOrigin)}
|
|
1
|
+
var ye=Object.defineProperty;var l=(e,r)=>ye(e,"name",{value:r,configurable:!0});import{accessSync as be,constants as xe}from"node:fs";import{isAbsolute as Ce,resolve as Se,join as Ee}from"node:path";import{appSpace as Oe}from"../layout.js";import{ApiError as ie}from"../../api/errors.js";import{spawnNode as Ie,forkSourceNode as $e,currentNodeContext as Re,rootOfSpine as Me,newNodeId as ae,preflightNodeId as Fe}from"./nodes.js";import{resolveProfileOperand as De}from"../profiles/manifest.js";import{selectProfileForCwd as Ne,selectProfileForCwdReadOnly as Be}from"../profiles/select.js";import{buildLaunchSpecAsync as de,buildPiArgv as Pe}from"./launch.js";import{devEnvironmentCwd as Le,runsOnBlaxel as Te,sandboxWorktreeRequest as Ae}from"../../daemon/api/environment-of.js";import{createManagedWorktreeAsync as We,rollbackManagedWorktreeAsync as je}from"../worktree-mutation-async.js";import{createManagedWorktreeOnMachine as ze,rollbackManagedWorktreeOnMachine as He,worktreeMachineOf as Ke}from"../worktree-machine.js";import{usage as p,brokerLaunchFailed as H}from"../errors.js";import{writeGoal as Ue}from"./kickoff.js";import{appendSituationalContext as Xe,formatSituationalProse as Ge}from"./situational-context.js";import{ensureRoadmap as Ve}from"./roadmap.js";import{buildWakeBearings as qe}from"./bearings.js";import{encodeKickoffOrigin as Je,KICKOFF_ORIGIN_ENV as Ye}from"./stamp/protocol.js";import{carryInitialInput as Qe}from"../runs/initial-input.js";import{ExecutionCapReached as se,beginExecution as le,crtrHome as Ze,getNode as w,fullName as ce,jobDir as en,recordExecutionPid as nn,abortExecution as B,setFrozen as X}from"../canvas/index.js";import{contextDir as G,nodeAgentDir as V}from"../canvas/node-agent-paths.js";import{copyTreeBeneath as rn}from"../spaces/open-beneath.js";import{conversationIdFromPath as K,conversationStore as $}from"../conversation-store/index.js";import{appMemoryTooSmall as on,boundFleet as ue,brokerThresholdsForDaemon as q}from"./fleet.js";import{admitBrokerMemory as tn}from"./memory-admission.js";import{emitEvent as v}from"../events/emit.js";import{remoteEnvironmentOf as an}from"./blaxel-environment.js";import{openViewerWindow as dn,focusOf as sn,windowOfPane as ln}from"./placement.js";import{awaitBrokerViewSocket as cn}from"./view-socket.js";import{readLogSnapshot as un}from"../events/read.js";import{transition as C}from"./lifecycle.js";import{beginBootFaultAttempt as fn}from"../canvas/recovery.js";import{headlessBrokerHost as J,brokerLaunchJson as wn}from"./host.js";import{openDb as mn,withCanvasWrite as hn}from"../canvas/db.js";import{warmNodeRepos as pn}from"../graph/reader.js";import{mintNodeToken as _n}from"../canvas/node-tokens.js";import{personIdAsync as kn}from"../canvas/person.js";import{recordLaunch as vn}from"../canvas/canvas.js";import{setExecutionLaunchJson as gn}from"../canvas/executions.js";import{acceptedRelease as fe,remoteMachineEnvironmentOf as yn}from"../../daemon/reconcilers/node-lifecycle/remote-wake.js";import{enqueueMachineCall as bn,awaitMachineCall as xn}from"./runner/machine/call.js";import{MachineLostError as Cn,MachineOfflineError as Sn}from"./runner/machine/ops.js";import{isDrained as En}from"../../daemon/drain.js";import{ensureDaemon as On}from"../../daemon/manage.js";import{readConfig as In}from"../config.js";import{modelRequestFromConfig as $n,unregisteredConcreteModel as Rn,unroutableConcreteModel as Mn}from"../model-routes.js";import{openModelRegistry as Fn}from"./model-registry.js";import{MODEL_SPEC_NEXT as Dn}from"./model-selection.js";import{forkNodeLedger as Nn}from"./ledger.js";import{appRungForGrant as Bn}from"../llm/app-rungs.js";import{APP_FAMILY as Y}from"../model-routes.js";import{discoverLifecycleHookRegistry as Pn}from"../command-hooks/discovery.js";import{invokeLifecycleHooks as Ln}from"../command-hooks/transport/exec-lifecycle.js";import{someAsync as Tn}from"../async-array.js";import{checkStart as An}from"./start-check.js";function S(e){return{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}l(S,"launchFailureOutcome");async function Wn(e,r,a){try{return await J.launch(e,r,a)}catch(o){try{await C(e,"crash",{reason:"launch_failed",outcome:S(o)})}catch{}const t=o.message;throw H(t.startsWith("[broker]")?t:`[broker] refusing to launch ${e}: ${t}`,"Inspect the cause above, fix the launch recipe or environment, then retry.")}}l(Wn,"launchBrokerOrCrash");function jn(e){return un({nodeId:e,component:"broker",pattern:"broker.startup."},!1).items.flatMap(a=>a.kind==="event"&&a.envelope.event.startsWith("broker.startup.")&&a.envelope.event!=="broker.startup.warning"?[a.envelope.event.slice(15)]:[]).at(-1)??null}l(jn,"lastStartupStep");function zn(e,r){const a=jn(e),o=a===null?"it had logged no startup step":`the last startup step it logged was \`${a}\``;if(r.reason==="exited"){const{code:t,signal:d}=r.status;return{text:`exited (code ${t??"null"}, signal ${d??"null"}) before binding its view socket; ${o}`,fields:{reason:"exited",code:t,signal:d,last_startup_step:a}}}return{text:`was still starting after ${Math.round(r.waitedMs/1e3)} s without binding its view socket, so the launcher stopped it; ${o}`,fields:{reason:"timeout",waited_ms:r.waitedMs,last_startup_step:a}}}l(zn,"notReadyDescription");async function Hn(e,r){try{await C(e,"crash",{reason:"launch_failed",outcome:S(r)})}catch{}try{J.teardown(e)}catch{}}l(Hn,"crashAndTearDown");async function Kn(e){const r=(await $().list()).map(({conversation_id:t,path:d})=>({id:t,path:d})),a=r.filter(t=>t.id===e),o=a.length>0?a:r.filter(t=>t.id.startsWith(e));if(o.length===0)throw p(`--fork-from '${e}': no pi session with that id found.`,{next:"Pass a live node id, a real session uuid/prefix, or an absolute .jsonl session path."});if(o.length>1)throw p(`--fork-from '${e}': ambiguous \u2014 ${o.length} sessions match that id prefix; pass the full id or the .jsonl path.`,{next:"Pass the full session uuid or an absolute .jsonl path to disambiguate."});return o[0].path}l(Kn,"resolveSessionUuid");async function we(e){const r=e.trim();if(r==="")throw p("--fork-from requires a node id, session file, or session uuid.",{next:"Pass a live node id, an absolute .jsonl session path, or a session uuid/prefix."});if(r.includes("/")||r.endsWith(".jsonl")){const o=K(Ce(r)?r:Se(process.cwd(),r));if(o===null)throw p(`--fork-from '${r}': invalid conversation path.`,{next:"Pass a conversation file path or id."});return(await $().header(o)).path}const a=await w(r);if(a!==null){const o=a.pi_session_file;if(o==null||o==="")throw p(`node ${r} has no pi session yet \u2014 it has not captured a session FILE to fork from (the broker forks a .jsonl path, not a bare id).`,{next:"Pick a node that has captured a session, or drop --fork-from."});const t=K(o);if(t===null)throw p(`node ${r} has no valid conversation id.`,{next:"Pick a node with a captured conversation."});return(await $().header(t)).path}return await Kn(r)}l(we,"resolveForkSource");async function Un(e,r,a,o={}){return e===null?null:e!==void 0&&e!==""?De(e).profileId:r!==null?(await w(r))?.profile_id??null:o.readOnlySelection===!0?Be(a):Ne(a)}l(Un,"resolveProfileId");function me(e){const r=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return $n(e.model,r,e.modelExact===!0)}l(me,"requestFromLaunch");async function he(e,r,a){const o=a??(e.modelIntent?`${e.modelIntent.family}/${e.modelIntent.strength}`:e.model),t=await Bn(r,o,e.modelExact===!0);if(t===null)return e;const{CRTR_MODEL_INTENT:d,...c}=e.env??{};return{...e,model:t.model,modelIntent:{family:Y,strength:t.strength},modelExact:void 0,env:{...c,CRTR_MODEL_INTENT:`${Y}/${t.strength}`}}}l(he,"appPaidLaunch");async function pe(e,r,a){if(e===void 0||e.kind==="logical"&&e.family!==Y)return;const o=await Rn(e.kind==="logical"?{kind:"concrete",spec:e.spec}:e,a??await Fn(),r);if(o!==void 0)throw p(`model '${o.request.spec}' is not registered in this daemon.`,{received:o.request.spec,next:Dn});const t=await Mn(e,r);if(t!==void 0)throw p(`model '${t.spec}' is registered but no configured model route offers it, so no turn could be served.`,{received:t.spec,next:"Pick a model from your configured routes (`crtr sys config get modelLadders`), or add this one to a ladder or route."})}l(pe,"assertLaunchModelRegistered");function Xn(e,r,a){const o=e??r??null;if(!a&&o===null)throw new Error("spawnChild requires a calling node (CRTR_NODE_ID) or an explicit parent");return o}l(Xn,"resolveSpawner");async function Gn(e,r,a){const{buildStartBundle:o}=await import("../../daemon/api/handlers/execution-start.js"),{renderCarriedStart:t}=await import("../../daemon/api/handlers/broker-ops.js");if(await En())return"full";let d;try{d=await le(e.node_id,{daemonEpoch:ue().epoch(),cap:q().automaticReviveCap,runner:"machine",release:fe()})}catch(s){return s instanceof se?"full":(v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),"failed")}let c;try{a.env={...a.env,CRTR_EXECUTION_ID:d};const s=await wn(e.node_id,a,e.cwd);await gn(d,s);const P=d;await pn(await mn(),e.node_id);const E=e.sub??await kn(),L=await o({nodeId:e.node_id,app:e.grantee??"app:terminal",sub:E,launchJson:s,runner:"machine"});c=await hn(async _=>{const R=await t(e.node_id),M=await _n(_,P,e.node_id,new Date().toISOString());return await bn(r,"start",{executionId:P,nodeId:e.node_id,attempt:1,sandboxName:null,release:fe(),launchJson:s,cwd:e.cwd,resuming:!1,nodeToken:M,bundle:L,start:R})})}catch(s){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),await B(d,{reason:"launch_failed"}),"failed"}try{await xn(r,"start",c)}catch(s){return v({level:"warn",event:"broker.create_start_failed",node_id:e.node_id,error:s}),s instanceof Cn||s instanceof Sn&&s.sent?"uncertain":(await B(d,{reason:"launch_failed"}),"failed")}try{await vn(e.node_id,new Date().toISOString())}catch(s){v({level:"warn",event:"broker.create_start_record_failed",node_id:e.node_id,error:s})}return"started"}l(Gn,"startOnMachine");async function _e(e,r,a){try{On()}catch{}const o=Re(),t=e.root===!0,d=Xn(e.parent,o.nodeId??null,t),c=e.mode??"base",s=e.rootLifecycle??(t?"resident":"terminal"),P=t&&s==="resident",E=d===null?null:await w(d),L=e.creator===void 0||e.creator===null?null:await w(e.creator);e.nodeId!==void 0&&await Fe(e.nodeId);const _=e.forkFrom!==void 0?await we(e.forkFrom):void 0,R=_===void 0?null:await $e(_),M=await Tn([E,L,R],async f=>f?.isolated===!0||f?.run_id!=null&&(await w(f.run_id))?.isolated===!0);if(M&&e.isolated===!1)throw new ie(403,"isolated_run","isolation cannot be turned off under an isolated run",{param:"isolated"});const F=M||e.isolated===!0;if(F&&e.worktree===!0)throw new ie(400,"invalid_request","isolated nodes cannot use a worktree",{param:"worktree"});let m=F||e.worktree===!0?e.nodeId??await ae():e.nodeId,O=F?e.run!==void 0&&t&&!M?e.cwd:Ee(Oe(e.run?.grantee??E?.grantee??"app:terminal").nodes,m):e.cwd;const h=await Un(e.profile,d,O),T=F?null:await Le(h,e.worktreeCwd??O);T!==null&&(O=T,m??=await ae());const D=e.worktree===!0||T!==null,Q=e.run?.grant_id??E?.grant_id??null,N=e.run??L??E??R,Z=await he((await de(e.kind,c,{lifecycle:s,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:O,profileId:h,app:N?.grantee??"app:terminal"})).launch,Q,e.model);await pe(me(Z),{cwd:O,profileId:h}),await An({grantee:N?.grantee??"app:terminal",sub:N?.sub,grant_id:N?.grant_id});const ee=R?.node_id??null;let g,A=O;const W=D&&await Te(h)?await Ae(h,T??e.worktreeCwd??e.cwd,m,e.worktreeBase):void 0,j=D&&W===void 0?await Ke(h):null;try{D&&W===void 0&&(g=j!==null?await ze(j,e.worktreeCwd??e.cwd,m,e.worktreeBase):await We(e.worktreeCwd??e.cwd,m,e.worktreeBase),A=g.path);const f=D?await he((await de(e.kind,c,{lifecycle:s,hasManager:!t,model:e.model,modelOverride:e.model!==void 0,cwd:A,profileId:h,app:N?.grantee??"app:terminal"})).launch,Q,e.model):Z;W!==void 0&&(f.worktree=W),D&&await pe(me(f),{cwd:A,profileId:h});const n=await Ie({kind:e.kind,mode:c,lifecycle:s,cwd:A,name:e.name??e.kind,description:e.description,parent:t?null:d,creator:e.creator,...e.actor===void 0?{}:{actor:e.actor},forkSourceNode:ee,spawnedBy:t?d??void 0:void 0,profile_id:h,...e.scopes===void 0?{}:{scopes:e.scopes},isolated:F,...e.run===void 0?{}:{run:e.run},...e.causedBy===void 0?{}:{causedBy:e.causedBy},...e.withinCreate===void 0?{}:{withinCreate:e.withinCreate},forkFrom:e.forkFrom,forkSourceFile:_,modelOverride:e.model===void 0?void 0:f.model,...g!==void 0?{managedWorktree:g}:{},...m!==void 0?{nodeId:m}:{},...e.reviewBinding===void 0?{}:{reviewBinding:e.reviewBinding},...e.deadlineAt===void 0?{}:{deadlineAt:e.deadlineAt},...e.outcomeDelivery===void 0?{}:{outcomeDelivery:e.outcomeDelivery},launch:f});if(a?.(n.node_id),e.forkFrom!==void 0)try{await Nn(n.node_id,ee??null)}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}if(await Ue(n.node_id,e.prompt),e.situationalContext!==void 0&&await Xe(n.node_id,Ge(e.situationalContext)),r!==void 0)try{r(n.node_id)}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}const U=e.prompt!=="",ke=`${U&&e.wakeOrigin!==void 0?`${qe(e.wakeOrigin)}
|
|
2
2
|
|
|
3
|
-
`:""}${e.prompt}`;
|
|
3
|
+
`:""}${e.prompt}`;c==="orchestrator"&&await Ve(n.node_id,{goal:e.prompt.trim()}),await Vn(n);let ne;if(_!==void 0)try{const i=K(_);if(i===null)throw new Error(`invalid fork source ${_}`);const u=await $().fork(i,n.node_id);ne=(await $().header(u)).path}catch(i){throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}const k=Pe(n,{prompt:ke,resumeSessionPath:ne});if(k.env={...k.env,CRTR_SUBTREE:await Me(n.node_id)},U){const i=e.wakeOrigin!==void 0?{type:"runtime",kind:"wake",wake:e.wakeOrigin}:{type:"runtime",kind:"kickoff",...n.spawned_by!=null&&n.spawned_by!==""?{spawnedBy:n.spawned_by}:{}};k.env[Ye]=Je(i),await Qe(k,n)}const y=ue();if(await an(n.profile_id??null)!==null){const i=new Date().toISOString(),u=e.start===!0?await yn(n.profile_id??null):null;if(u!==null){const x=await Gn(n,u,k);if(x==="started"||x==="uncertain")return{node:n,frozen:!1,window:null,session:null}}return await X(n.node_id,i),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"remote_environment"}}),{node:{...n,frozen_at:i},frozen:!0,window:null,session:null}}const re=await y.reserveSlot(n.node_id),b=re?await tn(n.node_id):null;if(b?.verdict==="too_small"){y.releaseReservation(n.node_id);const i=on(b);throw await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),i}if(!re||b?.verdict==="denied")return b?.verdict==="denied"&&y.releaseReservation(n.node_id),await X(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:b?.verdict==="denied"?{reason:"app_memory",free_bytes:b.free_bytes,needed_bytes:b.needed_bytes}:{reason:"broker_cap",live_count:await y.occupancy(),hard_cap:q().automaticReviveCap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null};const ve=await fn(n.node_id),{automaticReviveCap:ge}=q();let I;try{I=await le(n.node_id,{daemonEpoch:y.epoch(),cap:ge})}catch(i){if(!(i instanceof se))throw i;return y.releaseReservation(n.node_id),await X(n.node_id,new Date().toISOString()),v({level:"info",event:"broker.frozen",node_id:n.node_id,fields:{reason:"broker_cap",live_count:i.live,hard_cap:i.cap}}),{node:await w(n.node_id),frozen:!0,window:null,session:null}}k.env={...k.env,CRTR_EXECUTION_ID:I};let z;try{z=await Wn(n.node_id,k,{cwd:n.cwd,name:ce(n),resuming:!1})}catch(i){throw await B(I,{reason:"launch_failed"}),i}finally{y.releaseReservation(n.node_id)}if(z.pid===null){const i=new Error(`broker host returned no pid for ${n.node_id}`);throw await B(I,{reason:"launch_failed"}),await C(n.node_id,"crash",{reason:"launch_failed",outcome:S(i)}),H(`failed to launch the broker engine for ${n.node_id} (${n.name}) \u2014 the node was not started.`,`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then verify the pi engine can start in this environment.`)}if(await nn(I,n.node_id,z.pid)==="shutdown")throw await B(I,{reason:"superseded"}),J.teardown(n.node_id),H(`broker execution was superseded for ${n.node_id}`,"Retry spawning the node.");if(P&&e.readiness==="await"){const i=await cn(n.node_id,z.exited);if(!i.ready){const u=zn(n.node_id,i);v({level:"error",event:"broker.launch.not_ready",node_id:n.node_id,fields:u.fields});const x=await ve.explanation();throw await Hn(n.node_id,new Error(x??u.text)),H(x!==null?`the root broker ${n.node_id} could not start \u2014 ${x}`:`the root broker ${n.node_id} ${u.text} \u2014 it was not started.`,x!==null?"Resolve the cause named above, then retry.":`Inspect canonical event diagnostics with \`crtr sys logs --node ${n.node_id}\`, then retry.`)}}let oe=null,te=null;if(!t&&d!==null&&In("user").auto_open_child_viewers)try{const i=await sn(d);if(i!==null&&i.pane!==null&&i.pane!==""){const u=await dn(n.node_id,i.session??"",{name:ce(n),cwd:e.cwd,besidePane:i.pane,waitForBroker:!0,initialWhip:U});u!==null&&u.pane!==null&&u.pane!==""&&(te=u.session,oe=ln(u.pane))}}catch{}return{node:await w(n.node_id),frozen:!1,window:oe,session:te}}catch(f){throw g!==void 0&&m!==void 0&&await w(m)===null&&(j!==null?await He(j,g):await je(g)),f}}l(_e,"spawnChildPrepared");async function Zr(e){return _e(e)}l(Zr,"spawnChild");async function Vn(e){const r=Pn(e.cwd,e.profile_id).plans.get("node:start")??[];await Ln(r,{node:{id:e.node_id,name:e.name,kind:e.kind,mode:e.mode,lifecycle:e.lifecycle,cwd:e.cwd,nodeDir:await V(e.node_id),contextDir:await G(e.node_id),jobDir:en(e.node_id)},runtime:{isBirth:!0,canvasHome:Ze(),profile:e.profile_id??null}})}l(Vn,"invokeBirthLifecycleHooks");const qn=new Set(["initial-prompt.md","yield-message.md","result.json","jobs"]);async function eo(e,r,a){const o=await w(e);if(o===null)throw p(`unknown node: ${e}`,{received:e,next:"List nodes and pass the id of a node with a captured pi session."});const t=await we(e),d=await G(e);try{await $().header(K(t)),be(d,xe.R_OK)}catch(c){throw new Error(`cannot fork ${e}: its conversation or context is unreadable \u2014 ${c.message}`)}return _e({kind:o.kind,mode:"base",cwd:o.cwd,prompt:"",root:!0,readiness:"await",forkFrom:e,...a===void 0?{}:{actor:a},profile:o.profile_id,model:o.model_override??void 0,...r===void 0?{}:{scopes:r}},async c=>{const s=await G(c);rn(await V(e),d,await V(c),s,qn)})}l(eo,"forkNode");export{he as appPaidLaunch,pe as assertLaunchModelRegistered,eo as forkNode,Vn as invokeBirthLifecycleHooks,we as resolveForkSource,Un as resolveProfileId,Xn as resolveSpawner,Zr as spawnChild,_e as spawnChildPrepared};
|
|
@@ -39,6 +39,8 @@ export declare class RefreshTimeoutError extends Error {
|
|
|
39
39
|
constructor(provider: ManagedProviderId);
|
|
40
40
|
}
|
|
41
41
|
export declare const aadOf: (person: string, provider: string, id: string, part: "refresh" | "access") => string;
|
|
42
|
+
/** Every managed provider's pool for the person in two statements (accounts, cooldowns), tokens opened. A provider with no account is absent. */
|
|
43
|
+
export declare function readAllSubscriptionPools(): Promise<Map<ManagedProviderId, SubscriptionCredential[]>>;
|
|
42
44
|
export declare function insertAccount(db: CanvasDb, person: string, provider: ManagedProviderId, row: ProviderRow, entry: StoredCredential): Promise<void>;
|
|
43
45
|
export declare function upsertModelCooldown(db: CanvasDb, person: string, provider: string, accountId: string, family: string, until: number, rateLimitedAt: number): Promise<void>;
|
|
44
46
|
export declare function readSubscriptionPool(provider: ManagedProviderId): Promise<SubscriptionCredential[]>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _t=Object.defineProperty;var l=(t,a)=>_t(t,"name",{value:a,configurable:!0});import{createHash as pt,randomUUID as I}from"node:crypto";import{brokerConfigSnapshot as ht}from"./config.js";import{openDb as K,withCanvasWrite as F}from"./canvas/db.js";import{personIdAsync as y}from"./canvas/person.js";import{loadSecretsKey as B,open as Y,seal as $}from"./secrets/index.js";import{classifyRateLimit as wt,modelCooldownFamily as At}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as bt,REFRESH_TIMEOUT_PHRASE as yt}from"./provider-error-recognition.js";import{registerRotationReader as Et}from"./model-routes.js";import{coolingUntilFor as Lt,retryAfterMsFromHeaders as Rt,getProviderLabel as p,isInvalidRefreshTokenError as J,DuplicateSubscriptionError as O,ANTHROPIC_PROVIDER_ID as gt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as xt}from"./managed-providers.js";export*from"./managed-providers.js";const Q="strong";function Z(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(Z,"normalizeStrength");function _(t){return t.toLowerCase()}l(_,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function It(t){const a=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",n=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!a||!e||!n||!Number.isFinite(i))return;const r=V(t.accountId),s=V(t.clientId);return{label:a,refresh:e,access:n,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...v(t.modelCooldowns)?{modelCooldowns:v(t.modelCooldowns)}:{}}}l(It,"credential");function v(t){if(!t||typeof t!="object"||Array.isArray(t))return;const a=Object.entries(t).filter(([e,n])=>e.trim()!==""&&Number.isFinite(Number(n))).map(([e,n])=>[e,Number(n)]);return a.length?Object.fromEntries(a):void 0}l(v,"modelCooldowns");function N(t,a){if(!a.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=It(a);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${a.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(N,"assertCredential");function tt(t,a){const e=t.accountId?.trim(),n=a.accountId?.trim();return!!(e&&n&&e!==n)}l(tt,"differentAccount");function h(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${pt("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(h,"identity");function et(t,a){const e=V(a);return e?{...t,clientId:e}:t}l(et,"withClientId");function at(t,a,e){const n=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!n||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${a}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:n,access:i,expires:r}}l(at,"assertTokens");const nt=1e4,Ft="15s",Nt="55P03";class it extends Error{static{l(this,"RefreshBusyError")}constructor(a,e){super(`${p(a)} subscription "${e}" ${bt}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class St extends Error{static{l(this,"RefreshTimeoutError")}constructor(a){super(`${p(a)} ${yt} ${nt} ms`),this.name="RefreshTimeoutError"}}const rt="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",x=l((t,a,e,n)=>`model_accounts|${t}|${a}|${e}|${n}`,"aadOf");function E(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(E,"stored");function Tt(t,a){return{providerId:t,id:a.id,label:a.label,labelKey:a.label_key,position:a.position,lastAttemptAt:a.last_attempt_at,lastRateLimitedAt:a.last_rate_limited_at,rateLimitedUntil:a.rate_limited_until,...a.auth_failure?{authFailure:a.auth_failure}:{}}}l(Tt,"rowOf");function st(t,a,e,n=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${a} account ${e.id} has no credential record`);const i=B(),r=Y(e.refresh_sealed,e.key_id,i,x(t,a,e.id,"refresh")),s=Y(e.access_sealed,e.key_id,i,x(t,a,e.id,"access")),o=Tt(a,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+j),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...n.length?{modelCooldowns:Object.fromEntries(n.map(d=>[d.family,d.lastRateLimitedAt?Math.min(d.rateLimitedUntil,d.lastRateLimitedAt+j):d.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(st,"toPublic");async function S(t,a,e){const n=new Map,i=await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(a,e);for(const r of i){const s=n.get(r.account_id)??[];s.push({family:r.family,rateLimitedUntil:r.rate_limited_until,lastRateLimitedAt:r.last_rate_limited_at}),n.set(r.account_id,s)}return n}l(S,"loadCooldowns");async function k(t,a,e,n=!1){const i=await t.prepare(`SELECT ${rt} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${n?" FOR UPDATE":""}`).all(a,e),r=await S(t,a,e);return i.map(s=>st(a,e,s,r.get(s.id)))}l(k,"loadPool");async function ot(t,a,e,n){const i=n.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${rt} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(a,e,s?r-1:i);if(o)return st(a,e,o,(await S(t,a,e)).get(o.id))}l(ot,"lockedAccount");async function T(t){await t.exec(`SET LOCAL lock_timeout = '${Ft}'`)}l(T,"setLockTimeout");async function L(t,a){const e=await y();return F(async n=>(await T(n),await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),a({db:n,person:e,rows:await k(n,e,t,!0)})))}l(L,"locked");async function C(t,a,e,n,i){const r=B(),s=$(i.refresh,r,x(a,e,n.id,"refresh")),o=$(i.access,r,x(a,e,n.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(a,e,n.id,n.label,n.labelKey,n.position,n.lastAttemptAt,n.lastRateLimitedAt,n.rateLimitedUntil,n.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(C,"insertAccount");async function M(t,a,e,n,i){const r=B(),s=$(i.refresh,r,x(a,e,n,"refresh")),o=$(i.access,r,x(a,e,n,"access"));await t.prepare("UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?").run(s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId,a,e,n)}l(M,"setCredential");async function b(t,a,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,a,e.providerId,e.id)}l(b,"updateHealth");async function lt(t,a,e,n,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(a,e,n,i,r,s)}l(lt,"upsertModelCooldown");async function U(t,a,e,n){n===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(a,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(a,e,n)}l(U,"deleteModelCooldowns");const R=l(async({db:t,person:a},e)=>(await k(t,a,e)).map(({entry:n})=>n),"publicPool"),ct=l(t=>t?.code===Nt,"lockWaitExpired");function ut(t,a){let e;return Promise.race([a,new Promise((n,i)=>{e=setTimeout(()=>i(new St(t)),nt)})]).finally(()=>clearTimeout(e))}l(ut,"withExchangeTimeout");async function G(t){return(await Ut(t)).map(({entry:a})=>a)}l(G,"readSubscriptionPool");async function Ut(t){const a=await y();return(await k(await K(),a,t)).map(({row:e,entry:n})=>({id:e.id,entry:n}))}l(Ut,"readSubscriptionPoolRows");async function Yt(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=a.map(d=>N(t,d)),o=s.map((d,u)=>({entry:d,id:r[u]?.row.id??I()})),c=await S(n,i,t);await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await U(n,i,t);for(const[d,{entry:u,id:m}]of o.entries()){await C(n,i,t,{providerId:t,id:m,label:u.label,labelKey:_(u.label),position:d,lastAttemptAt:u.lastAttemptAt,lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:u.rateLimitedUntil,...u.authFailure?{authFailure:u.authFailure}:{}},E(u));for(const[f,A]of Object.entries(u.modelCooldowns??{}))await lt(n,i,t,m,f,A,c.get(m)?.find(D=>D.family===f)?.lastRateLimitedAt??u.lastRateLimitedAt)}return s})}l(Yt,"writeSubscriptionPool");function H(t,a){const e=a.trim().toLowerCase(),n=Number.parseInt(e,10);return Number.isFinite(n)&&String(n)===e&&n>=1&&n<=t.length?n-1:t.findIndex(({entry:i})=>_(i.label)===e)}l(H,"resolve");const P=l((t,a)=>new O(`This ${p(t)} account is already added as \u201C${a}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Dt(t,a){const e=N(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n;if(s.some(({entry:d})=>_(d.label)===_(e.label)))throw new O(`${p(t)} subscription already exists: ${e.label}`);const o=h(e),c=s.find(({entry:d})=>h(d)===o);if(o&&c)throw P(t,c.entry.label);return await C(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},E(e)),R(n,t)})}l(Dt,"addSubscription");async function Jt(t,a){const e=N(t,a);return(await G(t)).find(i=>_(i.label)===_(e.label))?$t(t,e):Dt(t,e)}l(Jt,"upsertSubscription");async function $t(t,a){const e=N(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=s.findIndex(({entry:f})=>_(f.label)===_(e.label)),c=s[o],d=s.find(({entry:f},A)=>A!==o&&h(f)===h(e));if(h(e)&&d)throw P(t,d.entry.label);if(!c)return await C(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},E(e)),R(n,t);const u=c.row,m=e.lastRateLimitedAt>=u.lastRateLimitedAt;return await M(i,r,t,u.id,E(e)),await b(i,r,{...u,authFailure:void 0,label:e.label,labelKey:_(e.label),lastAttemptAt:Math.max(u.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:m?e.lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:m?e.rateLimitedUntil:u.rateLimitedUntil}),tt(c.entry,e)&&await U(i,r,t,u.id),R(n,t)})}l($t,"upsertSubscriptionWithUniqueAccount");async function Qt(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=H(s,a);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const c=e.trim();if(!c)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((d,u)=>u!==o&&_(d.entry.label)===_(c)))throw new O(`${p(t)} subscription already exists: ${c}`);return await b(i,r,{...s[o].row,label:c,labelKey:_(c)}),R(n,t)})}l(Qt,"renameSubscription");async function z(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=a(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await U(i,r,t,c.id),R(n,t)})}l(z,"remove");async function Ot(t,a){return z(t,e=>H(e,a),a)}l(Ot,"removeManagedAccount");async function Zt(t,a){return z(t,e=>e.findIndex(({row:n})=>n.id===a),a)}l(Zt,"removeManagedAccountById");async function vt(t,a){return z(t,e=>H(e,a),a)}l(vt,"removeSubscription");async function kt(t){return L(t,async({db:a,person:e,rows:n})=>(await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await U(a,e,t),n.length))}l(kt,"removeAllManagedAccounts");async function te(t,a){return a===void 0?(await kt(t),[]):Ot(t,a)}l(te,"removeManagedProvider");async function ee(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=H(r,a);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const o=[r[s],...r.filter((c,d)=>d!==s)];for(const[c,d]of o.entries())await b(n,i,{...d.row,position:c});return R(e,t)})}l(ee,"promoteSubscription");async function W(t,a,e){const n=await y();return await F(async i=>{await T(i);const r=await ot(i,n,t,a);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${a}`);await e(i,n,r.row)}),G(t)}l(W,"healthWrite");async function ae(t,a,e=Date.now()){return W(t,a,(n,i,r)=>b(n,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(ae,"markSubscriptionAttempt");async function ne(t,a,e,n=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),W(t,a,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n)});const d=(await S(s,o,t)).get(c.id)?.find(u=>u.family===r.family);d&&i<d.lastRateLimitedAt||await lt(s,o,t,c.id,r.family,i+e,i)})}l(ne,"markSubscriptionRateLimited");async function ie(t,a,e=Date.now(),n){const i=At(n);return W(t,a,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await b(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await S(r,s,t)).get(o.id)?.find(d=>d.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(ie,"markSubscriptionSuccess");async function q(t,a,e){const n=Date.now();await b(t,a,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,n),rateLimitedUntil:Math.max(e.rateLimitedUntil,n+xt)})}l(q,"recordInvalidGrant");function re(t,a,e,n=15e3,i=Date.now()){const r=Rt(t),s=wt(t,a,i),o=e??r??n;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(re,"vendorRateLimit");async function se(t,a){return W(t,a,(e,n,i)=>q(e,n,i))}l(se,"markSubscriptionAuthFailure");async function oe(t,a,e){const n=await y();let i;try{i=await F(async r=>{await T(r);const s=await ot(r,n,t,a);if(!s)throw new Error(`${p(t)} subscription "${a}" no longer exists`);if(s.entry.expires>Date.now())return{entry:s.entry};if(s.row.authFailure)throw new Error(`${p(t)} subscription "${s.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);let o;try{o=await ut(t,e(s.entry.refresh,s.entry.clientId))}catch(d){if(!J(d))throw d;return await q(r,n,s.row),{refused:d}}const c=et(at(t,s.entry.label,o),o.clientId??s.entry.clientId);return await M(r,n,t,s.row.id,E({...s.entry,...c})),{entry:{...s.entry,...c}}})}catch(r){throw ct(r)?new it(t,a):r}if("refused"in i)throw i.refused;return i.entry}l(oe,"refreshSubscriptionCredential");async function le(t,a,e){const n=await y();let i;try{i=await F(async r=>{await T(r);const s=await k(r,n,t,!0),o=new Set;let c;for(;o.size<s.length;){const d=a(s.filter(({entry:m})=>!o.has(m.label)).map(({entry:m})=>m));if(!d)break;const u=s.find(({entry:m})=>m.label===d.label);o.add(u.entry.label);try{const m=await ut(t,e(u.entry));if(!m)return{entry:u.entry};const f=et(at(t,u.entry.label,m),m.clientId??u.entry.clientId);return await M(r,n,t,u.row.id,E({...u.entry,...f})),{entry:{...u.entry,...f}}}catch(m){if(!J(m))throw m;c=m,await q(r,n,u.row)}}return c?{refused:c}:{}})}catch(r){throw ct(r)?new it(t,a([])?.label??t):r}if("refused"in i)throw i.refused;return i.entry}l(le,"modifyElectedSubscription");async function Ct(t,a){const e=a.accountId?.trim(),n=a.email?.trim();if(t!==gt)return{...e?{accountId:e}:{},...n?{email:n}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${a.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Ct,"enrichManagedLoginIdentity");async function ce(t,a,e){const n=await Ct(t,e);return L(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:a?.trim(),d=h({refresh:e.refresh,accountId:n.accountId}),u=(c?o.find(({entry:w})=>_(w.label)===_(c)):void 0)??o.find(({entry:w})=>h(w)===d);let m=u?.entry.label??c;if(!m&&e.autoLabel){const w=n.email||a?.trim()||`Account ${o.length+1}`;m=w;for(let g=2;o.some(({entry:ft})=>_(ft.label)===_(m));g++)m=`${w} (${g})`}if(!m)throw new Error(`${p(t)} subscription label cannot be empty`);const f=N(t,{label:m,refresh:e.refresh,access:e.access,expires:e.expires,...n.accountId?{accountId:n.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!u){if(o.some(({entry:g})=>_(g.label)===_(f.label)))throw new O(`${p(t)} subscription already exists: ${f.label}`);const w=o.find(({entry:g})=>h(g)===h(f));if(h(f)&&w)throw P(t,w.entry.label);return await C(r,s,t,{providerId:t,id:I(),label:f.label,labelKey:_(f.label),position:o.length,lastAttemptAt:f.lastAttemptAt,lastRateLimitedAt:f.lastRateLimitedAt,rateLimitedUntil:f.rateLimitedUntil},E(f)),R(i,t)}const A=u.row,D=o.find(({entry:w})=>w.label!==u.entry.label&&h(w)===h(f));if(h(f)&&D)throw P(t,D.entry.label);const X=f.lastRateLimitedAt>=A.lastRateLimitedAt;return await M(r,s,t,A.id,E(f)),await b(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,f.lastAttemptAt),lastRateLimitedAt:X?f.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:X?0:A.rateLimitedUntil}),tt(u.entry,f)&&await U(r,s,t,A.id),R(i,t)})}l(ce,"commitManagedLogin");const dt=new Map;function mt(t){return{defaultFallbackStrength:Z(t?.default_fallback_strength)??Q,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(mt,"rotationFromRow");async function Mt(){const t=await y(),a=mt(await(await K()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return dt.set(t,a),a}l(Mt,"loadRotationConfig"),Et(()=>Ht());async function Ht(){const t=ht();return t?t.rotation:Mt()}l(Ht,"readRotationConfig");async function ue(t){const a=await y(),e=await F(async n=>{await T(n),await n.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(a);const i=mt(await n.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(a)),r={defaultFallbackStrength:Z(t.defaultFallbackStrength)??i.defaultFallbackStrength??Q,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await n.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,a),r});return dt.set(a,e),e}l(ue,"writeRotationConfig");async function de(){const t=await y();return(await(await K()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,I())).openai_device_id}l(de,"openAIDeviceId");async function me(t,a=Date.now(),e){const n=await G(t),i=n.filter(s=>s.authFailure===void 0&&Lt(s,e)<=a),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${n.length} ready)`}l(me,"formatStatusLine");export{nt as REFRESH_EXCHANGE_TIMEOUT_MS,it as RefreshBusyError,St as RefreshTimeoutError,x as aadOf,Dt as addSubscription,ce as commitManagedLogin,Ct as enrichManagedLoginIdentity,me as formatStatusLine,C as insertAccount,Mt as loadRotationConfig,ae as markSubscriptionAttempt,se as markSubscriptionAuthFailure,ne as markSubscriptionRateLimited,ie as markSubscriptionSuccess,le as modifyElectedSubscription,de as openAIDeviceId,ee as promoteSubscription,Ht as readRotationConfig,G as readSubscriptionPool,Ut as readSubscriptionPoolRows,oe as refreshSubscriptionCredential,kt as removeAllManagedAccounts,Ot as removeManagedAccount,Zt as removeManagedAccountById,te as removeManagedProvider,vt as removeSubscription,Qt as renameSubscription,lt as upsertModelCooldown,Jt as upsertSubscription,$t as upsertSubscriptionWithUniqueAccount,re as vendorRateLimit,ue as writeRotationConfig,Yt as writeSubscriptionPool};
|
|
1
|
+
var pt=Object.defineProperty;var l=(t,n)=>pt(t,"name",{value:n,configurable:!0});import{createHash as ht,randomUUID as I}from"node:crypto";import{brokerConfigSnapshot as wt}from"./config.js";import{openDb as O,withCanvasWrite as F}from"./canvas/db.js";import{personIdAsync as y}from"./canvas/person.js";import{loadSecretsKey as B,open as Q,seal as $}from"./secrets/index.js";import{classifyRateLimit as At,modelCooldownFamily as yt}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as bt,REFRESH_TIMEOUT_PHRASE as Et}from"./provider-error-recognition.js";import{registerRotationReader as Rt}from"./model-routes.js";import{coolingUntilFor as Lt,retryAfterMsFromHeaders as gt,getProviderLabel as p,isInvalidRefreshTokenError as Z,DuplicateSubscriptionError as C,ANTHROPIC_PROVIDER_ID as xt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as It}from"./managed-providers.js";export*from"./managed-providers.js";const v="strong";function tt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(tt,"normalizeStrength");function _(t){return t.toLowerCase()}l(_,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function Ft(t){const n=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",a=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!n||!e||!a||!Number.isFinite(i))return;const r=V(t.accountId),s=V(t.clientId);return{label:n,refresh:e,access:a,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...et(t.modelCooldowns)?{modelCooldowns:et(t.modelCooldowns)}:{}}}l(Ft,"credential");function et(t){if(!t||typeof t!="object"||Array.isArray(t))return;const n=Object.entries(t).filter(([e,a])=>e.trim()!==""&&Number.isFinite(Number(a))).map(([e,a])=>[e,Number(a)]);return n.length?Object.fromEntries(n):void 0}l(et,"modelCooldowns");function S(t,n){if(!n.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=Ft(n);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${n.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(S,"assertCredential");function nt(t,n){const e=t.accountId?.trim(),a=n.accountId?.trim();return!!(e&&a&&e!==a)}l(nt,"differentAccount");function h(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${ht("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(h,"identity");function at(t,n){const e=V(n);return e?{...t,clientId:e}:t}l(at,"withClientId");function it(t,n,e){const a=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!a||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${n}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:a,access:i,expires:r}}l(it,"assertTokens");const rt=1e4,St="15s",Nt="55P03";class st extends Error{static{l(this,"RefreshBusyError")}constructor(n,e){super(`${p(n)} subscription "${e}" ${bt}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class Tt extends Error{static{l(this,"RefreshTimeoutError")}constructor(n){super(`${p(n)} ${Et} ${rt} ms`),this.name="RefreshTimeoutError"}}const G="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",x=l((t,n,e,a)=>`model_accounts|${t}|${n}|${e}|${a}`,"aadOf");function E(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(E,"stored");function Dt(t,n){return{providerId:t,id:n.id,label:n.label,labelKey:n.label_key,position:n.position,lastAttemptAt:n.last_attempt_at,lastRateLimitedAt:n.last_rate_limited_at,rateLimitedUntil:n.rate_limited_until,...n.auth_failure?{authFailure:n.auth_failure}:{}}}l(Dt,"rowOf");function Y(t,n,e,a=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${n} account ${e.id} has no credential record`);const i=B(),r=Q(e.refresh_sealed,e.key_id,i,x(t,n,e.id,"refresh")),s=Q(e.access_sealed,e.key_id,i,x(t,n,e.id,"access")),o=Dt(n,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+j),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...a.length?{modelCooldowns:Object.fromEntries(a.map(d=>[d.family,d.lastRateLimitedAt?Math.min(d.rateLimitedUntil,d.lastRateLimitedAt+j):d.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(Y,"toPublic");function ot(t){const n=new Map;for(const e of t){const a=n.get(e.account_id)??[];a.push({family:e.family,rateLimitedUntil:e.rate_limited_until,lastRateLimitedAt:e.last_rate_limited_at}),n.set(e.account_id,a)}return n}l(ot,"groupCooldowns");async function N(t,n,e){return ot(await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(n,e))}l(N,"loadCooldowns");async function k(t,n,e,a=!1){const i=await t.prepare(`SELECT ${G} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${a?" FOR UPDATE":""}`).all(n,e),r=await N(t,n,e);return i.map(s=>Y(n,e,s,r.get(s.id)))}l(k,"loadPool");async function Jt(){const t=await y(),n=await O(),e=await n.prepare(`SELECT provider_id,${G} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(t),a=ot(await n.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? ORDER BY family").all(t)),i=new Map;for(const r of e){const s=i.get(r.provider_id)??[];s.push(Y(t,r.provider_id,r,a.get(r.id)).entry),i.set(r.provider_id,s)}return i}l(Jt,"readAllSubscriptionPools");async function lt(t,n,e,a){const i=a.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${G} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(n,e,s?r-1:i);if(o)return Y(n,e,o,(await N(t,n,e)).get(o.id))}l(lt,"lockedAccount");async function T(t){await t.exec(`SET LOCAL lock_timeout = '${St}'`)}l(T,"setLockTimeout");async function R(t,n){const e=await y();return F(async a=>(await T(a),await a.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),n({db:a,person:e,rows:await k(a,e,t,!0)})))}l(R,"locked");async function M(t,n,e,a,i){const r=B(),s=$(i.refresh,r,x(n,e,a.id,"refresh")),o=$(i.access,r,x(n,e,a.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(n,e,a.id,a.label,a.labelKey,a.position,a.lastAttemptAt,a.lastRateLimitedAt,a.rateLimitedUntil,a.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(M,"insertAccount");async function H(t,n,e,a,i){const r=B(),s=$(i.refresh,r,x(n,e,a,"refresh")),o=$(i.access,r,x(n,e,a,"access"));await t.prepare("UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?").run(s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId,n,e,a)}l(H,"setCredential");async function b(t,n,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,n,e.providerId,e.id)}l(b,"updateHealth");async function ct(t,n,e,a,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(n,e,a,i,r,s)}l(ct,"upsertModelCooldown");async function D(t,n,e,a){a===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(n,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(n,e,a)}l(D,"deleteModelCooldowns");const L=l(async({db:t,person:n},e)=>(await k(t,n,e)).map(({entry:a})=>a),"publicPool"),ut=l(t=>t?.code===Nt,"lockWaitExpired");function dt(t,n){let e;return Promise.race([n,new Promise((a,i)=>{e=setTimeout(()=>i(new Tt(t)),rt)})]).finally(()=>clearTimeout(e))}l(dt,"withExchangeTimeout");async function z(t){return(await Ut(t)).map(({entry:n})=>n)}l(z,"readSubscriptionPool");async function Ut(t){const n=await y();return(await k(await O(),n,t)).map(({row:e,entry:a})=>({id:e.id,entry:a}))}l(Ut,"readSubscriptionPoolRows");async function Qt(t,n){return R(t,async e=>{const{db:a,person:i,rows:r}=e,s=n.map(d=>S(t,d)),o=s.map((d,u)=>({entry:d,id:r[u]?.row.id??I()})),c=await N(a,i,t);await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await D(a,i,t);for(const[d,{entry:u,id:m}]of o.entries()){await M(a,i,t,{providerId:t,id:m,label:u.label,labelKey:_(u.label),position:d,lastAttemptAt:u.lastAttemptAt,lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:u.rateLimitedUntil,...u.authFailure?{authFailure:u.authFailure}:{}},E(u));for(const[f,A]of Object.entries(u.modelCooldowns??{}))await ct(a,i,t,m,f,A,c.get(m)?.find(U=>U.family===f)?.lastRateLimitedAt??u.lastRateLimitedAt)}return s})}l(Qt,"writeSubscriptionPool");function W(t,n){const e=n.trim().toLowerCase(),a=Number.parseInt(e,10);return Number.isFinite(a)&&String(a)===e&&a>=1&&a<=t.length?a-1:t.findIndex(({entry:i})=>_(i.label)===e)}l(W,"resolve");const P=l((t,n)=>new C(`This ${p(t)} account is already added as \u201C${n}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Ot(t,n){const e=S(t,n);return R(t,async a=>{const{db:i,person:r,rows:s}=a;if(s.some(({entry:d})=>_(d.label)===_(e.label)))throw new C(`${p(t)} subscription already exists: ${e.label}`);const o=h(e),c=s.find(({entry:d})=>h(d)===o);if(o&&c)throw P(t,c.entry.label);return await M(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},E(e)),L(a,t)})}l(Ot,"addSubscription");async function Zt(t,n){const e=S(t,n);return(await z(t)).find(i=>_(i.label)===_(e.label))?$t(t,e):Ot(t,e)}l(Zt,"upsertSubscription");async function $t(t,n){const e=S(t,n);return R(t,async a=>{const{db:i,person:r,rows:s}=a,o=s.findIndex(({entry:f})=>_(f.label)===_(e.label)),c=s[o],d=s.find(({entry:f},A)=>A!==o&&h(f)===h(e));if(h(e)&&d)throw P(t,d.entry.label);if(!c)return await M(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},E(e)),L(a,t);const u=c.row,m=e.lastRateLimitedAt>=u.lastRateLimitedAt;return await H(i,r,t,u.id,E(e)),await b(i,r,{...u,authFailure:void 0,label:e.label,labelKey:_(e.label),lastAttemptAt:Math.max(u.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:m?e.lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:m?e.rateLimitedUntil:u.rateLimitedUntil}),nt(c.entry,e)&&await D(i,r,t,u.id),L(a,t)})}l($t,"upsertSubscriptionWithUniqueAccount");async function vt(t,n,e){return R(t,async a=>{const{db:i,person:r,rows:s}=a,o=W(s,n);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${n}`);const c=e.trim();if(!c)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((d,u)=>u!==o&&_(d.entry.label)===_(c)))throw new C(`${p(t)} subscription already exists: ${c}`);return await b(i,r,{...s[o].row,label:c,labelKey:_(c)}),L(a,t)})}l(vt,"renameSubscription");async function q(t,n,e){return R(t,async a=>{const{db:i,person:r,rows:s}=a,o=n(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await D(i,r,t,c.id),L(a,t)})}l(q,"remove");async function Ct(t,n){return q(t,e=>W(e,n),n)}l(Ct,"removeManagedAccount");async function te(t,n){return q(t,e=>e.findIndex(({row:a})=>a.id===n),n)}l(te,"removeManagedAccountById");async function ee(t,n){return q(t,e=>W(e,n),n)}l(ee,"removeSubscription");async function kt(t){return R(t,async({db:n,person:e,rows:a})=>(await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await D(n,e,t),a.length))}l(kt,"removeAllManagedAccounts");async function ne(t,n){return n===void 0?(await kt(t),[]):Ct(t,n)}l(ne,"removeManagedProvider");async function ae(t,n){return R(t,async e=>{const{db:a,person:i,rows:r}=e,s=W(r,n);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${n}`);const o=[r[s],...r.filter((c,d)=>d!==s)];for(const[c,d]of o.entries())await b(a,i,{...d.row,position:c});return L(e,t)})}l(ae,"promoteSubscription");async function K(t,n,e){const a=await y();return await F(async i=>{await T(i);const r=await lt(i,a,t,n);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${n}`);await e(i,a,r.row)}),z(t)}l(K,"healthWrite");async function ie(t,n,e=Date.now()){return K(t,n,(a,i,r)=>b(a,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(ie,"markSubscriptionAttempt");async function re(t,n,e,a=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),K(t,n,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,a),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,a)});const d=(await N(s,o,t)).get(c.id)?.find(u=>u.family===r.family);d&&i<d.lastRateLimitedAt||await ct(s,o,t,c.id,r.family,i+e,i)})}l(re,"markSubscriptionRateLimited");async function se(t,n,e=Date.now(),a){const i=yt(a);return K(t,n,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await b(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await N(r,s,t)).get(o.id)?.find(d=>d.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(se,"markSubscriptionSuccess");async function X(t,n,e){const a=Date.now();await b(t,n,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,a),rateLimitedUntil:Math.max(e.rateLimitedUntil,a+It)})}l(X,"recordInvalidGrant");function oe(t,n,e,a=15e3,i=Date.now()){const r=gt(t),s=At(t,n,i),o=e??r??a;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(oe,"vendorRateLimit");async function le(t,n){return K(t,n,(e,a,i)=>X(e,a,i))}l(le,"markSubscriptionAuthFailure");async function ce(t,n,e){const a=await y();let i;try{i=await F(async r=>{await T(r);const s=await lt(r,a,t,n);if(!s)throw new Error(`${p(t)} subscription "${n}" no longer exists`);if(s.entry.expires>Date.now())return{entry:s.entry};if(s.row.authFailure)throw new Error(`${p(t)} subscription "${s.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);let o;try{o=await dt(t,e(s.entry.refresh,s.entry.clientId))}catch(d){if(!Z(d))throw d;return await X(r,a,s.row),{refused:d}}const c=at(it(t,s.entry.label,o),o.clientId??s.entry.clientId);return await H(r,a,t,s.row.id,E({...s.entry,...c})),{entry:{...s.entry,...c}}})}catch(r){throw ut(r)?new st(t,n):r}if("refused"in i)throw i.refused;return i.entry}l(ce,"refreshSubscriptionCredential");async function ue(t,n,e){const a=await y();let i;try{i=await F(async r=>{await T(r);const s=await k(r,a,t,!0),o=new Set;let c;for(;o.size<s.length;){const d=n(s.filter(({entry:m})=>!o.has(m.label)).map(({entry:m})=>m));if(!d)break;const u=s.find(({entry:m})=>m.label===d.label);o.add(u.entry.label);try{const m=await dt(t,e(u.entry));if(!m)return{entry:u.entry};const f=at(it(t,u.entry.label,m),m.clientId??u.entry.clientId);return await H(r,a,t,u.row.id,E({...u.entry,...f})),{entry:{...u.entry,...f}}}catch(m){if(!Z(m))throw m;c=m,await X(r,a,u.row)}}return c?{refused:c}:{}})}catch(r){throw ut(r)?new st(t,n([])?.label??t):r}if("refused"in i)throw i.refused;return i.entry}l(ue,"modifyElectedSubscription");async function Mt(t,n){const e=n.accountId?.trim(),a=n.email?.trim();if(t!==xt)return{...e?{accountId:e}:{},...a?{email:a}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${n.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Mt,"enrichManagedLoginIdentity");async function de(t,n,e){const a=await Mt(t,e);return R(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:n?.trim(),d=h({refresh:e.refresh,accountId:a.accountId}),u=(c?o.find(({entry:w})=>_(w.label)===_(c)):void 0)??o.find(({entry:w})=>h(w)===d);let m=u?.entry.label??c;if(!m&&e.autoLabel){const w=a.email||n?.trim()||`Account ${o.length+1}`;m=w;for(let g=2;o.some(({entry:_t})=>_(_t.label)===_(m));g++)m=`${w} (${g})`}if(!m)throw new Error(`${p(t)} subscription label cannot be empty`);const f=S(t,{label:m,refresh:e.refresh,access:e.access,expires:e.expires,...a.accountId?{accountId:a.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!u){if(o.some(({entry:g})=>_(g.label)===_(f.label)))throw new C(`${p(t)} subscription already exists: ${f.label}`);const w=o.find(({entry:g})=>h(g)===h(f));if(h(f)&&w)throw P(t,w.entry.label);return await M(r,s,t,{providerId:t,id:I(),label:f.label,labelKey:_(f.label),position:o.length,lastAttemptAt:f.lastAttemptAt,lastRateLimitedAt:f.lastRateLimitedAt,rateLimitedUntil:f.rateLimitedUntil},E(f)),L(i,t)}const A=u.row,U=o.find(({entry:w})=>w.label!==u.entry.label&&h(w)===h(f));if(h(f)&&U)throw P(t,U.entry.label);const J=f.lastRateLimitedAt>=A.lastRateLimitedAt;return await H(r,s,t,A.id,E(f)),await b(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,f.lastAttemptAt),lastRateLimitedAt:J?f.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:J?0:A.rateLimitedUntil}),nt(u.entry,f)&&await D(r,s,t,A.id),L(i,t)})}l(de,"commitManagedLogin");const mt=new Map;function ft(t){return{defaultFallbackStrength:tt(t?.default_fallback_strength)??v,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(ft,"rotationFromRow");async function Ht(){const t=await y(),n=ft(await(await O()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return mt.set(t,n),n}l(Ht,"loadRotationConfig"),Rt(()=>Wt());async function Wt(){const t=wt();return t?t.rotation:Ht()}l(Wt,"readRotationConfig");async function me(t){const n=await y(),e=await F(async a=>{await T(a),await a.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(n);const i=ft(await a.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(n)),r={defaultFallbackStrength:tt(t.defaultFallbackStrength)??i.defaultFallbackStrength??v,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await a.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,n),r});return mt.set(n,e),e}l(me,"writeRotationConfig");async function fe(){const t=await y();return(await(await O()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,I())).openai_device_id}l(fe,"openAIDeviceId");async function _e(t,n=Date.now(),e){const a=await z(t),i=a.filter(s=>s.authFailure===void 0&&Lt(s,e)<=n),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${a.length} ready)`}l(_e,"formatStatusLine");export{rt as REFRESH_EXCHANGE_TIMEOUT_MS,st as RefreshBusyError,Tt as RefreshTimeoutError,x as aadOf,Ot as addSubscription,de as commitManagedLogin,Mt as enrichManagedLoginIdentity,_e as formatStatusLine,M as insertAccount,Ht as loadRotationConfig,ie as markSubscriptionAttempt,le as markSubscriptionAuthFailure,re as markSubscriptionRateLimited,se as markSubscriptionSuccess,ue as modifyElectedSubscription,fe as openAIDeviceId,ae as promoteSubscription,Jt as readAllSubscriptionPools,Wt as readRotationConfig,z as readSubscriptionPool,Ut as readSubscriptionPoolRows,ce as refreshSubscriptionCredential,kt as removeAllManagedAccounts,Ct as removeManagedAccount,te as removeManagedAccountById,ne as removeManagedProvider,ee as removeSubscription,vt as renameSubscription,ct as upsertModelCooldown,Zt as upsertSubscription,$t as upsertSubscriptionWithUniqueAccount,oe as vendorRateLimit,me as writeRotationConfig,Qt as writeSubscriptionPool};
|
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import type { BrokerExtensionNodeDTO } from '../../../api/dto/broker-ops.js';
|
|
1
|
+
import type { BrokerCycleStartRequest, BrokerCycleStartResultDTO, BrokerExtensionNodeDTO, BrokerExtensionStateDTO } from '../../../api/dto/broker-ops.js';
|
|
2
2
|
import { getNode } from '../../../core/canvas/canvas.js';
|
|
3
3
|
import { type RouteTable } from '../router.js';
|
|
4
|
+
import type { StartDataDTO } from '../../../api/dto/execution-start.js';
|
|
4
5
|
export declare function extensionNode(node: NonNullable<Awaited<ReturnType<typeof getNode>>>): Promise<BrokerExtensionNodeDTO>;
|
|
6
|
+
/** The node state, names, bearings and first system-prompt block a cycle opens with, and the persona acknowledgement the bearings make. A companion
|
|
7
|
+
* awaiting its marker may still be shut down by the bind: it gets the state and names only, with no bearings, ledger write, persona acknowledgement
|
|
8
|
+
* or system prompt until the bind commits. */
|
|
9
|
+
export declare function renderStartData(nodeId: string, bearings: BrokerCycleStartRequest['bearings'], namesOnly: boolean, warmed?: boolean): Promise<{
|
|
10
|
+
state: BrokerExtensionStateDTO;
|
|
11
|
+
delivery: Pick<BrokerCycleStartResultDTO, 'names' | 'boot' | 'system_prompt'>;
|
|
12
|
+
}>;
|
|
13
|
+
/** The start data a broker launched with a carried bundle opens its first cycle with: what `cycle-start` answers a fresh, unbound-nothing launch.
|
|
14
|
+
* The caller has already warmed the node's checkout identities, because that may ask the Mac and must not run inside its open transaction. */
|
|
15
|
+
export declare function renderCarriedStart(nodeId: string): Promise<StartDataDTO>;
|
|
5
16
|
/** crtrd sets this once at boot from its role: only a process that runs the reconciler lanes starts run observers (an api
|
|
6
17
|
* process leaves them to `pollRunObservers` in the reconcile process). */
|
|
7
18
|
export declare function setRequestsStartRunObservers(enabled: boolean): void;
|