@north-light/cli 0.3.630 → 0.3.631

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.
@@ -1,3 +1,3 @@
1
- var Ke=Object.defineProperty;var l=(e,t)=>Ke(e,"name",{value:t,configurable:!0});import{randomUUID as Ue}from"node:crypto";import{streamSimple as Be}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as Je,probeRouteAvailability as We}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as He,parseModelSpec as ze}from"../model-routes.js";import{openModelRegistry as Xe}from"../runtime/model-registry.js";import{isInvalidRefreshTokenError as Ge}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Ae,coolingUntilFor as je,isManagedProvider as H,markSubscriptionRateLimited as Ve,markSubscriptionSuccess as Ye,readSubscriptionPool as Ze,retryAfterMsFromHeaders as he,retryAfterMsFromError as Qe,refreshSubscriptionCredential as et,subscriptionNeedsSuccessWrite as tt,vendorRateLimit as nt,RefreshBusyError as ot,RefreshTimeoutError as rt}from"../subscription-state.js";import{describeRateLimitScope as Me,rateLimitHeaders as it}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as _e}from"../provider-error-recognition.js";import{isSafetyRefusal as at}from"./refusal.js";import{findRefusal as st,payerOf as $e,refusalError as dt,refusedMark as lt,writeCharge as ye}from"../ledger/index.js";import{storedApiKey as Se}from"../auth-file.js";import{eligibleHostedEndpoint as ut,readHostedEndpoint as Ce}from"../grants/hosted-endpoint.js";import{parseProviderPayment as ct}from"../provider-failure.js";import{personIdAsync as ft}from"../canvas/person.js";import{getNode as Ee}from"../canvas/canvas.js";import{outboundToken as Ie}from"../providers/mint.js";import{discardFile as Oe}from"../providers/token-cache.js";import{ProviderError as mt}from"../providers/errors.js";import{appCandidates as pt}from"./app-rungs.js";import{hostedRoute as ht,matchesFeatures as _t,ownerCandidates as yt}from"./owner-candidates.js";function gt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(gt,"validContent");function Ne(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,a]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:a}}):e??""}l(Ne,"imageContent");function wt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],a=_e({message:o}).kind;return a!=="connection"&&a!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(wt,"refreshFailure");async function bt(e,t,o,a,s){if(o.expires>Date.now())return o.access;const j=e.getProvider(t)?.auth.oauth;if(!j)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:a});return(await et(t,o.label,async(r,p)=>{const y=await j.refresh({type:"oauth",refresh:r,access:"",expires:0,...p?{clientId:p}:{}},s??new AbortController().signal).catch(x=>{throw wt(x,a)}),k=y.clientId;return{refresh:y.refresh,access:y.access,expires:y.expires,...typeof k=="string"&&k?{clientId:k}:{}}}).catch(r=>{throw r instanceof ot||r instanceof rt?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:a}):r})).access}l(bt,"freshSubscriptionAccess");function Qt(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&gt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(a=>a&&typeof a.id=="string"&&typeof a.function?.name=="string"&&typeof a.function.arguments=="string"&&vt(a.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,a]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||o==="temperature"&&(a<0||a>2)||o==="top_p"&&(a<0||a>1)||o==="max_tokens"&&(!Number.isSafeInteger(a)||a<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(Qt,"parseLlmRequest");function vt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(vt,"isJsonObject");function kt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Ne(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(p=>({type:"toolCall",id:p.id,name:p.function.name,arguments:JSON.parse(p.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Ne(r.content),timestamp:t}),a=o.findIndex(r=>r.role!=="system"),s=o.slice(0,a<0?o.length:a).map(r=>r.content),j=s.join(`
1
+ var Je=Object.defineProperty;var l=(e,t)=>Je(e,"name",{value:t,configurable:!0});import{randomUUID as We}from"node:crypto";import{streamSimple as He}from"@earendil-works/pi-ai/compat";import{keyRouteProviders as ze,probeRouteAvailability as Xe}from"../model-routes-pool.js";import{KEY_CREDENTIAL_SOURCE as je,parseModelSpec as Ge}from"../model-routes.js";import{openModelRegistry as Ve}from"../runtime/model-registry.js";import{getProviderLabel as Ye,isInvalidRefreshTokenError as Ze}from"../managed-providers.js";import{MAX_RATE_LIMIT_COOLDOWN_MS as Me,coolingUntilFor as Se,isManagedProvider as N,markSubscriptionRateLimited as Qe,markSubscriptionSuccess as et,readSubscriptionPool as $e,retryAfterMsFromHeaders as _e,retryAfterMsFromError as tt,refreshSubscriptionCredential as nt,subscriptionNeedsSuccessWrite as ot,vendorRateLimit as rt,RefreshBusyError as it,RefreshTimeoutError as at}from"../subscription-state.js";import{describeRateLimitScope as Ce,rateLimitHeaders as st}from"../rate-limit-scope.js";import{RunError as i}from"../runs/operations.js";import{recognizeProviderError as ye}from"../provider-error-recognition.js";import{isSafetyRefusal as dt}from"./refusal.js";import{findRefusal as lt,payerOf as Ee,refusalError as ut,refusedMark as ct,writeCharge as ge}from"../ledger/index.js";import{storedApiKey as Ie}from"../auth-file.js";import{eligibleHostedEndpoint as ft,readHostedEndpoint as Oe}from"../grants/hosted-endpoint.js";import{parseProviderPayment as mt}from"../provider-failure.js";import{personIdAsync as pt}from"../canvas/person.js";import{getNode as Ne}from"../canvas/canvas.js";import{outboundToken as De}from"../providers/mint.js";import{discardFile as Te}from"../providers/token-cache.js";import{ProviderError as ht}from"../providers/errors.js";import{appCandidates as _t}from"./app-rungs.js";import{hostedRoute as yt,matchesFeatures as gt,ownerCandidates as wt}from"./owner-candidates.js";function bt(e){return typeof e=="string"||e===null||Array.isArray(e)&&e.every(t=>t&&typeof t=="object"&&(t.type==="text"&&typeof t.text=="string"||t.type==="image_url"&&typeof t.image_url?.url=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(t.image_url.url)))}l(bt,"validContent");function Fe(e){return Array.isArray(e)?e.map(t=>{if(t.type==="text")return t;const[,o,a]=/^data:(image\/(?:png|jpeg|gif|webp));base64,(.*)$/.exec(t.image_url.url);return{type:"image",mimeType:o,data:a}}):e??""}l(Fe,"imageContent");function vt(e,t){const o=(e instanceof Error?e.message:String(e)).split("; stack=",1)[0],a=ye({message:o}).kind;return a!=="connection"&&a!=="connection-only"?e:new i(503,"upstream_model_unavailable",o.slice(0,500),void 0,{served_model:t})}l(vt,"refreshFailure");async function kt(e,t,o,a,s){if(o.expires>Date.now())return o.access;const M=e.getProvider(t)?.auth.oauth;if(!M)throw new i(503,"upstream_model_unavailable",`no OAuth refresh for ${t}`,void 0,{served_model:a});return(await nt(t,o.label,async(r,h)=>{const g=await M.refresh({type:"oauth",refresh:r,access:"",expires:0,...h?{clientId:h}:{}},s??new AbortController().signal).catch(R=>{throw vt(R,a)}),x=g.clientId;return{refresh:g.refresh,access:g.access,expires:g.expires,...typeof x=="string"&&x?{clientId:x}:{}}}).catch(r=>{throw r instanceof it||r instanceof at?new i(503,"upstream_model_unavailable",r.message,void 0,{served_model:a}):r})).access}l(kt,"freshSubscriptionAccess");function tn(e){if(!e||typeof e!="object"||Array.isArray(e))throw new i(400,"invalid_request","body must be an object");const t=e;if(!Array.isArray(t.messages)||!t.messages.every(o=>o&&typeof o=="object"&&["system","user","assistant","tool"].includes(o.role)&&bt(o.content)))throw new i(400,"invalid_request","messages must be chat messages","messages");if(t.messages.some(o=>["system","assistant"].includes(o.role)&&typeof o.content!="string"&&o.content!==null))throw new i(400,"invalid_request","system and assistant content must be text","messages");if(t.model!==void 0&&typeof t.model!="string")throw new i(400,"invalid_request","model must be a string","model");if(t.model_policy!==void 0&&!["exact","substitute"].includes(t.model_policy))throw new i(400,"invalid_request","invalid model_policy","model_policy");if(t.payer!==void 0&&!["user","app"].includes(t.payer))throw new i(400,"invalid_request","invalid payer","payer");if(t.reasoning_effort!==void 0&&!["minimal","low","medium","high","xhigh","max"].includes(t.reasoning_effort))throw new i(400,"invalid_request","invalid reasoning_effort","reasoning_effort");if(t.stream!==void 0&&typeof t.stream!="boolean")throw new i(400,"invalid_request","stream must be boolean","stream");if(t.tools!==void 0&&(!Array.isArray(t.tools)||!t.tools.every(o=>o?.type==="function"&&typeof o.function?.name=="string"&&o.function.name.length>0&&(o.function.description===void 0||typeof o.function.description=="string")&&(o.function.parameters===void 0||o.function.parameters!==null&&typeof o.function.parameters=="object"&&!Array.isArray(o.function.parameters)&&o.function.parameters.type==="object"))))throw new i(400,"invalid_request","invalid tools","tools");if(t.tool_choice!==void 0&&t.tool_choice!=="auto"&&t.tool_choice!=="none"&&t.tool_choice!=="required"&&(typeof t.tool_choice!="object"||t.tool_choice===null||t.tool_choice.type!=="function"||typeof t.tool_choice.function?.name!="string"))throw new i(400,"invalid_request","invalid tool_choice","tool_choice");if(t.messages.some(o=>o.role==="assistant"&&o.tool_calls!==void 0&&(!Array.isArray(o.tool_calls)||!o.tool_calls.every(a=>a&&typeof a.id=="string"&&typeof a.function?.name=="string"&&typeof a.function.arguments=="string"&&xt(a.function.arguments)))))throw new i(400,"invalid_request","invalid assistant tool_calls","messages");if(t.stop!==void 0&&!(typeof t.stop=="string"||Array.isArray(t.stop)&&t.stop.every(o=>typeof o=="string")))throw new i(400,"invalid_request","invalid stop","stop");if(t.seed!==void 0&&!Number.isSafeInteger(t.seed))throw new i(400,"invalid_request","invalid seed","seed");for(const[o,a]of[["temperature",t.temperature],["top_p",t.top_p],["max_tokens",t.max_tokens]])if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)||o==="temperature"&&(a<0||a>2)||o==="top_p"&&(a<0||a>1)||o==="max_tokens"&&(!Number.isSafeInteger(a)||a<1)))throw new i(400,"invalid_request",`invalid ${o}`,o);if(t.response_format!==void 0){const o=t.response_format;if(!o||typeof o!="object"||Array.isArray(o)||!["text","json_object","json_schema"].includes(o.type)||o.type==="json_schema"&&(typeof o.json_schema?.name!="string"||!o.json_schema.name||!o.json_schema.schema||typeof o.json_schema.schema!="object"||Array.isArray(o.json_schema.schema)))throw new i(400,"invalid_request","invalid response_format","response_format")}if(t.metadata!==void 0&&Buffer.byteLength(JSON.stringify(t.metadata)??"")>4096)throw new i(400,"invalid_request","metadata exceeds 4 KB","metadata");return t}l(tn,"parseLlmRequest");function xt(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)}catch{return!1}}l(xt,"isJsonObject");function Rt(e){const t=Date.now(),o=e.messages.map(r=>r.role==="system"?{role:"system",content:r.content??"",timestamp:t}:r.role==="tool"?{role:"toolResult",toolCallId:r.tool_call_id??"",toolName:"",content:typeof r.content=="string"||r.content===null?[{type:"text",text:r.content??""}]:Fe(r.content),isError:!1,timestamp:t}:r.role==="assistant"?{role:"assistant",content:[...r.content?[{type:"text",text:r.content}]:[],...(r.tool_calls??[]).map(h=>({type:"toolCall",id:h.id,name:h.function.name,arguments:JSON.parse(h.function.arguments)}))],api:"openai-completions",provider:"openai",model:e.model??"",usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:t}:{role:"user",content:Fe(r.content),timestamp:t}),a=o.findIndex(r=>r.role!=="system"),s=o.slice(0,a<0?o.length:a).map(r=>r.content),M=s.join(`
2
2
 
3
- `),K=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...j?{systemPrompt:j}:{},messages:o.slice(s.length),...K?{tools:K}:{}}}l(kt,"contextOf");function xt(e){return ct(e?.payment)}l(xt,"paymentOf");function Rt(e,t){const o=e.find("anthropic",t);if(o)return o;const a=e.getAll().find(s=>s.provider==="anthropic"&&s.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}l(Rt,"hostedModel");function qt(e,t){const{input:o,output:a,cacheRead:s,cacheWrite:j}=e.cost;return o===0&&a===0&&s===0&&j===0?null:Number.isFinite(t)&&t>=0?t:null}l(qt,"usdEquivalent");function At(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.model===t)}l(At,"allowedFallback");function en(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(en,"llmCallerOf");function De(e){return e instanceof mt?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(De,"mintFailure");const jt=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Mt(e,t,o){if(!(e!=="openai-codex"||t===void 0||!jt.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Mt,"codexAccountModelRejection");function $t(e){return e.get("request-id")??e.get("x-request-id")}l($t,"vendorRequestId");async function tn(e,t,o,a,s,j,K){const r=j?.payer==="app"?j:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const p=r?.inference_endpoint??void 0,y=s===void 0?null:r?.sub??s.sub??await ft(),k=await Xe();let x;p?(x=pt(p,e.model,e.model_policy==="exact").flatMap((v,g)=>{const M=ze(v.model);return M?[{routeId:"app",credentialSource:"app",family:"app",strength:v.strength,...M,rank:g}]:[]}),x=x.filter(v=>_t(k,e,v))):x=await yt(k,e,a);const oe=!p&&s!==void 0&&y!==null?await ut():null,re=oe===null?void 0:ht(e,x,oe),Te=re?oe:null;re&&(x=[...x,re]);const Fe=p?new Set:Je(),ge=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Ce())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(x.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):p?new i(404,"model_unavailable","no eligible model route is configured"):await ge();const U=`chatcmpl-${Ue()}`;let N=1/0,z=1/0,ie,b,ae,se;const de=l(async()=>K??(s?.node?(await Ee(s.node))?.caused_by??null:null)??(s?.run?(await Ee(s.run))?.caused_by??null:null),"causeOf");for(const v of x){const g=v.credentialSource==="hosted";if(!r&&!g&&!(await We(v,k)).authenticated)continue;const M=g?Rt(k,v.modelId):k.find(v.providerId,v.modelId);if(!M)continue;const B=g?Te.base_url:void 0,c=p?{...M,baseUrl:`${p.base_url}/${M.provider}`}:B?{...M,baseUrl:`${B}/anthropic`,compat:{...M.compat,allowedFallbackModels:void 0}}:M,h=v.providerId,X=v.credentialSource===He&&H(h),le=!r&&!g&&!X&&H(h)?await Ze(h):[],J=le.filter($=>!$.authFailure),we=J.filter($=>je($,c.id)<=Date.now()),D=X?await Se(h):Fe.has(h)?void 0:le.length?await Se(h):void 0;if(X&&D===void 0||le.length>0&&J.length===0&&D===void 0)continue;if(J.length&&!we.length&&D===void 0){const $=Math.min(...J.map(E=>je(E,c.id)));$<N&&(N=$,ae=`${c.provider}/${c.id}`);continue}const be=r||g?[void 0,void 0]:X?["key"]:J.length||D!==void 0?[...we,...D!==void 0?["key"]:[]]:[void 0];let ve=!1;for(const[$,E]of be.entries()){if(ve&&E!=="key")continue;const w=E==="key"?void 0:E,ke=E==="key",G=Date.now();let xe=w?.access;if(w&&w.expires<=Date.now()&&H(h))try{xe=await bt(k,h,w,`${c.provider}/${c.id}`,t)}catch(n){if(!Ge(n))throw n;ie??=n;continue}const Pe=kt(e),T=w||r||g||ke?void 0:await k.getApiKeyAndHeaders(c);if(T&&!T.ok)continue;const u=`${c.provider}/${c.id}`,F=e.model??u,R=g?y===null?null:{payer:y,funding:"endpoint"}:r?$e({call:"model",route:"endpoint",grantee:r.grantee}):y===null?null:$e({call:"model",route:w?"subscription":"key",sub:y});if(s!==void 0&&R!==null){const n=await st({scope:"call",payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,provider:h});if(n!==null){if(await ye({request:s.request??U,kind:"model",what:u,usd:null,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),refused:lt(n)}),se??=n,E!=="key"&&be.includes("key")){ve=!0;continue}break}}let I;if(r&&p)try{I=await Ie({audience:p.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw De(n)}if(B)try{I=await Ie({audience:B,sub:y,grantee:s.grantee,initiating_app:s.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw De(n)}let P=null,Re=!1,_,W,V,S=!1,q,Y=null,A=3e4,L;const ue=[],ce=[],Z=[];let d,O;const Q=l((n,f=null)=>({id:U,object:"chat.completion.chunk",created:Math.floor(G/1e3),model:u,served_model:u,requested_model:F,substituted:F!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),ee=l(n=>{ue.push(n),o?.(n)},"emit"),Le=Be(c,Pe,{apiKey:I?.access_token??xe??(ke?D:void 0)??(T?.ok?T.apiKey:void 0),...T?.ok?{headers:T.headers}:{},signal:t,reasoning:e.reasoning_effort??v.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const f=e.tool_choice,m=f==="required"?c.api==="anthropic-messages"?{type:"any"}:"required":typeof f=="object"&&f!==null?c.api==="anthropic-messages"?{type:"tool",name:f.function.name}:f:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[c.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,f)=>{const m=await fetch(n,f);if(q=m.status,Y=$t(m.headers)??Y,g){if(P=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!P)throw Re=!0,await m.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return m.status===402&&(V=xt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(S=!0,L=m.headers,A=he(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{g&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(_=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!g&&n.status===429&&(S=!0,L=n.headers,A=he(n.headers)??15e3)},"onResponse")});try{for await(const n of Le)n.type==="text_delta"&&(ce.push(n.delta),ee(Q({content:n.delta}))),n.type==="thinking_delta"&&(Z.push(n.delta),ee(Q({reasoning_content:n.delta}))),n.type==="done"&&(d=n.message),n.type==="error"&&(d=n.error)}catch(n){const f=Qe(n);L===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(it(n.headers)).length&&(L=n.headers);const m=_e({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||g)O=n;else{if(!S&&m.kind!=="rate-limit")throw ue.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;S=!0,A=f??A}}if(g){if(Re)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:u});if(q===402&&V)throw new i(402,"payment_refused",V.message,void 0,{payment:V,served_model:u});if(q===401){if(I&&Oe(I.key),$===0)continue;throw new i(404,"model_unavailable",`${B} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||q!==void 0&&q>=400||d?.stopReason==="error"||d?.stopReason==="aborted"){const f=O instanceof Error?O.message:d?.errorMessage??`the inference endpoint answered ${q??"with an error"}`;throw q===403?new i(502,"upstream_refused",f,void 0,{served_model:u}):new i(503,"upstream_model_unavailable",f,void 0,{served_model:u})}if(_===null||typeof _!="object"||!("id"in _)||_.id!==P||!("served_model"in _)||typeof _.served_model!="string"||!_.served_model.trim()||!("list_usd"in _)||typeof _.list_usd!="number"||!Number.isFinite(_.list_usd)||_.list_usd<0||Number(_.list_usd.toFixed(6))!==_.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:u,charge_id:P});W={id:P,served_model:_.served_model,list_usd:_.list_usd}}if(r){if(q===401){if(I&&Oe(I.key),$===0)continue;throw new i(404,"model_unavailable",`${p.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(S&&he(L)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!S&&(O!==void 0||q!==void 0&&q>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:d?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!S&&d?.stopReason==="error"&&_e({message:d.errorMessage}).kind==="rate-limit"&&(S=!0,A=15e3),S){const n=nt(L,c.id,A),{observation:f,vendorReset:m}=n;if(A=n.retryMs,b={provider:h,model:c.id,...w?{account:w.label}:{},observation:f},console.error(`[llm] 429 from ${u}${w?` account "${w.label}"`:""}: scope=${Me(f.scope)} retry_after_ms=${A} headers=${JSON.stringify(f.headers)}`),w&&H(h)&&await Ve(h,w.label,A,G,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(A,Ae)<N&&(N=Date.now()+Math.min(A,Ae),ae=u),ce.length||Z.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const te=at(d);if(q===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(d?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(d?.errorMessage??""))throw new i(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:u});if(d?.stopReason==="error"){const n=Mt(c.provider,d.errorMessage,u);if(n)throw n}if(!d||d.stopReason==="error"&&!te||d.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",d?.errorMessage??"model request failed",void 0,{served_model:u});w&&H(h)&&tt(w,c.id)&&await Ye(h,w.label,G,c.id);const fe=d.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),me=te?"content_filter":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",pe=d.responseModel?At(c,d.responseModel):void 0,C=W?`${c.provider}/${W.served_model}`:pe?`${c.provider}/${pe.model}`:u,ne={prompt_tokens:d.usage.input,completion_tokens:d.usage.output,total_tokens:d.usage.totalTokens,cache_read_tokens:d.usage.cacheRead,cache_write_tokens:d.usage.cacheWrite,usd_equivalent:W?W.list_usd:qt(pe??c,d.usage.cost.total),served_model:C};g?s!==void 0&&R!==null&&await ye({id:P,request:s.request??U,kind:"model",what:C,usd:ne.usd_equivalent,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),vendorRef:Y}):s!==void 0&&R!==null&&await ye({request:s.request??U,kind:"model",what:C,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:ne.usd_equivalent,payer:R.payer,funding:R.funding,sub:y,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:h,causedBy:await de(),vendorRef:Y});const qe={id:U,object:"chat.completion",created:Math.floor(G/1e3),model:C,served_model:C,requested_model:F,substituted:F!==C&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(F),choices:[{index:0,message:{role:"assistant",content:ce.join("")||null,...Z.length?{reasoning_content:Z.join("")}:{},...fe.length?{tool_calls:fe}:{},...te?{refusal:d.errorMessage??"Content filtered"}:{}},finish_reason:me}],usage:ne,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of fe.entries())ee(Q({tool_calls:[{index:n,...f}]}));return ee({...Q({},me),model:C,served_model:C,substituted:qe.substituted,...te?{choices:[{index:0,delta:{},finish_reason:me,message:{refusal:d.errorMessage??"Content filtered"}}]}:{},usage:ne}),{completion:qe,chunks:ue}}}throw se!==void 0?dt(se):N!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Ce())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((N-Date.now())/1e3)),served_model:b?`${b.provider}/${b.model}`:ae,...b?{rate_limit:{provider:b.provider,model:b.model,...b.account?{account:b.account}:{},scope:Me(b.observation.scope),...b.observation.claim?{claim:b.observation.claim}:{},headers:b.observation.headers}}:{}},void 0,!0):ie!==void 0?ie:e.model_policy==="exact"?new i(400,"substitution_refused","the requested model is unavailable"):p?new i(404,"model_unavailable","no usable model route is available"):await ge()}l(tn,"runLlm");export{bt as freshSubscriptionAccess,en as llmCallerOf,Qt as parseLlmRequest,tn as runLlm,qt as usdEquivalent};
3
+ `),U=e.tools?.map(({function:r})=>({name:r.name,description:r.description??"",parameters:r.parameters??{type:"object",properties:{}}}));return{...M?{systemPrompt:M}:{},messages:o.slice(s.length),...U?{tools:U}:{}}}l(Rt,"contextOf");function qt(e){return mt(e?.payment)}l(qt,"paymentOf");function At(e,t){const o=e.find("anthropic",t);if(o)return o;const a=e.getAll().find(s=>s.provider==="anthropic"&&s.api==="anthropic-messages");return a?{...a,id:t,name:t}:void 0}l(At,"hostedModel");function jt(e,t){const{input:o,output:a,cacheRead:s,cacheWrite:M}=e.cost;return o===0&&a===0&&s===0&&M===0?null:Number.isFinite(t)&&t>=0?t:null}l(jt,"usdEquivalent");function Mt(e,t){return e.compat?.allowedFallbackModels?.find(a=>a.provider===e.provider&&a.model===t)}l(Mt,"allowedFallback");function nn(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(nn,"llmCallerOf");function Pe(e){return e instanceof ht?e.code==="server_error"?new i(503,"upstream_model_unavailable",e.message):new i(404,"model_unavailable",e.message):e}l(Pe,"mintFailure");const St=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function $t(e,t,o){if(!(e!=="openai-codex"||t===void 0||!St.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l($t,"codexAccountModelRejection");function Ct(e){return e.get("request-id")??e.get("x-request-id")}l(Ct,"vendorRequestId");async function on(e,t,o,a,s,M,U){const r=M?.payer==="app"?M:void 0;if(e.payer==="app"&&!r)throw new i(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&r)throw new i(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(r&&!r.inference_endpoint)throw new i(404,"model_unavailable",`${r.grantee} is app-paid but its grant carries no inference endpoint`);const h=r?.inference_endpoint??void 0,g=s===void 0?null:r?.sub??s.sub??await pt(),x=await Ve();let R;h?(R=_t(h,e.model,e.model_policy==="exact").flatMap((_,w)=>{const S=Ge(_.model);return S?[{routeId:"app",credentialSource:"app",family:"app",strength:_.strength,...S,rank:w}]:[]}),R=R.filter(_=>gt(x,e,_))):R=await wt(x,e,a);const re=!h&&s!==void 0&&g!==null?await ft():null,ie=re===null?void 0:yt(e,R,re),Le=ie?re:null;ie&&(R=[...R,ie]);const Ke=h?new Set:ze(),we=l(async()=>new i(429,"all_routes_exhausted","no available way to pay for this call",void 0,{payment:{reason:"nothing_left",message:"No available way to pay for this call",pay_url:(await Oe())?.payment_setup_url??null,reset_at:null}}),"nothingLeft");if(R.length===0)throw e.model_policy==="exact"?new i(400,"substitution_refused","no eligible model route is configured"):h?new i(404,"model_unavailable","no eligible model route is configured"):await we();const B=`chatcmpl-${We()}`;let D=1/0,z=1/0,ae,v,se,de;const X=new Set,le=l(async()=>U??(s?.node?(await Ne(s.node))?.caused_by??null:null)??(s?.run?(await Ne(s.run))?.caused_by??null:null),"causeOf");for(const _ of R){const w=_.credentialSource==="hosted";if(!r&&!w&&!(await Xe(_,x)).authenticated){if(_.credentialSource!==je&&N(_.providerId)){const k=await $e(_.providerId);k.length>0&&k.every($=>$.authFailure)&&X.add(_.providerId)}continue}const S=w?At(x,_.modelId):x.find(_.providerId,_.modelId);if(!S)continue;const J=w?Le.base_url:void 0,c=h?{...S,baseUrl:`${h.base_url}/${S.provider}`}:J?{...S,baseUrl:`${J}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,p=_.providerId,G=_.credentialSource===je&&N(p),ue=!r&&!w&&!G&&N(p)?await $e(p):[],W=ue.filter(k=>!k.authFailure),be=W.filter(k=>Se(k,c.id)<=Date.now()),T=G?await Ie(p):Ke.has(p)?void 0:ue.length?await Ie(p):void 0;if(G&&T===void 0)continue;if(ue.length>0&&W.length===0&&T===void 0){N(p)&&X.add(p);continue}if(W.length&&!be.length&&T===void 0){const k=Math.min(...W.map($=>Se($,c.id)));k<D&&(D=k,se=`${c.provider}/${c.id}`);continue}const ve=r||w?[void 0,void 0]:G?["key"]:W.length||T!==void 0?[...be,...T!==void 0?["key"]:[]]:[void 0];let ke=!1;for(const[k,$]of ve.entries()){if(ke&&$!=="key")continue;const b=$==="key"?void 0:$,xe=$==="key",V=Date.now();let Re=b?.access;if(b&&b.expires<=Date.now()&&N(p))try{Re=await kt(x,p,b,`${c.provider}/${c.id}`,t)}catch(n){if(!Ze(n))throw n;ae??=n;continue}const Ue=Rt(e),F=b||r||w||xe?void 0:await x.getApiKeyAndHeaders(c);if(F&&!F.ok)continue;const u=`${c.provider}/${c.id}`,P=e.model??u,q=w?g===null?null:{payer:g,funding:"endpoint"}:r?Ee({call:"model",route:"endpoint",grantee:r.grantee}):g===null?null:Ee({call:"model",route:b?"subscription":"key",sub:g});if(s!==void 0&&q!==null){const n=await lt({scope:"call",payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,provider:p});if(n!==null){if(await ge({request:s.request??B,kind:"model",what:u,usd:null,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),refused:ct(n)}),de??=n,$!=="key"&&ve.includes("key")){ke=!0;continue}break}}let I;if(r&&h)try{I=await De({audience:h.base_url,sub:r.sub,grantee:r.grantee,initiating_app:r.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}if(J)try{I=await De({audience:J,sub:g,grantee:s.grantee,initiating_app:s.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}let L=null,qe=!1,y,H,Y,C=!1,A,Z=null,j=3e4,K;const ce=[],fe=[],Q=[];let d,O;const ee=l((n,f=null)=>({id:B,object:"chat.completion.chunk",created:Math.floor(V/1e3),model:u,served_model:u,requested_model:P,substituted:P!==u&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,delta:n,finish_reason:f}]}),"chunk"),te=l(n=>{ce.push(n),o?.(n)},"emit"),Be=He(c,Ue,{apiKey:I?.access_token??Re??(xe?T:void 0)??(F?.ok?F.apiKey:void 0),...F?.ok?{headers:F.headers}:{},signal:t,reasoning:e.reasoning_effort??_.thinkingLevel,...e.temperature!==void 0?{temperature:e.temperature}:{},...e.max_tokens!==void 0?{maxTokens:e.max_tokens}:{},...e.top_p!==void 0?{samplingParams:{top_p:e.top_p}}:{},...e.tool_choice==="none"?{toolChoice:"none"}:{},onPayload:l(n=>{if(!n||typeof n!="object")return;const f=e.tool_choice,m=f==="required"?c.api==="anthropic-messages"?{type:"any"}:"required":typeof f=="object"&&f!==null?c.api==="anthropic-messages"?{type:"tool",name:f.function.name}:f:void 0;return{...n,...m?{tool_choice:m}:{},...e.stop!==void 0?{[c.api==="anthropic-messages"?"stop_sequences":"stop"]:typeof e.stop=="string"?[e.stop]:e.stop}:{},...e.seed!==void 0?{seed:e.seed}:{},...e.response_format!==void 0?{response_format:e.response_format}:{}}},"onPayload"),fetch:l(async(n,f)=>{const m=await fetch(n,f);if(A=m.status,Z=Ct(m.headers)??Z,w){if(L=m.headers.get("crtr-charge-id")?.trim()||null,m.ok&&!L)throw qe=!0,await m.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return m.status===402&&(Y=qt(await m.clone().json().catch(()=>{}))),m}return m.status===429&&(C=!0,K=m.headers,j=_e(m.headers)??15e3),m},"fetch"),onProviderStreamEvent:l(n=>{w&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(y=n.crtr_charge)},"onProviderStreamEvent"),onResponse:l(n=>{!w&&n.status===429&&(C=!0,K=n.headers,j=_e(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(fe.push(n.delta),te(ee({content:n.delta}))),n.type==="thinking_delta"&&(Q.push(n.delta),te(ee({reasoning_content:n.delta}))),n.type==="done"&&(d=n.message),n.type==="error"&&(d=n.error)}catch(n){const f=tt(n);K===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(st(n.headers)).length&&(K=n.headers);const m=ye({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(r||w)O=n;else{if(!C&&m.kind!=="rate-limit")throw ce.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:u}):n;C=!0,j=f??j}}if(w){if(qe)throw new i(502,"upstream_refused","The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.",void 0,{served_model:u});if(A===402&&Y)throw new i(402,"payment_refused",Y.message,void 0,{payment:Y,served_model:u});if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${J} refuses this runtime's tokens`,void 0,{served_model:u})}if(O!==void 0||A!==void 0&&A>=400||d?.stopReason==="error"||d?.stopReason==="aborted"){const f=O instanceof Error?O.message:d?.errorMessage??`the inference endpoint answered ${A??"with an error"}`;throw A===403?new i(502,"upstream_refused",f,void 0,{served_model:u}):new i(503,"upstream_model_unavailable",f,void 0,{served_model:u})}if(y===null||typeof y!="object"||!("id"in y)||y.id!==L||!("served_model"in y)||typeof y.served_model!="string"||!y.served_model.trim()||!("list_usd"in y)||typeof y.list_usd!="number"||!Number.isFinite(y.list_usd)||y.list_usd<0||Number(y.list_usd.toFixed(6))!==y.list_usd)throw new i(502,"upstream_refused","The hosted endpoint returned missing or invalid final charge accounting; output and cost may already exist. Do not automatically replay this call.",void 0,{served_model:u,charge_id:L});H={id:L,served_model:y.served_model,list_usd:y.list_usd}}if(r){if(A===401){if(I&&Te(I.key),k===0)continue;throw new i(404,"model_unavailable",`${h.base_url} refuses this runtime's tokens`,void 0,{served_model:u})}if(C&&_e(K)===void 0)throw new i(503,"upstream_model_unavailable",`${u} was rate-limited without a retry-after`,void 0,{served_model:u});if(!C&&(O!==void 0||A!==void 0&&A>=500))throw new i(503,"upstream_model_unavailable",O instanceof Error?O.message:d?.errorMessage??"inference endpoint failed",void 0,{served_model:u})}if(!C&&d?.stopReason==="error"&&ye({message:d.errorMessage}).kind==="rate-limit"&&(C=!0,j=15e3),C){const n=rt(K,c.id,j),{observation:f,vendorReset:m}=n;if(j=n.retryMs,v={provider:p,model:c.id,...b?{account:b.label}:{},observation:f},console.error(`[llm] 429 from ${u}${b?` account "${b.label}"`:""}: scope=${Ce(f.scope)} retry_after_ms=${j} headers=${JSON.stringify(f.headers)}`),b&&N(p)&&await Qe(p,b.label,j,V,Date.now(),f.scope),m!==void 0&&(z=Math.min(z,m)),Date.now()+Math.min(j,Me)<D&&(D=Date.now()+Math.min(j,Me),se=u),fe.length||Q.length)throw new i(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:u});if(r)break;continue}const ne=dt(d);if(A===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(d?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(d?.errorMessage??""))throw new i(400,"invalid_request",d.errorMessage,"tool_choice",{served_model:u});if(d?.stopReason==="error"){const n=$t(c.provider,d.errorMessage,u);if(n)throw n}if(!d||d.stopReason==="error"&&!ne||d.stopReason==="aborted")throw new i(503,"upstream_model_unavailable",d?.errorMessage??"model request failed",void 0,{served_model:u});b&&N(p)&&ot(b,c.id)&&await et(p,b.label,V,c.id);const me=d.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),pe=ne?"content_filter":d.stopReason==="toolUse"?"tool_calls":d.stopReason==="length"?"length":"stop",he=d.responseModel?Mt(c,d.responseModel):void 0,E=H?`${c.provider}/${H.served_model}`:he?`${c.provider}/${he.model}`:u,oe={prompt_tokens:d.usage.input,completion_tokens:d.usage.output,total_tokens:d.usage.totalTokens,cache_read_tokens:d.usage.cacheRead,cache_write_tokens:d.usage.cacheWrite,usd_equivalent:H?H.list_usd:jt(he??c,d.usage.cost.total),served_model:E};w?s!==void 0&&q!==null&&await ge({id:L,request:s.request??B,kind:"model",what:E,usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),vendorRef:Z}):s!==void 0&&q!==null&&await ge({request:s.request??B,kind:"model",what:E,units:{input:d.usage.input,output:d.usage.output,cache_read:d.usage.cacheRead,cache_write:d.usage.cacheWrite},usd:oe.usd_equivalent,payer:q.payer,funding:q.funding,sub:g,grantee:s.grantee,node:s.node??null,run:s.run??null,provider:p,causedBy:await le(),vendorRef:Z});const Ae={id:B,object:"chat.completion",created:Math.floor(V/1e3),model:E,served_model:E,requested_model:P,substituted:P!==E&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,message:{role:"assistant",content:fe.join("")||null,...Q.length?{reasoning_content:Q.join("")}:{},...me.length?{tool_calls:me}:{},...ne?{refusal:d.errorMessage??"Content filtered"}:{}},finish_reason:pe}],usage:oe,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,f]of me.entries())te(ee({tool_calls:[{index:n,...f}]}));return te({...ee({},pe),model:E,served_model:E,substituted:Ae.substituted,...ne?{choices:[{index:0,delta:{},finish_reason:pe,message:{refusal:d.errorMessage??"Content filtered"}}]}:{},usage:oe}),{completion:Ae,chunks:ce}}}throw de!==void 0?ut(de):D!==1/0?new i(429,"all_routes_exhausted","all eligible model routes are rate-limited",void 0,{payment:{reason:"nothing_left",message:"Every connected subscription and key is rate-limited or used up right now.",pay_url:(await Oe())?.payment_setup_url??null,reset_at:z===1/0?null:new Date(z).toISOString()},retry_after_s:Math.max(1,Math.ceil((D-Date.now())/1e3)),served_model:v?`${v.provider}/${v.model}`:se,...v?{rate_limit:{provider:v.provider,model:v.model,...v.account?{account:v.account}:{},scope:Ce(v.observation.scope),...v.observation.claim?{claim:v.observation.claim}:{},headers:v.observation.headers}}:{}},void 0,!0):ae!==void 0?ae:e.model_policy==="exact"?new i(400,"substitution_refused",X.size>0?`your ${[...X].map(Ye).join(" and ")} sign-in has expired; sign in again`:"the requested model is unavailable"):h?new i(404,"model_unavailable","no usable model route is available"):await we()}l(on,"runLlm");export{kt as freshSubscriptionAccess,nn as llmCallerOf,tn as parseLlmRequest,on as runLlm,jt as usdEquivalent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.630",
3
+ "version": "0.3.631",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -145,7 +145,7 @@
145
145
  },
146
146
  "license": "UNLICENSED",
147
147
  "dependencies": {
148
- "@north-light/identity": "0.3.630",
148
+ "@north-light/identity": "0.3.631",
149
149
  "@earendil-works/chord": "1.1.0",
150
150
  "@earendil-works/pi-agent-core": "1.1.0",
151
151
  "@earendil-works/pi-ai": "1.1.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.630",
3
+ "version": "0.3.631",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.630",
3
+ "version": "0.3.631",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.630",
9
+ "version": "0.3.631",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,7 +28,7 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.630",
31
+ "@north-light/identity": "0.3.631",
32
32
  "cron-parser": "^5.6.0",
33
33
  "esbuild": "^0.27.7",
34
34
  "jose": "^6.2.12",
@@ -11956,17 +11956,17 @@
11956
11956
  },
11957
11957
  "packages/crouter-api": {
11958
11958
  "name": "@north-light/api",
11959
- "version": "0.3.630",
11959
+ "version": "0.3.631",
11960
11960
  "license": "UNLICENSED"
11961
11961
  },
11962
11962
  "packages/crouter-env-docker": {
11963
11963
  "name": "@north-light/env-docker",
11964
- "version": "0.3.630",
11964
+ "version": "0.3.631",
11965
11965
  "license": "UNLICENSED"
11966
11966
  },
11967
11967
  "packages/crouter-identity": {
11968
11968
  "name": "@north-light/identity",
11969
- "version": "0.3.630",
11969
+ "version": "0.3.631",
11970
11970
  "license": "UNLICENSED",
11971
11971
  "dependencies": {
11972
11972
  "jose": "^6.2.1"
@@ -11974,21 +11974,21 @@
11974
11974
  },
11975
11975
  "packages/crouter-plugin": {
11976
11976
  "name": "@north-light/plugin",
11977
- "version": "0.3.630",
11977
+ "version": "0.3.631",
11978
11978
  "license": "UNLICENSED",
11979
11979
  "dependencies": {
11980
- "@north-light/api": "0.3.630",
11981
- "@north-light/identity": "0.3.630"
11980
+ "@north-light/api": "0.3.631",
11981
+ "@north-light/identity": "0.3.631"
11982
11982
  }
11983
11983
  },
11984
11984
  "packages/crouter-sdk": {
11985
11985
  "name": "@north-light/sdk",
11986
- "version": "0.3.630",
11986
+ "version": "0.3.631",
11987
11987
  "license": "UNLICENSED",
11988
11988
  "dependencies": {
11989
- "@north-light/api": "0.3.630",
11990
- "@north-light/identity": "0.3.630",
11991
- "@north-light/plugin": "0.3.630",
11989
+ "@north-light/api": "0.3.631",
11990
+ "@north-light/identity": "0.3.631",
11991
+ "@north-light/plugin": "0.3.631",
11992
11992
  "jose": "^6.2.1"
11993
11993
  },
11994
11994
  "bin": {