@north-light/cli 0.3.598 → 0.3.600
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/charges.d.ts +22 -0
- package/dist/api/dto/charges.js +1 -0
- package/dist/api/dto/modelauth.d.ts +26 -0
- package/dist/api/dto/node-outcomes.d.ts +4 -0
- package/dist/api/error-codes.d.ts +5 -0
- package/dist/api/error-codes.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +11 -0
- package/dist/cli.js +4 -4
- package/dist/clients/attach/viewer.js +503 -503
- package/dist/commands/daemon-generation.d.ts +2 -0
- package/dist/commands/daemon-generation.js +1 -0
- package/dist/commands/sys/join.js +1 -1
- package/dist/core/auth-file.d.ts +3 -11
- package/dist/core/auth-file.js +1 -1
- package/dist/core/canvas/export-sqlite.js +1 -1
- package/dist/core/canvas/person.js +7 -7
- package/dist/core/canvas/recovery.js +2 -2
- package/dist/core/canvas/schema-pg/012-charge-admission.sql +62 -0
- package/dist/core/canvas/schema-pg/013-grant-removal-reset.sql +19 -0
- package/dist/core/canvas/schema-version.d.ts +1 -1
- package/dist/core/canvas/schema-version.js +1 -1
- package/dist/core/canvas/types.d.ts +3 -0
- package/dist/core/grants/hosted-endpoint.d.ts +28 -0
- package/dist/core/grants/hosted-endpoint.js +1 -0
- package/dist/core/grants/mirror.d.ts +1 -0
- package/dist/core/grants/mirror.js +2 -3
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/import/load/run.js +2 -2
- package/dist/core/import/load/stage.d.ts +1 -1
- package/dist/core/import/load/stage.js +1 -1
- package/dist/core/import/load/stores.d.ts +2 -0
- package/dist/core/import/load/stores.js +2 -2
- package/dist/core/ledger/charges.js +1 -1
- package/dist/core/ledger/check.js +1 -1
- package/dist/core/ledger/chunks.js +2 -2
- package/dist/core/ledger/read.js +1 -1
- package/dist/core/ledger/types.d.ts +8 -0
- package/dist/core/llm/owner-candidates.d.ts +17 -0
- package/dist/core/llm/owner-candidates.js +1 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/model-auth/activations.d.ts +37 -0
- package/dist/core/model-auth/activations.js +1 -0
- package/dist/core/model-auth/flows.js +1 -1
- package/dist/core/model-auth/handoff-jti.d.ts +10 -1
- package/dist/core/model-auth/handoff-jti.js +1 -1
- package/dist/core/model-auth/key-routes.d.ts +30 -0
- package/dist/core/model-auth/key-routes.js +1 -0
- package/dist/core/model-auth/readiness.d.ts +8 -1
- package/dist/core/model-auth/readiness.js +1 -1
- package/dist/core/model-config.js +1 -1
- package/dist/core/model-routes-pool.d.ts +2 -0
- package/dist/core/model-routes-pool.js +1 -1
- package/dist/core/model-routes.d.ts +12 -3
- package/dist/core/model-routes.js +1 -1
- package/dist/core/provider-failure.d.ts +5 -0
- package/dist/core/provider-failure.js +1 -1
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/model-adapter.d.ts +6 -1
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/front-door.js +8 -8
- package/dist/core/runtime/launch-target.d.ts +2 -0
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/runner/blaxel/image-build.d.ts +4 -0
- package/dist/core/runtime/runner/blaxel/image-build.js +4 -4
- package/dist/core/runtime/start-check.d.ts +7 -1
- package/dist/core/runtime/start-check.js +1 -1
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/modelauth.js +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/key-signin.d.ts +9 -0
- package/dist/daemon/api/key-signin.js +124 -0
- package/dist/daemon/api/principal.d.ts +8 -3
- package/dist/daemon/api/principal.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/api/vendor-signin.d.ts +28 -1
- package/dist/daemon/api/vendor-signin.js +42 -24
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/crtrd.js +12 -12
- package/dist/daemon/reconcilers/broker-supervision.d.ts +2 -2
- package/dist/daemon/reconcilers/broker-supervision.js +2 -2
- package/dist/daemon/reconcilers/grant-effects.js +1 -1
- package/dist/daemon/reconcilers/ledger-r2.js +6 -6
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/docs/sdk/release-notes.md +11 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -1 +1 @@
|
|
|
1
|
-
var le=Object.defineProperty;var o=(e,t)=>le(e,"name",{value:t,configurable:!0});import{createHash as V,randomBytes as B,randomUUID as _e}from"node:crypto";import{createServer as fe}from"node:http";import{RunError as p}from"../runs/operations.js";import{openDb as R}from"../canvas/db.js";import{isCloudRole as ge,personIdAsync as O,runAsPerson as me}from"../canvas/person.js";import{loadSecretsKey as U,open as W,seal as we}from"../secrets/index.js";import{describeOutboundFailure as ye}from"../events/outbound.js";import{ANTHROPIC_PROVIDER_ID as m,OPENAI_CHATGPT_PROVIDER_ID as w,OPENAI_CODEX_PROVIDER_ID as K,commitManagedLogin as ve,openAIDeviceId as be,readSubscriptionPool as $}from"../subscription-state.js";const X=900,Y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Ae="https://claude.ai/oauth/authorize",Z="https://console.anthropic.com/oauth/code/callback",Q={port:53692,path:"/callback",redirect:"http://localhost:53692/callback"},xe="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",M="app_EMoamEEZ73f0CkXaXp7hrann",Pe="https://auth.openai.com/codex/device",ee="https://auth.openai.com/deviceauth/callback",te={port:1455,path:"/auth/callback",redirect:"http://localhost:1455/auth/callback"},Se="openid profile email offline_access",Ee=900,ne="https://api.openai.com/auth",Te="dynamic_agent_client",ke="crtr",Re="https://auth.openai.com/api/accounts/authorize",re="https://api.openai.com/v1",b={port:1455,path:"/auth/callback",redirect:"http://127.0.0.1:1455/auth/callback"},F="chatgpt.tokens.use.direct",Oe=`openid profile email offline_access resource.invoke ${F}`,Ce=180*1e3,Ie=o(()=>process.env.CRTR_MODEL_AUTH_ANTHROPIC_TOKEN_URL||"https://platform.claude.com/v1/oauth/token","anthropicTokenUrl"),C=o(()=>(process.env.CRTR_MODEL_AUTH_OPENAI_BASE||"https://auth.openai.com").replace(/\/$/,""),"openaiBase");class A extends p{static{o(this,"VendorSignInError")}category;step;url;httpStatus;constructor(t,n,r,a,i,s){super(502,"upstream_refused",a),this.category=t,this.step=n,this.url=r,this.httpStatus=s,i!==void 0&&(this.cause=i)}logFields(){return{category:this.category,...this.httpStatus===void 0?{}:{http_status:this.httpStatus},...ye(this.cause??this,{step:this.step,url:this.url})}}}async function x(e,t,n){try{return await fetch(t,n)}catch(r){throw new A("network",e,t,`could not reach ${new URL(t).host}${new URL(t).pathname}: ${r instanceof Error?r.message:String(r)}`,r)}}o(x,"vendorFetch");async function P(e,t,n){let r;try{r=await n.text()}catch(a){throw new A("network",e,t,`connection to ${new URL(t).host}${new URL(t).pathname} dropped while reading the answer: ${a instanceof Error?a.message:String(a)}`,a)}try{return JSON.parse(r)}catch{throw f(e,t,`${new URL(t).host}${new URL(t).pathname} answered with a body that is not JSON`,n.status)}}o(P,"vendorJson");const f=o((e,t,n,r)=>new A("refused",e,t,n,void 0,r),"refusal"),g=new Map,S=new Map,I=o((e,t)=>`${e}|${t}`,"providerKey"),H=o((e,t)=>`model_sign_in_flows|${e}|${t}`,"flowAad"),ie=o(e=>V("sha256").update(`state:${e}`).digest("hex").slice(0,32),"openaiState"),L=o(()=>ge(),"rowsAreShared");async function Le(e){if(!L())return;const t=e.person,{sealed:n,keyId:r}=we(JSON.stringify({verifier:e.verifier,...e.label?{label:e.label}:{},...e.jti?{jti:e.jti}:{}}),U(),H(t,e.id)),a=await R();await a.prepare("DELETE FROM model_sign_in_flows WHERE person = ? AND expires_at < ?").run(t,new Date().toISOString()),await a.prepare("INSERT INTO model_sign_in_flows (flow_id, provider, person, verifier_sealed, key_id, expires_at) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.provider,t,n,r,new Date(e.expiresAt).toISOString())}o(Le,"writeFlowRow");async function De(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),H(t,e))),a=n.provider;if(a!==m&&a!==w)return;const i={id:e,person:t,provider:a,kind:a===m?"code_page":"redirect_paste",state:a===m?r.verifier:ie(r.verifier),verifier:r.verifier,redirectUri:a===m?Z:b.redirect,expiresAt:Date.parse(n.expires_at),status:"pending",...r.jti?{jti:r.jti}:{},...r.label?{label:r.label}:{},lastRateLimitedAt:Math.max(0,...(await $(a)).map(s=>s.lastRateLimitedAt)),abort:new AbortController,timer:setTimeout(()=>_(i,"expired","the sign-in expired"),Math.max(0,Date.parse(n.expires_at)-Date.now())),waiters:new Set,exchanging:!1};return i.timer.unref(),i}o(De,"readFlowRow");function G(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}o(G,"base64url");function Ne(){const e=G(B(32));return{verifier:e,challenge:G(V("sha256").update(e).digest())}}o(Ne,"pkce");const ae="openai-chatgpt";function oe(e){if(e==="openai")return K;if(e===ae)return w;if(e===m||e===K)return e;throw new p(400,"invalid_request","provider must be anthropic, openai-codex, or openai-chatgpt","provider")}o(oe,"managedProvider");function et(e){return e===w?ae:e}o(et,"modelAuthApiProvider");function tt(e){return oe(e)}o(tt,"modelAuthProvider");function _(e,t,n,r){if(e.status==="pending"){e.status=t,n!==void 0&&(e.message=n),r instanceof A&&(e.failure=r),clearTimeout(e.timer),e.abort.abort(),e.server?.close(),e.server?.closeIdleConnections(),S.get(I(e.person,e.provider))===e.id&&S.delete(I(e.person,e.provider)),L()&&R().then(async a=>{await a.prepare("DELETE FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").run(e.id,e.person)}).catch(()=>{});for(const a of e.waiters)a();e.waiters.clear(),setTimeout(()=>{g.get(e.id)===e&&g.delete(e.id)},6e4).unref()}}o(_,"settle");async function j(e,t){if(e.status!=="pending")throw new Error("the sign-in ended before the credential was written");await me(e.person,()=>ve(e.provider,e.label,{access:t.access,refresh:t.refresh,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{},...t.email?{email:t.email}:{},lastRateLimitedAt:e.lastRateLimitedAt,autoLabel:e.label===void 0}))}o(j,"writeCredential");async function se(e,t,n){const r=Ie(),a=await x("token_exchange",r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:Y,code:t,state:n,redirect_uri:e.redirectUri,code_verifier:e.verifier}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`Anthropic token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||typeof i.refresh_token!="string"||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in))throw f("token_exchange",r,"Anthropic token exchange returned no credential");await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-300*1e3})}o(se,"exchangeAnthropic");function Ue(e){const t=e.split(".")[1];let n;try{n=JSON.parse(Buffer.from(t??"","base64url").toString("utf8"))[ne]?.chatgpt_account_id}catch{n=void 0}if(typeof n!="string"||n==="")throw new Error("OpenAI token carries no ChatGPT account id");return n}o(Ue,"openaiAccountId");async function ce(e,t,n,r){const a=`${C()}/oauth/token`,i=await x("token_exchange",a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:M,code:t,code_verifier:n,redirect_uri:r}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!i.ok)throw f("token_exchange",a,`OpenAI token exchange failed (${i.status})`,i.status);const s=await P("token_exchange",a,i);if(typeof s.access_token!="string"||typeof s.refresh_token!="string"||typeof s.expires_in!="number")throw f("token_exchange",a,"OpenAI token exchange returned no credential");await j(e,{access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3,accountId:Ue(s.access_token)})}o(ce,"exchangeOpenAI");function de(e){try{const t=JSON.parse(Buffer.from(e?.split(".")[1]??"","base64url").toString("utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}o(de,"jwtPayload");function $e(...e){for(const t of e){const n=de(t)?.[ne];if(typeof n?.chatgpt_account_id=="string"&&n.chatgpt_account_id)return n.chatgpt_account_id}}o($e,"chatgptAccountId");function ue(e,t){const n=e.searchParams.get("error");if(n)throw new p(400,"invalid_request",`ChatGPT authorization failed: ${n}`,"input");const r=e.searchParams.get("code");if(!r)throw new p(400,"invalid_request","the redirect URL has no authorization code","input");if(e.searchParams.get("state")!==t)throw new p(400,"invalid_request","the pasted redirect URL belongs to a different sign-in","state");const a=e.searchParams.get("client_id")?.trim();if(!a)throw new p(400,"invalid_request","the redirect URL carries no issued client id","input");return{code:r,clientId:a}}o(ue,"chatgptCallback");async function pe(e,t,n){const r=`${C()}/api/accounts/oauth/token`,a=await x("token_exchange",r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:n,code:t,code_verifier:e.verifier,redirect_uri:e.redirectUri,resource:re}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`ChatGPT token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||!i.access_token||typeof i.refresh_token!="string"||!i.refresh_token||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||typeof i.id_token!="string"||!i.id_token)throw f("token_exchange",r,"ChatGPT token exchange returned no credential");if(!(typeof i.scope=="string"?i.scope.trim().split(/\s+/):[]).includes(F))throw f("token_exchange",r,`ChatGPT sign-in did not grant ${F}`);const l=$e(i.access_token,i.id_token),d=de(i.id_token)?.email;await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-Ce,clientId:n,...l?{accountId:l}:{},...typeof d=="string"&&d?{email:d}:{}})}o(pe,"exchangeChatGPT");function Me(e,t){return new Promise((n,r)=>{if(t.aborted){r(new Error("flow ended"));return}const a=o(()=>{clearTimeout(i),r(new Error("flow ended"))},"onAbort"),i=setTimeout(()=>{t.removeEventListener("abort",a),n()},e);t.addEventListener("abort",a,{once:!0})})}o(Me,"sleep");async function Fe(e,t){const n=Math.min(e.expiresAt,Date.now()+Ee*1e3);let r=Math.max(1e3,Math.floor(t.intervalS*1e3));try{for(;Date.now()<n&&(await Me(Math.min(r,Math.max(0,n-Date.now())),e.abort.signal),!(Date.now()>=n));){const a=`${C()}/api/accounts/deviceauth/token`,i=await x("poll",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:t.deviceAuthId,user_code:t.userCode}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(i.ok){const d=await P("poll",a,i);if(typeof d.authorization_code!="string"||typeof d.code_verifier!="string")throw f("poll",a,"OpenAI device approval returned no code");await ce(e,d.authorization_code,d.code_verifier,ee),_(e,"connected");return}if(i.status===403||i.status===404)continue;let s;try{s=await i.text()}catch(d){throw new A("network","poll",a,`connection to ${new URL(a).host}${new URL(a).pathname} dropped while reading the answer: ${d instanceof Error?d.message:String(d)}`,d)}let l;try{const d=JSON.parse(s).error;l=typeof d=="object"&&d!==null?d.code:d}catch{l=void 0}if(l!=="deviceauth_authorization_pending"){if(l==="slow_down"){r+=5e3;continue}throw f("poll",a,`OpenAI device sign-in failed (${i.status})`,i.status)}}_(e,"expired","the OpenAI code expired")}catch(a){e.status==="pending"&&_(e,"failed",a instanceof Error?a.message:String(a),a)}}o(Fe,"pollDevice");function q(e,t){const n=fe((r,a)=>{const i=new URL(r.url??"/","http://localhost"),s=o((c,v)=>{a.writeHead(c,{"Content-Type":"text/plain; charset=utf-8",Connection:"close"}),a.end(v)},"reply");if(i.pathname!==t.path){s(404,"Not found.");return}const l=i.searchParams.get("code");if(i.searchParams.get("state")!==e.state||!l){s(400,"Sign-in could not be completed: state mismatch or missing code.");return}let d="";if(e.provider===w)try{d=ue(i,e.state).clientId}catch(c){s(400,`Sign-in could not be completed: ${c instanceof Error?c.message:String(c)}.`);return}if(e.status!=="pending"||e.exchanging){s(409,"This sign-in has already finished.");return}e.exchanging=!0,(e.provider===m?se(e,l,e.state):e.provider===w?pe(e,l,d):ce(e,l,e.verifier,e.redirectUri)).then(()=>{s(200,"Signed in. You can close this window."),_(e,"connected")},c=>{s(502,"The vendor refused the sign-in."),_(e,"failed",c instanceof Error?c.message:String(c),c)})});return e.server=n,new Promise((r,a)=>{n.once("error",i=>a(new p(409,"conflict",`cannot listen on localhost:${t.port} for the vendor redirect (${i.code??i.message})`,"redirect"))),n.listen(t.port,"127.0.0.1",()=>r())})}o(q,"listenLoopback");async function nt(e){const t=oe(e.provider);if(e.redirect!==void 0&&e.redirect!=="loopback")throw new p(400,"invalid_request",'redirect must be "loopback" when present',"redirect");if(e.label!==void 0&&typeof e.label!="string")throw new p(400,"invalid_request","label must be a string when present","label");const n=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0,r=await O(),a=Math.max(0,...(await $(t)).map(h=>h.lastRateLimitedAt)),i=S.get(I(r,t));if(i!==void 0){const h=g.get(i);h&&_(h,"failed","replaced by a newer sign-in")}const{verifier:s,challenge:l}=Ne(),d=e.redirect==="loopback",N=Date.now()+X*1e3,c={id:_e(),person:r,provider:t,kind:d?"loopback":t===m?"code_page":t===w?"redirect_paste":"device",state:t===m?s:ie(s),verifier:s,redirectUri:t===m?d?Q.redirect:Z:t===w?b.redirect:d?te.redirect:ee,expiresAt:N,status:"pending",...e.jti?{jti:e.jti}:{},...n?{label:n}:{},lastRateLimitedAt:a,abort:new AbortController,timer:setTimeout(()=>_(c,"expired","the sign-in expired"),X*1e3),waiters:new Set,exchanging:!1};c.timer.unref(),he(c),await Le(c);const v=o(()=>new p(409,"conflict","a newer sign-in for this provider replaced this one","provider"),"replacedDuringStart"),E={flow_id:c.id,provider:t,expires_at:new Date(N).toISOString()};try{if(t===m){const u=new URLSearchParams;if(u.set("code","true"),u.set("client_id",Y),u.set("response_type","code"),u.set("redirect_uri",c.redirectUri),u.set("scope",xe),u.set("code_challenge",l),u.set("code_challenge_method","S256"),u.set("state",c.state),d&&await q(c,Q),c.status!=="pending")throw v();return{...E,url:`${Ae}?${u.toString()}`,instructions:d?"Sign in to Claude in your browser; this finishes by itself.":"Sign in to Claude, then copy the code Claude shows and paste it here."}}if(t===w){const u=new URL(Re);if(u.search=new URLSearchParams({client_id:Te,agent_name_hint:ke,ext_agent_host_id:`urn:uuid:${await be()}`,response_type:"code",redirect_uri:c.redirectUri,resource:re,scope:Oe,state:c.state,code_challenge:l,code_challenge_method:"S256",nonce:G(B(32))}).toString(),d&&await q(c,b),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:d?"Sign in with ChatGPT in your browser; this finishes by itself. If it does not, paste the final redirect URL here.":`Sign in with ChatGPT, then copy the full URL your browser lands on (it starts with ${b.redirect} and may show a connection error) and paste it here.`}}if(d){const u=new URL("https://auth.openai.com/oauth/authorize");if(u.searchParams.set("response_type","code"),u.searchParams.set("client_id",M),u.searchParams.set("redirect_uri",c.redirectUri),u.searchParams.set("scope",Se),u.searchParams.set("code_challenge",l),u.searchParams.set("code_challenge_method","S256"),u.searchParams.set("state",c.state),u.searchParams.set("id_token_add_organizations","true"),u.searchParams.set("codex_cli_simplified_flow","true"),u.searchParams.set("originator","pi"),await q(c,te),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:"Sign in to ChatGPT in your browser; this finishes by itself."}}const h=`${C()}/api/accounts/deviceauth/usercode`,T=await x("device_code_start",h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:M}),signal:AbortSignal.timeout(3e4)});if(!T.ok)throw f("device_code_start",h,`OpenAI refused to issue a device code (${T.status})`,T.status);const y=await P("device_code_start",h,T),k=typeof y.interval=="string"?Number(y.interval.trim()):y.interval;if(typeof y.device_auth_id!="string"||typeof y.user_code!="string"||typeof k!="number"||!Number.isFinite(k)||k<0)throw f("device_code_start",h,"OpenAI returned an invalid device code");if(c.status!=="pending")throw v();return Fe(c,{deviceAuthId:y.device_auth_id,userCode:y.user_code,intervalS:k}),{...E,url:Pe,user_code:y.user_code,instructions:"Open the link, sign in to ChatGPT, and enter the code. The code expires in 15 minutes."}}catch(h){throw _(c,"failed",h instanceof Error?h.message:String(h),h),g.delete(c.id),h instanceof p?h:new p(502,"upstream_refused",`vendor sign-in could not start: ${h instanceof Error?h.message:String(h)}`)}}o(nt,"startModelAuthFlow");async function D(e){const t=g.get(e);return t&&t.person===await O()?t:void 0}o(D,"ownFlow");function he(e){g.set(e.id,e),S.set(I(e.person,e.provider),e.id)}o(he,"register");async function rt(e){const t=await D(e);if(t)return _(t,"failed","cancelled"),J(t)}o(rt,"cancelModelAuthFlow");function He(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(t.includes("#")){const[n,r]=t.split("#",2);return{code:n,state:r}}if(t.includes("code=")){const n=new URLSearchParams(t);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:t}}o(He,"parseCodeInput");async function Ge(e){let t=typeof e=="string"?await D(e):void 0;if(!t&&typeof e=="string"&&!g.has(e)&&(t=await De(e),t&&he(t)),!t||t.status!=="pending")throw new p(400,"invalid_request","no in-flight sign-in has this flow_id","flow_id");return t}o(Ge,"pendingFlow");async function it(e,t){const n=await Ge(e);if(n.provider===w)return je(n,t);if(n.kind!=="code_page")throw new p(400,"invalid_request","this sign-in completes without a pasted code","flow_id");if(n.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");if(typeof t!="string")throw new p(400,"invalid_request","input must be the code Claude shows","input");const{code:r,state:a}=He(t);if(!r)throw new p(400,"invalid_request","input must be the code Claude shows","input");if(a!==void 0&&a!==n.state)throw new p(400,"invalid_request","the pasted code belongs to a different sign-in","state");n.exchanging=!0;try{await se(n,r,a??n.state)}catch(i){throw _(n,"failed",i instanceof Error?i.message:String(i),i),new p(502,"upstream_refused","Anthropic refused the code")}return _(n,"connected"),{flow_id:n.id,provider:n.provider,status:"connected"}}o(it,"completeModelAuthFlow");async function je(e,t){if(e.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");const n=new URL(b.redirect);let r;try{r=typeof t=="string"?new URL(t.trim()):void 0}catch{r=void 0}if(!r||r.origin!==n.origin||r.pathname!==n.pathname)throw new p(400,"invalid_request",`input must be the full redirect URL starting with ${b.redirect}`,"input");const{code:a,clientId:i}=ue(r,e.state);e.exchanging=!0;try{await pe(e,a,i)}catch(s){throw _(e,"failed",s instanceof Error?s.message:String(s),s),new p(502,"upstream_refused","OpenAI refused the ChatGPT sign-in")}return _(e,"connected"),{flow_id:e.id,provider:e.provider,status:"connected"}}o(je,"completeChatGPTFlow");function J(e){return{flow_id:e.id,provider:e.provider,status:e.status,...e.message?{message:e.message}:{},...e.jti?{jti:e.jti}:{}}}o(J,"view");async function z(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),H(t,e)));return{flow_id:e,provider:n.provider,status:"pending",...r.jti?{jti:r.jti}:{}}}o(z,"pendingRowView");async function at(e){const t=await D(e);return t?J(t):g.has(e)?void 0:await z(e)}o(at,"readModelAuthFlow");function ot(e){const t=g.get(e);return t?.status==="expired"?{category:"expired",fields:{category:"expired"}}:t?.failure?{category:t.failure.category,step:t.failure.step,fields:t.failure.logFields()}:{category:"runtime",fields:{category:"runtime"}}}o(ot,"modelAuthFlowFailure");async function st(e,t,n){const r=await D(e);return r?(r.status==="pending"&&t>0&&!n?.aborted&&await new Promise(a=>{const i=o(()=>{clearTimeout(s),n?.removeEventListener("abort",i),r.waiters.delete(i),a()},"done"),s=setTimeout(i,t);n?.addEventListener("abort",i,{once:!0}),r.waiters.add(i)}),J(r)):g.has(e)?void 0:await Je(e,t,n)}o(st,"waitModelAuthFlow");const qe=1e3;async function Je(e,t,n){const r=await z(e);if(!r)return;const a=Date.now()+t;for(;!n?.aborted&&Date.now()<a&&(await new Promise(i=>setTimeout(i,Math.min(qe,Math.max(0,a-Date.now())))),!n?.aborted);)if(!await z(e)){const i=(await $(r.provider)).length>0;return{...r,status:i?"connected":"failed"}}return r}o(Je,"waitRowFlow");function ct(){for(const e of g.values())_(e,"failed","reset");g.clear(),S.clear()}o(ct,"resetModelAuthFlowsForTest");export{X as MODEL_AUTH_FLOW_TTL_S,ae as OPENAI_CHATGPT_API_PROVIDER,A as VendorSignInError,rt as cancelModelAuthFlow,it as completeModelAuthFlow,et as modelAuthApiProvider,ot as modelAuthFlowFailure,tt as modelAuthProvider,at as readModelAuthFlow,ct as resetModelAuthFlowsForTest,nt as startModelAuthFlow,st as waitModelAuthFlow};
|
|
1
|
+
var le=Object.defineProperty;var o=(e,t)=>le(e,"name",{value:t,configurable:!0});import{createHash as V,randomBytes as B,randomUUID as _e}from"node:crypto";import{createServer as fe}from"node:http";import{RunError as p}from"../runs/operations.js";import{recordCredentialActivation as ge}from"./activations.js";import{linkHandoffActivation as me}from"./handoff-jti.js";import{openDb as R}from"../canvas/db.js";import{isCloudRole as we,personIdAsync as O,runAsPerson as ye}from"../canvas/person.js";import{loadSecretsKey as U,open as W,seal as ve}from"../secrets/index.js";import{describeOutboundFailure as Ae}from"../events/outbound.js";import{ANTHROPIC_PROVIDER_ID as m,OPENAI_CHATGPT_PROVIDER_ID as w,OPENAI_CODEX_PROVIDER_ID as K,commitManagedLogin as be,openAIDeviceId as xe,readSubscriptionPool as $}from"../subscription-state.js";const X=900,Y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Pe="https://claude.ai/oauth/authorize",Z="https://console.anthropic.com/oauth/code/callback",Q={port:53692,path:"/callback",redirect:"http://localhost:53692/callback"},Se="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",M="app_EMoamEEZ73f0CkXaXp7hrann",Ee="https://auth.openai.com/codex/device",ee="https://auth.openai.com/deviceauth/callback",te={port:1455,path:"/auth/callback",redirect:"http://localhost:1455/auth/callback"},Te="openid profile email offline_access",ke=900,ne="https://api.openai.com/auth",Re="dynamic_agent_client",Oe="crtr",Ce="https://auth.openai.com/api/accounts/authorize",re="https://api.openai.com/v1",A={port:1455,path:"/auth/callback",redirect:"http://127.0.0.1:1455/auth/callback"},H="chatgpt.tokens.use.direct",Ie=`openid profile email offline_access resource.invoke ${H}`,Le=180*1e3,De=o(()=>process.env.CRTR_MODEL_AUTH_ANTHROPIC_TOKEN_URL||"https://platform.claude.com/v1/oauth/token","anthropicTokenUrl"),C=o(()=>(process.env.CRTR_MODEL_AUTH_OPENAI_BASE||"https://auth.openai.com").replace(/\/$/,""),"openaiBase");class b extends p{static{o(this,"VendorSignInError")}category;step;url;httpStatus;constructor(t,n,r,a,i,s){super(502,"upstream_refused",a),this.category=t,this.step=n,this.url=r,this.httpStatus=s,i!==void 0&&(this.cause=i)}logFields(){return{category:this.category,...this.httpStatus===void 0?{}:{http_status:this.httpStatus},...Ae(this.cause??this,{step:this.step,url:this.url})}}}async function x(e,t,n){try{return await fetch(t,n)}catch(r){throw new b("network",e,t,`could not reach ${new URL(t).host}${new URL(t).pathname}: ${r instanceof Error?r.message:String(r)}`,r)}}o(x,"vendorFetch");async function P(e,t,n){let r;try{r=await n.text()}catch(a){throw new b("network",e,t,`connection to ${new URL(t).host}${new URL(t).pathname} dropped while reading the answer: ${a instanceof Error?a.message:String(a)}`,a)}try{return JSON.parse(r)}catch{throw f(e,t,`${new URL(t).host}${new URL(t).pathname} answered with a body that is not JSON`,n.status)}}o(P,"vendorJson");const f=o((e,t,n,r)=>new b("refused",e,t,n,void 0,r),"refusal"),g=new Map,S=new Map,I=o((e,t)=>`${e}|${t}`,"providerKey"),F=o((e,t)=>`model_sign_in_flows|${e}|${t}`,"flowAad"),ie=o(e=>V("sha256").update(`state:${e}`).digest("hex").slice(0,32),"openaiState"),L=o(()=>we(),"rowsAreShared");async function Ne(e){if(!L())return;const t=e.person,{sealed:n,keyId:r}=ve(JSON.stringify({verifier:e.verifier,...e.label?{label:e.label}:{},...e.jti?{jti:e.jti}:{}}),U(),F(t,e.id)),a=await R();await a.prepare("DELETE FROM model_sign_in_flows WHERE person = ? AND expires_at < ?").run(t,new Date().toISOString()),await a.prepare("INSERT INTO model_sign_in_flows (flow_id, provider, person, verifier_sealed, key_id, expires_at) VALUES (?, ?, ?, ?, ?, ?)").run(e.id,e.provider,t,n,r,new Date(e.expiresAt).toISOString())}o(Ne,"writeFlowRow");async function Ue(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),F(t,e))),a=n.provider;if(a!==m&&a!==w)return;const i={id:e,person:t,provider:a,kind:a===m?"code_page":"redirect_paste",state:a===m?r.verifier:ie(r.verifier),verifier:r.verifier,redirectUri:a===m?Z:A.redirect,expiresAt:Date.parse(n.expires_at),status:"pending",...r.jti?{jti:r.jti}:{},...r.label?{label:r.label}:{},lastRateLimitedAt:Math.max(0,...(await $(a)).map(s=>s.lastRateLimitedAt)),abort:new AbortController,timer:setTimeout(()=>_(i,"expired","the sign-in expired"),Math.max(0,Date.parse(n.expires_at)-Date.now())),waiters:new Set,exchanging:!1};return i.timer.unref(),i}o(Ue,"readFlowRow");function G(e){return e.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}o(G,"base64url");function $e(){const e=G(B(32));return{verifier:e,challenge:G(V("sha256").update(e).digest())}}o($e,"pkce");const ae="openai-chatgpt";function oe(e){if(e==="openai")return K;if(e===ae)return w;if(e===m||e===K)return e;throw new p(400,"invalid_request","provider must be anthropic, openai-codex, or openai-chatgpt","provider")}o(oe,"managedProvider");function it(e){return e===w?ae:e}o(it,"modelAuthApiProvider");function at(e){return oe(e)}o(at,"modelAuthProvider");function _(e,t,n,r){if(e.status==="pending"){e.status=t,n!==void 0&&(e.message=n),r instanceof b&&(e.failure=r),clearTimeout(e.timer),e.abort.abort(),e.server?.close(),e.server?.closeIdleConnections(),S.get(I(e.person,e.provider))===e.id&&S.delete(I(e.person,e.provider)),L()&&R().then(async a=>{await a.prepare("DELETE FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").run(e.id,e.person)}).catch(()=>{});for(const a of e.waiters)a();e.waiters.clear(),setTimeout(()=>{g.get(e.id)===e&&g.delete(e.id)},6e4).unref()}}o(_,"settle");async function j(e,t){if(e.status!=="pending")throw new Error("the sign-in ended before the credential was written");await ye(e.person,()=>be(e.provider,e.label,{access:t.access,refresh:t.refresh,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{},...t.email?{email:t.email}:{},lastRateLimitedAt:e.lastRateLimitedAt,autoLabel:e.label===void 0}));const n=await ge(e.person,"subscription",e.provider);n!==null&&e.jti!==void 0&&await me(e.jti,n)}o(j,"writeCredential");async function se(e,t,n){const r=De(),a=await x("token_exchange",r,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"authorization_code",client_id:Y,code:t,state:n,redirect_uri:e.redirectUri,code_verifier:e.verifier}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`Anthropic token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||typeof i.refresh_token!="string"||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in))throw f("token_exchange",r,"Anthropic token exchange returned no credential");await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-300*1e3})}o(se,"exchangeAnthropic");function Me(e){const t=e.split(".")[1];let n;try{n=JSON.parse(Buffer.from(t??"","base64url").toString("utf8"))[ne]?.chatgpt_account_id}catch{n=void 0}if(typeof n!="string"||n==="")throw new Error("OpenAI token carries no ChatGPT account id");return n}o(Me,"openaiAccountId");async function ce(e,t,n,r){const a=`${C()}/oauth/token`,i=await x("token_exchange",a,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:M,code:t,code_verifier:n,redirect_uri:r}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!i.ok)throw f("token_exchange",a,`OpenAI token exchange failed (${i.status})`,i.status);const s=await P("token_exchange",a,i);if(typeof s.access_token!="string"||typeof s.refresh_token!="string"||typeof s.expires_in!="number")throw f("token_exchange",a,"OpenAI token exchange returned no credential");await j(e,{access:s.access_token,refresh:s.refresh_token,expires:Date.now()+s.expires_in*1e3,accountId:Me(s.access_token)})}o(ce,"exchangeOpenAI");function de(e){try{const t=JSON.parse(Buffer.from(e?.split(".")[1]??"","base64url").toString("utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}}o(de,"jwtPayload");function He(...e){for(const t of e){const n=de(t)?.[ne];if(typeof n?.chatgpt_account_id=="string"&&n.chatgpt_account_id)return n.chatgpt_account_id}}o(He,"chatgptAccountId");function ue(e,t){const n=e.searchParams.get("error");if(n)throw new p(400,"invalid_request",`ChatGPT authorization failed: ${n}`,"input");const r=e.searchParams.get("code");if(!r)throw new p(400,"invalid_request","the redirect URL has no authorization code","input");if(e.searchParams.get("state")!==t)throw new p(400,"invalid_request","the pasted redirect URL belongs to a different sign-in","state");const a=e.searchParams.get("client_id")?.trim();if(!a)throw new p(400,"invalid_request","the redirect URL carries no issued client id","input");return{code:r,clientId:a}}o(ue,"chatgptCallback");async function pe(e,t,n){const r=`${C()}/api/accounts/oauth/token`,a=await x("token_exchange",r,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:n,code:t,code_verifier:e.verifier,redirect_uri:e.redirectUri,resource:re}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(!a.ok)throw f("token_exchange",r,`ChatGPT token exchange failed (${a.status})`,a.status);const i=await P("token_exchange",r,a);if(typeof i.access_token!="string"||!i.access_token||typeof i.refresh_token!="string"||!i.refresh_token||typeof i.expires_in!="number"||!Number.isFinite(i.expires_in)||i.expires_in<=0||typeof i.id_token!="string"||!i.id_token)throw f("token_exchange",r,"ChatGPT token exchange returned no credential");if(!(typeof i.scope=="string"?i.scope.trim().split(/\s+/):[]).includes(H))throw f("token_exchange",r,`ChatGPT sign-in did not grant ${H}`);const l=He(i.access_token,i.id_token),d=de(i.id_token)?.email;await j(e,{access:i.access_token,refresh:i.refresh_token,expires:Date.now()+i.expires_in*1e3-Le,clientId:n,...l?{accountId:l}:{},...typeof d=="string"&&d?{email:d}:{}})}o(pe,"exchangeChatGPT");function Fe(e,t){return new Promise((n,r)=>{if(t.aborted){r(new Error("flow ended"));return}const a=o(()=>{clearTimeout(i),r(new Error("flow ended"))},"onAbort"),i=setTimeout(()=>{t.removeEventListener("abort",a),n()},e);t.addEventListener("abort",a,{once:!0})})}o(Fe,"sleep");async function Ge(e,t){const n=Math.min(e.expiresAt,Date.now()+ke*1e3);let r=Math.max(1e3,Math.floor(t.intervalS*1e3));try{for(;Date.now()<n&&(await Fe(Math.min(r,Math.max(0,n-Date.now())),e.abort.signal),!(Date.now()>=n));){const a=`${C()}/api/accounts/deviceauth/token`,i=await x("poll",a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:t.deviceAuthId,user_code:t.userCode}),signal:AbortSignal.any([e.abort.signal,AbortSignal.timeout(3e4)])});if(i.ok){const d=await P("poll",a,i);if(typeof d.authorization_code!="string"||typeof d.code_verifier!="string")throw f("poll",a,"OpenAI device approval returned no code");await ce(e,d.authorization_code,d.code_verifier,ee),_(e,"connected");return}if(i.status===403||i.status===404)continue;let s;try{s=await i.text()}catch(d){throw new b("network","poll",a,`connection to ${new URL(a).host}${new URL(a).pathname} dropped while reading the answer: ${d instanceof Error?d.message:String(d)}`,d)}let l;try{const d=JSON.parse(s).error;l=typeof d=="object"&&d!==null?d.code:d}catch{l=void 0}if(l!=="deviceauth_authorization_pending"){if(l==="slow_down"){r+=5e3;continue}throw f("poll",a,`OpenAI device sign-in failed (${i.status})`,i.status)}}_(e,"expired","the OpenAI code expired")}catch(a){e.status==="pending"&&_(e,"failed",a instanceof Error?a.message:String(a),a)}}o(Ge,"pollDevice");function q(e,t){const n=fe((r,a)=>{const i=new URL(r.url??"/","http://localhost"),s=o((c,v)=>{a.writeHead(c,{"Content-Type":"text/plain; charset=utf-8",Connection:"close"}),a.end(v)},"reply");if(i.pathname!==t.path){s(404,"Not found.");return}const l=i.searchParams.get("code");if(i.searchParams.get("state")!==e.state||!l){s(400,"Sign-in could not be completed: state mismatch or missing code.");return}let d="";if(e.provider===w)try{d=ue(i,e.state).clientId}catch(c){s(400,`Sign-in could not be completed: ${c instanceof Error?c.message:String(c)}.`);return}if(e.status!=="pending"||e.exchanging){s(409,"This sign-in has already finished.");return}e.exchanging=!0,(e.provider===m?se(e,l,e.state):e.provider===w?pe(e,l,d):ce(e,l,e.verifier,e.redirectUri)).then(()=>{s(200,"Signed in. You can close this window."),_(e,"connected")},c=>{s(502,"The vendor refused the sign-in."),_(e,"failed",c instanceof Error?c.message:String(c),c)})});return e.server=n,new Promise((r,a)=>{n.once("error",i=>a(new p(409,"conflict",`cannot listen on localhost:${t.port} for the vendor redirect (${i.code??i.message})`,"redirect"))),n.listen(t.port,"127.0.0.1",()=>r())})}o(q,"listenLoopback");async function ot(e){const t=oe(e.provider);if(e.redirect!==void 0&&e.redirect!=="loopback")throw new p(400,"invalid_request",'redirect must be "loopback" when present',"redirect");if(e.label!==void 0&&typeof e.label!="string")throw new p(400,"invalid_request","label must be a string when present","label");const n=typeof e.label=="string"&&e.label.trim()?e.label.trim():void 0,r=await O(),a=Math.max(0,...(await $(t)).map(h=>h.lastRateLimitedAt)),i=S.get(I(r,t));if(i!==void 0){const h=g.get(i);h&&_(h,"failed","replaced by a newer sign-in")}const{verifier:s,challenge:l}=$e(),d=e.redirect==="loopback",N=Date.now()+X*1e3,c={id:_e(),person:r,provider:t,kind:d?"loopback":t===m?"code_page":t===w?"redirect_paste":"device",state:t===m?s:ie(s),verifier:s,redirectUri:t===m?d?Q.redirect:Z:t===w?A.redirect:d?te.redirect:ee,expiresAt:N,status:"pending",...e.jti?{jti:e.jti}:{},...n?{label:n}:{},lastRateLimitedAt:a,abort:new AbortController,timer:setTimeout(()=>_(c,"expired","the sign-in expired"),X*1e3),waiters:new Set,exchanging:!1};c.timer.unref(),he(c),await Ne(c);const v=o(()=>new p(409,"conflict","a newer sign-in for this provider replaced this one","provider"),"replacedDuringStart"),E={flow_id:c.id,provider:t,expires_at:new Date(N).toISOString()};try{if(t===m){const u=new URLSearchParams;if(u.set("code","true"),u.set("client_id",Y),u.set("response_type","code"),u.set("redirect_uri",c.redirectUri),u.set("scope",Se),u.set("code_challenge",l),u.set("code_challenge_method","S256"),u.set("state",c.state),d&&await q(c,Q),c.status!=="pending")throw v();return{...E,url:`${Pe}?${u.toString()}`,instructions:d?"Sign in to Claude in your browser; this finishes by itself.":"Sign in to Claude, then copy the code Claude shows and paste it here."}}if(t===w){const u=new URL(Ce);if(u.search=new URLSearchParams({client_id:Re,agent_name_hint:Oe,ext_agent_host_id:`urn:uuid:${await xe()}`,response_type:"code",redirect_uri:c.redirectUri,resource:re,scope:Ie,state:c.state,code_challenge:l,code_challenge_method:"S256",nonce:G(B(32))}).toString(),d&&await q(c,A),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:d?"Sign in with ChatGPT in your browser; this finishes by itself. If it does not, paste the final redirect URL here.":`Sign in with ChatGPT, then copy the full URL your browser lands on (it starts with ${A.redirect} and may show a connection error) and paste it here.`}}if(d){const u=new URL("https://auth.openai.com/oauth/authorize");if(u.searchParams.set("response_type","code"),u.searchParams.set("client_id",M),u.searchParams.set("redirect_uri",c.redirectUri),u.searchParams.set("scope",Te),u.searchParams.set("code_challenge",l),u.searchParams.set("code_challenge_method","S256"),u.searchParams.set("state",c.state),u.searchParams.set("id_token_add_organizations","true"),u.searchParams.set("codex_cli_simplified_flow","true"),u.searchParams.set("originator","pi"),await q(c,te),c.status!=="pending")throw v();return{...E,url:u.toString(),instructions:"Sign in to ChatGPT in your browser; this finishes by itself."}}const h=`${C()}/api/accounts/deviceauth/usercode`,T=await x("device_code_start",h,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:M}),signal:AbortSignal.timeout(3e4)});if(!T.ok)throw f("device_code_start",h,`OpenAI refused to issue a device code (${T.status})`,T.status);const y=await P("device_code_start",h,T),k=typeof y.interval=="string"?Number(y.interval.trim()):y.interval;if(typeof y.device_auth_id!="string"||typeof y.user_code!="string"||typeof k!="number"||!Number.isFinite(k)||k<0)throw f("device_code_start",h,"OpenAI returned an invalid device code");if(c.status!=="pending")throw v();return Ge(c,{deviceAuthId:y.device_auth_id,userCode:y.user_code,intervalS:k}),{...E,url:Ee,user_code:y.user_code,instructions:"Open the link, sign in to ChatGPT, and enter the code. The code expires in 15 minutes."}}catch(h){throw _(c,"failed",h instanceof Error?h.message:String(h),h),g.delete(c.id),h instanceof p?h:new p(502,"upstream_refused",`vendor sign-in could not start: ${h instanceof Error?h.message:String(h)}`)}}o(ot,"startModelAuthFlow");async function D(e){const t=g.get(e);return t&&t.person===await O()?t:void 0}o(D,"ownFlow");function he(e){g.set(e.id,e),S.set(I(e.person,e.provider),e.id)}o(he,"register");async function st(e){const t=await D(e);if(t)return _(t,"failed","cancelled"),J(t)}o(st,"cancelModelAuthFlow");function je(e){const t=e.trim();if(!t)return{};try{const n=new URL(t);return{code:n.searchParams.get("code")??void 0,state:n.searchParams.get("state")??void 0}}catch{}if(t.includes("#")){const[n,r]=t.split("#",2);return{code:n,state:r}}if(t.includes("code=")){const n=new URLSearchParams(t);return{code:n.get("code")??void 0,state:n.get("state")??void 0}}return{code:t}}o(je,"parseCodeInput");async function qe(e){let t=typeof e=="string"?await D(e):void 0;if(!t&&typeof e=="string"&&!g.has(e)&&(t=await Ue(e),t&&he(t)),!t||t.status!=="pending")throw new p(400,"invalid_request","no in-flight sign-in has this flow_id","flow_id");return t}o(qe,"pendingFlow");async function ct(e,t){const n=await qe(e);if(n.provider===w)return Je(n,t);if(n.kind!=="code_page")throw new p(400,"invalid_request","this sign-in completes without a pasted code","flow_id");if(n.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");if(typeof t!="string")throw new p(400,"invalid_request","input must be the code Claude shows","input");const{code:r,state:a}=je(t);if(!r)throw new p(400,"invalid_request","input must be the code Claude shows","input");if(a!==void 0&&a!==n.state)throw new p(400,"invalid_request","the pasted code belongs to a different sign-in","state");n.exchanging=!0;try{await se(n,r,a??n.state)}catch(i){throw _(n,"failed",i instanceof Error?i.message:String(i),i),new p(502,"upstream_refused","Anthropic refused the code")}return _(n,"connected"),{flow_id:n.id,provider:n.provider,status:"connected"}}o(ct,"completeModelAuthFlow");async function Je(e,t){if(e.exchanging)throw new p(400,"invalid_request","this sign-in is already being completed","flow_id");const n=new URL(A.redirect);let r;try{r=typeof t=="string"?new URL(t.trim()):void 0}catch{r=void 0}if(!r||r.origin!==n.origin||r.pathname!==n.pathname)throw new p(400,"invalid_request",`input must be the full redirect URL starting with ${A.redirect}`,"input");const{code:a,clientId:i}=ue(r,e.state);e.exchanging=!0;try{await pe(e,a,i)}catch(s){throw _(e,"failed",s instanceof Error?s.message:String(s),s),new p(502,"upstream_refused","OpenAI refused the ChatGPT sign-in")}return _(e,"connected"),{flow_id:e.id,provider:e.provider,status:"connected"}}o(Je,"completeChatGPTFlow");function J(e){return{flow_id:e.id,provider:e.provider,status:e.status,...e.message?{message:e.message}:{},...e.jti?{jti:e.jti}:{}}}o(J,"view");async function z(e){if(!L())return;const t=await O(),n=await(await R()).prepare("SELECT provider, verifier_sealed, key_id, expires_at FROM model_sign_in_flows WHERE flow_id = ? AND person = ?").get(e,t);if(!n||Date.parse(n.expires_at)<=Date.now())return;const r=JSON.parse(W(n.verifier_sealed,n.key_id,U(),F(t,e)));return{flow_id:e,provider:n.provider,status:"pending",...r.jti?{jti:r.jti}:{}}}o(z,"pendingRowView");async function dt(e){const t=await D(e);return t?J(t):g.has(e)?void 0:await z(e)}o(dt,"readModelAuthFlow");function ut(e){const t=g.get(e);return t?.status==="expired"?{category:"expired",fields:{category:"expired"}}:t?.failure?{category:t.failure.category,step:t.failure.step,fields:t.failure.logFields()}:{category:"runtime",fields:{category:"runtime"}}}o(ut,"modelAuthFlowFailure");async function pt(e,t,n){const r=await D(e);return r?(r.status==="pending"&&t>0&&!n?.aborted&&await new Promise(a=>{const i=o(()=>{clearTimeout(s),n?.removeEventListener("abort",i),r.waiters.delete(i),a()},"done"),s=setTimeout(i,t);n?.addEventListener("abort",i,{once:!0}),r.waiters.add(i)}),J(r)):g.has(e)?void 0:await Ve(e,t,n)}o(pt,"waitModelAuthFlow");const ze=1e3;async function Ve(e,t,n){const r=await z(e);if(!r)return;const a=Date.now()+t;for(;!n?.aborted&&Date.now()<a&&(await new Promise(i=>setTimeout(i,Math.min(ze,Math.max(0,a-Date.now())))),!n?.aborted);)if(!await z(e)){const i=(await $(r.provider)).length>0;return{...r,status:i?"connected":"failed"}}return r}o(Ve,"waitRowFlow");function ht(){for(const e of g.values())_(e,"failed","reset");g.clear(),S.clear()}o(ht,"resetModelAuthFlowsForTest");export{X as MODEL_AUTH_FLOW_TTL_S,ae as OPENAI_CHATGPT_API_PROVIDER,b as VendorSignInError,st as cancelModelAuthFlow,ct as completeModelAuthFlow,it as modelAuthApiProvider,ut as modelAuthFlowFailure,at as modelAuthProvider,dt as readModelAuthFlow,ht as resetModelAuthFlowsForTest,ot as startModelAuthFlow,pt as waitModelAuthFlow};
|
|
@@ -1,3 +1,12 @@
|
|
|
1
1
|
export declare function handoffJtiConsumed(jti: string): Promise<boolean>;
|
|
2
|
-
/** Record `jti` as consumed until `exp`; false when it already was. Expired rows
|
|
2
|
+
/** Record `jti` as consumed until `exp`; false when it already was. Expired rows, and the activation links of jtis no longer
|
|
3
|
+
* held, are pruned on every write. */
|
|
3
4
|
export declare function consumeHandoffJti(jti: string, exp: number): Promise<boolean>;
|
|
5
|
+
/** Give a consumed `jti` back, with its activation link: the save it was consumed for recorded no activation, so the person may
|
|
6
|
+
* try again. */
|
|
7
|
+
export declare function releaseHandoffJti(jti: string): Promise<void>;
|
|
8
|
+
/** Link a consumed key handoff to the activation id its save will record, before the save, so a retry with the same handoff (even
|
|
9
|
+
* one racing the save) waits on that activation instead of saving again. */
|
|
10
|
+
export declare function linkHandoffActivation(jti: string, activationId: string): Promise<void>;
|
|
11
|
+
/** The activation a consumed key handoff's save recorded; undefined when this handoff saved nothing. */
|
|
12
|
+
export declare function handoffActivation(jti: string): Promise<string | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Object.defineProperty;var n=(a,e)=>c(a,"name",{value:e,configurable:!0});import{openDb as t}from"../canvas/db.js";const r="handoff_jti|",E="handoff_activation|";async function u(a){const e=await(await t()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(`${r}${a}`);return e!==void 0&&Number(e.value)>Date.now()/1e3}n(u,"handoffJtiConsumed");async function T(a,e){const o=await t();await o.prepare("DELETE FROM canvas_meta WHERE key LIKE ? AND CAST(value AS DOUBLE PRECISION) <= ?").run(`${r}%`,Date.now()/1e3),await o.prepare(`DELETE FROM canvas_meta WHERE key LIKE ? AND NOT EXISTS (SELECT 1 FROM canvas_meta j WHERE j.key = CAST(? AS TEXT) || substr(canvas_meta.key, ${E.length+1}))`).run(`${E}%`,r);const{changes:i}=await o.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(`${r}${a}`,String(e));return i>0}n(T,"consumeHandoffJti");async function p(a){await(await t()).prepare("DELETE FROM canvas_meta WHERE key IN (?, ?)").run(`${r}${a}`,`${E}${a}`)}n(p,"releaseHandoffJti");async function O(a,e){await(await t()).prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(`${E}${a}`,e)}n(O,"linkHandoffActivation");async function v(a){return await u(a)?(await(await t()).prepare("SELECT value FROM canvas_meta WHERE key = ?").get(`${E}${a}`))?.value:void 0}n(v,"handoffActivation");export{T as consumeHandoffJti,v as handoffActivation,u as handoffJtiConsumed,O as linkHandoffActivation,p as releaseHandoffJti};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ModelStrength } from '../../types.js';
|
|
2
|
+
/** Providers a key can be saved for with a strength mapping (pi-ai provider ids). */
|
|
3
|
+
export declare const KEY_ROUTE_PROVIDERS: readonly ["anthropic", "openai", "openrouter", "moonshotai"];
|
|
4
|
+
export type KeyRouteProvider = typeof KEY_ROUTE_PROVIDERS[number];
|
|
5
|
+
/** A key save the caller got wrong; the message names what. */
|
|
6
|
+
export declare class KeyRouteError extends Error {
|
|
7
|
+
constructor(message: string);
|
|
8
|
+
}
|
|
9
|
+
export declare function isKeyRouteProvider(provider: string): provider is KeyRouteProvider;
|
|
10
|
+
export declare function keyRouteId(provider: string): string;
|
|
11
|
+
/** The models of `provider` a key route may name: registered chat models, all of which take tools. */
|
|
12
|
+
export declare function keyRouteModels(provider: KeyRouteProvider): Promise<Array<{
|
|
13
|
+
id: string;
|
|
14
|
+
name: string;
|
|
15
|
+
}>>;
|
|
16
|
+
/** Check a strength mapping: all four strengths, each `<provider>/<model-id>` of a registered chat model of `provider`. */
|
|
17
|
+
export declare function validateKeyRouteModels(provider: string, models: unknown): Promise<Record<ModelStrength, string>>;
|
|
18
|
+
/** Save `apiKey` for `provider`, its strength mapping and the activation as one transaction: a key never exists without its route
|
|
19
|
+
* and its activation row. Returns the activation id (null when the runtime has joined no directory: there is nobody to tell, so no row is kept). A failed save reloads the person's settings, because the route write refreshes the cache before the commit. */
|
|
20
|
+
export declare function saveKeyRoute(provider: string, apiKey: string, models: unknown, activationId?: string): Promise<{
|
|
21
|
+
activationId: string | null;
|
|
22
|
+
}>;
|
|
23
|
+
/** Remove a provider's key route (its key is removed by the caller). */
|
|
24
|
+
export declare function removeKeyRoute(provider: string): Promise<void>;
|
|
25
|
+
/** Every saved key with its strength mapping, without key material. `added_at` is when the key row was last written. */
|
|
26
|
+
export declare function listKeyRoutes(): Promise<Array<{
|
|
27
|
+
provider: string;
|
|
28
|
+
models: Record<ModelStrength, string>;
|
|
29
|
+
added_at: string;
|
|
30
|
+
}>>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var R=Object.defineProperty;var r=(t,o)=>R(t,"name",{value:o,configurable:!0});import{MODEL_STRENGTHS as f}from"../runtime/model-selection.js";import{apiKeyUpdatedAt as $,setAuthCredential as E}from"../auth-file.js";import{persistModelRoute as p,readConfig as h}from"../config.js";import{KEY_CREDENTIAL_SOURCE as y}from"../model-routes.js";import{openModelRegistry as w}from"../runtime/model-registry.js";import{userScopeRoot as g}from"../scope.js";import{withCanvasWrite as K}from"../canvas/db.js";import{personIdAsync as k}from"../canvas/person.js";import{loadPersonSettings as x}from"../scoped-state/person-rows.js";import{recordActivation as A}from"./activations.js";const d=["anthropic","openai","openrouter","moonshotai"];class u extends Error{static{r(this,"KeyRouteError")}constructor(o){super(o),this.name="KeyRouteError"}}function S(t){return d.includes(t)}r(S,"isKeyRouteProvider");function m(t){return`${y}:${t}`}r(m,"keyRouteId");async function W(t){return(await w()).getAll().filter(e=>e.provider===t&&e.type==="chat").map(e=>({id:e.id,name:e.name}))}r(W,"keyRouteModels");async function _(t,o){if(!S(t))throw new u(`keys with a model mapping are accepted for ${d.join(", ")}, not ${t}`);if(o===null||typeof o!="object"||Array.isArray(o))throw new u("`models` must be an object with ultra, strong, medium and light");const e=o;for(const n of Object.keys(e))if(!f.includes(n))throw new u(`models.${n} is not a strength`);const i=f.filter(n=>e[n]===void 0);if(i.length>0)throw new u(`models is missing ${i.map(n=>`\`${n}\``).join(", ")}`);const a=await w(),s={};for(const n of f){const c=e[n];if(typeof c!="string"||!c.startsWith(`${t}/`)||c.length===t.length+1)throw new u(`models.${n} must be ${t}/<model-id>`);const l=a.find(t,c.slice(t.length+1));if(l===void 0||l.type!=="chat")throw new u(`models.${n}: ${c} is not a ${t} model that takes tools`);s[n]=c}return s}r(_,"validateKeyRouteModels");async function Y(t,o,e,i){const a=await _(t,e),s=await k();try{return await K(async()=>(await E(t,{type:"api_key",key:o}),await p(g(),m(t),{family:t,credentialSource:y,providerId:t,models:a}),{activationId:await A({kind:"api_key",provider:t,id:i})}))}catch(n){throw await x(s),n}}r(Y,"saveKeyRoute");async function G(t){h("user").modelRoutes?.[m(t)]!==void 0&&await p(g(),m(t),void 0)}r(G,"removeKeyRoute");async function H(){const t=h("user").modelRoutes??{},o=await I(),e=[];for(const i of d){const a=t[m(i)],s=o.get(i);a?.credentialSource!==y||s===void 0||e.push({provider:i,models:{...a.models},added_at:s})}return e}r(H,"listKeyRoutes");async function I(){return $([...d])}r(I,"readKeyTimes");export{d as KEY_ROUTE_PROVIDERS,u as KeyRouteError,S as isKeyRouteProvider,m as keyRouteId,W as keyRouteModels,H as listKeyRoutes,G as removeKeyRoute,Y as saveKeyRoute,_ as validateKeyRouteModels};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ModeDTO, type ModelAuthReadinessDTO } from '../../api/index.js';
|
|
2
|
+
import { type ResolvedLaunchTarget } from '../runtime/launch-target.js';
|
|
2
3
|
/** A prospective launch: each field absent or null takes the default a root launch would. */
|
|
3
4
|
export interface ProspectiveLaunch {
|
|
4
5
|
profile?: string | null;
|
|
@@ -8,5 +9,11 @@ export interface ProspectiveLaunch {
|
|
|
8
9
|
model?: string | null;
|
|
9
10
|
mode?: ModeDTO | null;
|
|
10
11
|
}
|
|
11
|
-
/** Resolve `launch` (a root launch when it names no parent) and report its provider's credential state
|
|
12
|
+
/** Resolve `launch` (a root launch when it names no parent) and report its provider's credential state (`credential`: the person's own
|
|
13
|
+
* sign-in, never the hosted endpoint) and whether the launch's model calls would use the hosted endpoint (`hosted_endpoint`: `runLlm`'s
|
|
14
|
+
* rule, evaluated on the candidates the launch's own request would get). A refusal that asks "can this person start an agent" accepts
|
|
15
|
+
* either; a step that asks "is the person's own provider signed in" reads `credential` alone. */
|
|
12
16
|
export declare function modelAuthReadiness(launch: ProspectiveLaunch): Promise<ModelAuthReadinessDTO>;
|
|
17
|
+
/** Whether the model call this launch's broker would send is given the hosted endpoint as a route: the person is eligible for it and
|
|
18
|
+
* `runLlm` would add it to that request's owner candidates. */
|
|
19
|
+
export declare function launchUsesHostedEndpoint(target: ResolvedLaunchTarget): Promise<boolean>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var v=Object.defineProperty;var l=(e,o)=>v(e,"name",{value:o,configurable:!0});import{ApiError as p}from"../../api/index.js";import{storedApiKey as _}from"../auth-file.js";import{readConfig as h}from"../config.js";import{eligibleHostedEndpoint as g}from"../grants/hosted-endpoint.js";import{hostedRouteApplies as I,ownerCandidates as S}from"../llm/owner-candidates.js";import{KEY_CREDENTIAL_SOURCE as b,llmModelFor as E,parseModelSpec as u}from"../model-routes.js";import{keyRouteProviders as R}from"../model-routes-pool.js";import{PoolCredentialStore as k}from"../pool-credential-store.js";import{openModelRegistry as x}from"../runtime/model-registry.js";import{resolveLaunchTarget as A}from"../runtime/launch-target.js";import{readMergedLaunchConfigAsync as C}from"../runtime/launch.js";import{coolingUntilFor as f,isManagedProvider as M,readSubscriptionPool as O}from"../subscription-state.js";function P(e){const o=e.indexOf("/"),t=o>0?e.slice(0,o):"";if(t==="")throw new p(422,"unresolved_model","the selected launch has no concrete model provider");return t}l(P,"providerFromModel");async function s(e,o){if(await _(e)===void 0)return!1;if(!R().has(e))return!0;const t=Object.values(h("user").modelRoutes??{}).filter(r=>r.credentialSource===b&&r.providerId===e),n=u(o);return t.some(r=>Object.values(r.models).some(i=>{const d=u(i);return d?.providerId===n?.providerId&&d?.modelId===n?.modelId}))}l(s,"keyServes");async function J(e){const o=await A({root:!0,...e.profile!=null?{profile:e.profile}:{},...e.cwd!=null?{cwd:e.cwd}:{},...e.pin_cwd!=null?{pin_cwd:e.pin_cwd}:{},...e.mode!=null?{mode:e.mode}:{},...e.kind!=null?{kind:e.kind}:{},...e.model!=null?{model:e.model}:{}},{readOnlyProfileSelection:!0});return{...await D(o),hosted_endpoint:await F(o)}}l(J,"modelAuthReadiness");async function F(e){if(await g()===null)return!1;const{model:o,modelIntent:t,modelExact:n}=e.launch,r=n===!0,i={model:E(o,t===void 0?void 0:`${t.family}/${t.strength}`,r),model_policy:r?"exact":"substitute"};return I(i.model_policy,await S(await x(),i,{cwd:e.cwd,profileId:e.profileId},await C(e.cwd,e.profileId,e.app)))}l(F,"launchUsesHostedEndpoint");async function D(e){const o=e.launch.model;if(o===void 0)throw new p(422,"unresolved_model","the selected launch has no concrete model");const t=P(o);if(M(t)){const i=await O(t);if(i.length>0){const d=i.filter(a=>a.authFailure===void 0);if(d.length===0)return await s(t,o)?{provider:t,model:o,credential:"ready"}:{provider:t,model:o,credential:"unusable",reason:"invalid_grant"};const c=Date.now(),w=d.some(a=>f(a,o)<=c),m=Math.min(...d.map(a=>f(a,o))),y=!w&&m>c&&!await s(t,o);return{provider:t,model:o,credential:"ready",...y?{rate_limited_until:new Date(m).toISOString()}:{}}}}const n=await new k().read(t),r=n?.type==="oauth"||n?.type==="api_key"&&!!n.key&&await s(t,o);return{provider:t,model:o,credential:r?"ready":"missing"}}l(D,"ownCredentialReadiness");export{F as launchUsesHostedEndpoint,J as modelAuthReadiness};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var j=Object.defineProperty;var w=(r,o)=>j(r,"name",{value:o,configurable:!0});import{updateRawConfigAtomically as A}from"./config.js";import{KEY_CREDENTIAL_SOURCE as g}from"./model-routes.js";const $=["ultra","strong","medium","light"],E=/^[^/\s]+\/(ultra|strong|medium|light)$/;function f(r,o){if(r===null||typeof r!="object"||Array.isArray(r))throw new Error(`${o} must be an object`);return r}w(f,"object");function u(r,o){if(typeof r!="string"||r.trim()==="")throw new Error(`${o} must be a non-empty string`);return r}w(u,"nonempty");function v(r){const o=f(r,"model config"),k=f(o.modelRoutes,"modelRoutes"),t={};for(const[e,m]of Object.entries(k)){u(e,"route id");const i=f(m,`modelRoutes.${e}`),c=u(i.providerId,`modelRoutes.${e}.providerId`),l=f(i.models,`modelRoutes.${e}.models`),p={};for(const a of $){const R=u(l[a],`modelRoutes.${e}.models.${a}`),b=R.indexOf("/");if(b<=0||b===R.length-1||R.slice(0,b)!==c)throw new Error(`modelRoutes.${e}.models.${a} must be a ${c}/id ref`);p[a]=R}for(const a of Object.keys(l))if(!$.includes(a))throw new Error(`modelRoutes.${e}.models.${a} is not a model strength`);const O=u(i.credentialSource,`modelRoutes.${e}.credentialSource`);if(O===g)throw new Error(`modelRoutes.${e} uses credential source ${g}, which only a key save writes`);t[e]={family:u(i.family,`modelRoutes.${e}.family`),credentialSource:O,providerId:c,models:p}}const n=f(o.modelRouting,"modelRouting");for(const e of["credentialSourceOrder","familyOrder"])if(n[e]!==void 0&&(!Array.isArray(n[e])||!n[e].every(m=>typeof m=="string"&&m.trim()!=="")))throw new Error(`modelRouting.${e} must be an array of non-empty strings`);if(n.strengthFallback!==void 0&&(!Array.isArray(n.strengthFallback)||!n.strengthFallback.every(e=>$.includes(e))))throw new Error("modelRouting.strengthFallback must be an array of model strengths");const h=new Set(Object.values(t).map(e=>e.family)),s=new Set(Object.values(t).map(e=>e.credentialSource));for(const e of n.familyOrder??[])if(!h.has(e))throw new Error(`modelRouting.familyOrder names unknown route family ${e}`);for(const e of n.credentialSourceOrder??[]){if(e===g)throw new Error(`modelRouting.credentialSourceOrder cannot name ${g}: key routes always follow every other source`);if(!s.has(e))throw new Error(`modelRouting.credentialSourceOrder names unknown credential source ${e}`)}const d=f(o.kinds,"kinds"),y={};for(const[e,m]of Object.entries(d)){u(e,"kind");const i=f(m,`kinds.${e}`),c=u(i.model,`kinds.${e}.model`);if(!E.test(c))throw new Error(`kinds.${e}.model must be family/strength`);if(!h.has(c.slice(0,c.lastIndexOf("/"))))throw new Error(`kinds.${e}.model names unknown route family`);const l=i.orchestratorModel===void 0?void 0:u(i.orchestratorModel,`kinds.${e}.orchestratorModel`);if(l!==void 0&&!E.test(l))throw new Error(`kinds.${e}.orchestratorModel must be family/strength`);if(l!==void 0&&!h.has(l.slice(0,l.lastIndexOf("/"))))throw new Error(`kinds.${e}.orchestratorModel names unknown route family`);y[e]={model:c,...l===void 0?{}:{orchestratorModel:l}}}return{modelRoutes:t,modelRouting:structuredClone(n),kinds:y}}w(v,"validateCoreModelConfig");async function I(r){await A("user",o=>{const k=o.kinds!==null&&typeof o.kinds=="object"&&!Array.isArray(o.kinds)?o.kinds:{},t=Object.fromEntries(Object.entries(k).map(([s,d])=>{const y=d!==null&&typeof d=="object"&&!Array.isArray(d)?d:{},{model:e,orchestratorModel:m,...i}=y;return[s,i]}));for(const[s,d]of Object.entries(r.kinds)){const y=t[s]!==null&&typeof t[s]=="object"&&!Array.isArray(t[s])?t[s]:{};t[s]={...y,model:d.model,orchestratorModel:d.orchestratorModel??d.model}}const n=o.modelRoutes!==null&&typeof o.modelRoutes=="object"&&!Array.isArray(o.modelRoutes)?o.modelRoutes:{},h=Object.fromEntries(Object.entries(n).filter(([,s])=>s?.credentialSource===g));return{...o,modelRoutes:{...structuredClone(r.modelRoutes),...h},modelRouting:structuredClone(r.modelRouting),kinds:t}})}w(I,"replaceCoreModelConfig");export{I as replaceCoreModelConfig,v as validateCoreModelConfig};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type InitialModelRegistryLike, type InitialModelRouteSelection, type ModelRegistryLike, type ModelRequest, type RouteAvailability, type RoutedCandidate } from './model-routes.js';
|
|
2
2
|
/** Probe the common availability facts consumed unchanged by resolveProviderCandidates. Reads the person's credential rows: daemon-side callers only. */
|
|
3
3
|
export declare function probeRouteAvailability(candidate: RoutedCandidate, registry: ModelRegistryLike, now?: number): Promise<RouteAvailability>;
|
|
4
|
+
/** Providers whose saved key carries a strength mapping (a `key:<provider>` route in the person's config). */
|
|
5
|
+
export declare function keyRouteProviders(): Set<string>;
|
|
4
6
|
/** Select the first viable route for a new SDK session. Route declarations own
|
|
5
7
|
* preference order; logical requests append registered models not declared by a
|
|
6
8
|
* route. The caller owns broker faults/events and the no-viable outcome. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var w=Object.defineProperty;var a=(r,t)=>w(r,"name",{value:t,configurable:!0});import{isManagedProvider as s,resolveProviderCandidates as y}from"./managed-providers.js";import{readSubscriptionPool as b}from"./subscription-state.js";import{readConfig as S}from"./config.js";import{storedApiKey as h}from"./auth-file.js";import{expandModelCandidates as k,KEY_CREDENTIAL_SOURCE as f,routeAvailability as A}from"./model-routes.js";async function R(r,t,o=Date.now()){const i=r.credentialSource===f&&s(r.providerId)&&await h(r.providerId)!==void 0;return A(r,t,s(r.providerId)?await b(r.providerId):void 0,o,$(),i)}a(R,"probeRouteAvailability");function $(){return new Set(Object.values(S("user").modelRoutes??{}).filter(r=>r.credentialSource===f).map(r=>r.providerId))}a($,"keyRouteProviders");async function D(r,t,o={}){const i=await k(r,o.cwd,o.profileId),I=new Set(i.map(e=>`${e.providerId}/${e.modelId}`)),m=r.kind==="logical"?t.getAll().filter(e=>!I.has(`${e.provider}/${e.id}`)).map((e,n)=>({routeId:`registry:${e.provider}/${e.id}`,credentialSource:"registry",family:e.provider,strength:"strong",providerId:e.provider,modelId:e.id,rank:i.length+n})):[],c=[...i,...m],p=o.now??Date.now(),l=new Map;for(const e of c)l.set(e,await R(e,t,p));const g=c.some(e=>{const n=l.get(e);return s(e.providerId)&&n.registered&&n.authenticated}),u=y(c.map(e=>({...e,...l.get(e),automaticFallback:e.routeId.startsWith("registry:")?s(e.providerId)||!g:!0})),p,{pinnedToFirst:r.kind==="exact"}),d=u.candidates[0],v=d===void 0?void 0:t.find(d.providerId,d.modelId);return{...d!==void 0&&v!==void 0?{selected:{model:v,candidate:d}}:{},rejected:u.rejected}}a(D,"selectInitialModelRoute");export{$ as keyRouteProviders,R as probeRouteAvailability,D as selectInitialModelRoute};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type MergedLaunchConfig } from './config.js';
|
|
1
2
|
import type { ModelStrength } from '../types.js';
|
|
2
3
|
import { type ProviderCandidate, type ProviderCandidateRejection, type SubscriptionCredential } from './managed-providers.js';
|
|
3
4
|
export type ModelRequest = {
|
|
@@ -63,6 +64,9 @@ export interface UnregisteredConcreteModel {
|
|
|
63
64
|
}
|
|
64
65
|
/** The route family of an app-paid node's recipe: the intent is `app/<strength>`. */
|
|
65
66
|
export declare const APP_FAMILY = "app";
|
|
67
|
+
/** The credential source of a route a saved API key declares (`key:<provider>`). Key routes rank after every other credential
|
|
68
|
+
* source, whatever `credentialSourceOrder` says, and are offered for every requested family. */
|
|
69
|
+
export declare const KEY_CREDENTIAL_SOURCE = "key";
|
|
66
70
|
export declare function parseModelSpec(spec: string): {
|
|
67
71
|
providerId: string;
|
|
68
72
|
modelId: string;
|
|
@@ -74,7 +78,7 @@ type RotationReader = () => Promise<{
|
|
|
74
78
|
/** The process that owns the person's rows (daemon, API) registers how to read their rotation settings; a broker reads its launch snapshot, and a CLI process has neither and gets the default. */
|
|
75
79
|
export declare function registerRotationReader(reader: RotationReader): void;
|
|
76
80
|
/** Expand config-derived route order only. Availability never affects rank. */
|
|
77
|
-
export declare function expandModelCandidates(request: ModelRequest, cwd?: string, profileId?: string | null): Promise<RoutedCandidate[]>;
|
|
81
|
+
export declare function expandModelCandidates(request: ModelRequest, cwd?: string, profileId?: string | null, config?: MergedLaunchConfig): Promise<RoutedCandidate[]>;
|
|
78
82
|
/** Identify the one permanently invalid recipe shape: a concrete/exact request
|
|
79
83
|
* whose requested provider/model is absent from the serving registry. Auth and
|
|
80
84
|
* cooldown are deliberately outside this discriminator so callers retain their
|
|
@@ -92,7 +96,12 @@ export declare function unroutableConcreteModel(request: ModelRequest | undefine
|
|
|
92
96
|
}): Promise<Extract<ModelRequest, {
|
|
93
97
|
kind: 'concrete';
|
|
94
98
|
}> | undefined>;
|
|
95
|
-
/** The availability facts of one route given the managed pool already read for its provider (undefined for a provider that has no pool).
|
|
96
|
-
|
|
99
|
+
/** The availability facts of one route given the managed pool already read for its provider (undefined for a provider that has no pool).
|
|
100
|
+
* A `key:<provider>` route of a managed provider is available exactly when its own saved key exists (`keyStored`), never because the provider has a subscription; other providers' key routes use the registry's auth, as `/v1/llm` does.
|
|
101
|
+
* `keyRouteProviders` names the providers whose saved key carries a strength mapping: that key authenticates only the provider's
|
|
102
|
+
* `key:<provider>` route, and the provider's other routes count only subscription accounts. */
|
|
103
|
+
export declare function routeAvailability(candidate: RoutedCandidate, registry: ModelRegistryLike, pool: readonly SubscriptionCredential[] | undefined, now?: number, keyRouteProviders?: ReadonlySet<string>, keyStored?: boolean): RouteAvailability;
|
|
104
|
+
/** The `model` a broker sends `/v1/llm` for a launch on `concrete`: the logical intent when the launch has one, else the concrete model. */
|
|
105
|
+
export declare function llmModelFor(concrete: string, intent: string | undefined, exact: boolean): string;
|
|
97
106
|
export declare function modelRequestFromConfig(model: string | undefined, modelIntent: string | undefined, exact: boolean): ModelRequest | undefined;
|
|
98
107
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var H=Object.defineProperty;var s=(e,t)=>H(e,"name",{value:t,configurable:!0});import{readMergedLaunchConfig as K}from"./config.js";import{brokerConfigSnapshot as Y}from"./config.js";import{coolingUntilFor as T,isManagedProvider as z}from"./managed-providers.js";const S="app",p="key",F=["ultra","strong","medium","light"],j=new Set(["off","minimal","low","medium","high","xhigh","max"]);function x(e){const t=e.indexOf("/");if(t<=0||t===e.length-1)return;const r=e.slice(0,t),i=e.slice(t+1),c=i.lastIndexOf(":"),l=c>0?i.slice(c+1).toLowerCase():void 0;return{providerId:r,modelId:l!==void 0&&j.has(l)?i.slice(0,c):i,...l!==void 0&&j.has(l)&&l!=="off"?{thinkingLevel:l}:{}}}s(x,"parseModelSpec");function J(e){const t=s(r=>{const i=e[r].strong.slice(0,e[r].strong.indexOf("/"));return{family:r,credentialSource:"default",providerId:i,models:e[r]}},"route");return{anthropic:t("anthropic"),openai:t("openai")}}s(J,"synthesizeRoutes");function P(e,t){return[e,...t.filter(r=>r!==e)]}s(P,"ordered");function X(e,t){return P(e,t).filter((r,i,c)=>c.indexOf(r)===i)}s(X,"strengths");let b;function q(e){b=e}s(q,"registerRotationReader");async function B(){const e=Y();return e?e.rotation:b?b():{}}s(B,"rotationConfig");async function U(e,t,r,i){if(e.kind==="exact"){const n=x(e.spec);return n?[{routeId:"exact",credentialSource:"exact",family:n.providerId,strength:"strong",...n,rank:0,unrouted:!0}]:[]}if(e.kind==="logical"&&e.family===S){const n=x(e.spec);return n?[{routeId:S,credentialSource:S,family:S,strength:e.strength,...n,rank:0}]:[]}const c=i??K(t,r??null),l={...c.modelRoutes??{},...c.legacyModelRoutes??{}},g=Object.entries(l).filter(([,n])=>n.credentialSource===p),I=Object.entries(l).filter(([,n])=>n.credentialSource!==p),u=[...I.length>0?I:Object.entries(J(c.modelLadders)),...g],y=c.modelRouting?.strengthFallback??[(await B()).defaultFallbackStrength??"strong"],m=u.map(([,n])=>n.family).filter((n,o,d)=>d.indexOf(n)===o),M=u.map(([,n])=>n.credentialSource).filter((n,o,d)=>d.indexOf(n)===o),f=e.kind==="concrete"?x(e.spec):void 0,E=e.kind==="logical"?e:void 0,L=s((n,o)=>{const d=x(n);return d!==void 0&&f!==void 0&&d.providerId===f.providerId&&d.modelId===f.modelId&&(!o||d.thinkingLevel===f.thinkingLevel)},"matchesConcrete"),v=f===void 0?void 0:u.find(([,n])=>Object.values(n.models).some(o=>L(o,!1))),O=E?.strength??(()=>{if(!f)return"strong";for(const n of[!0,!1])for(const o of n?F:[...F].reverse())if(u.some(([,d])=>{const h=d.models[o];return h!==void 0&&L(h,n)}))return o;return"strong"})(),R=E?.family??v?.[1].family??f?.providerId??"anthropic",_=[...(f?M:c.modelRouting?.credentialSourceOrder??M).filter(n=>n!==p),...g.length>0?[p]:[]],D=f?[R]:c.modelRouting?.familyOrder??m,G=g.map(([,n])=>n.family).filter((n,o,d)=>d.indexOf(n)===o),w=[],A=new Set,N=s((n,o,d,h,C=!1)=>{const a=x(h);if(!a||f&&a.modelId!==f.modelId)return;const k=JSON.stringify([n,a.providerId,a.modelId,a.thinkingLevel]);A.has(k)||(A.add(k),w.push({routeId:n,credentialSource:o.credentialSource,family:o.family,strength:d,...a,rank:w.length,...C?{unrouted:!0}:{}}))},"append");if(f){const[n,o]=v??["concrete",{family:R,credentialSource:"default"}];N(n,o,O,e.spec,v===void 0)}for(const n of _)for(const o of f?[O]:X(O,y)){const d=P(R,D);n===p&&d.push(...G.filter(h=>!d.includes(h)));for(const h of d)for(const[C,a]of u){if(a.credentialSource!==n||a.family!==h)continue;const k=a.models[o];k&&N(C,a,o,k)}}return w.map((n,o)=>({...n,rank:o}))}s(U,"expandModelCandidates");async function ee(e,t,r={}){if(e===void 0||e.kind==="logical")return;const i=(await U(e,r.cwd,r.profileId))[0];if(!(i===void 0||t.find(i.providerId,i.modelId)!==void 0))return{request:e,candidate:i,reason:"unregistered"}}s(ee,"unregisteredConcreteModel");async function ne(e,t={}){if(e?.kind!=="concrete")return;const r=(await U(e,t.cwd,t.profileId))[0];return r===void 0||r.unrouted?e:void 0}s(ne,"unroutableConcreteModel");function te(e,t,r,i=Date.now(),c=new Set,l=!1){const g=t.find(e.providerId,e.modelId);if(g===void 0)return{registered:!1,authenticated:!1};if(e.credentialSource===p)return{registered:!0,authenticated:z(e.providerId)?l:t.hasConfiguredAuth(g)};const I=c.has(e.providerId);if(r===void 0)return{registered:!0,authenticated:!I&&t.hasConfiguredAuth(g)};const u=r.filter(m=>m.authFailure===void 0),y=u.length>0&&u.every(m=>T(m,e.modelId)>i);return{registered:!0,authenticated:u.length>0||!I&&t.hasConfiguredAuth(g),...y?{coolingUntil:Math.min(...u.map(m=>T(m,e.modelId)))}:{}}}s(te,"routeAvailability");function re(e,t,r){return Q(e,t,r)?.kind==="logical"?t:e}s(re,"llmModelFor");function Q(e,t,r){if(e){if(r)return{kind:"exact",spec:e};if(t){const i=t.lastIndexOf("/"),c=i>0?t.slice(i+1):"";if(F.includes(c))return{kind:"logical",family:t.slice(0,i),strength:c,spec:e}}return{kind:"concrete",spec:e}}}s(Q,"modelRequestFromConfig");export{S as APP_FAMILY,p as KEY_CREDENTIAL_SOURCE,U as expandModelCandidates,re as llmModelFor,Q as modelRequestFromConfig,x as parseModelSpec,q as registerRotationReader,te as routeAvailability,ee as unregisteredConcreteModel,ne as unroutableConcreteModel};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { AssistantMessageDiagnostic } from '@earendil-works/pi-ai';
|
|
2
|
+
import { type PaymentRefusalDTO } from '../api/dto/charges.js';
|
|
2
3
|
export declare const PROVIDER_FAILURE_DIAGNOSTIC = "crtr:provider-failure";
|
|
3
4
|
export interface ProviderFailureCause {
|
|
4
5
|
message?: string;
|
|
@@ -26,6 +27,8 @@ export interface ProviderFailureDetails {
|
|
|
26
27
|
body?: string;
|
|
27
28
|
causes?: ProviderFailureCause[];
|
|
28
29
|
ratelimit?: ProviderRateLimitDetails;
|
|
30
|
+
/** The daemon's structured payment refusal (`payment_refused`, `cap_exhausted`, `all_routes_exhausted`), unchanged. */
|
|
31
|
+
payment?: PaymentRefusalDTO;
|
|
29
32
|
}
|
|
30
33
|
export interface NormalizedProviderFailure extends ProviderFailureDetails {
|
|
31
34
|
message: string;
|
|
@@ -36,6 +39,8 @@ export declare function normalizeProviderFailure(error: unknown, observed?: {
|
|
|
36
39
|
}): NormalizedProviderFailure;
|
|
37
40
|
/** The stable diagnostic carrier for normalized provider error facts on an assistant error message. */
|
|
38
41
|
export declare function providerFailureDiagnostic(details: ProviderFailureDetails): AssistantMessageDiagnostic;
|
|
42
|
+
/** Strictly parse a recorded payment refusal: a known reason and a message, nothing else trusted. */
|
|
43
|
+
export declare function parseProviderPayment(value: unknown): PaymentRefusalDTO | undefined;
|
|
39
44
|
/** Strictly parse a recorded rate-limit block: string headers only, capped, unknown keys dropped. */
|
|
40
45
|
export declare function parseProviderRateLimit(value: unknown): ProviderRateLimitDetails | undefined;
|
|
41
46
|
/** Reads provider facts from the assistant-message diagnostic without trusting arbitrary nested error objects. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var d=(e,n)=>A(e,"name",{value:n,configurable:!0});import{isRecord as h}from"../shared/predicates.js";import{PAYMENT_REFUSAL_REASONS as E}from"../api/dto/charges.js";const g="crtr:provider-failure",I=8;function i(e){return typeof e=="string"&&e.trim()!==""?e.trim():void 0}d(i,"text");function c(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}d(c,"status");function m(e){return typeof e=="string"||typeof e=="number"?e:void 0}d(m,"code");function s(e){return h(e)?e:void 0}d(s,"record");function y(e){const n=i(e.errorMessage)??i(e.message)??i(e.reason)??i(e.statusText),r={...n===void 0?{}:{message:n},...c(e.status)===void 0?{}:{status:c(e.status)},...m(e.code)===void 0?{}:{code:m(e.code)},...i(e.errno)===void 0?{}:{errno:i(e.errno)},...i(e.body)===void 0?{}:{body:i(e.body)}};return Object.keys(r).length===0?void 0:r}d(y,"failureCause");function D(e,n={}){const r=s(e),o=r===void 0?void 0:y(r),t=[],u=new Set([e]);let f=r===void 0?void 0:s(r.cause);for(;f!==void 0&&!u.has(f)&&t.length<I;){u.add(f);const a=y(f);a!==void 0&&t.push(a),f=s(f.cause)}return{message:o?.message??(e instanceof Error?e.message:void 0)??String(e??"Provider request failed"),...(n.status??o?.status)===void 0?{}:{status:n.status??o?.status},...o?.code===void 0?{}:{code:o.code},...o?.errno===void 0?{}:{errno:o.errno},...o?.body===void 0?{}:{body:o.body},...t.length===0?{}:{causes:t}}}d(D,"normalizeProviderFailure");function F(e){return{type:g,timestamp:Date.now(),details:R(e)}}d(F,"providerFailureDiagnostic");function R(e){const n=b(e);if(e.causes!==void 0&&(n.causes=e.causes.map(b)),e.ratelimit!==void 0){const r={headers:{...e.ratelimit.headers}};e.ratelimit.scope!==void 0&&(r.scope=e.ratelimit.scope),e.ratelimit.claim!==void 0&&(r.claim=e.ratelimit.claim),e.ratelimit.account!==void 0&&(r.account=e.ratelimit.account),e.ratelimit.model!==void 0&&(r.model=e.ratelimit.model),n.ratelimit=r}return e.payment!==void 0&&(n.payment={reason:e.payment.reason,message:e.payment.message,pay_url:e.payment.pay_url,reset_at:e.payment.reset_at}),n}d(R,"jsonDetails");const T=48,L=256,S=new Set(E);function l(e){const n=s(e);if(!(n===void 0||typeof n.reason!="string"||!S.has(n.reason)||typeof n.message!="string"))return{reason:n.reason,message:n.message,pay_url:typeof n.pay_url=="string"?n.pay_url:null,reset_at:typeof n.reset_at=="string"?n.reset_at:null}}d(l,"parseProviderPayment");function _(e){const n=s(e),r=s(n?.headers);if(n===void 0||r===void 0)return;const o={};for(const[t,u]of Object.entries(r)){if(Object.keys(o).length>=T)break;typeof u=="string"&&(o[t.toLowerCase()]=u.slice(0,L))}return{...i(n.scope)===void 0?{}:{scope:i(n.scope)},...i(n.claim)===void 0?{}:{claim:i(n.claim)},...i(n.account)===void 0?{}:{account:i(n.account)},...i(n.model)===void 0?{}:{model:i(n.model)},headers:o}}d(_,"parseProviderRateLimit");function b(e){const n={};return e.message!==void 0&&(n.message=e.message),e.status!==void 0&&(n.status=e.status),e.code!==void 0&&(n.code=e.code),e.errno!==void 0&&(n.errno=e.errno),e.body!==void 0&&(n.body=e.body),n}d(b,"jsonCause");function x(e){const n=s(e)?.diagnostics;if(Array.isArray(n))for(const r of n){const o=s(r);if(o?.type!==g)continue;const t=s(o.details);if(t===void 0)continue;const u=Array.isArray(t.causes)?t.causes.flatMap(f=>{const p=s(f),a=p===void 0?void 0:y(p);return a===void 0?[]:[a]}):void 0;return{...c(t.status)===void 0?{}:{status:c(t.status)},...m(t.code)===void 0?{}:{code:m(t.code)},...i(t.errno)===void 0?{}:{errno:i(t.errno)},...i(t.body)===void 0?{}:{body:i(t.body)},...u===void 0||u.length===0?{}:{causes:u},..._(t.ratelimit)===void 0?{}:{ratelimit:_(t.ratelimit)},...l(t.payment)===void 0?{}:{payment:l(t.payment)}}}}d(x,"providerFailureDetails");function O(e){return x(e)}d(O,"extractProviderFailureDetails");export{g as PROVIDER_FAILURE_DIAGNOSTIC,O as extractProviderFailureDetails,D as normalizeProviderFailure,l as parseProviderPayment,_ as parseProviderRateLimit,F as providerFailureDiagnostic};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ue=Object.defineProperty;var m=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as G}from"../../api/command-manifest/result.js";import{callerAllows as le,requireGroup as pe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as ce}from"../grants/terminal.js";import{findRefusal as fe,payerOf as me,refusalError as ve,refusedMark as ge,writeCharge as he}from"../ledger/index.js";import{listInstalledPlugins as we}from"../resolver.js";import{emitEvent as ye}from"../events/emit.js";import{ProviderError as p,scopeMissing as be}from"./errors.js";import{resolveProviderRef as _e}from"./roots.js";import{providerToolPath as je}from"../plugin-objects-manifest.js";import{ensureProviderBundle as Ae,refreshProviderBundle as Y,resolveProviderBundle as S,unavailableProviderError as ke}from"./bundles.js";import{prepareFileCall as $e,resignForRetry as Z,resolveFileResult as ee}from"./files.js";import{consumeApproval as Pe,requireProviderApproval as Ee}from"./approval.js";import{outboundToken as qe}from"./mint.js";import{discardFile as Ce}from"./token-cache.js";import{registerProviderCall as Re}from"./inflight.js";import{buildRequestPlan as Me,paramKey as Te}from"../command-plugins/transport/http-plan.js";import{newTraceId as Ie}from"../../shared/traceparent.js";import{sendProviderRequest as Oe,ProviderTransportError as Be}from"./request.js";import{acceptProviderReceipt as Ne}from"./receipts.js";import{writeProviderAudit as Se}from"./audit.js";import{selectDevice as Fe,sendDeviceCall as De,deviceFailure as Ue,deviceUnreachable as re,DEFAULT_DEVICE_REQUEST_MS as Le}from"./device.js";import{isLibsSearch as te,wantsBundling as Je,callLibsSearch as He,bundleExec as xe,mapLibOutcome as Ge,reportLibCalls as ze}from"./device-libs.js";import{ownMachineId as Ke}from"../peer/directory.js";import{directoryIssuer as Qe}from"../directory/issuer.js";import{isCloudRole as Ve}from"../canvas/person-state.js";import{formatCrtrCaller as oe}from"../command-plugins/caller-header.js";import{getNode as We}from"../canvas/canvas.js";import{envelopeForProviderCaller as Xe,EnvelopeError as Ye}from"../peer/envelope.js";const Ze="app:terminal";function ne(e){const t=[],i=m((u,r,n)=>{const l=[...r,u.name],a=n||u.tier==="hidden";if(u.kind==="branch"){for(const v of u.children)i(v,l,a);return}const A=je(e.roots.length,l);t.push({tool:A,leaf:u,hidden:a})},"walk");for(const u of e.roots)i(u,[],!1);return t}m(ne,"providerLeaves");function ie(e){if(e.kind!=="branch")return null;const t=[];for(const h of e.children)if(h.kind==="branch"){const b=ie(h);b&&t.push(b)}else if("group"in h&&h.group){const{kind:b,name:c,description:_,whenToUse:w,tier:y,summary:k,params:$,output:o,effects:d,group:j}=h;t.push({kind:b,name:c,description:_,whenToUse:w,...y===void 0?{}:{tier:y},summary:k,params:$,output:o,effects:d,group:j})}if(t.length===0)return null;const{kind:i,name:u,description:r,whenToUse:n,tier:l,summary:a,model:A,rootEntry:v}=e;return{kind:i,name:u,description:r,whenToUse:n,...l===void 0?{}:{tier:l},summary:a,...A===void 0?{}:{model:A},...v===void 0?{}:{rootEntry:v},children:t}}m(ie,"providerHelpBranch");async function Sr(e,t){const i=await S(t),u=ne(i.commands),r=we("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>le(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:u.filter(({leaf:l,hidden:a})=>!a&&l.group===n.group).map(({tool:l,leaf:a})=>({tool:l,description:a.description,summary:a.summary,params:a.params,output:a.output}))})),commands:i.commands.roots.flatMap(n=>{const l=ie(n);return l?[l]:[]})}}m(Sr,"providerTools");async function er(e){return await Ne(e.headers["crtr-receipt"],e)}m(er,"onProviderResponse");async function rr(e){if(e.class==="person"){const t=(await ce())?.sub;if(!t)throw new p("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys join` again from /account/machines.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new p("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(rr,"identity");function tr(e,t){return[`${e.id}:${t.group}`]}m(tr,"callScope");function or(e,t){const i=ne(e.commands).find(u=>u.tool===t);if(!i)throw new p("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new p("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(or,"leafFor");function z(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(z,"errorBody");function nr(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const u=Date.parse(t);return Number.isFinite(u)?Math.max(0,Math.ceil((u-Date.now())/1e3)):void 0}m(nr,"retryAfter");function F(e,t,i,u=!1){const r=z(t),n=typeof r.code=="string"?r.code:void 0,l=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,a=typeof r.field=="string"?r.field:void 0,v={origin:"provider",details:{code:n??null,message:l,...a?{field:a}:{},...typeof r.next=="string"?{next:r.next}:{},...r.received!==void 0?{received:r.received}:{},status:e},...a?{param:a}:{}};return e===429?new p("provider_rate_limited",l,{...v,retry_after_s:nr(i["retry-after"])}):e===401||e>=500?new p("provider_unavailable",l,v):e===403&&n==="provider_refused"?new p("provider_refused",l,v):e===403&&n==="approval_required"?new p("provider_error",u?"provider asked for approval again":"provider approval question is invalid",{...v,status:e}):new p("provider_error",l,{...v,status:e})}m(F,"mapProviderResponse");function se(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(se,"approvalShape");async function ir(e){const t=e.origin!==void 0?oe({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):oe({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await We(e.node_id))?.profile_id??void 0:void 0,machine:Qe()!==null?Ke():void 0});return t===""?{}:{"Crtr-Caller":t}}m(ir,"crtrCallerHeader");async function Fr(e,t,i){const u=_e(t.provider);if(u===null)throw new p("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:u},n=new AbortController,l=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?l():i.signal.addEventListener("abort",l,{once:!0});let a=i.requestId;const A=i.traceId??Ie(),v=Re({request_id:a,run_id:e.run_id,node_id:e.node_id,controller:n});let h,b,c,_,w,y,k,$="allowed";try{if(Ve()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw be(`${r.provider}:*`);try{await Ae(r.provider)}catch{throw ke(r.provider)}let o=await S(r.provider,r.version),d=!1,j=!1,P,D,q,K=!1,Q=!1,U,V=0;for(;;){const g=or(o,r.tool);if(c=`${o.id}:${g.group}`,pe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new p("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await Fe(r.machine,void 0,{newest:te(o.major,r.tool)}),V=Date.now()+(o.commands.timeouts?.requestMs??Le));let L=null;if(r.approval&&!K){const s=await Pe(e,r,se(o,g));q=s.option,L=s.prepared,k=r.approval,a=s.requestId,K=!0}const O={params:g.params.filter(s=>"type"in s&&s.type==="file").map(s=>s.name),output:g.output.find(s=>s.type==="file")?.name??null},W=JSON.stringify(O);if(D!==void 0&&D!==W)throw new p("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=W,L&&(P=await Z(e,O,r.arguments,L,{signal:n.signal})),P??=await $e(e,O,r.arguments,{signal:n.signal});const{sub:M,grantee:B}=await rr(e);if(o.transport.kind==="machine"){const s=await ar(e,o,r,g,P,{sub:M,requestId:a,deadlineAt:V,signal:n.signal,machine:U});return y=s.responder,h=s.cleanup,{status:200,body:s.result}}const X=o.transport.endpoint;let C;try{C=await qe({audience:X,sub:M,grantee:B,initiating_app:B,scope:tr(o,g)},{signal:n.signal})}catch(s){if(!(s instanceof p)||s.details?.directory_error!=="invalid_target"||j)throw s;j=!0,await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===X)throw s;o=E;continue}_=C.jti;const J=e.class==="person"?Ze:B,T=me({call:"tool",tokenPayer:C.payer,sub:M}),H=await fe({scope:"call",payer:T.payer,funding:T.funding,sub:M,grantee:J,provider:`app:${o.id}`});if(H!==null)throw await he({request:a,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:T.payer,funding:T.funding,sub:M,grantee:J,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:ge(H)}),ve(H);const ae={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},de=Me(ae,P.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:a,traceId:A,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await ir(e),...q?{"Crtr-Approval":q}:{},...P.headers}});b??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await Oe(de,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:b,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(s){throw n.signal.aborted?n.signal.reason??s:s instanceof Be?new p("provider_unavailable",s.message,{origin:"provider",details:{status:null,code:s.kind}}):s}if(w??=await er({provider:o.id,tool:r.tool,request_id:a,run_id:e.run_id,sub:M,grantee:B,payer:C.payer,ledger_grantee:J,funding:T.funding,node_id:e.node_id,caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Ce(C.key),f.status>=200&&f.status<300){const s=f.body;if(!s||typeof s!="object"||Array.isArray(s))throw new p("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await ee(e,P,s,{signal:n.signal})}catch(I){throw I instanceof p&&I.code==="provider_error"?new p("provider_bad_response",I.message,{origin:"provider",details:{status:f.status,message:I.message}}):I}h=E.cleanup;const N=G(g.output,E.result);if(N)throw new p("provider_bad_response",`provider result has an invalid output field "${N.field}"`,{origin:"provider",param:N.field,details:{status:f.status,...N}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=z(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!Q){Q=!0;const s=await Ee(e,r,a,R.question,n.signal,se(o,g),P);if(k=s.questionId,q=s.option,P=await Z(e,O,r.arguments,P,{signal:n.signal}),b=void 0,n.signal.aborted)throw new p("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const x=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||x)&&!d){d=!0;const s=o.major;await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),ye({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:x?"unsupported_major":"manifest_stale",major_before:s,major_after:o.major,...x&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof p&&o.question_id&&(k=o.question_id),y===void 0&&o instanceof p&&typeof o.responder=="string"&&(y=o.responder),$=`refused:${o instanceof p?o.code:"server_error"}`,await h?.(),o}finally{try{await Se({request_id:a,caller:e,provider:r.provider,tool:r.tool,scope_checked:c,outcome:$,jti:_,receipt_id:w,responder:y,question_id:k})}finally{v()}i.signal.removeEventListener("abort",l)}}m(Fr,"callProvider");function sr(e,t){const i={...t};for(const{name:u}of e.params){const r=Te(u);r===u||!Object.hasOwn(i,r)||(i[u]=i[r],delete i[r])}return i}m(sr,"declaredNames");async function ar(e,t,i,u,r,n){const{machine:l}=n;let a;try{a=await Xe(e,n.sub)}catch(d){throw d instanceof Ye?new p("invalid_request",d.message,{origin:"runtime"}):d}const A={machine:l,envelope:a,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(te(t.major,i.tool)){const d=await He(A,r.arguments,t.major),j=G(u.output,d);if(j)throw new p("provider_bad_response",`the libraries result has an invalid output field "${j.field}"`,{origin:"provider",param:j.field,details:{status:200,...j}});return{result:d,responder:void 0,cleanup:void 0}}let v=r.arguments,h=null,b="";if(Je(t.major,i.tool,r.arguments)){const d=await xe(A,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw re(l,"timeout","");d!==null&&(v=d.arguments,h=d.services,b=d.release)}const c=await De(l,{tool:i.tool,arguments:sr(u,v),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},a,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in c)throw re(l,c.unreachable.reason,c.unreachable.message);const _=c.headers["crtr-responder"],w=z(c.body);if(c.status<200||c.status>=300){const d=Ue(l,c.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,c.body),j=d===null&&c.status>=500&&typeof w.code=="string"?new p("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${c.status}`,{origin:"runtime",status:c.status,details:{code:w.code,status:c.status}}):null;throw Object.assign(d??j??F(c.status,c.body,c.headers),{responder:_})}const y=c.body&&typeof c.body=="object"&&!Array.isArray(c.body)?c.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new p("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:c.status,message:"the device result is not a JSON object"}}),{responder:_});let k=y;if(h!==null){const d=Ge(k,h);if(ze(l,a,b,d.calls),"error"in d)throw Object.assign(d.error,{responder:_});k=d.result}let $;try{$=await ee(e,r,k,{signal:n.signal})}catch(d){throw d instanceof p&&d.code==="provider_error"?Object.assign(new p("provider_bad_response",d.message,{origin:"provider",details:{status:c.status,message:d.message}}),{responder:_}):d}const o=G(u.output,$.result);if(o)throw await $.cleanup?.(),Object.assign(new p("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:c.status,...o}}),{responder:_});return{result:$.result,responder:_,cleanup:$.cleanup}}m(ar,"callDevice");export{Fr as callProvider,ir as crtrCallerHeader,rr as identity,F as mapProviderResponse,er as onProviderResponse,ne as providerLeaves,Sr as providerTools};
|
|
1
|
+
var ue=Object.defineProperty;var m=(e,t)=>ue(e,"name",{value:t,configurable:!0});import{validateDeclaredResult as G}from"../../api/command-manifest/result.js";import{callerAllows as le,requireGroup as pe}from"../../daemon/api/handlers/providers.js";import{callerTerminalGrant as ce}from"../grants/terminal.js";import{findRefusal as fe,payerOf as me,refusalError as ve,refusedMark as ge,writeCharge as he}from"../ledger/index.js";import{listInstalledPlugins as we}from"../resolver.js";import{emitEvent as ye}from"../events/emit.js";import{ProviderError as c,scopeMissing as be}from"./errors.js";import{parseProviderPayment as _e}from"../provider-failure.js";import{resolveProviderRef as je}from"./roots.js";import{providerToolPath as Ae}from"../plugin-objects-manifest.js";import{ensureProviderBundle as ke,refreshProviderBundle as Y,resolveProviderBundle as S,unavailableProviderError as Pe}from"./bundles.js";import{prepareFileCall as $e,resignForRetry as Z,resolveFileResult as ee}from"./files.js";import{consumeApproval as Ee,requireProviderApproval as qe}from"./approval.js";import{outboundToken as Ce}from"./mint.js";import{discardFile as Re}from"./token-cache.js";import{registerProviderCall as Me}from"./inflight.js";import{buildRequestPlan as Te,paramKey as Ie}from"../command-plugins/transport/http-plan.js";import{newTraceId as Oe}from"../../shared/traceparent.js";import{sendProviderRequest as Be,ProviderTransportError as Ne}from"./request.js";import{acceptProviderReceipt as Se}from"./receipts.js";import{writeProviderAudit as Fe}from"./audit.js";import{selectDevice as De,sendDeviceCall as Ue,deviceFailure as Le,deviceUnreachable as re,DEFAULT_DEVICE_REQUEST_MS as xe}from"./device.js";import{isLibsSearch as te,wantsBundling as Je,callLibsSearch as He,bundleExec as Ge,mapLibOutcome as ze,reportLibCalls as Ke}from"./device-libs.js";import{ownMachineId as Qe}from"../peer/directory.js";import{directoryIssuer as Ve}from"../directory/issuer.js";import{isCloudRole as We}from"../canvas/person-state.js";import{formatCrtrCaller as oe}from"../command-plugins/caller-header.js";import{getNode as Xe}from"../canvas/canvas.js";import{envelopeForProviderCaller as Ye,EnvelopeError as Ze}from"../peer/envelope.js";const er="app:terminal";function ne(e){const t=[],i=m((l,r,n)=>{const p=[...r,l.name],d=n||l.tier==="hidden";if(l.kind==="branch"){for(const b of l.children)i(b,p,d);return}const h=Ae(e.roots.length,p);t.push({tool:h,leaf:l,hidden:d})},"walk");for(const l of e.roots)i(l,[],!1);return t}m(ne,"providerLeaves");function ie(e){if(e.kind!=="branch")return null;const t=[];for(const v of e.children)if(v.kind==="branch"){const _=ie(v);_&&t.push(_)}else if("group"in v&&v.group){const{kind:_,name:a,description:j,whenToUse:w,tier:y,summary:k,params:P,output:o,effects:u,group:A}=v;t.push({kind:_,name:a,description:j,whenToUse:w,...y===void 0?{}:{tier:y},summary:k,params:P,output:o,effects:u,group:A})}if(t.length===0)return null;const{kind:i,name:l,description:r,whenToUse:n,tier:p,summary:d,model:h,rootEntry:b}=e;return{kind:i,name:l,description:r,whenToUse:n,...p===void 0?{}:{tier:p},summary:d,...h===void 0?{}:{model:h},...b===void 0?{}:{rootEntry:b},children:t}}m(ie,"providerHelpBranch");async function Dr(e,t){const i=await S(t),l=ne(i.commands),r=we("user").find(n=>n.name===t)?.manifest.description??t;return{provider:t,status:"available",major:i.major,display_name:r,transport:i.transport.kind,groups:i.provider.groups.filter(n=>le(e,`${t}:${n.group}`)).map(n=>({group:n.group,leaves:l.filter(({leaf:p,hidden:d})=>!d&&p.group===n.group).map(({tool:p,leaf:d})=>({tool:p,description:d.description,summary:d.summary,params:d.params,output:d.output}))})),commands:i.commands.roots.flatMap(n=>{const p=ie(n);return p?[p]:[]})}}m(Dr,"providerTools");async function rr(e){return await Se(e.headers["crtr-receipt"],e)}m(rr,"onProviderResponse");async function tr(e){if(e.class==="person"){const t=(await ce())?.sub;if(!t)throw new c("grant_revoked","This machine has no active Northlight grant for your terminal. Run `crtr sys join` again from /account/machines.");return{sub:t,grantee:t}}if(!e.sub||!e.grantee)throw new c("grant_revoked","the caller has no active grant");return{sub:e.sub,grantee:e.grantee}}m(tr,"identity");function or(e,t){return[`${e.id}:${t.group}`]}m(or,"callScope");function nr(e,t){const i=ne(e.commands).find(l=>l.tool===t);if(!i)throw new c("not_found",`tool "${t}" is not in provider "${e.id}"`,{param:"tool"});if(!i.leaf.group)throw new c("not_found",`tool "${t}" has no group`,{param:"tool"});return i.leaf}m(nr,"leafFor");function z(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e.error;return!t||typeof t!="object"||Array.isArray(t)?{}:t}m(z,"errorBody");function ir(e){const t=Array.isArray(e)?e[0]:e;if(!t)return;const i=Number(t);if(Number.isFinite(i)&&i>=0)return i;const l=Date.parse(t);return Number.isFinite(l)?Math.max(0,Math.ceil((l-Date.now())/1e3)):void 0}m(ir,"retryAfter");function F(e,t,i,l=!1){const r=z(t),n=typeof r.code=="string"?r.code:void 0,p=typeof r.message=="string"?r.message:`provider answered HTTP ${e}`,d=typeof r.field=="string"?r.field:void 0,h=r.details&&typeof r.details=="object"?r.details:{},b=_e(h.payment),v=typeof r.next=="string"?r.next:typeof h.next=="string"?h.next:void 0,a={origin:"provider",details:{code:n??null,message:p,...d?{field:d}:{},...v!==void 0?{next:v}:{},...r.received!==void 0?{received:r.received}:{},...b===void 0?{}:{payment:b},status:e},...d?{param:d}:{}};return e===429?new c("provider_rate_limited",p,{...a,retry_after_s:ir(i["retry-after"])}):e===401||e>=500?new c("provider_unavailable",p,a):e===403&&n==="provider_refused"?new c("provider_refused",p,a):e===403&&n==="approval_required"?new c("provider_error",l?"provider asked for approval again":"provider approval question is invalid",{...a,status:e}):new c("provider_error",p,{...a,status:e})}m(F,"mapProviderResponse");function se(e,t){return JSON.stringify({major:e.major,endpoint:e.transport.kind==="http"?e.transport.endpoint:null,baseUrl:e.commands.baseUrl??null,rest:t.rest,params:t.params,output:t.output})}m(se,"approvalShape");async function sr(e){const t=e.origin!==void 0?oe({node:e.origin.node??void 0,run:e.origin.run??void 0,machine:e.origin.machine}):oe({node:e.node_id??void 0,run:e.run_id??void 0,profile:e.node_id?(await Xe(e.node_id))?.profile_id??void 0:void 0,machine:Ve()!==null?Qe():void 0});return t===""?{}:{"Crtr-Caller":t}}m(sr,"crtrCallerHeader");async function Ur(e,t,i){const l=je(t.provider);if(l===null)throw new c("not_found",`provider "${t.provider}" is not available`,{param:"provider"});const r={...t,provider:l},n=new AbortController,p=m(()=>n.abort(i.signal.reason),"abort");i.signal.aborted?p():i.signal.addEventListener("abort",p,{once:!0});let d=i.requestId;const h=i.traceId??Oe(),b=Me({request_id:d,run_id:e.run_id,node_id:e.node_id,controller:n});let v,_,a,j,w,y,k,P="allowed";try{if(We()&&e.class==="person"&&e.resolved!==null&&!e.resolved.some(g=>g.startsWith(`${r.provider}:`)))throw be(`${r.provider}:*`);try{await ke(r.provider)}catch{throw Pe(r.provider)}let o=await S(r.provider,r.version),u=!1,A=!1,$,D,q,K=!1,Q=!1,U,V=0;for(;;){const g=nr(o,r.tool);if(a=`${o.id}:${g.group}`,pe(e,o.id,g.group),o.transport.kind!=="machine"&&r.machine!==void 0)throw new c("invalid_argument",`provider "${o.id}" is not served by a device, so it takes no machine`,{param:"machine"});o.transport.kind==="machine"&&U===void 0&&(U=await De(r.machine,void 0,{newest:te(o.major,r.tool)}),V=Date.now()+(o.commands.timeouts?.requestMs??xe));let L=null;if(r.approval&&!K){const s=await Ee(e,r,se(o,g));q=s.option,L=s.prepared,k=r.approval,d=s.requestId,K=!0}const O={params:g.params.filter(s=>"type"in s&&s.type==="file").map(s=>s.name),output:g.output.find(s=>s.type==="file")?.name??null},W=JSON.stringify(O);if(D!==void 0&&D!==W)throw new c("provider_bad_response","the refreshed manifest changed the tool file contract",{origin:"provider",details:{status:409,message:"manifest_stale changed the tool file contract"}});D=W,L&&($=await Z(e,O,r.arguments,L,{signal:n.signal})),$??=await $e(e,O,r.arguments,{signal:n.signal});const{sub:M,grantee:B}=await tr(e);if(o.transport.kind==="machine"){const s=await dr(e,o,r,g,$,{sub:M,requestId:d,deadlineAt:V,signal:n.signal,machine:U});return y=s.responder,v=s.cleanup,{status:200,body:s.result}}const X=o.transport.endpoint;let C;try{C=await Ce({audience:X,sub:M,grantee:B,initiating_app:B,scope:or(o,g)},{signal:n.signal})}catch(s){if(!(s instanceof c)||s.details?.directory_error!=="invalid_target"||A)throw s;A=!0,await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}});const E=await S(o.id,r.version);if(E.transport.kind==="machine"||E.transport.endpoint===X)throw s;o=E;continue}j=C.jti;const x=e.class==="person"?er:B,T=me({call:"tool",tokenPayer:C.payer,sub:M}),J=await fe({scope:"call",payer:T.payer,funding:T.funding,sub:M,grantee:x,provider:`app:${o.id}`});if(J!==null)throw await he({request:d,kind:"tool",what:`${o.id}:${r.tool}`,usd:0,payer:T.payer,funding:T.funding,sub:M,grantee:x,node:e.node_id,run:e.run_id,provider:`app:${o.id}`,causedBy:i.causedBy??null,refused:ge(J)}),ve(J);const ae={registration:{name:o.id,endpoint:o.transport.endpoint},...o.commands.baseUrl?{baseUrl:o.commands.baseUrl}:{},...o.commands.timeouts?{timeouts:o.commands.timeouts}:{},params:g.params,rest:g.rest,output:g.output,commandPath:[o.id,...r.tool.split(" ")]},de=Te(ae,$.arguments,void 0,{authorization:`Bearer ${C.access_token}`,requestId:d,traceId:h,fileMode:"pass-through",extraHeaders:{...i.causedBy?{"Crtr-Caused-By":i.causedBy}:{},...e.run_id?{"Crtr-Run-Id":e.run_id}:{},...await sr(e),...q?{"Crtr-Approval":q}:{},...$.headers}});_??=Date.now()+(o.commands.timeouts?.requestMs??3e4);let f;try{if(f=await Be(de,{connectMs:o.commands.timeouts?.connectMs,requestMs:o.commands.timeouts?.requestMs,deadlineAt:_,signal:n.signal}),n.signal.aborted)throw n.signal.reason??new Error("provider call aborted")}catch(s){throw n.signal.aborted?n.signal.reason??s:s instanceof Ne?new c("provider_unavailable",s.message,{origin:"provider",details:{status:null,code:s.kind}}):s}if(w??=await rr({provider:o.id,tool:r.tool,request_id:d,run_id:e.run_id,sub:M,grantee:B,payer:C.payer,ledger_grantee:x,funding:T.funding,node_id:e.node_id,caused_by:i.causedBy??null,jti:C.jti,status:f.status,headers:f.headers}),y=f.headers["crtr-responder"],f.status===401&&Re(C.key),f.status>=200&&f.status<300){const s=f.body;if(!s||typeof s!="object"||Array.isArray(s))throw new c("provider_bad_response","provider result is not a JSON object",{origin:"provider",details:{status:f.status,message:"provider result is not a JSON object"}});let E;try{E=await ee(e,$,s,{signal:n.signal})}catch(I){throw I instanceof c&&I.code==="provider_error"?new c("provider_bad_response",I.message,{origin:"provider",details:{status:f.status,message:I.message}}):I}v=E.cleanup;const N=G(g.output,E.result);if(N)throw new c("provider_bad_response",`provider result has an invalid output field "${N.field}"`,{origin:"provider",param:N.field,details:{status:f.status,...N}});if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");return{status:200,body:E.result}}const R=z(f.body);if(f.status===403&&R.code==="approval_required"&&!q&&!Q){Q=!0;const s=await qe(e,r,d,R.question,n.signal,se(o,g),$);if(k=s.questionId,q=s.option,$=await Z(e,O,r.arguments,$,{signal:n.signal}),_=void 0,n.signal.aborted)throw new c("user_denied","the approval wait was canceled");continue}if(f.status===403&&R.code==="approval_required"&&q)throw F(f.status,f.body,f.headers,!0);const H=f.status===410&&R.code==="unsupported_major"&&r.version===void 0;if(f.status!==401&&(R.manifest_stale===!0||H)&&!u){u=!0;const s=o.major;await Y(o.id,{conditional:!1,...r.version===void 0?{}:{version:r.version}}),o=await S(o.id,r.version),ye({level:"info",event:"daemon.providers.call_retried",fields:{provider:o.id,tool:r.tool,reason:H?"unsupported_major":"manifest_stale",major_before:s,major_after:o.major,...H&&typeof R.received=="number"?{received:R.received}:{}}});continue}throw F(f.status,f.body,f.headers,!!q)}}catch(o){throw o instanceof c&&o.question_id&&(k=o.question_id),y===void 0&&o instanceof c&&typeof o.responder=="string"&&(y=o.responder),P=`refused:${o instanceof c?o.code:"server_error"}`,await v?.(),o}finally{try{await Fe({request_id:d,caller:e,provider:r.provider,tool:r.tool,scope_checked:a,outcome:P,jti:j,receipt_id:w,responder:y,question_id:k})}finally{b()}i.signal.removeEventListener("abort",p)}}m(Ur,"callProvider");function ar(e,t){const i={...t};for(const{name:l}of e.params){const r=Ie(l);r===l||!Object.hasOwn(i,r)||(i[l]=i[r],delete i[r])}return i}m(ar,"declaredNames");async function dr(e,t,i,l,r,n){const{machine:p}=n;let d;try{d=await Ye(e,n.sub)}catch(u){throw u instanceof Ze?new c("invalid_request",u.message,{origin:"runtime"}):u}const h={machine:p,envelope:d,signal:n.signal,deadlineAt:n.deadlineAt,mapFailure:F};if(te(t.major,i.tool)){const u=await He(h,r.arguments,t.major),A=G(l.output,u);if(A)throw new c("provider_bad_response",`the libraries result has an invalid output field "${A.field}"`,{origin:"provider",param:A.field,details:{status:200,...A}});return{result:u,responder:void 0,cleanup:void 0}}let b=r.arguments,v=null,_="";if(Je(t.major,i.tool,r.arguments)){const u=await Ge(h,r.arguments,t.major);if(n.deadlineAt-Date.now()<=0)throw re(p,"timeout","");u!==null&&(b=u.arguments,v=u.services,_=u.release)}const a=await Ue(p,{tool:i.tool,arguments:ar(l,b),version:t.major,requestId:n.requestId,runId:e.run_id,deadlineAt:n.deadlineAt,upload:r.upload===null?null:{id:r.upload.upload_id,link:r.upload.upload_link}},d,n.signal);if(n.signal.aborted)throw n.signal.reason??new Error("provider call aborted");if("unreachable"in a)throw re(p,a.unreachable.reason,a.unreachable.message);const j=a.headers["crtr-responder"],w=z(a.body);if(a.status<200||a.status>=300){const u=Le(p,a.status,typeof w.code=="string"?w.code:void 0,typeof w.message=="string"?w.message:void 0,a.body),A=u===null&&a.status>=500&&typeof w.code=="string"?new c("provider_error",typeof w.message=="string"?w.message:`the device answered HTTP ${a.status}`,{origin:"runtime",status:a.status,details:{code:w.code,status:a.status}}):null;throw Object.assign(u??A??F(a.status,a.body,a.headers),{responder:j})}const y=a.body&&typeof a.body=="object"&&!Array.isArray(a.body)?a.body.result:void 0;if(!y||typeof y!="object"||Array.isArray(y))throw Object.assign(new c("provider_bad_response","the device result is not a JSON object",{origin:"provider",details:{status:a.status,message:"the device result is not a JSON object"}}),{responder:j});let k=y;if(v!==null){const u=ze(k,v);if(Ke(p,d,_,u.calls),"error"in u)throw Object.assign(u.error,{responder:j});k=u.result}let P;try{P=await ee(e,r,k,{signal:n.signal})}catch(u){throw u instanceof c&&u.code==="provider_error"?Object.assign(new c("provider_bad_response",u.message,{origin:"provider",details:{status:a.status,message:u.message}}),{responder:j}):u}const o=G(l.output,P.result);if(o)throw await P.cleanup?.(),Object.assign(new c("provider_bad_response",`the device result has an invalid output field "${o.field}"`,{origin:"provider",param:o.field,details:{status:a.status,...o}}),{responder:j});return{result:P.result,responder:j,cleanup:P.cleanup}}m(dr,"callDevice");export{Ur as callProvider,sr as crtrCallerHeader,tr as identity,F as mapProviderResponse,rr as onProviderResponse,ne as providerLeaves,Dr as providerTools};
|