@north-light/cli 0.3.623 → 0.3.625
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/builtin-memory/crouter-sdk/release-notes.md +17 -0
- package/dist/core/import/export/cloud.d.ts +2 -1
- package/dist/core/import/export/cloud.js +1 -1
- package/dist/core/llm/anthropic-messages.d.ts +11 -0
- package/dist/core/llm/anthropic-messages.js +2 -0
- package/dist/core/llm/run.d.ts +14 -0
- package/dist/core/llm/run.js +2 -2
- package/dist/core/subscription-state.d.ts +9 -1
- package/dist/core/subscription-state.js +1 -1
- package/dist/daemon/api/app-listener.js +13 -13
- package/dist/daemon/api/operations.js +1 -1
- package/docs/sdk/release-notes.md +17 -0
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
package/dist/api/contract.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
|
|
2
|
-
export declare const CONTRACT_LEVEL = "1.
|
|
2
|
+
export declare const CONTRACT_LEVEL = "1.50";
|
|
3
3
|
/** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
|
|
4
4
|
export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
|
|
5
5
|
/** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
|
package/dist/api/contract.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.
|
|
1
|
+
var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.50",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
|
|
@@ -9,6 +9,23 @@ when-and-why-to-read: When you need Release notes, this knowledge should be read
|
|
|
9
9
|
|
|
10
10
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
11
11
|
|
|
12
|
+
## 0.3.625
|
|
13
|
+
|
|
14
|
+
### `inferenceEndpoint` serves Anthropic Messages, admits and settles every call (breaking, no existing consumer outside Northlight's own apps)
|
|
15
|
+
|
|
16
|
+
`inferenceEndpoint` now runs the directory's per-call admission and settlement itself, so an app no longer writes that proxy. It serves only `POST <baseURL>/anthropic/v1/messages`; any other path is 404. Options and return value change:
|
|
17
|
+
|
|
18
|
+
- New options: `apiKey` (the app's Anthropic key), `directoryToken` (the app's `OAuth2Client.directoryToken`), `settlements` (a `SettlementStore` over the app's own database: `save`, `remove`, `due`, `retryLater`). `rungs` values must be `anthropic/<model>` for a model the SDK has a list price for; the constructor throws for any other.
|
|
19
|
+
- Removed options: `providers` and `onUsage`. The `InferenceProvider` and `InferenceUsage` types are removed; `InferenceSettlement` and `SettlementStore` are added.
|
|
20
|
+
- It returns `{handle(request), sweep(now?)}` instead of a bare handler. Mount `handle` at the path of `baseURL` and call `sweep` on a timer (every 30 s is typical) to post usage reports the directory has not yet accepted.
|
|
21
|
+
- Per call it verifies the directory token, refuses server-side tools and service tiers (400) and models outside `rungs` (404), then asks the directory to admit the call. A refusal is a 402 carrying the directory's `payment` body; an unreachable or unexpected directory is a 503 with nothing sent upstream.
|
|
22
|
+
- When the admission carries `pool`, the call goes to the team Claude pool at `pool.url` with `pool.token` and settles at list price with `cost_usd` 0; a pool 429 keeps its `Retry-After`. Otherwise it goes to Anthropic with `apiKey` and settles with `cost_usd` equal to the list price. A call is never sent to `apiKey` when the admission carried `pool`.
|
|
23
|
+
- The answer carries `Crtr-Charge-Id`, and the terminal `message_stop` event (or JSON body) carries `crtr_charge`.
|
|
24
|
+
|
|
25
|
+
### `POST /v1/llm/anthropic/messages`, a new route served from the owner's Claude logins
|
|
26
|
+
|
|
27
|
+
`POST /v1/llm/anthropic/messages` is a new app-class route that serves an Anthropic Messages request (JSON or SSE, the vendor's answer passed through unchanged) with the runtime owner's Claude subscription logins. It needs the `crtr:llm` scope and an owner-paid grant: an app-paid grant is refused `403 permission_error`. It never uses a stored API key, a hosted endpoint or an app endpoint. A model that is not an Anthropic catalog model answers `404 model_unavailable`, as does an account with no usable Claude login. When every login is cooling down it answers `429 all_routes_exhausted` with `Retry-After` and `retry_after_s`; a spend limit on the owner's subscription spend answers `402 cap_exhausted`. Each completed call writes one `funding: subscription` ledger row at list price. It exists for the SDK's inference helper; no existing route changes.
|
|
28
|
+
|
|
12
29
|
## 0.3.622
|
|
13
30
|
|
|
14
31
|
`oauth.authorizeUrl` takes an optional `loginHint`: a phone number your app already collected, sent as the standard `login_hint`. A signed-out person's sign-in page then shows the number with one "Text me a link" button instead of asking for it (US and Canadian numbers in any format they type; a number the directory cannot text only prefills its form). Nothing is texted until the person presses the button. No existing call changes.
|
|
@@ -6,8 +6,9 @@ export declare class ImportCloud {
|
|
|
6
6
|
private readonly apiUrl;
|
|
7
7
|
private readonly token;
|
|
8
8
|
private readonly retryBaseMs;
|
|
9
|
+
private readonly putIdleMs;
|
|
9
10
|
/** `token` is a fixed import token, or a getter for a person bearer (5-minute tokens, so a long import asks per call). */
|
|
10
|
-
constructor(apiUrl: string, token: string | (() => Promise<string>), retryBaseMs?: number);
|
|
11
|
+
constructor(apiUrl: string, token: string | (() => Promise<string>), retryBaseMs?: number, putIdleMs?: number);
|
|
11
12
|
private call;
|
|
12
13
|
start(request: ImportStartRequest): Promise<ImportStartedDTO>;
|
|
13
14
|
uploadUrls(run: string, keys: string[]): Promise<ImportUploadUrlsDTO>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var S=Object.defineProperty;var d=(m,t)=>S(m,"name",{value:t,configurable:!0});import{general as f}from"../../errors.js";const U="stores.json",E=["auth","credentials","env","settings","plugins"],y=8,M=15e3,P=6e4,g=64*1024;class x{static{d(this,"ImportCloud")}apiUrl;token;retryBaseMs;putIdleMs;constructor(t,e,s=500,a=P){this.apiUrl=t,this.token=e,this.retryBaseMs=s,this.putIdleMs=a}async call(t,e,s){const a=await fetch(new URL(e,this.apiUrl),{method:t,headers:{authorization:`Bearer ${typeof this.token=="string"?this.token:await this.token()}`,...s===void 0?{}:{"content-type":"application/json"}},...s===void 0?{}:{body:JSON.stringify(s)}}),i=await a.text();if(!a.ok){let o;try{o=JSON.parse(i).error?.code}catch{o=void 0}throw f(`${t} ${e} answered ${a.status}: ${i.slice(0,500)}`,{status:a.status,...typeof o=="string"?{code:o}:{}})}return i===""?void 0:JSON.parse(i)}start(t){return this.call("POST","/v1/imports",t)}uploadUrls(t,e){return this.call("POST",`/v1/imports/${t}/upload-urls`,{keys:e})}putStore(t,e,s){return this.call("PUT",`/v1/imports/${t}/stores/${e}`,s)}load(t){return this.call("POST",`/v1/imports/${t}/load`,{})}get(t){return this.call("GET",`/v1/imports/${t}`)}machineCredential(t,e=!1){return this.call("POST",`/v1/imports/${t}/machine-credential${e?"?rotate=1":""}`,{})}async put(t,e,s,a){let i=!1;for(let o=1;;o+=1){let l,u;const $=new AbortController;let h;const p=d(()=>{clearTimeout(h),h=setTimeout(()=>$.abort(new Error(`no progress for ${Math.round(this.putIdleMs/1e3)}s`)),this.putIdleMs)},"arm");let c=0;const w=new ReadableStream({pull(r){if(p(),c>=e.length){r.close();return}r.enqueue(e.subarray(c,c+g)),c+=g}},{highWaterMark:0});try{p();const r=await fetch(t,{method:"PUT",headers:{"content-length":String(e.length)},body:w,duplex:"half",signal:$.signal});if(p(),r.ok){await r.arrayBuffer();return}const n=r.status;let T="";try{T=(await r.text()).slice(0,300)}catch{}if(l=`answered ${n}: ${T}`,n===403&&a!==void 0&&!i){i=!0,t=await a();continue}u=n===408||n===429||n>=500}catch(r){const n=r.cause;l=`failed: ${r instanceof Error?r.message:String(r)}${typeof n?.code=="string"?` (${n.code})`:""}`,u=!0}finally{clearTimeout(h)}if(!u)throw f(`upload of ${s} ${l}`,{key:s});if(o>=y)throw f(`upload of ${s} ${l} after ${o} tries`,{key:s});await new Promise(r=>setTimeout(r,Math.min(this.retryBaseMs*2**(o-1),M)*(.5+Math.random()/2)))}}}export{x as ImportCloud,U as STORE_FILE,E as STORE_ORDER};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { IncomingHttpHeaders, ServerResponse } from 'node:http';
|
|
2
|
+
export interface AnthropicMessagesCaller {
|
|
3
|
+
grant: string;
|
|
4
|
+
sub: string;
|
|
5
|
+
grantee: string;
|
|
6
|
+
request: string;
|
|
7
|
+
causedBy?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Serve one Anthropic Messages request with the runtime owner's Claude subscription logins, and nothing else: never a stored API key,
|
|
10
|
+
* a hosted endpoint or an app endpoint. Only an owner-paid grant reaches it. The vendor's answer (SSE included) is written to `res` unchanged. */
|
|
11
|
+
export declare function runAnthropicMessages(raw: Buffer, headers: IncomingHttpHeaders, signal: AbortSignal, caller: AnthropicMessagesCaller, res: ServerResponse): Promise<void>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var P=Object.defineProperty;var s=(e,t)=>P(e,"name",{value:t,configurable:!0});import{openModelRegistry as G}from"../runtime/model-registry.js";import{calculateCost as V}from"@earendil-works/pi-ai";import{MAX_RATE_LIMIT_COOLDOWN_MS as H,coolingUntilFor as q,markSubscriptionAuthFailure as X,markSubscriptionRateLimited as Y,markSubscriptionSuccess as z,readSubscriptionPool as K,subscriptionNeedsSuccessWrite as Q,vendorRateLimit as Z}from"../subscription-state.js";import{isInvalidRefreshTokenError as ee}from"../managed-providers.js";import{RunError as f}from"../runs/operations.js";import{findRefusal as te,payerOf as ne,refusalError as oe,refusedMark as ie,writeCharge as $}from"../ledger/index.js";import{activeGrant as re,payerOfGrant as ae}from"../grants/mirror.js";import{freshSubscriptionAccess as se,usdEquivalent as ce}from"./run.js";const ue="2.1.280",U="You are Claude Code, Anthropic's official CLI for Claude.",de=["claude-code-20250219","oauth-2025-04-20"],l="anthropic",fe=10*6e4,R=s(e=>Array.isArray(e)?e[0]:e,"one");function le(e){const t={type:"text",text:U};if(e==null)return[t];const i=typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:void 0;if(!i)throw new f(400,"invalid_request","system must be a string or an array of text blocks","system");const n=i[0];return n?.type==="text"&&n.text===U?i:[t,...i]}s(le,"withIdentity");function pe(e){return[...new Set([...(e??"").split(",").map(t=>t.trim()).filter(Boolean),...de])].join(",")}s(pe,"betasOf");function C(e,t){if(!t)return;const i=s(o=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:void 0,"count"),n=t.cache_creation;e.input=i(t.input_tokens)??e.input,e.output=i(t.output_tokens)??e.output,e.cacheRead=i(t.cache_read_input_tokens)??e.cacheRead,e.cacheWrite=i(t.cache_creation_input_tokens)??e.cacheWrite,e.cacheWrite1h=i(n?.ephemeral_1h_input_tokens)??e.cacheWrite1h,e.seen=!0}s(C,"foldUsage");function he(e){let t="";return i=>{t+=i;const n=t.split(`
|
|
2
|
+
`);t=n.pop()??"";for(const o of n){if(!o.startsWith("data:"))continue;let y;try{y=JSON.parse(o.slice(5))}catch{continue}y.type==="message_start"?C(e,y.message?.usage):y.type==="message_delta"&&C(e,y.usage)}}}s(he,"sseUsage");function me(e,t){try{C(e,JSON.parse(t).usage)}catch{}}s(me,"jsonUsage");function ye(e,t){const i={input:0,output:0,cacheRead:0,cacheWrite:0,total:0};return ce(e,V(e,{input:t.input,output:t.output,cacheRead:t.cacheRead,cacheWrite:t.cacheWrite,cacheWrite1h:t.cacheWrite1h,totalTokens:t.input+t.output+t.cacheRead+t.cacheWrite,cost:i}).total)}s(ye,"listUsd");async function Oe(e,t,i,n,o){if(!await re(n.grant)||await ae(n.grant)!=="user")throw new f(403,"permission_error","this route serves owner-paid grants only");let c;try{c=JSON.parse(e.toString("utf8"))}catch{throw new f(400,"invalid_request","invalid JSON body")}if(c===null||typeof c!="object"||Array.isArray(c))throw new f(400,"invalid_request","body must be an object");if(typeof c.model!="string")throw new f(400,"invalid_request","model must be a string","model");const E=await G(),u=E.find(l,c.model);if(!u||u.api!=="anthropic-messages")throw new f(404,"model_unavailable",`${c.model} is not an Anthropic model this runtime serves`);const h=`${l}/${u.id}`,W=(await K(l)).filter(p=>!p.authFailure);if(W.length===0)throw new f(404,"model_unavailable","no Claude login on this account");const B=JSON.stringify({...c,system:le(c.system)}),w=ne({call:"model",route:"subscription",sub:n.sub}),j=R(t.accept),L=c.stream===!0?i:AbortSignal.timeout(fe);let b=1/0,v=1/0,k;for(const p of W){if(q(p,u.id)>Date.now()){b=Math.min(b,q(p,u.id));continue}let I;try{I=await se(E,l,p,h,i)}catch(r){if(ee(r))continue;throw r}const A=await te({scope:"call",payer:w.payer,funding:w.funding,sub:n.sub,grantee:n.grantee,provider:l});if(A!==null){await $({request:n.request,kind:"model",what:h,usd:null,payer:w.payer,funding:w.funding,sub:n.sub,grantee:n.grantee,provider:l,causedBy:n.causedBy??null,refused:ie(A)}),k=A;break}const M=Date.now();let a;try{a=await fetch(`${u.baseUrl}/v1/messages`,{method:"POST",signal:L,body:B,headers:{authorization:`Bearer ${I}`,"content-type":R(t["content-type"])??"application/json",accept:j??"application/json","anthropic-version":R(t["anthropic-version"])??"2023-06-01","anthropic-beta":pe(R(t["anthropic-beta"])),"anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${ue}`,"x-app":"cli"}})}catch(r){throw i.aborted?r:new f(503,"upstream_model_unavailable",r instanceof Error?r.message:String(r),void 0,{served_model:h})}if(a.status===429||a.status===529){await a.body?.cancel();const{retryMs:r,vendorReset:m,observation:g}=Z(a.headers,u.id,void 0);await Y(l,p.label,r,M,Date.now(),g.scope),m!==void 0&&(v=Math.min(v,m)),b=Math.min(b,Date.now()+Math.min(r,H));continue}if(a.status===401){await a.body?.cancel(),await X(l,p.label);continue}const x=a.headers.get("content-type")??"application/json",_=x.startsWith("text/event-stream"),S=a.headers.get("request-id"),O=a.status>=200&&a.status<300;O&&Q(p,u.id)&&await z(l,p.label,M,u.id),o.writeHead(a.status,{"Content-Type":x,...S?{"Request-Id":S}:{},..._?{"Cache-Control":"no-cache","X-Accel-Buffering":"no"}:{}});const d={input:0,output:0,cacheRead:0,cacheWrite:0,cacheWrite1h:0,seen:!1},F=he(d),D=new TextDecoder,T=[];let N=!1;try{if(a.body)for await(const r of a.body){if(O){const m=D.decode(r,{stream:!0});_?F(m):T.push(m)}if(_&&o.destroyed){await a.body.cancel().catch(()=>{});break}if(!o.destroyed&&(o.write(r)||await new Promise(m=>{const g=s(()=>{o.off("drain",g),o.off("close",g),m()},"done");o.once("drain",g),o.once("close",g)}),_&&o.destroyed)){await a.body.cancel().catch(()=>{});break}}N=!o.destroyed}catch(r){i.aborted||console.error(`[llm] anthropic messages stream from ${h} failed after ${d.seen?"usage was reported":"no usage"}: ${r instanceof Error?r.message:String(r)}`)}finally{O&&(_||me(d,T.join("")+D.decode()),d.seen?await $({request:n.request,kind:"model",what:h,units:{input:d.input,output:d.output,cache_read:d.cacheRead,cache_write:d.cacheWrite,cache_write_1h:d.cacheWrite1h},usd:ye(u,d),payer:w.payer,funding:w.funding,sub:n.sub,grantee:n.grantee,provider:l,causedBy:n.causedBy??null,vendorRef:S}):console.error(`[llm] anthropic messages ${S??n.request} on ${h} was served with no usage observed; nothing was charged`))}N?o.end():o.destroy();return}if(k!==void 0)throw oe(k);if(b===1/0)throw new f(404,"model_unavailable","every Claude login on this account needs a new sign-in");const J={reason:"nothing_left",message:"Every Claude login on this account is rate-limited right now.",pay_url:null,reset_at:v===1/0?null:new Date(v).toISOString()};throw new f(429,"all_routes_exhausted","every Claude login is rate-limited",void 0,{payment:J,retry_after_s:Math.max(1,Math.ceil((b-Date.now())/1e3)),served_model:h},void 0,!0)}s(Oe,"runAnthropicMessages");export{Oe as runAnthropicMessages};
|
package/dist/core/llm/run.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type ThinkingLevel } from '@earendil-works/pi-ai/compat';
|
|
2
|
+
import { openModelRegistry } from '../runtime/model-registry.js';
|
|
3
|
+
import { type ManagedProviderId, type SubscriptionCredential } from '../managed-providers.js';
|
|
2
4
|
import type { GrantRecord, InferenceEndpoint } from '../grants/mirror.js';
|
|
3
5
|
type WireContent = string | null | Array<{
|
|
4
6
|
type: 'text';
|
|
@@ -49,11 +51,23 @@ export interface LlmRequest {
|
|
|
49
51
|
stop?: string | string[];
|
|
50
52
|
seed?: number;
|
|
51
53
|
}
|
|
54
|
+
/** The account's access token, refreshed under the pool's row lock when it has expired. Throws the vendor's refusal unchanged (a rejected refresh token is `isInvalidRefreshTokenError`, and the pool has already flagged the row); a vendor that is unreachable, or a refresh already in flight too long, is the retryable `503 upstream_model_unavailable`. */
|
|
55
|
+
export declare function freshSubscriptionAccess(registry: Awaited<ReturnType<typeof openModelRegistry>>, provider: ManagedProviderId, account: SubscriptionCredential, served: string, signal?: AbortSignal): Promise<string>;
|
|
52
56
|
export declare function parseLlmRequest(raw: unknown): LlmRequest;
|
|
53
57
|
export interface LlmResult {
|
|
54
58
|
completion: Record<string, unknown>;
|
|
55
59
|
chunks: Array<Record<string, unknown>>;
|
|
56
60
|
}
|
|
61
|
+
/** A completion's list-price cost: pi-ai prices it from the model's per-million rates.
|
|
62
|
+
* A model with no list price (every rate 0: an unpriced or custom endpoint) is null, never 0. */
|
|
63
|
+
export declare function usdEquivalent(model: {
|
|
64
|
+
cost: {
|
|
65
|
+
input: number;
|
|
66
|
+
output: number;
|
|
67
|
+
cacheRead: number;
|
|
68
|
+
cacheWrite: number;
|
|
69
|
+
};
|
|
70
|
+
}, total: number): number | null;
|
|
57
71
|
/** Who the call is made for: the caller's grant decides the payer (RT-RTE-12). A caller with no grant (the person) is user-paid. */
|
|
58
72
|
export interface LlmCaller {
|
|
59
73
|
payer: 'user' | 'app';
|
package/dist/core/llm/run.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
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)&>(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(`
|
|
2
2
|
|
|
3
|
-
`),z=e.tools?.map(({function:i})=>({name:i.name,description:i.description??"",parameters:i.parameters??{type:"object",properties:{}}}));return{...E?{systemPrompt:E}:{},messages:o.slice(d.length),...z?{tools:z}:{}}}c(At,"contextOf");function qt(e){return ht(e?.payment)}c(qt,"paymentOf");function jt(e,t){const o=e.find("anthropic",t);if(o)return o;const s=e.getAll().find(d=>d.provider==="anthropic"&&d.api==="anthropic-messages");return s?{...s,id:t,name:t}:void 0}c(jt,"hostedModel");function Mt(e,t){const{input:o,output:s,cacheRead:d,cacheWrite:E}=e.cost;return o===0&&s===0&&d===0&&E===0?null:Number.isFinite(t)&&t>=0?t:null}c(Mt,"usdEquivalent");function $t(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}c($t,"allowedFallback");function on(e){return e?{payer:e.payer??"user",sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}c(on,"llmCallerOf");function Pe(e){return e instanceof yt?e.code==="server_error"?new r(503,"upstream_model_unavailable",e.message):new r(404,"model_unavailable",e.message):e}c(Pe,"mintFailure");const Ct=/\bmodel is not supported when using Codex with a ChatGPT account\b/i;function Et(e,t,o){if(!(e!=="openai-codex"||t===void 0||!Ct.test(t)))return new r(404,"model_unavailable",t,void 0,{served_model:o})}c(Et,"codexAccountModelRejection");function St(e){return e.get("request-id")??e.get("x-request-id")}c(St,"vendorRequestId");async function rn(e,t,o,s,d,E,z){const i=E?.payer==="app"?E:void 0;if(e.payer==="app"&&!i)throw new r(403,"payer_not_app","this grant is not app-paid");if(e.payer==="user"&&i)throw new r(400,"invalid_request","this grant is app-paid; payer cannot be user","payer");if(i&&!i.inference_endpoint)throw new r(404,"model_unavailable",`${i.grantee} is app-paid but its grant carries no inference endpoint`);const _=i?.inference_endpoint??void 0,R=d===void 0?null:i?.sub??d.sub??await _t(),S=await Ze();let A;_?(A=gt(_,e.model,e.model_policy==="exact").flatMap((b,y)=>{const q=Ye(b.model);return q?[{routeId:"app",credentialSource:"app",family:"app",strength:b.strength,...q,rank:y}]:[]}),A=A.filter(b=>bt(S,e,b))):A=await vt(S,e,s);const ie=!_&&d!==void 0&&R!==null?await pt():null,ae=ie===null?void 0:wt(e,A,ie),Le=ae?ie:null;ae&&(A=[...A,ae]);const Ke=_?new Set:Xe(),be=c(async()=>new r(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(A.length===0)throw e.model_policy==="exact"?new r(400,"substitution_refused","no eligible model route is configured"):_?new r(404,"model_unavailable","no eligible model route is configured"):await be();const K=`chatcmpl-${He()}`;let N=1/0,X=1/0,se,w,de,le;const ue=c(async()=>z??(d?.node?(await De(d.node))?.caused_by??null:null)??(d?.run?(await De(d.run))?.caused_by??null:null),"causeOf");for(const b of A){const y=b.credentialSource==="hosted";if(!i&&!y&&!(await Ge(b,S)).authenticated)continue;const q=y?jt(S,b.modelId):S.find(b.providerId,b.modelId);if(!q)continue;const U=y?Le.base_url:void 0,u=_?{...q,baseUrl:`${_.base_url}/${q.provider}`}:U?{...q,baseUrl:`${U}/anthropic`,compat:{...q.compat,allowedFallbackModels:void 0}}:q,p=b.providerId,G=b.credentialSource===Ve&&W(p),ce=!i&&!y&&!G&&W(p)?await nt(p):[],B=ce.filter(j=>!j.authFailure),ve=B.filter(j=>Ce(j,u.id)<=Date.now()),T=G?await Ie(p):Ke.has(p)?void 0:ce.length?await Ie(p):void 0;if(G&&T===void 0||ce.length>0&&B.length===0&&T===void 0)continue;if(B.length&&!ve.length&&T===void 0){const j=Math.min(...B.map(I=>Ce(I,u.id)));j<N&&(N=j,de=`${u.provider}/${u.id}`);continue}const ke=i||y?[void 0,void 0]:G?["key"]:B.length||T!==void 0?[...ve,...T!==void 0?["key"]:[]]:[void 0];let xe=!1;for(const[j,I]of ke.entries()){if(xe&&I!=="key")continue;const g=I==="key"?void 0:I,Re=I==="key",V=Date.now();let Ae=g?.access;if(g&&g.expires<=Date.now()&&W(p)){const n=S.getProvider(p)?.auth.oauth;if(!n)throw new r(503,"upstream_model_unavailable",`no OAuth refresh for ${p}`,void 0,{served_model:`${u.provider}/${u.id}`});let m;try{m=await rt(p,g.label,async(l,Me)=>{const re=await n.refresh({type:"oauth",refresh:l,access:"",expires:0,...Me?{clientId:Me}:{}},t??new AbortController().signal).catch(Je=>{throw xt(Je,`${u.provider}/${u.id}`)}),ye=re.clientId;return{refresh:re.refresh,access:re.access,expires:re.expires,...typeof ye=="string"&&ye?{clientId:ye}:{}}}).catch(l=>{throw l instanceof at||l instanceof st?new r(503,"upstream_model_unavailable",l.message,void 0,{served_model:`${u.provider}/${u.id}`}):l})}catch(l){if(!Qe(l))throw l;se??=l;continue}Ae=m.access}const Ue=At(e),F=g||i||y||Re?void 0:await S.getApiKeyAndHeaders(u);if(F&&!F.ok)continue;const f=`${u.provider}/${u.id}`,P=e.model??f,k=y?R===null?null:{payer:R,funding:"endpoint"}:i?Se({call:"model",route:"endpoint",grantee:i.grantee}):R===null?null:Se({call:"model",route:g?"subscription":"key",sub:R});if(d!==void 0&&k!==null){const n=await ct({scope:"call",payer:k.payer,funding:k.funding,sub:R,grantee:d.grantee,provider:p});if(n!==null){if(await we({request:d.request??K,kind:"model",what:f,usd:null,payer:k.payer,funding:k.funding,sub:R,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await ue(),refused:mt(n)}),le??=n,I!=="key"&&ke.includes("key")){xe=!0;continue}break}}let O;if(i&&_)try{O=await Ne({audience:_.base_url,sub:i.sub,grantee:i.grantee,initiating_app:i.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}if(U)try{O=await Ne({audience:U,sub:R,grantee:d.grantee,initiating_app:d.grantee,scope:["crtr:llm"]},{signal:t})}catch(n){throw Pe(n)}let L=null,qe=!1,h,J,Y,M=!1,x,Z=null,v=3e4,$;const fe=[],me=[],Q=[];let a,D;const ee=c((n,m=null)=>({id:K,object:"chat.completion.chunk",created:Math.floor(V/1e3),model:f,served_model:f,requested_model:P,substituted:P!==f&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,delta:n,finish_reason:m}]}),"chunk"),te=c(n=>{fe.push(n),o?.(n)},"emit"),Be=ze(u,Ue,{apiKey:O?.access_token??Ae??(Re?T:void 0)??(F?.ok?F.apiKey:void 0),...F?.ok?{headers:F.headers}:{},signal:t,reasoning:e.reasoning_effort??b.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:c(n=>{if(!n||typeof n!="object")return;const m=e.tool_choice,l=m==="required"?u.api==="anthropic-messages"?{type:"any"}:"required":typeof m=="object"&&m!==null?u.api==="anthropic-messages"?{type:"tool",name:m.function.name}:m:void 0;return{...n,...l?{tool_choice:l}:{},...e.stop!==void 0?{[u.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:c(async(n,m)=>{const l=await fetch(n,m);if(x=l.status,Z=St(l.headers)??Z,y){if(L=l.headers.get("crtr-charge-id")?.trim()||null,l.ok&&!L)throw qe=!0,await l.body?.cancel(),new Error("The hosted endpoint omitted Crtr-Charge-Id; the call may already have been charged. Do not automatically replay it.");return l.status===402&&(Y=qt(await l.clone().json().catch(()=>{}))),l}return l.status===429&&(M=!0,$=l.headers,v=H(l.headers)??15e3),l},"fetch"),onProviderStreamEvent:c(n=>{y&&n!==null&&typeof n=="object"&&"type"in n&&n.type==="message_stop"&&"crtr_charge"in n&&(h=n.crtr_charge)},"onProviderStreamEvent"),onResponse:c(n=>{!y&&n.status===429&&(M=!0,$=n.headers,v=H(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(me.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"&&(a=n.message),n.type==="error"&&(a=n.error)}catch(n){const m=ot(n);$===void 0&&n&&typeof n=="object"&&"headers"in n&&Object.keys(lt(n.headers)).length&&($=n.headers);const l=ge({status:n&&typeof n=="object"&&"status"in n?n.status:void 0,message:n instanceof Error?n.message:String(n)});if(i||y)D=n;else{if(!M&&l.kind!=="rate-limit")throw fe.length?new r(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;M=!0,v=m??v}}if(y){if(qe)throw new r(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:f});if(x===402&&Y)throw new r(402,"payment_refused",Y.message,void 0,{payment:Y,served_model:f});if(x===401){if(O&&Te(O.key),j===0)continue;throw new r(404,"model_unavailable",`${U} refuses this runtime's tokens`,void 0,{served_model:f})}if(D!==void 0||x!==void 0&&x>=400||a?.stopReason==="error"||a?.stopReason==="aborted"){const m=D instanceof Error?D.message:a?.errorMessage??`the inference endpoint answered ${x??"with an error"}`;throw x===403?new r(502,"upstream_refused",m,void 0,{served_model:f}):new r(503,"upstream_model_unavailable",m,void 0,{served_model:f})}if(h===null||typeof h!="object"||!("id"in h)||h.id!==L||!("served_model"in h)||typeof h.served_model!="string"||!h.served_model.trim()||!("list_usd"in h)||typeof h.list_usd!="number"||!Number.isFinite(h.list_usd)||h.list_usd<0||Number(h.list_usd.toFixed(6))!==h.list_usd)throw new r(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:f,charge_id:L});J={id:L,served_model:h.served_model,list_usd:h.list_usd}}if(i){if(x===401){if(O&&Te(O.key),j===0)continue;throw new r(404,"model_unavailable",`${_.base_url} refuses this runtime's tokens`,void 0,{served_model:f})}if(M&&H($)===void 0)throw new r(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!M&&(D!==void 0||x!==void 0&&x>=500))throw new r(503,"upstream_model_unavailable",D instanceof Error?D.message:a?.errorMessage??"inference endpoint failed",void 0,{served_model:f})}if(!M&&a?.stopReason==="error"&&ge({message:a.errorMessage}).kind==="rate-limit"&&(M=!0,v=15e3),M){const n=dt($,u.id),m=H($)!==void 0?Date.now()+v:n.resetAt;if(H($)===void 0&&n.resetAt!==void 0&&(v=Math.max(v,n.resetAt-Date.now())),w={provider:p,model:u.id,...g?{account:g.label}:{},observation:n},console.error(`[llm] 429 from ${f}${g?` account "${g.label}"`:""}: scope=${Ee(n.scope)} retry_after_ms=${v} headers=${JSON.stringify(n.headers)}`),g&&W(p)&&await et(p,g.label,v,V,Date.now(),n.scope),m!==void 0&&(X=Math.min(X,m)),Date.now()+Math.min(v,$e)<N&&(N=Date.now()+Math.min(v,$e),de=f),me.length||Q.length)throw new r(503,"service_unavailable","vendor rate limit after output began",void 0,{served_model:f});if(i)break;continue}const ne=ut(a);if(x===400&&e.tool_choice!==void 0&&e.tool_choice!=="auto"&&e.tool_choice!=="none"&&/\btool[_ ]choice\b/i.test(a?.errorMessage??"")&&/not supported|does not support|unsupported|cannot|must be auto/i.test(a?.errorMessage??""))throw new r(400,"invalid_request",a.errorMessage,"tool_choice",{served_model:f});if(a?.stopReason==="error"){const n=Et(u.provider,a.errorMessage,f);if(n)throw n}if(!a||a.stopReason==="error"&&!ne||a.stopReason==="aborted")throw new r(503,"upstream_model_unavailable",a?.errorMessage??"model request failed",void 0,{served_model:f});g&&W(p)&&it(g,u.id)&&await tt(p,g.label,V,u.id);const pe=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),he=ne?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",_e=a.responseModel?$t(u,a.responseModel):void 0,C=J?`${u.provider}/${J.served_model}`:_e?`${u.provider}/${_e.model}`:f,oe={prompt_tokens:a.usage.input,completion_tokens:a.usage.output,total_tokens:a.usage.totalTokens,cache_read_tokens:a.usage.cacheRead,cache_write_tokens:a.usage.cacheWrite,usd_equivalent:J?J.list_usd:Mt(_e??u,a.usage.cost.total),served_model:C};y?d!==void 0&&k!==null&&await we({id:L,request:d.request??K,kind:"model",what:C,usd:oe.usd_equivalent,payer:k.payer,funding:k.funding,sub:R,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await ue(),vendorRef:Z}):d!==void 0&&k!==null&&await we({request:d.request??K,kind:"model",what:C,units:{input:a.usage.input,output:a.usage.output,cache_read:a.usage.cacheRead,cache_write:a.usage.cacheWrite},usd:oe.usd_equivalent,payer:k.payer,funding:k.funding,sub:R,grantee:d.grantee,node:d.node??null,run:d.run??null,provider:p,causedBy:await ue(),vendorRef:Z});const je={id:K,object:"chat.completion",created:Math.floor(V/1e3),model:C,served_model:C,requested_model:P,substituted:P!==C&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(P),choices:[{index:0,message:{role:"assistant",content:me.join("")||null,...Q.length?{reasoning_content:Q.join("")}:{},...pe.length?{tool_calls:pe}:{},...ne?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:he}],usage:oe,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of pe.entries())te(ee({tool_calls:[{index:n,...m}]}));return te({...ee({},he),model:C,served_model:C,substituted:je.substituted,...ne?{choices:[{index:0,delta:{},finish_reason:he,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:oe}),{completion:je,chunks:fe}}}throw le!==void 0?ft(le):N!==1/0?new r(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:X===1/0?null:new Date(X).toISOString()},retry_after_s:Math.max(1,Math.ceil((N-Date.now())/1e3)),served_model:w?`${w.provider}/${w.model}`:de,...w?{rate_limit:{provider:w.provider,model:w.model,...w.account?{account:w.account}:{},scope:Ee(w.observation.scope),...w.observation.claim?{claim:w.observation.claim}:{},headers:w.observation.headers}}:{}},void 0,!0):se!==void 0?se:e.model_policy==="exact"?new r(400,"substitution_refused","the requested model is unavailable"):_?new r(404,"model_unavailable","no usable model route is available"):await be()}c(rn,"runLlm");export{on as llmCallerOf,nn as parseLlmRequest,rn as runLlm};
|
|
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};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type CanvasDb } from './canvas/db.js';
|
|
2
|
-
import { type RateLimitScope } from './rate-limit-scope.js';
|
|
2
|
+
import { type RateLimitObservation, type RateLimitScope } from './rate-limit-scope.js';
|
|
3
3
|
import { type ManagedProviderId, type RotationConfig, type SubscriptionCredential } from './managed-providers.js';
|
|
4
4
|
export * from './managed-providers.js';
|
|
5
5
|
/** One `model_accounts` row without its sealed tokens. */
|
|
@@ -64,6 +64,14 @@ export declare function markSubscriptionAttempt(provider: ManagedProviderId, ref
|
|
|
64
64
|
export declare function markSubscriptionRateLimited(provider: ManagedProviderId, ref: string, retryAfterMs: number, attemptAt?: number, rateLimitedAt?: number, scope?: RateLimitScope): Promise<SubscriptionCredential[]>;
|
|
65
65
|
/** A call on `modelId` succeeded: clear the account-wide cooldown and auth failure, and that model family's cooldown, unless a newer 429 for the same scope landed after `attemptAt` began. */
|
|
66
66
|
export declare function markSubscriptionSuccess(provider: ManagedProviderId, ref: string, attemptAt?: number, modelId?: string): Promise<SubscriptionCredential[]>;
|
|
67
|
+
/** What a vendor 429 asks of the account that received it, parsed once from its headers. The wait is `current` when the caller already holds one, else the vendor's Retry-After, else `defaultMs`; with no Retry-After, a rejected window's reset lengthens it to the window. `vendorReset` is the reset the vendor itself named (Retry-After or the window), never a default. */
|
|
68
|
+
export declare function vendorRateLimit(headers: Headers | Record<string, string> | undefined, modelId: string, current: number | undefined, defaultMs?: number, now?: number): {
|
|
69
|
+
retryMs: number;
|
|
70
|
+
vendorReset: number | undefined;
|
|
71
|
+
observation: RateLimitObservation;
|
|
72
|
+
};
|
|
73
|
+
/** The vendor refused this account's access token on a request (401): flag the row as a refused refresh does, so every pool reader skips it until a sign-in replaces it. */
|
|
74
|
+
export declare function markSubscriptionAuthFailure(provider: ManagedProviderId, ref: string): Promise<SubscriptionCredential[]>;
|
|
67
75
|
/** Refresh one account's tokens under its row lock. A process that waited on the lock finds the tokens already fresh (or the account already flagged) and does not call the vendor again. */
|
|
68
76
|
export declare function refreshSubscriptionCredential(provider: ManagedProviderId, label: string, exchange: (refreshToken: string, clientId?: string) => Promise<RefreshedTokens>): Promise<SubscriptionCredential>;
|
|
69
77
|
export declare function modifyElectedSubscription(provider: ManagedProviderId, elect: (pool: SubscriptionCredential[]) => SubscriptionCredential | undefined, apply: (current: SubscriptionCredential) => Promise<RefreshedTokens | undefined>): Promise<SubscriptionCredential | undefined>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var _t=Object.defineProperty;var l=(t,a)=>_t(t,"name",{value:a,configurable:!0});import{createHash as ht,randomUUID as x}from"node:crypto";import{brokerConfigSnapshot as pt}from"./config.js";import{openDb as W,withCanvasWrite as N}from"./canvas/db.js";import{personIdAsync as y}from"./canvas/person.js";import{loadSecretsKey as K,open as X,seal as $}from"./secrets/index.js";import{modelCooldownFamily as wt}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as At,REFRESH_TIMEOUT_PHRASE as bt}from"./provider-error-recognition.js";import{registerRotationReader as yt}from"./model-routes.js";import{coolingUntilFor as Et,getProviderLabel as h,isInvalidRefreshTokenError as Y,DuplicateSubscriptionError as O,ANTHROPIC_PROVIDER_ID as Lt,MAX_RATE_LIMIT_COOLDOWN_MS as B,INVALID_REFRESH_TOKEN_BACKOFF_MS as Rt}from"./managed-providers.js";export*from"./managed-providers.js";const J="strong";function Q(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(Q,"normalizeStrength");function _(t){return t.toLowerCase()}l(_,"key");function j(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(j,"optionalString");function gt(t){const a=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",n=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!a||!e||!n||!Number.isFinite(i))return;const r=j(t.accountId),s=j(t.clientId);return{label:a,refresh:e,access:n,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...Z(t.modelCooldowns)?{modelCooldowns:Z(t.modelCooldowns)}:{}}}l(gt,"credential");function Z(t){if(!t||typeof t!="object"||Array.isArray(t))return;const a=Object.entries(t).filter(([e,n])=>e.trim()!==""&&Number.isFinite(Number(n))).map(([e,n])=>[e,Number(n)]);return a.length?Object.fromEntries(a):void 0}l(Z,"modelCooldowns");function F(t,a){if(!a.label?.trim())throw new Error(`${h(t)} subscription label cannot be empty`);const e=gt(a);if(!e)throw new Error(`Refusing to persist incomplete ${h(t)} subscription "${a.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(F,"assertCredential");function v(t,a){const e=t.accountId?.trim(),n=a.accountId?.trim();return!!(e&&n&&e!==n)}l(v,"differentAccount");function p(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${ht("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(p,"identity");function tt(t,a){const e=j(a);return e?{...t,clientId:e}:t}l(tt,"withClientId");function et(t,a,e){const n=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!n||!i||!Number.isFinite(r))throw new Error(`${h(t)} subscription "${a}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:n,access:i,expires:r}}l(et,"assertTokens");const at=1e4,It="15s",xt="55P03";class nt extends Error{static{l(this,"RefreshBusyError")}constructor(a,e){super(`${h(a)} subscription "${e}" ${At}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class Nt extends Error{static{l(this,"RefreshTimeoutError")}constructor(a){super(`${h(a)} ${bt} ${at} ms`),this.name="RefreshTimeoutError"}}const it="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",I=l((t,a,e,n)=>`model_accounts|${t}|${a}|${e}|${n}`,"aadOf");function E(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(E,"stored");function Ft(t,a){return{providerId:t,id:a.id,label:a.label,labelKey:a.label_key,position:a.position,lastAttemptAt:a.last_attempt_at,lastRateLimitedAt:a.last_rate_limited_at,rateLimitedUntil:a.rate_limited_until,...a.auth_failure?{authFailure:a.auth_failure}:{}}}l(Ft,"rowOf");function rt(t,a,e,n=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${a} account ${e.id} has no credential record`);const i=K(),r=X(e.refresh_sealed,e.key_id,i,I(t,a,e.id,"refresh")),s=X(e.access_sealed,e.key_id,i,I(t,a,e.id,"access")),o=Ft(a,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+B),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...n.length?{modelCooldowns:Object.fromEntries(n.map(d=>[d.family,d.lastRateLimitedAt?Math.min(d.rateLimitedUntil,d.lastRateLimitedAt+B):d.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(rt,"toPublic");async function S(t,a,e){const n=new Map,i=await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(a,e);for(const r of i){const s=n.get(r.account_id)??[];s.push({family:r.family,rateLimitedUntil:r.rate_limited_until,lastRateLimitedAt:r.last_rate_limited_at}),n.set(r.account_id,s)}return n}l(S,"loadCooldowns");async function k(t,a,e,n=!1){const i=await t.prepare(`SELECT ${it} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${n?" FOR UPDATE":""}`).all(a,e),r=await S(t,a,e);return i.map(s=>rt(a,e,s,r.get(s.id)))}l(k,"loadPool");async function st(t,a,e,n){const i=n.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${it} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(a,e,s?r-1:i);if(o)return rt(a,e,o,(await S(t,a,e)).get(o.id))}l(st,"lockedAccount");async function T(t){await t.exec(`SET LOCAL lock_timeout = '${It}'`)}l(T,"setLockTimeout");async function L(t,a){const e=await y();return N(async n=>(await T(n),await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),a({db:n,person:e,rows:await k(n,e,t,!0)})))}l(L,"locked");async function C(t,a,e,n,i){const r=K(),s=$(i.refresh,r,I(a,e,n.id,"refresh")),o=$(i.access,r,I(a,e,n.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(a,e,n.id,n.label,n.labelKey,n.position,n.lastAttemptAt,n.lastRateLimitedAt,n.rateLimitedUntil,n.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(C,"insertAccount");async function M(t,a,e,n,i){const r=K(),s=$(i.refresh,r,I(a,e,n,"refresh")),o=$(i.access,r,I(a,e,n,"access"));await t.prepare("UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?").run(s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId,a,e,n)}l(M,"setCredential");async function b(t,a,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,a,e.providerId,e.id)}l(b,"updateHealth");async function ot(t,a,e,n,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(a,e,n,i,r,s)}l(ot,"upsertModelCooldown");async function U(t,a,e,n){n===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(a,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(a,e,n)}l(U,"deleteModelCooldowns");const R=l(async({db:t,person:a},e)=>(await k(t,a,e)).map(({entry:n})=>n),"publicPool"),lt=l(t=>t?.code===xt,"lockWaitExpired");function ct(t,a){let e;return Promise.race([a,new Promise((n,i)=>{e=setTimeout(()=>i(new Nt(t)),at)})]).finally(()=>clearTimeout(e))}l(ct,"withExchangeTimeout");async function V(t){return(await St(t)).map(({entry:a})=>a)}l(V,"readSubscriptionPool");async function St(t){const a=await y();return(await k(await W(),a,t)).map(({row:e,entry:n})=>({id:e.id,entry:n}))}l(St,"readSubscriptionPoolRows");async function qt(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=a.map(d=>F(t,d)),o=s.map((d,u)=>({entry:d,id:r[u]?.row.id??x()})),c=await S(n,i,t);await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await U(n,i,t);for(const[d,{entry:u,id:m}]of o.entries()){await C(n,i,t,{providerId:t,id:m,label:u.label,labelKey:_(u.label),position:d,lastAttemptAt:u.lastAttemptAt,lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:u.rateLimitedUntil,...u.authFailure?{authFailure:u.authFailure}:{}},E(u));for(const[f,A]of Object.entries(u.modelCooldowns??{}))await ot(n,i,t,m,f,A,c.get(m)?.find(D=>D.family===f)?.lastRateLimitedAt??u.lastRateLimitedAt)}return s})}l(qt,"writeSubscriptionPool");function H(t,a){const e=a.trim().toLowerCase(),n=Number.parseInt(e,10);return Number.isFinite(n)&&String(n)===e&&n>=1&&n<=t.length?n-1:t.findIndex(({entry:i})=>_(i.label)===e)}l(H,"resolve");const P=l((t,a)=>new O(`This ${h(t)} account is already added as \u201C${a}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Tt(t,a){const e=F(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n;if(s.some(({entry:d})=>_(d.label)===_(e.label)))throw new O(`${h(t)} subscription already exists: ${e.label}`);const o=p(e),c=s.find(({entry:d})=>p(d)===o);if(o&&c)throw P(t,c.entry.label);return await C(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},E(e)),R(n,t)})}l(Tt,"addSubscription");async function Xt(t,a){const e=F(t,a);return(await V(t)).find(i=>_(i.label)===_(e.label))?Ut(t,e):Tt(t,e)}l(Xt,"upsertSubscription");async function Ut(t,a){const e=F(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=s.findIndex(({entry:f})=>_(f.label)===_(e.label)),c=s[o],d=s.find(({entry:f},A)=>A!==o&&p(f)===p(e));if(p(e)&&d)throw P(t,d.entry.label);if(!c)return await C(i,r,t,{providerId:t,id:x(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},E(e)),R(n,t);const u=c.row,m=e.lastRateLimitedAt>=u.lastRateLimitedAt;return await M(i,r,t,u.id,E(e)),await b(i,r,{...u,authFailure:void 0,label:e.label,labelKey:_(e.label),lastAttemptAt:Math.max(u.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:m?e.lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:m?e.rateLimitedUntil:u.rateLimitedUntil}),v(c.entry,e)&&await U(i,r,t,u.id),R(n,t)})}l(Ut,"upsertSubscriptionWithUniqueAccount");async function Yt(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=H(s,a);if(o<0)throw new Error(`Unknown ${h(t)} subscription: ${a}`);const c=e.trim();if(!c)throw new Error(`${h(t)} subscription label cannot be empty`);if(s.some((d,u)=>u!==o&&_(d.entry.label)===_(c)))throw new O(`${h(t)} subscription already exists: ${c}`);return await b(i,r,{...s[o].row,label:c,labelKey:_(c)}),R(n,t)})}l(Yt,"renameSubscription");async function G(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=a(s);if(o<0)throw new Error(`Unknown ${h(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await U(i,r,t,c.id),R(n,t)})}l(G,"remove");async function Dt(t,a){return G(t,e=>H(e,a),a)}l(Dt,"removeManagedAccount");async function Jt(t,a){return G(t,e=>e.findIndex(({row:n})=>n.id===a),a)}l(Jt,"removeManagedAccountById");async function Qt(t,a){return G(t,e=>H(e,a),a)}l(Qt,"removeSubscription");async function $t(t){return L(t,async({db:a,person:e,rows:n})=>(await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await U(a,e,t),n.length))}l($t,"removeAllManagedAccounts");async function Zt(t,a){return a===void 0?(await $t(t),[]):Dt(t,a)}l(Zt,"removeManagedProvider");async function vt(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=H(r,a);if(s<0)throw new Error(`Unknown ${h(t)} subscription: ${a}`);const o=[r[s],...r.filter((c,d)=>d!==s)];for(const[c,d]of o.entries())await b(n,i,{...d.row,position:c});return R(e,t)})}l(vt,"promoteSubscription");async function z(t,a,e){const n=await y();return await N(async i=>{await T(i);const r=await st(i,n,t,a);if(!r)throw new Error(`Unknown ${h(t)} subscription: ${a}`);await e(i,n,r.row)}),V(t)}l(z,"healthWrite");async function te(t,a,e=Date.now()){return z(t,a,(n,i,r)=>b(n,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(te,"markSubscriptionAttempt");async function ee(t,a,e,n=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),B),z(t,a,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n)});const d=(await S(s,o,t)).get(c.id)?.find(u=>u.family===r.family);d&&i<d.lastRateLimitedAt||await ot(s,o,t,c.id,r.family,i+e,i)})}l(ee,"markSubscriptionRateLimited");async function ae(t,a,e=Date.now(),n){const i=wt(n);return z(t,a,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await b(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await S(r,s,t)).get(o.id)?.find(d=>d.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(ae,"markSubscriptionSuccess");async function ut(t,a,e){const n=Date.now();await b(t,a,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,n),rateLimitedUntil:Math.max(e.rateLimitedUntil,n+Rt)})}l(ut,"recordInvalidGrant");async function ne(t,a,e){const n=await y();let i;try{i=await N(async r=>{await T(r);const s=await st(r,n,t,a);if(!s)throw new Error(`${h(t)} subscription "${a}" no longer exists`);if(s.entry.expires>Date.now())return{entry:s.entry};if(s.row.authFailure)throw new Error(`${h(t)} subscription "${s.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);let o;try{o=await ct(t,e(s.entry.refresh,s.entry.clientId))}catch(d){if(!Y(d))throw d;return await ut(r,n,s.row),{refused:d}}const c=tt(et(t,s.entry.label,o),o.clientId??s.entry.clientId);return await M(r,n,t,s.row.id,E({...s.entry,...c})),{entry:{...s.entry,...c}}})}catch(r){throw lt(r)?new nt(t,a):r}if("refused"in i)throw i.refused;return i.entry}l(ne,"refreshSubscriptionCredential");async function ie(t,a,e){const n=await y();let i;try{i=await N(async r=>{await T(r);const s=await k(r,n,t,!0),o=new Set;let c;for(;o.size<s.length;){const d=a(s.filter(({entry:m})=>!o.has(m.label)).map(({entry:m})=>m));if(!d)break;const u=s.find(({entry:m})=>m.label===d.label);o.add(u.entry.label);try{const m=await ct(t,e(u.entry));if(!m)return{entry:u.entry};const f=tt(et(t,u.entry.label,m),m.clientId??u.entry.clientId);return await M(r,n,t,u.row.id,E({...u.entry,...f})),{entry:{...u.entry,...f}}}catch(m){if(!Y(m))throw m;c=m,await ut(r,n,u.row)}}return c?{refused:c}:{}})}catch(r){throw lt(r)?new nt(t,a([])?.label??t):r}if("refused"in i)throw i.refused;return i.entry}l(ie,"modifyElectedSubscription");async function Ot(t,a){const e=a.accountId?.trim(),n=a.email?.trim();if(t!==Lt)return{...e?{accountId:e}:{},...n?{email:n}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${a.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Ot,"enrichManagedLoginIdentity");async function re(t,a,e){const n=await Ot(t,e);return L(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:a?.trim(),d=p({refresh:e.refresh,accountId:n.accountId}),u=(c?o.find(({entry:w})=>_(w.label)===_(c)):void 0)??o.find(({entry:w})=>p(w)===d);let m=u?.entry.label??c;if(!m&&e.autoLabel){const w=n.email||a?.trim()||`Account ${o.length+1}`;m=w;for(let g=2;o.some(({entry:ft})=>_(ft.label)===_(m));g++)m=`${w} (${g})`}if(!m)throw new Error(`${h(t)} subscription label cannot be empty`);const f=F(t,{label:m,refresh:e.refresh,access:e.access,expires:e.expires,...n.accountId?{accountId:n.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!u){if(o.some(({entry:g})=>_(g.label)===_(f.label)))throw new O(`${h(t)} subscription already exists: ${f.label}`);const w=o.find(({entry:g})=>p(g)===p(f));if(p(f)&&w)throw P(t,w.entry.label);return await C(r,s,t,{providerId:t,id:x(),label:f.label,labelKey:_(f.label),position:o.length,lastAttemptAt:f.lastAttemptAt,lastRateLimitedAt:f.lastRateLimitedAt,rateLimitedUntil:f.rateLimitedUntil},E(f)),R(i,t)}const A=u.row,D=o.find(({entry:w})=>w.label!==u.entry.label&&p(w)===p(f));if(p(f)&&D)throw P(t,D.entry.label);const q=f.lastRateLimitedAt>=A.lastRateLimitedAt;return await M(r,s,t,A.id,E(f)),await b(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,f.lastAttemptAt),lastRateLimitedAt:q?f.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:q?0:A.rateLimitedUntil}),v(u.entry,f)&&await U(r,s,t,A.id),R(i,t)})}l(re,"commitManagedLogin");const dt=new Map;function mt(t){return{defaultFallbackStrength:Q(t?.default_fallback_strength)??J,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(mt,"rotationFromRow");async function kt(){const t=await y(),a=mt(await(await W()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return dt.set(t,a),a}l(kt,"loadRotationConfig"),yt(()=>Ct());async function Ct(){const t=pt();return t?t.rotation:kt()}l(Ct,"readRotationConfig");async function se(t){const a=await y(),e=await N(async n=>{await T(n),await n.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(a);const i=mt(await n.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(a)),r={defaultFallbackStrength:Q(t.defaultFallbackStrength)??i.defaultFallbackStrength??J,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await n.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,a),r});return dt.set(a,e),e}l(se,"writeRotationConfig");async function oe(){const t=await y();return(await(await W()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,x())).openai_device_id}l(oe,"openAIDeviceId");async function le(t,a=Date.now(),e){const n=await V(t),i=n.filter(s=>s.authFailure===void 0&&Et(s,e)<=a),r=h(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${n.length} ready)`}l(le,"formatStatusLine");export{at as REFRESH_EXCHANGE_TIMEOUT_MS,nt as RefreshBusyError,Nt as RefreshTimeoutError,I as aadOf,Tt as addSubscription,re as commitManagedLogin,Ot as enrichManagedLoginIdentity,le as formatStatusLine,C as insertAccount,kt as loadRotationConfig,te as markSubscriptionAttempt,ee as markSubscriptionRateLimited,ae as markSubscriptionSuccess,ie as modifyElectedSubscription,oe as openAIDeviceId,vt as promoteSubscription,Ct as readRotationConfig,V as readSubscriptionPool,St as readSubscriptionPoolRows,ne as refreshSubscriptionCredential,$t as removeAllManagedAccounts,Dt as removeManagedAccount,Jt as removeManagedAccountById,Zt as removeManagedProvider,Qt as removeSubscription,Yt as renameSubscription,ot as upsertModelCooldown,Xt as upsertSubscription,Ut as upsertSubscriptionWithUniqueAccount,se as writeRotationConfig,qt as writeSubscriptionPool};
|
|
1
|
+
var _t=Object.defineProperty;var l=(t,a)=>_t(t,"name",{value:a,configurable:!0});import{createHash as pt,randomUUID as I}from"node:crypto";import{brokerConfigSnapshot as ht}from"./config.js";import{openDb as K,withCanvasWrite as F}from"./canvas/db.js";import{personIdAsync as y}from"./canvas/person.js";import{loadSecretsKey as B,open as Y,seal as $}from"./secrets/index.js";import{classifyRateLimit as wt,modelCooldownFamily as At}from"./rate-limit-scope.js";import{REFRESH_BUSY_PHRASE as bt,REFRESH_TIMEOUT_PHRASE as yt}from"./provider-error-recognition.js";import{registerRotationReader as Et}from"./model-routes.js";import{coolingUntilFor as Lt,retryAfterMsFromHeaders as Rt,getProviderLabel as p,isInvalidRefreshTokenError as J,DuplicateSubscriptionError as O,ANTHROPIC_PROVIDER_ID as gt,MAX_RATE_LIMIT_COOLDOWN_MS as j,INVALID_REFRESH_TOKEN_BACKOFF_MS as xt}from"./managed-providers.js";export*from"./managed-providers.js";const Q="strong";function Z(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"?t:void 0}l(Z,"normalizeStrength");function _(t){return t.toLowerCase()}l(_,"key");function V(t){return typeof t=="string"&&t.trim()?t.trim():void 0}l(V,"optionalString");function It(t){const a=typeof t.label=="string"?t.label.trim():"",e=typeof t.refresh=="string"?t.refresh.trim():"",n=typeof t.access=="string"?t.access.trim():"",i=Number(t.expires);if(!a||!e||!n||!Number.isFinite(i))return;const r=V(t.accountId),s=V(t.clientId);return{label:a,refresh:e,access:n,expires:i,rateLimitedUntil:Number.isFinite(Number(t.rateLimitedUntil))?Number(t.rateLimitedUntil):0,lastAttemptAt:Number.isFinite(Number(t.lastAttemptAt))?Number(t.lastAttemptAt):0,lastRateLimitedAt:Number.isFinite(Number(t.lastRateLimitedAt))?Number(t.lastRateLimitedAt):0,...t.authFailure==="invalid_grant"?{authFailure:"invalid_grant"}:{},...r?{accountId:r}:{},...s?{clientId:s}:{},...v(t.modelCooldowns)?{modelCooldowns:v(t.modelCooldowns)}:{}}}l(It,"credential");function v(t){if(!t||typeof t!="object"||Array.isArray(t))return;const a=Object.entries(t).filter(([e,n])=>e.trim()!==""&&Number.isFinite(Number(n))).map(([e,n])=>[e,Number(n)]);return a.length?Object.fromEntries(a):void 0}l(v,"modelCooldowns");function N(t,a){if(!a.label?.trim())throw new Error(`${p(t)} subscription label cannot be empty`);const e=It(a);if(!e)throw new Error(`Refusing to persist incomplete ${p(t)} subscription "${a.label.trim()}"; pool rows require both OAuth tokens.`);return e}l(N,"assertCredential");function tt(t,a){const e=t.accountId?.trim(),n=a.accountId?.trim();return!!(e&&n&&e!==n)}l(tt,"differentAccount");function h(t){return t.accountId?.trim()||(t.refresh.trim()?`refresh:${pt("sha256").update(t.refresh.trim()).digest("hex")}`:void 0)}l(h,"identity");function et(t,a){const e=V(a);return e?{...t,clientId:e}:t}l(et,"withClientId");function at(t,a,e){const n=e.refresh?.trim()??"",i=e.access?.trim()??"",r=Number(e.expires);if(!n||!i||!Number.isFinite(r))throw new Error(`${p(t)} subscription "${a}" returned an incomplete credential; the stored credential was left unchanged.`);return{refresh:n,access:i,expires:r}}l(at,"assertTokens");const nt=1e4,Ft="15s",Nt="55P03";class it extends Error{static{l(this,"RefreshBusyError")}constructor(a,e){super(`${p(a)} subscription "${e}" ${bt}; treating it as cooling for this call`),this.name="RefreshBusyError"}}class St extends Error{static{l(this,"RefreshTimeoutError")}constructor(a){super(`${p(a)} ${yt} ${nt} ms`),this.name="RefreshTimeoutError"}}const rt="id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id",x=l((t,a,e,n)=>`model_accounts|${t}|${a}|${e}|${n}`,"aadOf");function E(t){return{refresh:t.refresh,access:t.access,expires:t.expires,...t.accountId?{accountId:t.accountId}:{},...t.clientId?{clientId:t.clientId}:{}}}l(E,"stored");function Tt(t,a){return{providerId:t,id:a.id,label:a.label,labelKey:a.label_key,position:a.position,lastAttemptAt:a.last_attempt_at,lastRateLimitedAt:a.last_rate_limited_at,rateLimitedUntil:a.rate_limited_until,...a.auth_failure?{authFailure:a.auth_failure}:{}}}l(Tt,"rowOf");function st(t,a,e,n=[]){if(!e.refresh_sealed||!e.access_sealed||e.expires===null||!e.key_id)throw new Error(`managed ${a} account ${e.id} has no credential record`);const i=B(),r=Y(e.refresh_sealed,e.key_id,i,x(t,a,e.id,"refresh")),s=Y(e.access_sealed,e.key_id,i,x(t,a,e.id,"access")),o=Tt(a,e),c={label:o.label,refresh:r,access:s,expires:e.expires,rateLimitedUntil:o.authFailure||!o.lastRateLimitedAt?o.rateLimitedUntil:Math.min(o.rateLimitedUntil,o.lastRateLimitedAt+j),lastAttemptAt:o.lastAttemptAt,lastRateLimitedAt:o.lastRateLimitedAt,...o.authFailure?{authFailure:o.authFailure}:{},...e.vendor_account_id?{accountId:e.vendor_account_id}:{},...e.client_id?{clientId:e.client_id}:{},...n.length?{modelCooldowns:Object.fromEntries(n.map(d=>[d.family,d.lastRateLimitedAt?Math.min(d.rateLimitedUntil,d.lastRateLimitedAt+j):d.rateLimitedUntil]))}:{}};return{row:o,entry:c}}l(st,"toPublic");async function S(t,a,e){const n=new Map,i=await t.prepare("SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family").all(a,e);for(const r of i){const s=n.get(r.account_id)??[];s.push({family:r.family,rateLimitedUntil:r.rate_limited_until,lastRateLimitedAt:r.last_rate_limited_at}),n.set(r.account_id,s)}return n}l(S,"loadCooldowns");async function k(t,a,e,n=!1){const i=await t.prepare(`SELECT ${rt} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${n?" FOR UPDATE":""}`).all(a,e),r=await S(t,a,e);return i.map(s=>st(a,e,s,r.get(s.id)))}l(k,"loadPool");async function ot(t,a,e,n){const i=n.trim().toLowerCase(),r=Number.parseInt(i,10),s=Number.isFinite(r)&&String(r)===i&&r>=1,o=await t.prepare(`SELECT ${rt} FROM model_accounts WHERE person=? AND provider_id=? AND ${s?"position=?":"label_key=?"} FOR UPDATE`).get(a,e,s?r-1:i);if(o)return st(a,e,o,(await S(t,a,e)).get(o.id))}l(ot,"lockedAccount");async function T(t){await t.exec(`SET LOCAL lock_timeout = '${Ft}'`)}l(T,"setLockTimeout");async function L(t,a){const e=await y();return F(async n=>(await T(n),await n.prepare("SELECT pg_advisory_xact_lock(hashtext(?))").get(`model_accounts|${e}|${t}`),a({db:n,person:e,rows:await k(n,e,t,!0)})))}l(L,"locked");async function C(t,a,e,n,i){const r=B(),s=$(i.refresh,r,x(a,e,n.id,"refresh")),o=$(i.access,r,x(a,e,n.id,"access"));await t.prepare("INSERT INTO model_accounts(person,provider_id,id,label,label_key,position,last_attempt_at,last_rate_limited_at,rate_limited_until,auth_failure,refresh_sealed,access_sealed,expires,vendor_account_id,client_id,key_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(a,e,n.id,n.label,n.labelKey,n.position,n.lastAttemptAt,n.lastRateLimitedAt,n.rateLimitedUntil,n.authFailure??null,s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId)}l(C,"insertAccount");async function M(t,a,e,n,i){const r=B(),s=$(i.refresh,r,x(a,e,n,"refresh")),o=$(i.access,r,x(a,e,n,"access"));await t.prepare("UPDATE model_accounts SET refresh_sealed=?,access_sealed=?,expires=?,vendor_account_id=?,client_id=?,key_id=? WHERE person=? AND provider_id=? AND id=?").run(s.sealed,o.sealed,i.expires,i.accountId??null,i.clientId??null,s.keyId,a,e,n)}l(M,"setCredential");async function b(t,a,e){await t.prepare("UPDATE model_accounts SET label=?,label_key=?,position=?,last_attempt_at=?,last_rate_limited_at=?,rate_limited_until=?,auth_failure=? WHERE person=? AND provider_id=? AND id=?").run(e.label,e.labelKey,e.position,e.lastAttemptAt,e.lastRateLimitedAt,e.rateLimitedUntil,e.authFailure??null,a,e.providerId,e.id)}l(b,"updateHealth");async function lt(t,a,e,n,i,r,s){await t.prepare("INSERT INTO model_account_cooldowns(person,provider_id,account_id,family,rate_limited_until,last_rate_limited_at) VALUES(?,?,?,?,?,?) ON CONFLICT(person,provider_id,account_id,family) DO UPDATE SET rate_limited_until=excluded.rate_limited_until,last_rate_limited_at=excluded.last_rate_limited_at").run(a,e,n,i,r,s)}l(lt,"upsertModelCooldown");async function U(t,a,e,n){n===void 0?await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=?").run(a,e):await t.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=?").run(a,e,n)}l(U,"deleteModelCooldowns");const R=l(async({db:t,person:a},e)=>(await k(t,a,e)).map(({entry:n})=>n),"publicPool"),ct=l(t=>t?.code===Nt,"lockWaitExpired");function ut(t,a){let e;return Promise.race([a,new Promise((n,i)=>{e=setTimeout(()=>i(new St(t)),nt)})]).finally(()=>clearTimeout(e))}l(ut,"withExchangeTimeout");async function G(t){return(await Ut(t)).map(({entry:a})=>a)}l(G,"readSubscriptionPool");async function Ut(t){const a=await y();return(await k(await K(),a,t)).map(({row:e,entry:n})=>({id:e.id,entry:n}))}l(Ut,"readSubscriptionPoolRows");async function Yt(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=a.map(d=>N(t,d)),o=s.map((d,u)=>({entry:d,id:r[u]?.row.id??I()})),c=await S(n,i,t);await n.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(i,t),await U(n,i,t);for(const[d,{entry:u,id:m}]of o.entries()){await C(n,i,t,{providerId:t,id:m,label:u.label,labelKey:_(u.label),position:d,lastAttemptAt:u.lastAttemptAt,lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:u.rateLimitedUntil,...u.authFailure?{authFailure:u.authFailure}:{}},E(u));for(const[f,A]of Object.entries(u.modelCooldowns??{}))await lt(n,i,t,m,f,A,c.get(m)?.find(D=>D.family===f)?.lastRateLimitedAt??u.lastRateLimitedAt)}return s})}l(Yt,"writeSubscriptionPool");function H(t,a){const e=a.trim().toLowerCase(),n=Number.parseInt(e,10);return Number.isFinite(n)&&String(n)===e&&n>=1&&n<=t.length?n-1:t.findIndex(({entry:i})=>_(i.label)===e)}l(H,"resolve");const P=l((t,a)=>new O(`This ${p(t)} account is already added as \u201C${a}\u201D \u2014 it shares the same quota, so a second slot adds no redundancy.`),"duplicateAccount");async function Dt(t,a){const e=N(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n;if(s.some(({entry:d})=>_(d.label)===_(e.label)))throw new O(`${p(t)} subscription already exists: ${e.label}`);const o=h(e),c=s.find(({entry:d})=>h(d)===o);if(o&&c)throw P(t,c.entry.label);return await C(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil,...e.authFailure?{authFailure:e.authFailure}:{}},E(e)),R(n,t)})}l(Dt,"addSubscription");async function Jt(t,a){const e=N(t,a);return(await G(t)).find(i=>_(i.label)===_(e.label))?$t(t,e):Dt(t,e)}l(Jt,"upsertSubscription");async function $t(t,a){const e=N(t,a);return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=s.findIndex(({entry:f})=>_(f.label)===_(e.label)),c=s[o],d=s.find(({entry:f},A)=>A!==o&&h(f)===h(e));if(h(e)&&d)throw P(t,d.entry.label);if(!c)return await C(i,r,t,{providerId:t,id:I(),label:e.label,labelKey:_(e.label),position:s.length,lastAttemptAt:e.lastAttemptAt,lastRateLimitedAt:e.lastRateLimitedAt,rateLimitedUntil:e.rateLimitedUntil},E(e)),R(n,t);const u=c.row,m=e.lastRateLimitedAt>=u.lastRateLimitedAt;return await M(i,r,t,u.id,E(e)),await b(i,r,{...u,authFailure:void 0,label:e.label,labelKey:_(e.label),lastAttemptAt:Math.max(u.lastAttemptAt,e.lastAttemptAt),lastRateLimitedAt:m?e.lastRateLimitedAt:u.lastRateLimitedAt,rateLimitedUntil:m?e.rateLimitedUntil:u.rateLimitedUntil}),tt(c.entry,e)&&await U(i,r,t,u.id),R(n,t)})}l($t,"upsertSubscriptionWithUniqueAccount");async function Qt(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=H(s,a);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const c=e.trim();if(!c)throw new Error(`${p(t)} subscription label cannot be empty`);if(s.some((d,u)=>u!==o&&_(d.entry.label)===_(c)))throw new O(`${p(t)} subscription already exists: ${c}`);return await b(i,r,{...s[o].row,label:c,labelKey:_(c)}),R(n,t)})}l(Qt,"renameSubscription");async function z(t,a,e){return L(t,async n=>{const{db:i,person:r,rows:s}=n,o=a(s);if(o<0)throw new Error(`Unknown ${p(t)} subscription: ${e}`);const c=s[o].row;return await i.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=? AND id=?").run(r,t,c.id),await U(i,r,t,c.id),R(n,t)})}l(z,"remove");async function Ot(t,a){return z(t,e=>H(e,a),a)}l(Ot,"removeManagedAccount");async function Zt(t,a){return z(t,e=>e.findIndex(({row:n})=>n.id===a),a)}l(Zt,"removeManagedAccountById");async function vt(t,a){return z(t,e=>H(e,a),a)}l(vt,"removeSubscription");async function kt(t){return L(t,async({db:a,person:e,rows:n})=>(await a.prepare("DELETE FROM model_accounts WHERE person=? AND provider_id=?").run(e,t),await U(a,e,t),n.length))}l(kt,"removeAllManagedAccounts");async function te(t,a){return a===void 0?(await kt(t),[]):Ot(t,a)}l(te,"removeManagedProvider");async function ee(t,a){return L(t,async e=>{const{db:n,person:i,rows:r}=e,s=H(r,a);if(s<0)throw new Error(`Unknown ${p(t)} subscription: ${a}`);const o=[r[s],...r.filter((c,d)=>d!==s)];for(const[c,d]of o.entries())await b(n,i,{...d.row,position:c});return R(e,t)})}l(ee,"promoteSubscription");async function W(t,a,e){const n=await y();return await F(async i=>{await T(i);const r=await ot(i,n,t,a);if(!r)throw new Error(`Unknown ${p(t)} subscription: ${a}`);await e(i,n,r.row)}),G(t)}l(W,"healthWrite");async function ae(t,a,e=Date.now()){return W(t,a,(n,i,r)=>b(n,i,{...r,lastAttemptAt:Math.max(r.lastAttemptAt,e)}))}l(ae,"markSubscriptionAttempt");async function ne(t,a,e,n=Date.now(),i=Date.now(),r={kind:"account"}){return e=Math.min(Math.max(0,e),j),W(t,a,async(s,o,c)=>{if(r.kind==="account"){if(i<c.lastRateLimitedAt)return;await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n),lastRateLimitedAt:i,rateLimitedUntil:i+e});return}await b(s,o,{...c,lastAttemptAt:Math.max(c.lastAttemptAt,n)});const d=(await S(s,o,t)).get(c.id)?.find(u=>u.family===r.family);d&&i<d.lastRateLimitedAt||await lt(s,o,t,c.id,r.family,i+e,i)})}l(ne,"markSubscriptionRateLimited");async function ie(t,a,e=Date.now(),n){const i=At(n);return W(t,a,async(r,s,o)=>{if(e>=o.lastRateLimitedAt&&await b(r,s,{...o,authFailure:void 0,lastAttemptAt:Math.max(o.lastAttemptAt,e),rateLimitedUntil:0}),i===void 0)return;const c=(await S(r,s,t)).get(o.id)?.find(d=>d.family===i);c&&e>=c.lastRateLimitedAt&&await r.prepare("DELETE FROM model_account_cooldowns WHERE person=? AND provider_id=? AND account_id=? AND family=?").run(s,t,o.id,i)})}l(ie,"markSubscriptionSuccess");async function q(t,a,e){const n=Date.now();await b(t,a,{...e,authFailure:"invalid_grant",lastAttemptAt:Math.max(e.lastAttemptAt,n),rateLimitedUntil:Math.max(e.rateLimitedUntil,n+xt)})}l(q,"recordInvalidGrant");function re(t,a,e,n=15e3,i=Date.now()){const r=Rt(t),s=wt(t,a,i),o=e??r??n;return r!==void 0?{retryMs:o,vendorReset:i+o,observation:s}:{retryMs:s.resetAt!==void 0?Math.max(o,s.resetAt-i):o,vendorReset:s.resetAt,observation:s}}l(re,"vendorRateLimit");async function se(t,a){return W(t,a,(e,n,i)=>q(e,n,i))}l(se,"markSubscriptionAuthFailure");async function oe(t,a,e){const n=await y();let i;try{i=await F(async r=>{await T(r);const s=await ot(r,n,t,a);if(!s)throw new Error(`${p(t)} subscription "${a}" no longer exists`);if(s.entry.expires>Date.now())return{entry:s.entry};if(s.row.authFailure)throw new Error(`${p(t)} subscription "${s.entry.label}" refresh refused with status=400 invalid_grant; it needs a new sign-in`);let o;try{o=await ut(t,e(s.entry.refresh,s.entry.clientId))}catch(d){if(!J(d))throw d;return await q(r,n,s.row),{refused:d}}const c=et(at(t,s.entry.label,o),o.clientId??s.entry.clientId);return await M(r,n,t,s.row.id,E({...s.entry,...c})),{entry:{...s.entry,...c}}})}catch(r){throw ct(r)?new it(t,a):r}if("refused"in i)throw i.refused;return i.entry}l(oe,"refreshSubscriptionCredential");async function le(t,a,e){const n=await y();let i;try{i=await F(async r=>{await T(r);const s=await k(r,n,t,!0),o=new Set;let c;for(;o.size<s.length;){const d=a(s.filter(({entry:m})=>!o.has(m.label)).map(({entry:m})=>m));if(!d)break;const u=s.find(({entry:m})=>m.label===d.label);o.add(u.entry.label);try{const m=await ut(t,e(u.entry));if(!m)return{entry:u.entry};const f=et(at(t,u.entry.label,m),m.clientId??u.entry.clientId);return await M(r,n,t,u.row.id,E({...u.entry,...f})),{entry:{...u.entry,...f}}}catch(m){if(!J(m))throw m;c=m,await q(r,n,u.row)}}return c?{refused:c}:{}})}catch(r){throw ct(r)?new it(t,a([])?.label??t):r}if("refused"in i)throw i.refused;return i.entry}l(le,"modifyElectedSubscription");async function Ct(t,a){const e=a.accountId?.trim(),n=a.email?.trim();if(t!==gt)return{...e?{accountId:e}:{},...n?{email:n}:{}};try{const i=await fetch("https://api.anthropic.com/api/oauth/profile",{headers:{Authorization:`Bearer ${a.access}`,Accept:"application/json"},signal:AbortSignal.timeout(3e3)});if(!i.ok)return e?{accountId:e}:{};const r=await i.json(),s=typeof r.account?.uuid=="string"&&r.account.uuid.trim()?r.account.uuid.trim():void 0,o=typeof r.account?.email=="string"&&r.account.email.trim()?r.account.email.trim():void 0;return{...s?{accountId:s}:{},...o?{email:o}:{}}}catch{return e?{accountId:e}:{}}}l(Ct,"enrichManagedLoginIdentity");async function ce(t,a,e){const n=await Ct(t,e);return L(t,async i=>{const{db:r,person:s,rows:o}=i,c=e.autoLabel?void 0:a?.trim(),d=h({refresh:e.refresh,accountId:n.accountId}),u=(c?o.find(({entry:w})=>_(w.label)===_(c)):void 0)??o.find(({entry:w})=>h(w)===d);let m=u?.entry.label??c;if(!m&&e.autoLabel){const w=n.email||a?.trim()||`Account ${o.length+1}`;m=w;for(let g=2;o.some(({entry:ft})=>_(ft.label)===_(m));g++)m=`${w} (${g})`}if(!m)throw new Error(`${p(t)} subscription label cannot be empty`);const f=N(t,{label:m,refresh:e.refresh,access:e.access,expires:e.expires,...n.accountId?{accountId:n.accountId}:{},...e.clientId?{clientId:e.clientId}:{},rateLimitedUntil:0,lastAttemptAt:Date.now(),lastRateLimitedAt:e.lastRateLimitedAt});if(!u){if(o.some(({entry:g})=>_(g.label)===_(f.label)))throw new O(`${p(t)} subscription already exists: ${f.label}`);const w=o.find(({entry:g})=>h(g)===h(f));if(h(f)&&w)throw P(t,w.entry.label);return await C(r,s,t,{providerId:t,id:I(),label:f.label,labelKey:_(f.label),position:o.length,lastAttemptAt:f.lastAttemptAt,lastRateLimitedAt:f.lastRateLimitedAt,rateLimitedUntil:f.rateLimitedUntil},E(f)),R(i,t)}const A=u.row,D=o.find(({entry:w})=>w.label!==u.entry.label&&h(w)===h(f));if(h(f)&&D)throw P(t,D.entry.label);const X=f.lastRateLimitedAt>=A.lastRateLimitedAt;return await M(r,s,t,A.id,E(f)),await b(r,s,{...A,authFailure:void 0,lastAttemptAt:Math.max(A.lastAttemptAt,f.lastAttemptAt),lastRateLimitedAt:X?f.lastRateLimitedAt:A.lastRateLimitedAt,rateLimitedUntil:X?0:A.rateLimitedUntil}),tt(u.entry,f)&&await U(r,s,t,A.id),R(i,t)})}l(ce,"commitManagedLogin");const dt=new Map;function mt(t){return{defaultFallbackStrength:Z(t?.default_fallback_strength)??Q,revertWhenAvailable:t?.revert_when_available===void 0||t.revert_when_available===null?!0:!!t.revert_when_available}}l(mt,"rotationFromRow");async function Mt(){const t=await y(),a=mt(await(await K()).prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=?").get(t));return dt.set(t,a),a}l(Mt,"loadRotationConfig"),Et(()=>Ht());async function Ht(){const t=ht();return t?t.rotation:Mt()}l(Ht,"readRotationConfig");async function ue(t){const a=await y(),e=await F(async n=>{await T(n),await n.prepare("INSERT INTO model_settings(person) VALUES(?) ON CONFLICT(person) DO NOTHING").run(a);const i=mt(await n.prepare("SELECT default_fallback_strength,revert_when_available FROM model_settings WHERE person=? FOR UPDATE").get(a)),r={defaultFallbackStrength:Z(t.defaultFallbackStrength)??i.defaultFallbackStrength??Q,revertWhenAvailable:t.revertWhenAvailable??i.revertWhenAvailable??!0};return await n.prepare("UPDATE model_settings SET default_fallback_strength=?,revert_when_available=?,revision=revision+1 WHERE person=?").run(r.defaultFallbackStrength,r.revertWhenAvailable?1:0,a),r});return dt.set(a,e),e}l(ue,"writeRotationConfig");async function de(){const t=await y();return(await(await K()).prepare("INSERT INTO model_settings(person,openai_device_id) VALUES(?,?) ON CONFLICT(person) DO UPDATE SET openai_device_id=COALESCE(model_settings.openai_device_id,EXCLUDED.openai_device_id) RETURNING openai_device_id").get(t,I())).openai_device_id}l(de,"openAIDeviceId");async function me(t,a=Date.now(),e){const n=await G(t),i=n.filter(s=>s.authFailure===void 0&&Lt(s,e)<=a),r=p(t);return i.length===0?`${r} pool exhausted`:`${r} ${i[0]?.label??t} (${i.length}/${n.length} ready)`}l(me,"formatStatusLine");export{nt as REFRESH_EXCHANGE_TIMEOUT_MS,it as RefreshBusyError,St as RefreshTimeoutError,x as aadOf,Dt as addSubscription,ce as commitManagedLogin,Ct as enrichManagedLoginIdentity,me as formatStatusLine,C as insertAccount,Mt as loadRotationConfig,ae as markSubscriptionAttempt,se as markSubscriptionAuthFailure,ne as markSubscriptionRateLimited,ie as markSubscriptionSuccess,le as modifyElectedSubscription,de as openAIDeviceId,ee as promoteSubscription,Ht as readRotationConfig,G as readSubscriptionPool,Ut as readSubscriptionPoolRows,oe as refreshSubscriptionCredential,kt as removeAllManagedAccounts,Ot as removeManagedAccount,Zt as removeManagedAccountById,te as removeManagedProvider,vt as removeSubscription,Qt as renameSubscription,lt as upsertModelCooldown,Jt as upsertSubscription,$t as upsertSubscriptionWithUniqueAccount,re as vendorRateLimit,ue as writeRotationConfig,Yt as writeSubscriptionPool};
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var
|
|
2
|
-
data: ${JSON.stringify(
|
|
1
|
+
var Z=Object.defineProperty;var i=(e,n)=>Z(e,"name",{value:n,configurable:!0});import{AsyncResource as ee}from"node:async_hooks";import{randomUUID as te}from"node:crypto";import{createServer as ne}from"node:http";import{Router as V,causedByOf as re}from"./router.js";import{toErrorBody as ae}from"./map.js";import{objectRoutes as oe}from"./handlers/objects.js";import{customObjectRoutes as ie}from"./handlers/custom-objects.js";import{checkRoutes as se}from"./handlers/check.js";import{chargeRoutes as ue}from"./handlers/charges.js";import{docRoutes as de}from"./handlers/docs.js";import{relationRoutes as ce}from"./handlers/relations.js";import{schemaRoutes as le}from"./handlers/schemas.js";import{OPERATIONS as me}from"./operations.js";import{runtimeReadiness as fe}from"../readiness.js";import{errorCodes as z}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as pe,RUNTIME_VERSION_HEADER as he,minimumRuntimeRefusal as we}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ye,CONTRACT_LEVEL as G,REQUIRED_CONTRACT_HEADER as _e,contractRefusal as ge}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as ve,parseTraceparent as Re}from"../../shared/traceparent.js";import{AppPrincipalResolver as Oe}from"./principal.js";import{isDaemonRoute as be,runtimeOwner as Ee,servePeer as Y}from"../peer/ingress.js";import{applySyncNotice as Ae}from"./sync-notice.js";import{ownMachineId as Se}from"../../core/peer/directory.js";import{handleRunOperation as Te,integer as Ne}from"./handlers/runs.js";import{runAnthropicMessages as Ce}from"../../core/llm/anthropic-messages.js";import{llmCallerOf as Ie,parseLlmRequest as Pe,runLlm as ke}from"../../core/llm/run.js";import{parseUsageMonth as Me,usageFor as He}from"../../core/ledger/index.js";import{capFields as De}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as F,MODEL_CONTEXT_BODY_MAX_BYTES as Q}from"../../core/llm/body-limits.js";import{RunError as l,cloudPersonScope as Be,runIsRunning as xe}from"../../core/runs/operations.js";import{requireRun as L}from"./router.js";import{deferHead as je}from"./deferred-head.js";import{readRunEvents as W,registerGrantStream as Je,subscribeRunEvents as Le}from"../../core/runs/events.js";import{activeGrant as q,payerOfGrant as Ue}from"../../core/grants/mirror.js";async function Xe(e){if(await Ue(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Xe,"appPaidGone");import{releaseGrantWaiters as $e}from"../../core/grants/watch.js";import{emitEvent as Ve}from"../../core/events/emit.js";import{runNotices as ze}from"../run-notices.js";import{handleRuntimeSignIn as Ge,isRuntimeSignInPath as Ye}from"./key-signin.js";import{listAppProfiles as Fe}from"./handlers/app-profiles.js";import{handleTransferDownload as Qe,handleTransferOperation as We,TRANSFER_OPERATIONS as qe}from"./handlers/transfer.js";import{handleQuestionOperation as Ke,QUESTION_OPERATIONS as Ze}from"./handlers/questions.js";import{removeVendorAccount as et,vendorStatus as tt}from"./handlers/vendor-status.js";import{handleMemoryOperation as nt,MEMORY_OPERATIONS as rt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as at,handleExec as ot}from"./handlers/exec.js";import{abortOnClose as U,callerFromApp as it,handleProviderOperation as st,PROVIDER_OPERATIONS as ut,providerFailure as dt}from"./handlers/providers.js";function ct(e){return Object.prototype.hasOwnProperty.call(z,e)?z[e]:void 0}i(ct,"fixedRow");function lt(e){const n=ct(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(lt,"errorType");function mt(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(mt,"appDetails");function x(e,n,o){const m=mt(e.details);return{error:{code:e.code,message:e.message,...m===void 0?{}:{details:m},type:lt(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...De(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(x,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function ft(e,n,o,m,d){const y=n instanceof l?n:new l(500,"server_failure","runtime request failed");if(n instanceof l||console.error("[app-listener]",`trace_id=${m}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
|
|
2
|
+
data: ${JSON.stringify(x(y,o,d))}
|
|
3
3
|
|
|
4
|
-
`);return}e.writeHead(
|
|
4
|
+
`);return}e.writeHead(y.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(y)!==void 0?{"Retry-After":String(j(y))}:{}}),e.end(JSON.stringify(x(y,o,d)))}i(ft,"fail");function X(e){return Array.isArray(e)?e[0]:e}i(X,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function K(e,n=F){const o=[];let m=0;for await(const d of e){if(m+=d.length,m>n)throw new l(400,"invalid_request","request body too large");o.push(d)}return Buffer.concat(o)}i(K,"rawBodyOf");async function I(e,n=F){const o=await K(e,n);if(o.length)try{return JSON.parse(o.toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function pt(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return Ne(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(pt,"cursor");function ht(e){return`id: ${e.sequence_number}
|
|
5
5
|
event: ${e.type}
|
|
6
6
|
data: ${JSON.stringify(e)}
|
|
7
7
|
|
|
8
|
-
`}i(
|
|
8
|
+
`}i(ht,"frame");const wt=6e4;async function yt(e,n,o,m,d,y,A,S={},r){await L(m,o);let t=await W(o,d);if(d>t.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new l(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":A==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),A==="sse"?n.write(`: connected
|
|
9
9
|
|
|
10
|
-
`):n.flushHeaders();let p=d;const
|
|
11
|
-
data: ${JSON.stringify(
|
|
10
|
+
`):n.flushHeaders();let p=d;const _=await ze().streamOpened(o);let v=!1,T=!1,N=!1,O;const h=new Promise(f=>{O=f}),R=i(()=>{v||(v=!0,_(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),clearInterval(B),clearInterval(M),C(),u(),n.off("close",R),n.off("drain",a),n.end(),O())},"end"),a=i(()=>{N=!1,b()},"onDrain"),H=i(f=>{v||n.write(A==="sse"?`event: error
|
|
11
|
+
data: ${JSON.stringify(x(f,y,o))}
|
|
12
12
|
|
|
13
|
-
`:`${JSON.stringify({type:"error",...
|
|
14
|
-
`),R()},"error"),b=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await
|
|
15
|
-
`),p=
|
|
13
|
+
`:`${JSON.stringify({type:"error",...x(f,y,o)})}
|
|
14
|
+
`),R()},"error"),b=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await W(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){H(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(A==="sse"?ht(f):`${JSON.stringify(f)}
|
|
15
|
+
`),p=f.sequence_number}}catch(f){H(f instanceof l?f:new l(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>H(new l(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in m||await q(m.grant)!==null,"grantActive"),C=await Le(o,ee.bind(b)),u="class"in m?()=>{}:Je(m.grant,P),B=setInterval(()=>{!v&&!N&&A==="sse"&&n.write(`: keepalive
|
|
16
16
|
|
|
17
|
-
`)},15e3),s=S.idleMs??
|
|
17
|
+
`)},15e3),s=S.idleMs??wt,w=S.isRunning??xe;let c=Date.now(),E=p;const k=i(async()=>{if(v||A!=="sse")return;const f=Date.now();let $=!0;try{$=await w(o)}catch{}if(!v){if($||p!==E){c=f,E=p;return}f-c<s||N||(n.write(`event: idle
|
|
18
18
|
data: {}
|
|
19
19
|
|
|
20
|
-
`),R())}},"checkIdle"),
|
|
20
|
+
`),R())}},"checkIdle"),M=setInterval(()=>{k().catch(f=>Ve({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},S.idleCheckMs??1e3);return M.unref(),n.on("drain",a),n.on("close",R),await b(),h}i(yt,"streamRunEvents");function _t(e,n,o,m={}){const d=new V,y=new Map;for(const r of me.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),y.set(t,r)}const A=new V().registerAll(oe).registerAll(ie).registerAll(de).registerAll(le).registerAll(ce).registerAll(se).registerAll(ue);return i((r,t,p)=>(async()=>{je(r,t,m.deferHead);const _=te();t.setHeader("Request-Id",_);const v=Re(X(r.headers.traceparent))??ve();t.setHeader(he,J()),t.setHeader(ye,G);let T;try{const N=X(r.headers[pe.toLowerCase()]),O=we(N,J())??ge(X(r.headers[_e.toLowerCase()]),G,{legacyMinimum:N,runtimeVersion:J()});if(O!==null)throw O.status===400?new l(400,O.code,O.message,O.param):new l(426,O.code,O.message,void 0,O.details);const h=new URL(r.url??"/","http://runtime.local");if(Ye(h.pathname)){await Ge(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?y.get(R.handler):void 0,H=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let b,P;if(p!==void 0)b=p;else if(!H&&r.headers.authorization!==void 0)try{b=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Ee,self:Se,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(b?.chain[0]?.sub.startsWith("runtime:")){await Y(r,t,D,b);return}if(b===void 0&&a===void 0&&await be(r.method??"GET",h.pathname)){await Y(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),w=await fe({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,w.ready?200:503,w);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new l(503,"runtime_starting","runtime_starting");if(!R||!a)throw new l(404,"not_found","unknown operation");T=R.params.run_id;const C=re(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Ae(await e.verifySyncNotice(r.headers.authorization),o,_),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await tt());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await et(await I(r)));return}if(b===void 0)throw P??new l(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(b,a.scope);if(t.setHeader("Request-Id",_),T&&await L(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=A.match(a.method,h.pathname);if(!s)throw new l(404,"not_found","unknown operation");const w={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let c;try{c=await s.handler(w)}catch(E){const{status:k,body:M}=ae(E);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,E),new l(k,M.error.code,M.error.message,void 0,M.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream==="bytes"){await Qe(r,t,u,h.searchParams);return}if(a.stream){await yt(r,t,T,u,pt(r,h.searchParams),_,"sse",m.stream,v);return}if(a.name==="llm"){const s=Pe(await I(r,Q)),w=new AbortController,c=i(()=>w.abort(),"abort");t.on("close",c);try{const E=await ke(s,w.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
|
|
21
21
|
|
|
22
|
-
`)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:
|
|
22
|
+
`)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:_},Ie(await q(u.grant)??await Xe(u.grant)),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
|
|
23
23
|
|
|
24
|
-
`)):g(t,200,E.completion)}finally{t.off("close",c)}return}if(a.name==="
|
|
24
|
+
`)):g(t,200,E.completion)}finally{t.off("close",c)}return}if(a.name==="llm.anthropic_messages"){const{signal:s,release:w}=U(t);try{await Ce(await K(r,Q),r.headers,s,{grant:u.grant,sub:u.sub,grantee:u.grantee,request:_,...C===void 0?{}:{causedBy:C}},t)}finally{w()}return}if(a.name==="exec"){const{signal:s,release:w}=U(t);try{g(t,200,await ot(u,await I(r,at),s))}finally{w()}return}if(a.name==="usage.get"){g(t,200,await He(u.grantee,Me(h.searchParams.get("month")),Be(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Fe(u));return}if(Ze.has(a.name)){const s=await Ke(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(ut.has(a.name)){const{signal:s,release:w}=U(t);try{const c=await st(a.name,it(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:_,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,c.status,c.body)}catch(c){const E=dt(c,_,!0);t.writeHead(E.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...E.headers}),t.end(JSON.stringify(E.body))}finally{w()}return}if(rt.has(a.name)){const s=await nt(a.name,{class:"app",app:u.grantee,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(qe.has(a.name)){const s=await We(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const B=await Te(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,B.status,B.body)}catch(N){ft(t,N,_,v,T)}})(),"handle")}i(_t,"createAppRequestHandler");async function mn(e,n,o,m={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<1||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const y=new Oe(e.issuer,e.audience,o,e.jwksUrl),A=_t(y,n,o,m),S=ne((t,p)=>{A(t,p)});return{ready:new Promise((t,p)=>{S.once("error",p),S.listen(d.port,d.address,()=>{S.off("error",p),t()})}),close:i(async()=>{y.close(),$e(),S.closeAllConnections(),await new Promise((t,p)=>S.close(_=>_?p(_):t()))},"close")}}i(mn,"createAppListener");export{wt as RUN_STREAM_IDLE_MS,mn as createAppListener,_t as createAppRequestHandler,pt as cursor,yt as streamRunEvents};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var a=Object.defineProperty;var r=(e,s)=>a(e,"name",{value:s,configurable:!0});const n=[{name:"conversation.create",method:"POST",path:"/v1/conversations",classes:["broker"],resource:"none"},{name:"conversation.list",method:"GET",path:"/v1/conversations",classes:["broker","person"],resource:"none"},{name:"conversation.append",method:"POST",path:"/v1/conversations/:id/entries",classes:["broker"],resource:"none"},{name:"conversation.commit",method:"POST",path:"/v1/conversations/:id/commit",classes:["broker"],resource:"none"},{name:"conversation.read",method:"GET",path:"/v1/conversations/:id",classes:["broker","person"],resource:"none"},{name:"conversation.header",method:"GET",path:"/v1/conversations/:id/header",classes:["broker","person"],resource:"none"},{name:"conversation.replace",method:"PUT",path:"/v1/conversations/:id",classes:["broker"],resource:"none"},{name:"conversation.fork",method:"POST",path:"/v1/conversations/:id/fork",classes:["broker"],resource:"none"},{name:"conversation.delete",method:"DELETE",path:"/v1/conversations/:id",classes:["broker"],resource:"none"},{name:"health",method:"GET",path:"/v1/health",classes:["anonymous"],resource:"none",stage:"v0.5"},{name:"ready",method:"GET",path:"/v1/ready",classes:["anonymous"],resource:"none",stage:"v0.5"},{name:"chat-inventory.get.1",method:"GET",path:"/v1/nodes/:id/chat-inventory",classes:["person","broker","cron"],resource:"node-read"},{name:"settings.get",method:"GET",path:"/v1/settings",classes:["person","broker"],resource:"none"},{name:"settings.put",method:"PUT",path:"/v1/settings",classes:["person","broker"],resource:"none"},{name:"model-config.put.2",method:"PUT",path:"/v1/model-config",classes:["person","broker"],resource:"none"},{name:"files.get.3",method:"GET",path:"/v1/files/peek",classes:["person","broker"],resource:"none"},{name:"files.post.4",method:"POST",path:"/v1/files/write",classes:["person","broker"],resource:"none"},{name:"files.get.5",method:"GET",path:"/v1/files/list",classes:["person","broker"],resource:"none"},{name:"reviews.post.6",method:"POST",path:"/v1/human/reviews",classes:["person","broker"],resource:"human",scope:"crtr:act"},{name:"reviews.get.7",method:"GET",path:"/v1/human/reviews",classes:["person","broker"],resource:"human"},{name:"reviews.get.8",method:"GET",path:"/v1/human/reviews/:review_id",classes:["person","broker"],resource:"human"},{name:"reviews.post.9",method:"POST",path:"/v1/human/reviews/:review_id/submit",classes:["person","broker"],resource:"human"},{name:"reviews.post.10",method:"POST",path:"/v1/human/reviews/:review_id/cancel",classes:["person","broker"],resource:"human"},{name:"reviews.get.11",method:"GET",path:"/v1/human/reviews/:review_id/document",classes:["person","broker"],resource:"human"},{name:"feedback-comments.post.12",method:"POST",path:"/v1/human/inbox/:ticket_id/feedback-comments",classes:["person","broker"],resource:"human"},{name:"feedback-comments.post.13",method:"POST",path:"/v1/human/inbox/:ticket_id/feedback-comments/:comment_id/resolve",classes:["person","broker"],resource:"human"},{name:"node.log.append",method:"POST",path:"/v1/nodes/:id/records/log",classes:["person","broker"],resource:"node-own"},{name:"node.summaries.put",method:"PUT",path:"/v1/nodes/:id/records/summaries",classes:["person","broker"],resource:"node-own"},{name:"node.attachments.list",method:"GET",path:"/v1/nodes/:id/attachments",classes:["person","broker"],resource:"node-own"},{name:"node.attachments.read",method:"GET",path:"/v1/nodes/:id/attachments/:sha256",classes:["person","broker"],resource:"node-own"},{name:"node.telemetry.put",method:"PUT",path:"/v1/nodes/:id/records/telemetry",classes:["person","broker"],resource:"node-own"},{name:"node.recap.put",method:"PUT",path:"/v1/nodes/:id/records/recap",classes:["person","broker"],resource:"node-own"},{name:"node.inbox.read",method:"GET",path:"/v1/nodes/:id/records/inbox",classes:["person","broker"],resource:"node-own"},{name:"node.passive.read",method:"GET",path:"/v1/nodes/:id/records/passive",classes:["person","broker"],resource:"node-own"},{name:"node.pushed-final",method:"POST",path:"/v1/nodes/:id/records/pushed-final",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.14",method:"POST",path:"/v1/nodes/:id/broker/session-bound",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.15",method:"POST",path:"/v1/nodes/:id/broker/settle",classes:["person","broker"],resource:"node-own"},{name:"broker.idle",method:"POST",path:"/v1/nodes/:id/broker/idle",classes:["broker"],resource:"node-own"},{name:"broker-ops.post.16",method:"POST",path:"/v1/nodes/:id/broker/park-complete",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.17",method:"POST",path:"/v1/nodes/:id/broker/park-activity",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.18",method:"POST",path:"/v1/nodes/:id/broker/telemetry",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.19",method:"POST",path:"/v1/nodes/:id/broker/model",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.get.20",method:"GET",path:"/v1/nodes/:id/broker/extension-state",classes:["person","broker"],resource:"node-own"},{name:"broker.signals",method:"GET",path:"/v1/nodes/:id/broker/signals",classes:["broker"],resource:"node-own",stream:!0},{name:"nodes.broker-structured-request",method:"GET",path:"/v1/nodes/:id/broker/structured-request",classes:["person","broker"],resource:"node-own"},{name:"nodes.broker-goal",method:"POST",path:"/v1/nodes/:id/broker/goal",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.21",method:"POST",path:"/v1/nodes/:id/broker/generated-name",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.22",method:"POST",path:"/v1/nodes/:id/broker/persona-ack",classes:["person","broker"],resource:"node-own"},{name:"objects.read",method:"GET",path:"/v1/objects/:ref",classes:["person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.list",method:"GET",path:"/v1/objects",classes:["person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.search",method:"POST",path:"/v1/objects/search",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"objects.watch",method:"POST",path:"/v1/objects/:ref/watch",classes:["anonymous","person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.unwatch",method:"DELETE",path:"/v1/objects/:ref/watch",classes:["anonymous","person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.shares",method:"GET",path:"/v1/objects/:ref/shares",classes:["person","broker"],resource:"objects",stage:"objects"},{name:"objects.share",method:"POST",path:"/v1/objects/:ref/shares",classes:["person","broker"],resource:"objects",stage:"objects"},{name:"objects.unshare",method:"DELETE",path:"/v1/objects/:ref/shares",classes:["person","broker"],resource:"objects",stage:"objects"},{name:"custom-objects.register",method:"POST",path:"/v1/custom-objects",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"custom-objects.publish",method:"POST",path:"/v1/custom-objects/:ref/events",classes:["anonymous","person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"custom-objects.unregister",method:"DELETE",path:"/v1/custom-objects/:ref",classes:["anonymous","person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"custom-objects.receive",method:"GET",path:"/v1/custom-objects/:ref/deliveries",classes:["anonymous","person","app","broker","cron"],resource:"objects",stream:!0,stage:"objects"},{name:"custom-objects.ack",method:"POST",path:"/v1/custom-objects/:ref/deliveries/ack",classes:["anonymous","person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"objects.edges",method:"GET",path:"/v1/objects/:ref/edges",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.write",method:"POST",path:"/v1/docs",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.edit",method:"PATCH",path:"/v1/docs/:ref",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.move",method:"POST",path:"/v1/docs/:ref/move",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.delete",method:"DELETE",path:"/v1/docs/:ref",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.history",method:"GET",path:"/v1/docs/:ref/history",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"schemas.register",method:"POST",path:"/v1/schemas",classes:["app"],resource:"objects",stage:"objects"},{name:"relations.write",method:"POST",path:"/v1/relations",classes:["app"],resource:"objects",stage:"objects"},{name:"relations.replace",method:"PUT",path:"/v1/relations",classes:["app"],resource:"objects",stage:"objects"},{name:"relations.list",method:"GET",path:"/v1/relations",classes:["app"],resource:"objects",stage:"objects"},{name:"check",method:"POST",path:"/v1/check",classes:["app"],resource:"objects",stage:"objects"},{name:"docs.lint",method:"POST",path:"/v1/docs/lint",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"plugins.app-token",method:"GET",path:"/v1/plugins/:name/app-token",classes:["person","broker"],resource:"none"},{name:"plugins.call-headers",method:"POST",path:"/v1/plugins/:name/call-headers",classes:["person","broker"],resource:"none"},{name:"documents.browser-access",method:"GET",path:"/v1/documents/browser-access",classes:["person"],resource:"none"},{name:"documents.reconcile-packages",method:"POST",path:"/v1/documents/reconcile-packages",classes:["person","broker"],resource:"none"},{name:"nodes.delivery",method:"POST",path:"/v1/nodes/:id/delivery",classes:["person","broker"],resource:"node-own"},{name:"delivery.dry-run",method:"POST",path:"/v1/delivery/dry-run",classes:["person","broker"],resource:"none"},{name:"bash-jobs.background",method:"POST",path:"/v1/nodes/:id/jobs/:jobId/background",classes:["broker"],resource:"node-own",scope:"crtr:act"},{name:"health.get.33",method:"GET",path:"/healthz",classes:["anonymous"],resource:"none"},{name:"health.get.34",method:"GET",path:"/v1/status",classes:["person","broker"],resource:"none"},{name:"daemon.due",method:"GET",path:"/v1/due",classes:["person","broker"],resource:"none"},{name:"bash-jobs.report",method:"POST",path:"/v1/nodes/:id/jobs/:jobId/report",classes:["broker"],resource:"node-own",scope:"crtr:act"},{name:"bash-jobs.patch",method:"PATCH",path:"/v1/nodes/:id/jobs/:jobId",classes:["person","broker"],resource:"node-write"},{name:"bash-jobs.start",method:"POST",path:"/v1/nodes/:id/jobs/start",classes:["broker"],resource:"node-own",scope:"crtr:act"},{name:"hooks.plan",method:"GET",path:"/v1/nodes/:id/hooks/plan",classes:["broker"],resource:"node-own"},{name:"hooks.exec",method:"POST",path:"/v1/nodes/:id/hooks/exec",classes:["broker"],resource:"node-own"},{name:"hooks.exec.person",method:"POST",path:"/v1/hooks/exec",classes:["person","broker"],resource:"none"},{name:"bash-jobs.get.35",method:"GET",path:"/v1/nodes/:id/jobs",classes:["person","broker","cron"],resource:"node-read"},{name:"bash-jobs.output",method:"GET",path:"/v1/nodes/:id/jobs/:jobId/output",classes:["person","broker","cron"],resource:"node-read"},{name:"bash-jobs.delete.36",method:"DELETE",path:"/v1/nodes/:id/jobs/:jobId",classes:["person","broker"],resource:"node-write"},{name:"prospective-chat-inventory.get.37",method:"GET",path:"/v1/prospective-chat-inventory",classes:["person","broker"],resource:"none"},{name:"node-events.get.38",method:"GET",path:"/v1/nodes/:id/events",classes:["person","broker","cron"],resource:"node-read"},{name:"bash.post.39",method:"POST",path:"/v1/bash",classes:["person","broker"],resource:"daemon-bash",scope:"crtr:act"},{name:"subscriptions.post.40",method:"POST",path:"/v1/nodes/:id/subscriptions",classes:["person","broker"],resource:"node-write"},{name:"subscriptions.delete.41",method:"DELETE",path:"/v1/nodes/:id/subscriptions/:target",classes:["person","broker"],resource:"node-write"},{name:"attach.post.42",method:"POST",path:"/v1/nodes/:id/attach",classes:["person","broker"],resource:"node-write"},{name:"review-comments.post.44",method:"POST",path:"/v1/human/reviews/self/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.get.45",method:"GET",path:"/v1/human/reviews/self/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.post.46",method:"POST",path:"/v1/human/reviews/:review_id/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.get.47",method:"GET",path:"/v1/human/reviews/:review_id/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.get.48",method:"GET",path:"/v1/human/reviews/:review_id/comment-events",classes:["person","broker"],resource:"human"},{name:"review-comments.post.49",method:"POST",path:"/v1/human/reviews/:review_id/comment-ranges",classes:["person","broker"],resource:"human"},{name:"review-comments.get.50",method:"GET",path:"/v1/human/comments/:comment_id",classes:["person","broker"],resource:"human"},{name:"review-comments.post.51",method:"POST",path:"/v1/human/comments/:comment_id/edit",classes:["person","broker"],resource:"human"},{name:"review-comments.post.52",method:"POST",path:"/v1/human/comments/:comment_id/resolve",classes:["person","broker"],resource:"human"},{name:"review-comments.post.53",method:"POST",path:"/v1/human/comments/:comment_id/reopen",classes:["person","broker"],resource:"human"},{name:"review-comments.post.54",method:"POST",path:"/v1/human/comments/:comment_id/delete",classes:["person","broker"],resource:"human"},{name:"review-comments.post.55",method:"POST",path:"/v1/human/comments/:comment_id/fork",classes:["person","broker"],resource:"human"},{name:"messages.post.56",method:"POST",path:"/v1/nodes/:id/mail/claim",classes:["person","broker"],resource:"node-own"},{name:"messages.post.57",method:"POST",path:"/v1/nodes/:id/mail/acknowledge",classes:["person","broker"],resource:"node-own"},{name:"messages.post.58",method:"POST",path:"/v1/nodes/:id/messages",classes:["person","broker","cron","forwarded"],resource:"node-write"},{name:"messages.post.59",method:"POST",path:"/v1/nodes/:id/interrupt",classes:["person","broker","cron","forwarded"],resource:"node-write"},{name:"reports.post.60",method:"POST",path:"/v1/nodes/:id/reports",classes:["person","broker"],resource:"node-own"},{name:"reports.get.61",method:"GET",path:"/v1/nodes/:id/reports",classes:["person","broker","cron"],resource:"node-read"},{name:"reports.post.62",method:"POST",path:"/v1/nodes/:id/result",classes:["person","broker"],resource:"node-own"},{name:"inbox.get.63",method:"GET",path:"/v1/human/inbox",classes:["person","broker"],resource:"human"},{name:"inbox.get.64",method:"GET",path:"/v1/human/inbox/history",classes:["person","broker"],resource:"human"},{name:"inbox.get.65",method:"GET",path:"/v1/human/inbox/:ticket_id",classes:["person","broker"],resource:"human"},{name:"inbox.get.66",method:"GET",path:"/v1/human/inbox/:ticket_id/response",classes:["person","broker"],resource:"human"},{name:"inbox.post.67",method:"POST",path:"/v1/human/inbox/:ticket_id/respond",classes:["person","broker"],resource:"human"},{name:"inbox.post.68",method:"POST",path:"/v1/human/inbox/:ticket_id/progress",classes:["person","broker"],resource:"human"},{name:"inbox.post.69",method:"POST",path:"/v1/human/inbox/:ticket_id/cancel",classes:["person","broker"],resource:"human"},{name:"worktree.post.70",method:"POST",path:"/v1/nodes/:id/worktree/close",classes:["person","broker"],resource:"node-write"},{name:"worktree.post.71",method:"POST",path:"/v1/nodes/:id/worktree/abandon",classes:["person","broker"],resource:"node-write"},{name:"worktree.get.72",method:"GET",path:"/v1/worktrees/quarantined",classes:["person","broker"],resource:"none"},{name:"crons.post.73",method:"POST",path:"/v1/crons",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.get.74",method:"GET",path:"/v1/crons",classes:["person","app","broker","cron"],resource:"cron"},{name:"crons.get.75",method:"GET",path:"/v1/crons/:cronId",classes:["person","app","broker","cron"],resource:"cron"},{name:"crons.post.76",method:"POST",path:"/v1/crons/:cronId/pause",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.post.77",method:"POST",path:"/v1/crons/:cronId/resume",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.post.78",method:"POST",path:"/v1/crons/poke",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.post.79",method:"POST",path:"/v1/crons/:cronId/run",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.delete.80",method:"DELETE",path:"/v1/crons/:cronId",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"modelauth.get.81",method:"GET",path:"/v1/model-auth",classes:["person","broker"],resource:"none"},{name:"modelauth.get.82",method:"GET",path:"/v1/model-auth/readiness",classes:["person","broker"],resource:"none"},{name:"modelauth.put.83",method:"PUT",path:"/v1/model-auth/:provider",classes:["person","broker"],resource:"none"},{name:"modelauth.delete.84",method:"DELETE",path:"/v1/model-auth/:provider",classes:["person","broker"],resource:"none"},{name:"modelauth.delete.account",method:"DELETE",path:"/v1/model-auth/:provider/accounts/:label",classes:["person","broker"],resource:"none"},{name:"modelauth.patch.account",method:"PATCH",path:"/v1/model-auth/:provider/accounts/:label",classes:["person","broker"],resource:"none"},{name:"model_auth.start",method:"POST",path:"/v1/model-auth/flows",classes:["person","broker"],resource:"none"},{name:"model_auth.complete",method:"POST",path:"/v1/model-auth/flows/:flow_id/complete",classes:["person","broker"],resource:"none"},{name:"model_auth.cancel",method:"POST",path:"/v1/model-auth/flows/:flow_id/cancel",classes:["person","broker"],resource:"none"},{name:"model_auth.get",method:"GET",path:"/v1/model-auth/flows/:flow_id",classes:["person","broker"],resource:"none"},{name:"nodes.post.85",method:"POST",path:"/v1/nodes",classes:["person","broker","cron"],resource:"node-own",scope:"crtr:act"},{name:"nodes.get.86",method:"GET",path:"/v1/nodes",classes:["person","broker"],resource:"nodes-list"},{name:"nodes.post.87",method:"POST",path:"/v1/nodes/revive-all",classes:["person","broker"],resource:"none"},{name:"nodes.get.88",method:"GET",path:"/v1/nodes/:id",classes:["person","broker","cron","forwarded"],resource:"node-read"},{name:"nodes.get.89",method:"GET",path:"/v1/nodes/:id/snapshot",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.90",method:"GET",path:"/v1/nodes/:id/subject",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.91",method:"GET",path:"/v1/nodes/:id/messages",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.92",method:"GET",path:"/v1/nodes/:id/session",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.93",method:"GET",path:"/v1/nodes/:id/transcript",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.94",method:"GET",path:"/v1/nodes/:id/context",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.post.96",method:"POST",path:"/v1/nodes/:id/fork",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.97",method:"POST",path:"/v1/nodes/:id/revive",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.98",method:"POST",path:"/v1/nodes/:id/relaunch-root",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.99",method:"POST",path:"/v1/nodes/:id/close",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.read",method:"POST",path:"/v1/nodes/:id/read",classes:["person"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.100",method:"POST",path:"/v1/nodes/:id/recycle",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.101",method:"POST",path:"/v1/nodes/:id/demote",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.102",method:"POST",path:"/v1/nodes/:id/promote",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.103",method:"POST",path:"/v1/nodes/:id/yield",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.104",method:"POST",path:"/v1/nodes/:id/wait",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.patch.105",method:"PATCH",path:"/v1/nodes/:id/config",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"broker-recovery.post.106",method:"POST",path:"/v1/broker/:id/turn",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.post.107",method:"POST",path:"/v1/broker/:id/provider-retry",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.post.108",method:"POST",path:"/v1/broker/:id/fault",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.get.109",method:"GET",path:"/v1/broker/:id/recovery",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.post.110",method:"POST",path:"/v1/nodes/:id/fault",classes:["person","broker"],resource:"node-write"},{name:"broker-recovery.delete.111",method:"DELETE",path:"/v1/nodes/:id/fault",classes:["person","broker"],resource:"node-write"},{name:"profiles.put.112",method:"PUT",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"profiles.post.113",method:"POST",path:"/v1/profiles/:name/pause",classes:["person","broker"],resource:"profile"},{name:"profiles.post.114",method:"POST",path:"/v1/profiles/:name/resume",classes:["person","broker"],resource:"profile"},{name:"profiles.patch.115",method:"PATCH",path:"/v1/profiles/:name/metadata",classes:["person","app","broker"],resource:"profile"},{name:"profile.create",method:"POST",path:"/v1/profiles",classes:["person","app","broker"],resource:"profile"},{name:"profile.update",method:"PATCH",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"app.env.list",method:"GET",path:"/v1/apps/self/env",classes:["person","app","broker"],resource:"profile"},{name:"app.env.set",method:"PUT",path:"/v1/apps/self/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"app.env.remove",method:"DELETE",path:"/v1/apps/self/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"profile.env.list",method:"GET",path:"/v1/profiles/:name/env",classes:["person","app","broker"],resource:"profile"},{name:"profile.env.set",method:"PUT",path:"/v1/profiles/:name/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"profile.env.remove",method:"DELETE",path:"/v1/profiles/:name/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"profiles.delete.116",method:"DELETE",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"profile.list",method:"GET",path:"/v1/profiles",classes:["person","app","broker"],resource:"profile",stage:"chat"},{name:"profiles.get.118",method:"GET",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"import.start",method:"POST",path:"/v1/imports",classes:["person","import"],resource:"none"},{name:"import.upload-urls",method:"POST",path:"/v1/imports/:run_id/upload-urls",classes:["person","import"],resource:"none"},{name:"import.store",method:"PUT",path:"/v1/imports/:run_id/stores/:name",classes:["person","import"],resource:"none"},{name:"import.load",method:"POST",path:"/v1/imports/:run_id/load",classes:["person","import"],resource:"none"},{name:"import.get",method:"GET",path:"/v1/imports/:run_id",classes:["person","import"],resource:"none"},{name:"import.rollback",method:"POST",path:"/v1/imports/:run_id/rollback",classes:["person"],resource:"none"},{name:"import.machine-credential",method:"POST",path:"/v1/imports/:run_id/machine-credential",classes:["person"],resource:"none"},{name:"execution.import-unpacked",method:"POST",path:"/v1/executions/:execution_id/import-unpacked",classes:["broker"],resource:"none"},{name:"execution.start",method:"GET",path:"/v1/executions/:execution_id/start",classes:["broker"],resource:"none"},{name:"environment.git-credential",method:"POST",path:"/v1/environments/:environment_id/git-credential",classes:["broker"],resource:"none"},{name:"node-outcomes.get.119",method:"GET",path:"/v1/nodes/:id/outcome",classes:["person","broker","cron"],resource:"node-read"},{name:"node-outcomes.put.120",method:"PUT",path:"/v1/nodes/:id/outcome-delivery",classes:["person","broker"],resource:"node-write"},{name:"node-outcomes.get.121",method:"GET",path:"/v1/nodes/:id/outcome-delivery",classes:["person","broker","cron"],resource:"node-read"},{name:"node-outcomes.delete.122",method:"DELETE",path:"/v1/nodes/:id/outcome-delivery",classes:["person","broker"],resource:"node-write"},{name:"canvas.get.123",method:"GET",path:"/v1/canvas/attention",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.124",method:"POST",path:"/v1/canvas/attention/counts",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.125",method:"POST",path:"/v1/canvas/history/search",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.126",method:"POST",path:"/v1/canvas/history/grep",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.get.127",method:"GET",path:"/v1/canvas/history/read",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.128",method:"POST",path:"/v1/canvas/history/stats",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.get.129",method:"GET",path:"/v1/canvas/snapshot",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.get.130",method:"GET",path:"/v1/canvas/roster",classes:["person","broker"],resource:"canvas-read"},{name:"canvas.get.live-roots",method:"GET",path:"/v1/canvas/live-roots",classes:["person"],resource:"canvas-read"},{name:"canvas.get.browse",method:"GET",path:"/v1/canvas/browse",classes:["person","broker"],resource:"canvas-read"},{name:"canvas.get.analytics",method:"GET",path:"/v1/canvas/analytics",classes:["person","broker"],resource:"canvas-read"},{name:"memory-reads.post",method:"POST",path:"/v1/nodes/:id/memory-reads",classes:["person","broker"],resource:"node-own"},{name:"canvas.get.131",method:"GET",path:"/v1/canvas/graph",classes:["person","broker"],resource:"canvas-read"},{name:"canvas.post.132",method:"POST",path:"/v1/canvas/prune",classes:["person","broker"],resource:"none"},{name:"daemon.post.133",method:"POST",path:"/v1/daemon/restart",classes:["person","broker"],resource:"daemon-control"},{name:"daemon.post.134",method:"POST",path:"/v1/daemon/migrate",classes:["person","broker"],resource:"daemon-control"},{name:"daemon.drain.start",method:"POST",path:"/v1/daemon/drain",classes:["person"],resource:"daemon-control"},{name:"daemon.drain.end",method:"DELETE",path:"/v1/daemon/drain",classes:["person"],resource:"daemon-control"},{name:"daemon.post.135",method:"POST",path:"/v1/daemon/admit",classes:["person","broker"],resource:"daemon-control"},{name:"human.components.list",method:"GET",path:"/v1/human/components",classes:["person","broker"],resource:"none"},{name:"human-requests.post.136",method:"POST",path:"/v1/human/requests",classes:["person","broker"],resource:"human",scope:"crtr:act"},{name:"human-requests.get.137",method:"GET",path:"/v1/human/requests/:request_id",classes:["person","broker"],resource:"human"},{name:"human-requests.post.138",method:"POST",path:"/v1/human/requests/:request_id/replace",classes:["person","broker"],resource:"human"},{name:"human-requests.post.139",method:"POST",path:"/v1/human/requests/:request_id/respond",classes:["person","broker"],resource:"human"},{name:"human-requests.post.140",method:"POST",path:"/v1/human/requests/:request_id/dismiss",classes:["person","broker"],resource:"human"},{name:"human-requests.post.141",method:"POST",path:"/v1/human/requests/:request_id/cancel",classes:["person","broker"],resource:"human"},{name:"focus.get.142",method:"GET",path:"/v1/focuses",classes:["person","broker"],resource:"none"},{name:"focus.post.143",method:"POST",path:"/v1/focuses",classes:["person","broker"],resource:"none"},{name:"focus.get.144",method:"GET",path:"/v1/focuses/by-node",classes:["person","broker"],resource:"none"},{name:"focus.get.145",method:"GET",path:"/v1/focuses/by-pane",classes:["person","broker"],resource:"none"},{name:"focus.patch.146",method:"PATCH",path:"/v1/focuses/:focus_id",classes:["person","broker"],resource:"none"},{name:"focus.delete.147",method:"DELETE",path:"/v1/focuses/:focus_id",classes:["person","broker"],resource:"none"},{name:"delivery.retry",method:"POST",path:"/v1/deliveries/:delivery_id/retry",classes:["person","broker"],resource:"none"},{name:"limits.show",method:"GET",path:"/v1/limits",classes:["person"],resource:"none"},{name:"limits.set",method:"PUT",path:"/v1/limits/apps/:app",classes:["person"],resource:"none"},{name:"limits.remove",method:"DELETE",path:"/v1/limits/apps/:app",classes:["person"],resource:"none"},{name:"charges.list",method:"GET",path:"/v1/charges",classes:["person","app","broker"],resource:"none",stage:"objects"},{name:"spend_limits.list",method:"GET",path:"/v1/spend-limits",classes:["person"],resource:"none"},{name:"spend_limits.set",method:"PUT",path:"/v1/spend-limits/:id",classes:["person"],resource:"none"},{name:"spend_limits.remove",method:"DELETE",path:"/v1/spend-limits/:id",classes:["person"],resource:"none"},{name:"space.list",method:"GET",path:"/v1/spaces",classes:["person","broker"],resource:"none"},{name:"kinds.list",method:"GET",path:"/v1/kinds",classes:["person","app","broker"],resource:"none"},{name:"grant.get",method:"GET",path:"/v1/grant",classes:["app"],resource:"none",stage:"v0.5"},{name:"exec",method:"POST",path:"/v1/exec",classes:["app"],scope:"crtr:act",resource:"none",stage:"v0.5"},{name:"usage.get",method:"GET",path:"/v1/usage",classes:["person","app","broker"],resource:"none",stage:"v1"},{name:"llm",method:"POST",path:"/v1/llm",classes:["app","person","broker"],scope:"crtr:llm",resource:"none",stage:"v1"},{name:"structured-request.create",method:"POST",path:"/v1/structured-requests",classes:["person","app","broker"],scope:"crtr:act",resource:"none"},{name:"structured-request.get",method:"GET",path:"/v1/structured-requests/:request_id",classes:["person","app","broker"],resource:"none"},{name:"structured-request.cancel",method:"POST",path:"/v1/structured-requests/:request_id/cancel",classes:["person","app","broker"],scope:"crtr:act",resource:"none"},{name:"run.start",method:"POST",path:"/v1/runs",classes:["app"],scope:"crtr:act",resource:"none",stage:"v0.5",idempotency:"24h"},{name:"run.list",method:"GET",path:"/v1/runs",classes:["app","person","broker","cron"],resource:"run",stage:"v0.5"},{name:"run.get",method:"GET",path:"/v1/runs/:run_id",classes:["app","person","broker","cron"],resource:"run",stage:"v0.5"},{name:"run.message",method:"POST",path:"/v1/runs/:run_id/messages",classes:["app","person","broker","cron"],scope:"crtr:act",resource:"run",stage:"v0.5",idempotency:"24h"},{name:"run.events",method:"GET",path:"/v1/runs/:run_id/events",classes:["app","person","broker","cron"],resource:"run",stage:"v0.5",stream:!0},{name:"run.interrupt",method:"POST",path:"/v1/runs/:run_id/interrupt",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"run.cancel",method:"POST",path:"/v1/runs/:run_id/cancel",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"run.delete",method:"DELETE",path:"/v1/runs/:run_id",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"run.rename",method:"POST",path:"/v1/runs/:run_id/rename",classes:["app"],resource:"run",stage:"chat"},{name:"question.get",method:"GET",path:"/v1/questions/:question_id",classes:["app"],resource:"none",stage:"chat"},{name:"question.answer",method:"POST",path:"/v1/questions/:question_id/answer",classes:["app"],resource:"none",stage:"chat"},{name:"question.cancel",method:"POST",path:"/v1/questions/:question_id/cancel",classes:["app"],resource:"none",stage:"chat"},{name:"trace.get",method:"GET",path:"/v1/runs/:run_id/trace",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"upload.create",method:"POST",path:"/v1/uploads",classes:["app"],scope:"crtr:act",resource:"none",stage:"file-transfer"},{name:"attachment.link",method:"GET",path:"/v1/attachments/link",classes:["app"],resource:"none",stage:"file-transfer"},{name:"file.download",method:"GET",path:"/v1/files/download",classes:["app"],resource:"none",stage:"file-transfer",stream:"bytes"},{name:"share.create",method:"POST",path:"/v1/shares",classes:["app"],resource:"none",stage:"file-transfer"},{name:"share.list",method:"GET",path:"/v1/shares",classes:["app"],resource:"none",stage:"file-transfer"},{name:"share.delete",method:"DELETE",path:"/v1/shares/:share_id",classes:["app"],resource:"none",stage:"file-transfer"},{name:"memory.list",method:"GET",path:"/v1/memory",classes:["person","app","broker"],resource:"none",stage:"m13"},{name:"memory.get",method:"GET",path:"/v1/memory/document",classes:["person","app","broker"],resource:"none",stage:"m13"},{name:"audit.list",method:"GET",path:"/v1/audit",classes:["person","app"],resource:"none",stage:"v1"},{name:"provider.tools",method:"GET",path:"/v1/providers/tools",classes:["person","app","broker","cron"],resource:"none",stage:"v1"},{name:"provider.tools",method:"GET",path:"/v1/providers/:provider/tools",classes:["person","app","broker","cron"],resource:"none",stage:"v1"},{name:"provider.call",method:"POST",path:"/v1/provider/call",classes:["person","app","broker","cron"],resource:"none",stage:"v1"},{name:"peer.events",method:"POST",path:"/v1/peer/events",classes:["machine"],resource:"none"},{name:"peer.outbox.claim",method:"POST",path:"/v1/peer/outbox/claim",classes:["machine"],resource:"none"},{name:"peer.outbox.ack",method:"POST",path:"/v1/peer/outbox/ack",classes:["machine"],resource:"none"},{name:"peer.locate",method:"POST",path:"/v1/peer/locate",classes:["machine"],resource:"none"},{name:"runtime.sync-notice",method:"POST",path:"/v1/runtime/sync-notice",classes:["directory"],resource:"none",stage:"v1"},{name:"runtime.vendor-status",method:"GET",path:"/v1/runtime/vendor-status",classes:["directory"],resource:"none",stage:"v1"},{name:"runtime.vendor-account-remove",method:"POST",path:"/v1/runtime/vendor-account-remove",classes:["directory"],resource:"none",stage:"v1"}];function c(e,s){return n.find(o=>o.method===e.toUpperCase()&&o.path===s)}r(c,"operationFor");export{n as OPERATIONS,c as operationFor};
|
|
1
|
+
var a=Object.defineProperty;var r=(e,s)=>a(e,"name",{value:s,configurable:!0});const n=[{name:"conversation.create",method:"POST",path:"/v1/conversations",classes:["broker"],resource:"none"},{name:"conversation.list",method:"GET",path:"/v1/conversations",classes:["broker","person"],resource:"none"},{name:"conversation.append",method:"POST",path:"/v1/conversations/:id/entries",classes:["broker"],resource:"none"},{name:"conversation.commit",method:"POST",path:"/v1/conversations/:id/commit",classes:["broker"],resource:"none"},{name:"conversation.read",method:"GET",path:"/v1/conversations/:id",classes:["broker","person"],resource:"none"},{name:"conversation.header",method:"GET",path:"/v1/conversations/:id/header",classes:["broker","person"],resource:"none"},{name:"conversation.replace",method:"PUT",path:"/v1/conversations/:id",classes:["broker"],resource:"none"},{name:"conversation.fork",method:"POST",path:"/v1/conversations/:id/fork",classes:["broker"],resource:"none"},{name:"conversation.delete",method:"DELETE",path:"/v1/conversations/:id",classes:["broker"],resource:"none"},{name:"health",method:"GET",path:"/v1/health",classes:["anonymous"],resource:"none",stage:"v0.5"},{name:"ready",method:"GET",path:"/v1/ready",classes:["anonymous"],resource:"none",stage:"v0.5"},{name:"chat-inventory.get.1",method:"GET",path:"/v1/nodes/:id/chat-inventory",classes:["person","broker","cron"],resource:"node-read"},{name:"settings.get",method:"GET",path:"/v1/settings",classes:["person","broker"],resource:"none"},{name:"settings.put",method:"PUT",path:"/v1/settings",classes:["person","broker"],resource:"none"},{name:"model-config.put.2",method:"PUT",path:"/v1/model-config",classes:["person","broker"],resource:"none"},{name:"files.get.3",method:"GET",path:"/v1/files/peek",classes:["person","broker"],resource:"none"},{name:"files.post.4",method:"POST",path:"/v1/files/write",classes:["person","broker"],resource:"none"},{name:"files.get.5",method:"GET",path:"/v1/files/list",classes:["person","broker"],resource:"none"},{name:"reviews.post.6",method:"POST",path:"/v1/human/reviews",classes:["person","broker"],resource:"human",scope:"crtr:act"},{name:"reviews.get.7",method:"GET",path:"/v1/human/reviews",classes:["person","broker"],resource:"human"},{name:"reviews.get.8",method:"GET",path:"/v1/human/reviews/:review_id",classes:["person","broker"],resource:"human"},{name:"reviews.post.9",method:"POST",path:"/v1/human/reviews/:review_id/submit",classes:["person","broker"],resource:"human"},{name:"reviews.post.10",method:"POST",path:"/v1/human/reviews/:review_id/cancel",classes:["person","broker"],resource:"human"},{name:"reviews.get.11",method:"GET",path:"/v1/human/reviews/:review_id/document",classes:["person","broker"],resource:"human"},{name:"feedback-comments.post.12",method:"POST",path:"/v1/human/inbox/:ticket_id/feedback-comments",classes:["person","broker"],resource:"human"},{name:"feedback-comments.post.13",method:"POST",path:"/v1/human/inbox/:ticket_id/feedback-comments/:comment_id/resolve",classes:["person","broker"],resource:"human"},{name:"node.log.append",method:"POST",path:"/v1/nodes/:id/records/log",classes:["person","broker"],resource:"node-own"},{name:"node.summaries.put",method:"PUT",path:"/v1/nodes/:id/records/summaries",classes:["person","broker"],resource:"node-own"},{name:"node.attachments.list",method:"GET",path:"/v1/nodes/:id/attachments",classes:["person","broker"],resource:"node-own"},{name:"node.attachments.read",method:"GET",path:"/v1/nodes/:id/attachments/:sha256",classes:["person","broker"],resource:"node-own"},{name:"node.telemetry.put",method:"PUT",path:"/v1/nodes/:id/records/telemetry",classes:["person","broker"],resource:"node-own"},{name:"node.recap.put",method:"PUT",path:"/v1/nodes/:id/records/recap",classes:["person","broker"],resource:"node-own"},{name:"node.inbox.read",method:"GET",path:"/v1/nodes/:id/records/inbox",classes:["person","broker"],resource:"node-own"},{name:"node.passive.read",method:"GET",path:"/v1/nodes/:id/records/passive",classes:["person","broker"],resource:"node-own"},{name:"node.pushed-final",method:"POST",path:"/v1/nodes/:id/records/pushed-final",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.14",method:"POST",path:"/v1/nodes/:id/broker/session-bound",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.15",method:"POST",path:"/v1/nodes/:id/broker/settle",classes:["person","broker"],resource:"node-own"},{name:"broker.idle",method:"POST",path:"/v1/nodes/:id/broker/idle",classes:["broker"],resource:"node-own"},{name:"broker-ops.post.16",method:"POST",path:"/v1/nodes/:id/broker/park-complete",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.17",method:"POST",path:"/v1/nodes/:id/broker/park-activity",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.18",method:"POST",path:"/v1/nodes/:id/broker/telemetry",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.19",method:"POST",path:"/v1/nodes/:id/broker/model",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.get.20",method:"GET",path:"/v1/nodes/:id/broker/extension-state",classes:["person","broker"],resource:"node-own"},{name:"broker.signals",method:"GET",path:"/v1/nodes/:id/broker/signals",classes:["broker"],resource:"node-own",stream:!0},{name:"nodes.broker-structured-request",method:"GET",path:"/v1/nodes/:id/broker/structured-request",classes:["person","broker"],resource:"node-own"},{name:"nodes.broker-goal",method:"POST",path:"/v1/nodes/:id/broker/goal",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.21",method:"POST",path:"/v1/nodes/:id/broker/generated-name",classes:["person","broker"],resource:"node-own"},{name:"broker-ops.post.22",method:"POST",path:"/v1/nodes/:id/broker/persona-ack",classes:["person","broker"],resource:"node-own"},{name:"objects.read",method:"GET",path:"/v1/objects/:ref",classes:["person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.list",method:"GET",path:"/v1/objects",classes:["person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.search",method:"POST",path:"/v1/objects/search",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"objects.watch",method:"POST",path:"/v1/objects/:ref/watch",classes:["anonymous","person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.unwatch",method:"DELETE",path:"/v1/objects/:ref/watch",classes:["anonymous","person","app","broker","cron","forwarded"],resource:"objects",stage:"objects"},{name:"objects.shares",method:"GET",path:"/v1/objects/:ref/shares",classes:["person","broker"],resource:"objects",stage:"objects"},{name:"objects.share",method:"POST",path:"/v1/objects/:ref/shares",classes:["person","broker"],resource:"objects",stage:"objects"},{name:"objects.unshare",method:"DELETE",path:"/v1/objects/:ref/shares",classes:["person","broker"],resource:"objects",stage:"objects"},{name:"custom-objects.register",method:"POST",path:"/v1/custom-objects",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"custom-objects.publish",method:"POST",path:"/v1/custom-objects/:ref/events",classes:["anonymous","person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"custom-objects.unregister",method:"DELETE",path:"/v1/custom-objects/:ref",classes:["anonymous","person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"custom-objects.receive",method:"GET",path:"/v1/custom-objects/:ref/deliveries",classes:["anonymous","person","app","broker","cron"],resource:"objects",stream:!0,stage:"objects"},{name:"custom-objects.ack",method:"POST",path:"/v1/custom-objects/:ref/deliveries/ack",classes:["anonymous","person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"objects.edges",method:"GET",path:"/v1/objects/:ref/edges",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.write",method:"POST",path:"/v1/docs",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.edit",method:"PATCH",path:"/v1/docs/:ref",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.move",method:"POST",path:"/v1/docs/:ref/move",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.delete",method:"DELETE",path:"/v1/docs/:ref",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"docs.history",method:"GET",path:"/v1/docs/:ref/history",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"schemas.register",method:"POST",path:"/v1/schemas",classes:["app"],resource:"objects",stage:"objects"},{name:"relations.write",method:"POST",path:"/v1/relations",classes:["app"],resource:"objects",stage:"objects"},{name:"relations.replace",method:"PUT",path:"/v1/relations",classes:["app"],resource:"objects",stage:"objects"},{name:"relations.list",method:"GET",path:"/v1/relations",classes:["app"],resource:"objects",stage:"objects"},{name:"check",method:"POST",path:"/v1/check",classes:["app"],resource:"objects",stage:"objects"},{name:"docs.lint",method:"POST",path:"/v1/docs/lint",classes:["person","app","broker","cron"],resource:"objects",stage:"objects"},{name:"plugins.app-token",method:"GET",path:"/v1/plugins/:name/app-token",classes:["person","broker"],resource:"none"},{name:"plugins.call-headers",method:"POST",path:"/v1/plugins/:name/call-headers",classes:["person","broker"],resource:"none"},{name:"documents.browser-access",method:"GET",path:"/v1/documents/browser-access",classes:["person"],resource:"none"},{name:"documents.reconcile-packages",method:"POST",path:"/v1/documents/reconcile-packages",classes:["person","broker"],resource:"none"},{name:"nodes.delivery",method:"POST",path:"/v1/nodes/:id/delivery",classes:["person","broker"],resource:"node-own"},{name:"delivery.dry-run",method:"POST",path:"/v1/delivery/dry-run",classes:["person","broker"],resource:"none"},{name:"bash-jobs.background",method:"POST",path:"/v1/nodes/:id/jobs/:jobId/background",classes:["broker"],resource:"node-own",scope:"crtr:act"},{name:"health.get.33",method:"GET",path:"/healthz",classes:["anonymous"],resource:"none"},{name:"health.get.34",method:"GET",path:"/v1/status",classes:["person","broker"],resource:"none"},{name:"daemon.due",method:"GET",path:"/v1/due",classes:["person","broker"],resource:"none"},{name:"bash-jobs.report",method:"POST",path:"/v1/nodes/:id/jobs/:jobId/report",classes:["broker"],resource:"node-own",scope:"crtr:act"},{name:"bash-jobs.patch",method:"PATCH",path:"/v1/nodes/:id/jobs/:jobId",classes:["person","broker"],resource:"node-write"},{name:"bash-jobs.start",method:"POST",path:"/v1/nodes/:id/jobs/start",classes:["broker"],resource:"node-own",scope:"crtr:act"},{name:"hooks.plan",method:"GET",path:"/v1/nodes/:id/hooks/plan",classes:["broker"],resource:"node-own"},{name:"hooks.exec",method:"POST",path:"/v1/nodes/:id/hooks/exec",classes:["broker"],resource:"node-own"},{name:"hooks.exec.person",method:"POST",path:"/v1/hooks/exec",classes:["person","broker"],resource:"none"},{name:"bash-jobs.get.35",method:"GET",path:"/v1/nodes/:id/jobs",classes:["person","broker","cron"],resource:"node-read"},{name:"bash-jobs.output",method:"GET",path:"/v1/nodes/:id/jobs/:jobId/output",classes:["person","broker","cron"],resource:"node-read"},{name:"bash-jobs.delete.36",method:"DELETE",path:"/v1/nodes/:id/jobs/:jobId",classes:["person","broker"],resource:"node-write"},{name:"prospective-chat-inventory.get.37",method:"GET",path:"/v1/prospective-chat-inventory",classes:["person","broker"],resource:"none"},{name:"node-events.get.38",method:"GET",path:"/v1/nodes/:id/events",classes:["person","broker","cron"],resource:"node-read"},{name:"bash.post.39",method:"POST",path:"/v1/bash",classes:["person","broker"],resource:"daemon-bash",scope:"crtr:act"},{name:"subscriptions.post.40",method:"POST",path:"/v1/nodes/:id/subscriptions",classes:["person","broker"],resource:"node-write"},{name:"subscriptions.delete.41",method:"DELETE",path:"/v1/nodes/:id/subscriptions/:target",classes:["person","broker"],resource:"node-write"},{name:"attach.post.42",method:"POST",path:"/v1/nodes/:id/attach",classes:["person","broker"],resource:"node-write"},{name:"review-comments.post.44",method:"POST",path:"/v1/human/reviews/self/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.get.45",method:"GET",path:"/v1/human/reviews/self/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.post.46",method:"POST",path:"/v1/human/reviews/:review_id/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.get.47",method:"GET",path:"/v1/human/reviews/:review_id/comments",classes:["person","broker"],resource:"human"},{name:"review-comments.get.48",method:"GET",path:"/v1/human/reviews/:review_id/comment-events",classes:["person","broker"],resource:"human"},{name:"review-comments.post.49",method:"POST",path:"/v1/human/reviews/:review_id/comment-ranges",classes:["person","broker"],resource:"human"},{name:"review-comments.get.50",method:"GET",path:"/v1/human/comments/:comment_id",classes:["person","broker"],resource:"human"},{name:"review-comments.post.51",method:"POST",path:"/v1/human/comments/:comment_id/edit",classes:["person","broker"],resource:"human"},{name:"review-comments.post.52",method:"POST",path:"/v1/human/comments/:comment_id/resolve",classes:["person","broker"],resource:"human"},{name:"review-comments.post.53",method:"POST",path:"/v1/human/comments/:comment_id/reopen",classes:["person","broker"],resource:"human"},{name:"review-comments.post.54",method:"POST",path:"/v1/human/comments/:comment_id/delete",classes:["person","broker"],resource:"human"},{name:"review-comments.post.55",method:"POST",path:"/v1/human/comments/:comment_id/fork",classes:["person","broker"],resource:"human"},{name:"messages.post.56",method:"POST",path:"/v1/nodes/:id/mail/claim",classes:["person","broker"],resource:"node-own"},{name:"messages.post.57",method:"POST",path:"/v1/nodes/:id/mail/acknowledge",classes:["person","broker"],resource:"node-own"},{name:"messages.post.58",method:"POST",path:"/v1/nodes/:id/messages",classes:["person","broker","cron","forwarded"],resource:"node-write"},{name:"messages.post.59",method:"POST",path:"/v1/nodes/:id/interrupt",classes:["person","broker","cron","forwarded"],resource:"node-write"},{name:"reports.post.60",method:"POST",path:"/v1/nodes/:id/reports",classes:["person","broker"],resource:"node-own"},{name:"reports.get.61",method:"GET",path:"/v1/nodes/:id/reports",classes:["person","broker","cron"],resource:"node-read"},{name:"reports.post.62",method:"POST",path:"/v1/nodes/:id/result",classes:["person","broker"],resource:"node-own"},{name:"inbox.get.63",method:"GET",path:"/v1/human/inbox",classes:["person","broker"],resource:"human"},{name:"inbox.get.64",method:"GET",path:"/v1/human/inbox/history",classes:["person","broker"],resource:"human"},{name:"inbox.get.65",method:"GET",path:"/v1/human/inbox/:ticket_id",classes:["person","broker"],resource:"human"},{name:"inbox.get.66",method:"GET",path:"/v1/human/inbox/:ticket_id/response",classes:["person","broker"],resource:"human"},{name:"inbox.post.67",method:"POST",path:"/v1/human/inbox/:ticket_id/respond",classes:["person","broker"],resource:"human"},{name:"inbox.post.68",method:"POST",path:"/v1/human/inbox/:ticket_id/progress",classes:["person","broker"],resource:"human"},{name:"inbox.post.69",method:"POST",path:"/v1/human/inbox/:ticket_id/cancel",classes:["person","broker"],resource:"human"},{name:"worktree.post.70",method:"POST",path:"/v1/nodes/:id/worktree/close",classes:["person","broker"],resource:"node-write"},{name:"worktree.post.71",method:"POST",path:"/v1/nodes/:id/worktree/abandon",classes:["person","broker"],resource:"node-write"},{name:"worktree.get.72",method:"GET",path:"/v1/worktrees/quarantined",classes:["person","broker"],resource:"none"},{name:"crons.post.73",method:"POST",path:"/v1/crons",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.get.74",method:"GET",path:"/v1/crons",classes:["person","app","broker","cron"],resource:"cron"},{name:"crons.get.75",method:"GET",path:"/v1/crons/:cronId",classes:["person","app","broker","cron"],resource:"cron"},{name:"crons.post.76",method:"POST",path:"/v1/crons/:cronId/pause",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.post.77",method:"POST",path:"/v1/crons/:cronId/resume",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.post.78",method:"POST",path:"/v1/crons/poke",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.post.79",method:"POST",path:"/v1/crons/:cronId/run",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"crons.delete.80",method:"DELETE",path:"/v1/crons/:cronId",classes:["person","app","broker","cron"],resource:"cron",scope:"crtr:schedule"},{name:"modelauth.get.81",method:"GET",path:"/v1/model-auth",classes:["person","broker"],resource:"none"},{name:"modelauth.get.82",method:"GET",path:"/v1/model-auth/readiness",classes:["person","broker"],resource:"none"},{name:"modelauth.put.83",method:"PUT",path:"/v1/model-auth/:provider",classes:["person","broker"],resource:"none"},{name:"modelauth.delete.84",method:"DELETE",path:"/v1/model-auth/:provider",classes:["person","broker"],resource:"none"},{name:"modelauth.delete.account",method:"DELETE",path:"/v1/model-auth/:provider/accounts/:label",classes:["person","broker"],resource:"none"},{name:"modelauth.patch.account",method:"PATCH",path:"/v1/model-auth/:provider/accounts/:label",classes:["person","broker"],resource:"none"},{name:"model_auth.start",method:"POST",path:"/v1/model-auth/flows",classes:["person","broker"],resource:"none"},{name:"model_auth.complete",method:"POST",path:"/v1/model-auth/flows/:flow_id/complete",classes:["person","broker"],resource:"none"},{name:"model_auth.cancel",method:"POST",path:"/v1/model-auth/flows/:flow_id/cancel",classes:["person","broker"],resource:"none"},{name:"model_auth.get",method:"GET",path:"/v1/model-auth/flows/:flow_id",classes:["person","broker"],resource:"none"},{name:"nodes.post.85",method:"POST",path:"/v1/nodes",classes:["person","broker","cron"],resource:"node-own",scope:"crtr:act"},{name:"nodes.get.86",method:"GET",path:"/v1/nodes",classes:["person","broker"],resource:"nodes-list"},{name:"nodes.post.87",method:"POST",path:"/v1/nodes/revive-all",classes:["person","broker"],resource:"none"},{name:"nodes.get.88",method:"GET",path:"/v1/nodes/:id",classes:["person","broker","cron","forwarded"],resource:"node-read"},{name:"nodes.get.89",method:"GET",path:"/v1/nodes/:id/snapshot",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.90",method:"GET",path:"/v1/nodes/:id/subject",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.91",method:"GET",path:"/v1/nodes/:id/messages",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.92",method:"GET",path:"/v1/nodes/:id/session",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.93",method:"GET",path:"/v1/nodes/:id/transcript",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.get.94",method:"GET",path:"/v1/nodes/:id/context",classes:["person","broker","cron"],resource:"node-read"},{name:"nodes.post.96",method:"POST",path:"/v1/nodes/:id/fork",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.97",method:"POST",path:"/v1/nodes/:id/revive",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.98",method:"POST",path:"/v1/nodes/:id/relaunch-root",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.99",method:"POST",path:"/v1/nodes/:id/close",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.read",method:"POST",path:"/v1/nodes/:id/read",classes:["person"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.100",method:"POST",path:"/v1/nodes/:id/recycle",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.101",method:"POST",path:"/v1/nodes/:id/demote",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.102",method:"POST",path:"/v1/nodes/:id/promote",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.103",method:"POST",path:"/v1/nodes/:id/yield",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.post.104",method:"POST",path:"/v1/nodes/:id/wait",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"nodes.patch.105",method:"PATCH",path:"/v1/nodes/:id/config",classes:["person","broker"],resource:"node-write",scope:"crtr:act"},{name:"broker-recovery.post.106",method:"POST",path:"/v1/broker/:id/turn",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.post.107",method:"POST",path:"/v1/broker/:id/provider-retry",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.post.108",method:"POST",path:"/v1/broker/:id/fault",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.get.109",method:"GET",path:"/v1/broker/:id/recovery",classes:["person","broker"],resource:"node-own"},{name:"broker-recovery.post.110",method:"POST",path:"/v1/nodes/:id/fault",classes:["person","broker"],resource:"node-write"},{name:"broker-recovery.delete.111",method:"DELETE",path:"/v1/nodes/:id/fault",classes:["person","broker"],resource:"node-write"},{name:"profiles.put.112",method:"PUT",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"profiles.post.113",method:"POST",path:"/v1/profiles/:name/pause",classes:["person","broker"],resource:"profile"},{name:"profiles.post.114",method:"POST",path:"/v1/profiles/:name/resume",classes:["person","broker"],resource:"profile"},{name:"profiles.patch.115",method:"PATCH",path:"/v1/profiles/:name/metadata",classes:["person","app","broker"],resource:"profile"},{name:"profile.create",method:"POST",path:"/v1/profiles",classes:["person","app","broker"],resource:"profile"},{name:"profile.update",method:"PATCH",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"app.env.list",method:"GET",path:"/v1/apps/self/env",classes:["person","app","broker"],resource:"profile"},{name:"app.env.set",method:"PUT",path:"/v1/apps/self/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"app.env.remove",method:"DELETE",path:"/v1/apps/self/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"profile.env.list",method:"GET",path:"/v1/profiles/:name/env",classes:["person","app","broker"],resource:"profile"},{name:"profile.env.set",method:"PUT",path:"/v1/profiles/:name/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"profile.env.remove",method:"DELETE",path:"/v1/profiles/:name/env/:var",classes:["person","app","broker"],resource:"profile"},{name:"profiles.delete.116",method:"DELETE",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"profile.list",method:"GET",path:"/v1/profiles",classes:["person","app","broker"],resource:"profile",stage:"chat"},{name:"profiles.get.118",method:"GET",path:"/v1/profiles/:name",classes:["person","app","broker"],resource:"profile"},{name:"import.start",method:"POST",path:"/v1/imports",classes:["person","import"],resource:"none"},{name:"import.upload-urls",method:"POST",path:"/v1/imports/:run_id/upload-urls",classes:["person","import"],resource:"none"},{name:"import.store",method:"PUT",path:"/v1/imports/:run_id/stores/:name",classes:["person","import"],resource:"none"},{name:"import.load",method:"POST",path:"/v1/imports/:run_id/load",classes:["person","import"],resource:"none"},{name:"import.get",method:"GET",path:"/v1/imports/:run_id",classes:["person","import"],resource:"none"},{name:"import.rollback",method:"POST",path:"/v1/imports/:run_id/rollback",classes:["person"],resource:"none"},{name:"import.machine-credential",method:"POST",path:"/v1/imports/:run_id/machine-credential",classes:["person"],resource:"none"},{name:"execution.import-unpacked",method:"POST",path:"/v1/executions/:execution_id/import-unpacked",classes:["broker"],resource:"none"},{name:"execution.start",method:"GET",path:"/v1/executions/:execution_id/start",classes:["broker"],resource:"none"},{name:"environment.git-credential",method:"POST",path:"/v1/environments/:environment_id/git-credential",classes:["broker"],resource:"none"},{name:"node-outcomes.get.119",method:"GET",path:"/v1/nodes/:id/outcome",classes:["person","broker","cron"],resource:"node-read"},{name:"node-outcomes.put.120",method:"PUT",path:"/v1/nodes/:id/outcome-delivery",classes:["person","broker"],resource:"node-write"},{name:"node-outcomes.get.121",method:"GET",path:"/v1/nodes/:id/outcome-delivery",classes:["person","broker","cron"],resource:"node-read"},{name:"node-outcomes.delete.122",method:"DELETE",path:"/v1/nodes/:id/outcome-delivery",classes:["person","broker"],resource:"node-write"},{name:"canvas.get.123",method:"GET",path:"/v1/canvas/attention",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.124",method:"POST",path:"/v1/canvas/attention/counts",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.125",method:"POST",path:"/v1/canvas/history/search",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.126",method:"POST",path:"/v1/canvas/history/grep",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.get.127",method:"GET",path:"/v1/canvas/history/read",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.post.128",method:"POST",path:"/v1/canvas/history/stats",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.get.129",method:"GET",path:"/v1/canvas/snapshot",classes:["person","broker","forwarded"],resource:"canvas-read"},{name:"canvas.get.130",method:"GET",path:"/v1/canvas/roster",classes:["person","broker"],resource:"canvas-read"},{name:"canvas.get.live-roots",method:"GET",path:"/v1/canvas/live-roots",classes:["person"],resource:"canvas-read"},{name:"canvas.get.browse",method:"GET",path:"/v1/canvas/browse",classes:["person","broker"],resource:"canvas-read"},{name:"canvas.get.analytics",method:"GET",path:"/v1/canvas/analytics",classes:["person","broker"],resource:"canvas-read"},{name:"memory-reads.post",method:"POST",path:"/v1/nodes/:id/memory-reads",classes:["person","broker"],resource:"node-own"},{name:"canvas.get.131",method:"GET",path:"/v1/canvas/graph",classes:["person","broker"],resource:"canvas-read"},{name:"canvas.post.132",method:"POST",path:"/v1/canvas/prune",classes:["person","broker"],resource:"none"},{name:"daemon.post.133",method:"POST",path:"/v1/daemon/restart",classes:["person","broker"],resource:"daemon-control"},{name:"daemon.post.134",method:"POST",path:"/v1/daemon/migrate",classes:["person","broker"],resource:"daemon-control"},{name:"daemon.drain.start",method:"POST",path:"/v1/daemon/drain",classes:["person"],resource:"daemon-control"},{name:"daemon.drain.end",method:"DELETE",path:"/v1/daemon/drain",classes:["person"],resource:"daemon-control"},{name:"daemon.post.135",method:"POST",path:"/v1/daemon/admit",classes:["person","broker"],resource:"daemon-control"},{name:"human.components.list",method:"GET",path:"/v1/human/components",classes:["person","broker"],resource:"none"},{name:"human-requests.post.136",method:"POST",path:"/v1/human/requests",classes:["person","broker"],resource:"human",scope:"crtr:act"},{name:"human-requests.get.137",method:"GET",path:"/v1/human/requests/:request_id",classes:["person","broker"],resource:"human"},{name:"human-requests.post.138",method:"POST",path:"/v1/human/requests/:request_id/replace",classes:["person","broker"],resource:"human"},{name:"human-requests.post.139",method:"POST",path:"/v1/human/requests/:request_id/respond",classes:["person","broker"],resource:"human"},{name:"human-requests.post.140",method:"POST",path:"/v1/human/requests/:request_id/dismiss",classes:["person","broker"],resource:"human"},{name:"human-requests.post.141",method:"POST",path:"/v1/human/requests/:request_id/cancel",classes:["person","broker"],resource:"human"},{name:"focus.get.142",method:"GET",path:"/v1/focuses",classes:["person","broker"],resource:"none"},{name:"focus.post.143",method:"POST",path:"/v1/focuses",classes:["person","broker"],resource:"none"},{name:"focus.get.144",method:"GET",path:"/v1/focuses/by-node",classes:["person","broker"],resource:"none"},{name:"focus.get.145",method:"GET",path:"/v1/focuses/by-pane",classes:["person","broker"],resource:"none"},{name:"focus.patch.146",method:"PATCH",path:"/v1/focuses/:focus_id",classes:["person","broker"],resource:"none"},{name:"focus.delete.147",method:"DELETE",path:"/v1/focuses/:focus_id",classes:["person","broker"],resource:"none"},{name:"delivery.retry",method:"POST",path:"/v1/deliveries/:delivery_id/retry",classes:["person","broker"],resource:"none"},{name:"limits.show",method:"GET",path:"/v1/limits",classes:["person"],resource:"none"},{name:"limits.set",method:"PUT",path:"/v1/limits/apps/:app",classes:["person"],resource:"none"},{name:"limits.remove",method:"DELETE",path:"/v1/limits/apps/:app",classes:["person"],resource:"none"},{name:"charges.list",method:"GET",path:"/v1/charges",classes:["person","app","broker"],resource:"none",stage:"objects"},{name:"spend_limits.list",method:"GET",path:"/v1/spend-limits",classes:["person"],resource:"none"},{name:"spend_limits.set",method:"PUT",path:"/v1/spend-limits/:id",classes:["person"],resource:"none"},{name:"spend_limits.remove",method:"DELETE",path:"/v1/spend-limits/:id",classes:["person"],resource:"none"},{name:"space.list",method:"GET",path:"/v1/spaces",classes:["person","broker"],resource:"none"},{name:"kinds.list",method:"GET",path:"/v1/kinds",classes:["person","app","broker"],resource:"none"},{name:"grant.get",method:"GET",path:"/v1/grant",classes:["app"],resource:"none",stage:"v0.5"},{name:"exec",method:"POST",path:"/v1/exec",classes:["app"],scope:"crtr:act",resource:"none",stage:"v0.5"},{name:"usage.get",method:"GET",path:"/v1/usage",classes:["person","app","broker"],resource:"none",stage:"v1"},{name:"llm",method:"POST",path:"/v1/llm",classes:["app","person","broker"],scope:"crtr:llm",resource:"none",stage:"v1"},{name:"llm.anthropic_messages",method:"POST",path:"/v1/llm/anthropic/messages",classes:["app"],scope:"crtr:llm",resource:"none",stage:"v1"},{name:"structured-request.create",method:"POST",path:"/v1/structured-requests",classes:["person","app","broker"],scope:"crtr:act",resource:"none"},{name:"structured-request.get",method:"GET",path:"/v1/structured-requests/:request_id",classes:["person","app","broker"],resource:"none"},{name:"structured-request.cancel",method:"POST",path:"/v1/structured-requests/:request_id/cancel",classes:["person","app","broker"],scope:"crtr:act",resource:"none"},{name:"run.start",method:"POST",path:"/v1/runs",classes:["app"],scope:"crtr:act",resource:"none",stage:"v0.5",idempotency:"24h"},{name:"run.list",method:"GET",path:"/v1/runs",classes:["app","person","broker","cron"],resource:"run",stage:"v0.5"},{name:"run.get",method:"GET",path:"/v1/runs/:run_id",classes:["app","person","broker","cron"],resource:"run",stage:"v0.5"},{name:"run.message",method:"POST",path:"/v1/runs/:run_id/messages",classes:["app","person","broker","cron"],scope:"crtr:act",resource:"run",stage:"v0.5",idempotency:"24h"},{name:"run.events",method:"GET",path:"/v1/runs/:run_id/events",classes:["app","person","broker","cron"],resource:"run",stage:"v0.5",stream:!0},{name:"run.interrupt",method:"POST",path:"/v1/runs/:run_id/interrupt",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"run.cancel",method:"POST",path:"/v1/runs/:run_id/cancel",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"run.delete",method:"DELETE",path:"/v1/runs/:run_id",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"run.rename",method:"POST",path:"/v1/runs/:run_id/rename",classes:["app"],resource:"run",stage:"chat"},{name:"question.get",method:"GET",path:"/v1/questions/:question_id",classes:["app"],resource:"none",stage:"chat"},{name:"question.answer",method:"POST",path:"/v1/questions/:question_id/answer",classes:["app"],resource:"none",stage:"chat"},{name:"question.cancel",method:"POST",path:"/v1/questions/:question_id/cancel",classes:["app"],resource:"none",stage:"chat"},{name:"trace.get",method:"GET",path:"/v1/runs/:run_id/trace",classes:["app","person","broker"],resource:"run",stage:"v0.5"},{name:"upload.create",method:"POST",path:"/v1/uploads",classes:["app"],scope:"crtr:act",resource:"none",stage:"file-transfer"},{name:"attachment.link",method:"GET",path:"/v1/attachments/link",classes:["app"],resource:"none",stage:"file-transfer"},{name:"file.download",method:"GET",path:"/v1/files/download",classes:["app"],resource:"none",stage:"file-transfer",stream:"bytes"},{name:"share.create",method:"POST",path:"/v1/shares",classes:["app"],resource:"none",stage:"file-transfer"},{name:"share.list",method:"GET",path:"/v1/shares",classes:["app"],resource:"none",stage:"file-transfer"},{name:"share.delete",method:"DELETE",path:"/v1/shares/:share_id",classes:["app"],resource:"none",stage:"file-transfer"},{name:"memory.list",method:"GET",path:"/v1/memory",classes:["person","app","broker"],resource:"none",stage:"m13"},{name:"memory.get",method:"GET",path:"/v1/memory/document",classes:["person","app","broker"],resource:"none",stage:"m13"},{name:"audit.list",method:"GET",path:"/v1/audit",classes:["person","app"],resource:"none",stage:"v1"},{name:"provider.tools",method:"GET",path:"/v1/providers/tools",classes:["person","app","broker","cron"],resource:"none",stage:"v1"},{name:"provider.tools",method:"GET",path:"/v1/providers/:provider/tools",classes:["person","app","broker","cron"],resource:"none",stage:"v1"},{name:"provider.call",method:"POST",path:"/v1/provider/call",classes:["person","app","broker","cron"],resource:"none",stage:"v1"},{name:"peer.events",method:"POST",path:"/v1/peer/events",classes:["machine"],resource:"none"},{name:"peer.outbox.claim",method:"POST",path:"/v1/peer/outbox/claim",classes:["machine"],resource:"none"},{name:"peer.outbox.ack",method:"POST",path:"/v1/peer/outbox/ack",classes:["machine"],resource:"none"},{name:"peer.locate",method:"POST",path:"/v1/peer/locate",classes:["machine"],resource:"none"},{name:"runtime.sync-notice",method:"POST",path:"/v1/runtime/sync-notice",classes:["directory"],resource:"none",stage:"v1"},{name:"runtime.vendor-status",method:"GET",path:"/v1/runtime/vendor-status",classes:["directory"],resource:"none",stage:"v1"},{name:"runtime.vendor-account-remove",method:"POST",path:"/v1/runtime/vendor-account-remove",classes:["directory"],resource:"none",stage:"v1"}];function c(e,s){return n.find(o=>o.method===e.toUpperCase()&&o.path===s)}r(c,"operationFor");export{n as OPERATIONS,c as operationFor};
|
|
@@ -7,6 +7,23 @@ description: Behavior changes in @north-light/sdk that an app must act on, newes
|
|
|
7
7
|
|
|
8
8
|
Changes to `@north-light/sdk` that can change what an existing app sees. Newest first.
|
|
9
9
|
|
|
10
|
+
## 0.3.625
|
|
11
|
+
|
|
12
|
+
### `inferenceEndpoint` serves Anthropic Messages, admits and settles every call (breaking, no existing consumer outside Northlight's own apps)
|
|
13
|
+
|
|
14
|
+
`inferenceEndpoint` now runs the directory's per-call admission and settlement itself, so an app no longer writes that proxy. It serves only `POST <baseURL>/anthropic/v1/messages`; any other path is 404. Options and return value change:
|
|
15
|
+
|
|
16
|
+
- New options: `apiKey` (the app's Anthropic key), `directoryToken` (the app's `OAuth2Client.directoryToken`), `settlements` (a `SettlementStore` over the app's own database: `save`, `remove`, `due`, `retryLater`). `rungs` values must be `anthropic/<model>` for a model the SDK has a list price for; the constructor throws for any other.
|
|
17
|
+
- Removed options: `providers` and `onUsage`. The `InferenceProvider` and `InferenceUsage` types are removed; `InferenceSettlement` and `SettlementStore` are added.
|
|
18
|
+
- It returns `{handle(request), sweep(now?)}` instead of a bare handler. Mount `handle` at the path of `baseURL` and call `sweep` on a timer (every 30 s is typical) to post usage reports the directory has not yet accepted.
|
|
19
|
+
- Per call it verifies the directory token, refuses server-side tools and service tiers (400) and models outside `rungs` (404), then asks the directory to admit the call. A refusal is a 402 carrying the directory's `payment` body; an unreachable or unexpected directory is a 503 with nothing sent upstream.
|
|
20
|
+
- When the admission carries `pool`, the call goes to the team Claude pool at `pool.url` with `pool.token` and settles at list price with `cost_usd` 0; a pool 429 keeps its `Retry-After`. Otherwise it goes to Anthropic with `apiKey` and settles with `cost_usd` equal to the list price. A call is never sent to `apiKey` when the admission carried `pool`.
|
|
21
|
+
- The answer carries `Crtr-Charge-Id`, and the terminal `message_stop` event (or JSON body) carries `crtr_charge`.
|
|
22
|
+
|
|
23
|
+
### `POST /v1/llm/anthropic/messages`, a new route served from the owner's Claude logins
|
|
24
|
+
|
|
25
|
+
`POST /v1/llm/anthropic/messages` is a new app-class route that serves an Anthropic Messages request (JSON or SSE, the vendor's answer passed through unchanged) with the runtime owner's Claude subscription logins. It needs the `crtr:llm` scope and an owner-paid grant: an app-paid grant is refused `403 permission_error`. It never uses a stored API key, a hosted endpoint or an app endpoint. A model that is not an Anthropic catalog model answers `404 model_unavailable`, as does an account with no usable Claude login. When every login is cooling down it answers `429 all_routes_exhausted` with `Retry-After` and `retry_after_s`; a spend limit on the owner's subscription spend answers `402 cap_exhausted`. Each completed call writes one `funding: subscription` ledger row at list price. It exists for the SDK's inference helper; no existing route changes.
|
|
26
|
+
|
|
10
27
|
## 0.3.622
|
|
11
28
|
|
|
12
29
|
`oauth.authorizeUrl` takes an optional `loginHint`: a phone number your app already collected, sent as the standard `login_hint`. A signed-out person's sign-in page then shows the number with one "Text me a link" button instead of asking for it (US and Canadian numbers in any format they type; a number the directory cannot text only prefills its form). Nothing is texted until the person presses the button. No existing call changes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.625",
|
|
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.
|
|
148
|
+
"@north-light/identity": "0.3.625",
|
|
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",
|
package/runtime.lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/cli",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.625",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@north-light/cli",
|
|
9
|
-
"version": "0.3.
|
|
9
|
+
"version": "0.3.625",
|
|
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.
|
|
31
|
+
"@north-light/identity": "0.3.625",
|
|
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.
|
|
11959
|
+
"version": "0.3.625",
|
|
11960
11960
|
"license": "UNLICENSED"
|
|
11961
11961
|
},
|
|
11962
11962
|
"packages/crouter-env-docker": {
|
|
11963
11963
|
"name": "@north-light/env-docker",
|
|
11964
|
-
"version": "0.3.
|
|
11964
|
+
"version": "0.3.625",
|
|
11965
11965
|
"license": "UNLICENSED"
|
|
11966
11966
|
},
|
|
11967
11967
|
"packages/crouter-identity": {
|
|
11968
11968
|
"name": "@north-light/identity",
|
|
11969
|
-
"version": "0.3.
|
|
11969
|
+
"version": "0.3.625",
|
|
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.
|
|
11977
|
+
"version": "0.3.625",
|
|
11978
11978
|
"license": "UNLICENSED",
|
|
11979
11979
|
"dependencies": {
|
|
11980
|
-
"@north-light/api": "0.3.
|
|
11981
|
-
"@north-light/identity": "0.3.
|
|
11980
|
+
"@north-light/api": "0.3.625",
|
|
11981
|
+
"@north-light/identity": "0.3.625"
|
|
11982
11982
|
}
|
|
11983
11983
|
},
|
|
11984
11984
|
"packages/crouter-sdk": {
|
|
11985
11985
|
"name": "@north-light/sdk",
|
|
11986
|
-
"version": "0.3.
|
|
11986
|
+
"version": "0.3.625",
|
|
11987
11987
|
"license": "UNLICENSED",
|
|
11988
11988
|
"dependencies": {
|
|
11989
|
-
"@north-light/api": "0.3.
|
|
11990
|
-
"@north-light/identity": "0.3.
|
|
11991
|
-
"@north-light/plugin": "0.3.
|
|
11989
|
+
"@north-light/api": "0.3.625",
|
|
11990
|
+
"@north-light/identity": "0.3.625",
|
|
11991
|
+
"@north-light/plugin": "0.3.625",
|
|
11992
11992
|
"jose": "^6.2.1"
|
|
11993
11993
|
},
|
|
11994
11994
|
"bin": {
|