@north-light/plugin 0.3.497 → 0.3.499

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/README.md CHANGED
@@ -124,15 +124,15 @@ On Node, Express or Nest, mount the Fetch handler with `createNodeHandler(handle
124
124
 
125
125
  ## Metered provider tools
126
126
 
127
- With directory authentication, configure `createFetchHandler(plugin, { auth, receipts: { provider: 'app:acme', outbox } })`. `provider` must be the provider's authenticated `app:<id>` principal, not the plugin name. Emitted receipt `tool` values, and the `tool` that `ctx.checkSpend()` sends, are command paths **after** the plugin name: `send` for `crtr acme send`, or `messages send` for `crtr acme messages send`. A handler calls `ctx.meter({ units, unit })` to emit a `Crtr-Receipt`; the provider persists and posts that same receipt to the directory ledger.
127
+ With directory authentication, configure `createFetchHandler(plugin, { auth, receipts: { provider: 'app:acme', outbox } })`. `provider` must be the provider's authenticated `app:<id>` principal, not the plugin name. Emitted receipt `tool` values, and the `tool` that `ctx.checkSpend()` sends, are command paths **after** the plugin name: `send` for `crtr acme send`, or `messages send` for `crtr acme messages send`. A handler calls `ctx.meter({ units, unit })` to emit a `Crtr-Receipt`; the provider persists and posts that same receipt to the directory ledger. `ctx.meter` may be called once for each distinct `unit` in a call (a repeated unit throws); pass `receiptId` to name a receipt (the default is the request id, and each receipt in a call needs its own id). One receipt rides in `Crtr-Receipt` as an object, several as a JSON array, and receipts metered before a `LeafError` ride on the error response.
128
128
 
129
- The kit holds no prices: the directory owns every price, maximum and allowance (set in the console or with `crtr cloud apps provider pricing`), and charges from the receipt's `units` or its reported cost. `ctx.meter` sets the receipt's `usd_equivalent` to the first of: the `usdEquivalent` you pass (a tool that reports its cost passes it); `units` × the unit price that this request's `ctx.checkSpend()` answered, for a unit-priced tool; otherwise `0`. It never throws for a missing price. The figure is what the runtime shows as the call's cost; the directory recomputes the charge itself and never trusts it. `ReceiptOptions.rates` no longer exists: delete it when you upgrade (TypeScript flags it; a JavaScript config that still passes it is ignored).
129
+ The kit holds no prices: the directory owns every price, maximum and allowance (set in the console or with `crtr cloud apps provider pricing`), and charges from the receipt's `units` or its reported cost. `ctx.meter` sets the receipt's `usd_equivalent` to the first of: the `usdEquivalent` you pass (a tool that reports its cost passes it); `units` × the price row of this request's `ctx.checkSpend()` answer whose `unit` matches, for a unit-priced tool; otherwise `0`. It never throws for a missing price. The figure is what the runtime shows as the call's cost; the directory recomputes the charge itself and never trusts it. `ReceiptOptions.rates` no longer exists: delete it when you upgrade (TypeScript flags it; a JavaScript config that still passes it is ignored).
130
130
 
131
- `ctx.caller.payer` is the principal charged for the call, `user:<id>` or `app:<id>`: the token's `payer` claim, or `sub` when the token has none. `ctx.meter` stamps it on the receipt. Before a priced call, `await ctx.checkSpend()` asks the directory (`POST <auth.issuer>/v1/billing/check`, sending the request's outbound token) whether that payer may spend on this command (it posts `{ token, tool }`, `tool` being the command path above) and keeps the price it answers for `ctx.meter`; it reserves nothing. It needs `receipts.ledger: { clientId, privateKey, keyId? }`, the same credentials you pass to `postReceipt`, and throws a plain `Error` without them or without a verified caller. It resolves when the call may go ahead, throws `SpendRefusedError { code, message, next }` on a refusal (`payment_required` or `limit_reached`, with `next` the page that fixes it), and throws `ReceiptPostError` when the check cannot be completed. To refuse the call, rethrow it as `new LeafError({ code: e.code, message: e.message, status: 402, next: e.next })`.
131
+ `ctx.caller.payer` is the principal charged for the call, `user:<id>` or `app:<id>`: the token's `payer` claim, or `sub` when the token has none. `ctx.meter` stamps it on the receipt. Before a priced call, `await ctx.checkSpend()` asks the directory (`POST <auth.issuer>/v1/billing/check`, sending the request's outbound token) whether that payer may spend on this command (it posts `{ token, tool }`, `tool` being the command path above) and keeps the price rows it answers for `ctx.meter`; it reserves nothing and resolves with `{ prices }` (every row of the group's price, `[price]` when the directory answers only `price`, empty when unpriced). It needs `receipts.ledger: { clientId, privateKey, keyId? }`, the same credentials you pass to `postReceipt`, and throws a plain `Error` without them or without a verified caller. It resolves when the call may go ahead, throws `SpendRefusedError { code, message, next }` on a refusal (`payment_required` or `limit_reached`, with `next` the page that fixes it), and throws `ReceiptPostError` when the check cannot be completed. To refuse the call, rethrow it as `new LeafError({ code: e.code, message: e.message, status: 402, next: e.next })`.
132
132
 
133
133
  To answer a rate limit, throw a `LeafError` with `retryAfter` (seconds, or a `Date`): `throw new LeafError({ code: 'rate_limited', status: 429, message: 'Slow down.', retryAfter: 30 })` answers 429 with `Retry-After: 30`. `headers: { 'X-RateLimit-Reset': '…' }` sets any other response header; `Content-Type`, `Content-Length`, `Content-Encoding`, `Transfer-Encoding` and `Crtr-Receipt` belong to the kit. For a side-effect leaf the kit passes the headers to `requests.store` as `answer.headers` (lowercase names); a store that keeps and returns them makes a repeated request answer with the same headers.
134
134
 
135
- For side-effect leaves, provide `requests: { record, read, store, delete }`. `record(requestId, identity)` atomically inserts both the id and `{sub, grantee}` from the verified caller (or `null` for a legacy static-token plugin); `read(requestId)` returns `{identity, recordedAt, answer}`. The kit refuses a repeated id from a different caller rather than replaying another person's result. `store` saves the result and receipt transactionally with the outbox. For provider logging, `onAnswer(event)` receives one metadata-only event per answered leaf POST (principal-chain fields, request/run ids, relative tool, status, duration, receipt id, replay flag); it never receives bearer tokens, arguments, or result bodies, and a logging failure does not alter the answer. `createCallerVerifier(auth)` is exported for providers that verify requests outside the Fetch handler.
135
+ For side-effect leaves, provide `requests: { record, read, store, delete }`. `record(requestId, identity)` atomically inserts both the id and `{sub, grantee}` from the verified caller (or `null` for a legacy static-token plugin); `read(requestId)` returns `{identity, recordedAt, answer}`. The kit refuses a repeated id from a different caller rather than replaying another person's result. `store` saves the result and receipt transactionally with the outbox. `answer.receipt` is the call's first receipt, as always; when a call metered more than one, `answer.receipts` also lists all of them (first included) and a store must save and return it from `read` (replay rebuilds `Crtr-Receipt` from `receipts` when present, else `receipt`). An unrecorded request saves each receipt with its own `outbox.save` call. `onError` gets `(error, path, receipt, receipts?)` and `onAnswer` gets `receiptIds` under the same rule. For provider logging, `onAnswer(event)` receives one metadata-only event per answered leaf POST (principal-chain fields, request/run ids, relative tool, status, duration, receipt id, replay flag); it never receives bearer tokens, arguments, or result bodies, and a logging failure does not alter the answer. `createCallerVerifier(auth)` is exported for providers that verify requests outside the Fetch handler.
136
136
 
137
137
  ## Reference
138
138
 
package/dist/define.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { CrtrCaller } from './caller.js';
2
2
  import type { OutField, Output } from './fields.js';
3
3
  import type { LeafErrorQuestion } from './errors.js';
4
- import type { Receipt } from './receipts.js';
4
+ import type { Receipt, SpendPrice } from './receipts.js';
5
5
  import type { AnyParam, Input } from './params.js';
6
6
  /** Thrown by `definePlugin` when a declaration is malformed, before anything is served. */
7
7
  export declare class PluginDefinitionError extends Error {
@@ -55,24 +55,30 @@ export interface LeafContext {
55
55
  require(question: LeafErrorQuestion): Promise<string>;
56
56
  };
57
57
  /**
58
- * Records the cost of this call once, including when the leaf later fails. The receipt's
59
- * `usd_equivalent` is `usdEquivalent` when given; otherwise `units` × the unit price that this
60
- * request's `checkSpend()` answered, for a unit-priced tool; otherwise 0. The directory owns every
61
- * price and recomputes the charge itself, so this figure is the cost shown to the runtime only.
58
+ * Records the cost of this call: once for each distinct `unit`, including when the leaf later
59
+ * fails; a repeated unit throws. `receiptId` names the receipt (default: the request id); several
60
+ * receipts in one call need distinct ids. The receipt's `usd_equivalent` is `usdEquivalent` when
61
+ * given; otherwise `units` × the price row this request's `checkSpend()` answered whose `unit`
62
+ * matches; otherwise 0. The directory owns every price and recomputes the charge itself, so this
63
+ * figure is the cost shown to the runtime only. One receipt rides on `Crtr-Receipt` as an object,
64
+ * several as a JSON array.
62
65
  */
63
66
  readonly meter: (usage: {
64
67
  units: number;
65
68
  unit: string;
66
69
  usdEquivalent?: number;
70
+ receiptId?: string;
67
71
  }) => Receipt;
68
72
  /**
69
73
  * Asks the directory, before a priced call, whether `caller.payer` may spend on this command
70
- * (it sends the command path after the plugin name as `tool`). Resolves when it may and
71
- * reserves nothing; keeps the price the directory answered for `ctx.meter`. Throws `SpendRefusedError` when the directory refuses (HTTP 402) and
74
+ * (it sends the command path after the plugin name as `tool`). Resolves with the group's price
75
+ * rows (`prices`, empty when unpriced) and reserves nothing; keeps them for `ctx.meter`. Throws `SpendRefusedError` when the directory refuses (HTTP 402) and
72
76
  * `ReceiptPostError` when the check cannot be completed. Throws an `Error` when the leaf has no
73
77
  * verified caller or the handler has no `receipts` (with `receipts.ledger`).
74
78
  */
75
- readonly checkSpend: () => Promise<void>;
79
+ readonly checkSpend: () => Promise<{
80
+ readonly prices: readonly SpendPrice[];
81
+ }>;
76
82
  }
77
83
  /** One command an agent can invoke, as returned by `defineLeaf` or `defineStreamingLeaf`. */
78
84
  export interface LeafNode {
@@ -33,7 +33,7 @@ export interface ReceiptOptions {
33
33
  readonly ledger?: LedgerCredentials;
34
34
  }
35
35
  /**
36
- * The directory's current price for the checked tool's group, carried by an `ok` check answer.
36
+ * One of the directory's current prices for the checked tool's group, carried by an `ok` check answer.
37
37
  * The directory owns every price: the kit only uses this to show a unit-mode cost on the receipt.
38
38
  */
39
39
  export interface SpendPrice {
@@ -48,7 +48,9 @@ export interface SpendPrice {
48
48
  /** The directory's answer to a spend check that allowed the call. */
49
49
  export interface SpendCheckAnswer {
50
50
  readonly status: string;
51
- /** Present when the tool's group is priced. */
51
+ /** Every price row of the tool's group: empty when the group is unpriced, `[price]` when the answer carries only `price`. */
52
+ readonly prices: readonly SpendPrice[];
53
+ /** Present when the tool's group has exactly one price row. */
52
54
  readonly price?: SpendPrice;
53
55
  }
54
56
  export declare class ReceiptPostError extends Error {
@@ -76,7 +78,7 @@ export declare function postReceipt(receipt: Receipt, ledger: {
76
78
  /**
77
79
  * Asks the directory whether the caller whose outbound token this is may start a call to `tool`
78
80
  * (the command path after the plugin name, e.g. `search`). Resolves with the answer on 200 (its
79
- * `price` when the tool's group is priced), throws `SpendRefusedError` on 402 and `ReceiptPostError`
81
+ * `prices` when the tool's group is priced), throws `SpendRefusedError` on 402 and `ReceiptPostError`
80
82
  * on any other failure. The directory reserves nothing; the raw `token` goes to
81
83
  * `<issuer>/v1/billing/check` and nowhere else.
82
84
  */
package/dist/receipts.js CHANGED
@@ -1 +1 @@
1
- var b=Object.defineProperty;var i=(t,n)=>b(t,"name",{value:n,configurable:!0});class c extends Error{static{i(this,"ReceiptPostError")}permanent;status;constructor(n,r,e){super(n),this.permanent=r,this.status=e,this.name="ReceiptPostError"}}class A extends Error{static{i(this,"SpendRefusedError")}code;next;constructor(n,r,e){super(r),this.code=n,this.next=e,this.name="SpendRefusedError"}}async function C(t,n){const r=await m(n);let e;try{e=await fetch(n.url,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(o){throw new c(`Could not post receipt: ${String(o)}`,!1)}if(!e.ok)throw new c(`Ledger receipt request failed: HTTP ${e.status}`,l(e.status),e.status)}i(C,"postReceipt");async function m(t,n){const r=new URL("/token",t.url),e=await T(t,r.href);let o;try{o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:e}),...n===void 0?{}:{signal:n}})}catch(a){throw new c(`Could not obtain a ledger token: ${String(a)}`,!1)}if(!o.ok)throw new c(`Ledger token request failed: HTTP ${o.status}`,l(o.status),o.status);let u;try{u=(await o.json()).access_token}catch{throw new c("Ledger token response was not JSON",!1)}if(typeof u!="string"||u.length===0)throw new c("Ledger token response has no access_token",!1);return u}i(m,"ledgerToken");async function $(t,n,r,e){const o=AbortSignal.timeout(1e4),u=await m({...e,url:t},o);let a;try{a=await fetch(`${t.replace(/\/+$/,"")}/v1/billing/check`,{method:"POST",headers:{Authorization:`Bearer ${u}`,"Content-Type":"application/json"},body:JSON.stringify({token:n,tool:r}),signal:o})}catch(s){throw new c(`Could not reach the billing check: ${String(s)}`,!1)}if(a.ok)return x(await a.json().catch(()=>{}));if(a.status===402){let s;try{s=(await a.json()).error}catch{}throw typeof s?.code=="string"&&typeof s.message=="string"?new A(s.code,s.message,typeof s.details?.next=="string"?s.details.next:""):new c("Billing check answered 402 without a code and message",!0,402)}throw new c(`Billing check request failed: HTTP ${a.status}`,l(a.status),a.status)}i($,"requestSpendCheck");function x(t){const n=typeof t=="object"&&t!==null?t:{},r=typeof n.status=="string"?n.status:"ok",e=n.price;return typeof e!="object"||e===null||typeof e.max_usd_per_call!="number"?{status:r}:e.mode==="reported"?{status:r,price:{mode:"reported",unit:null,usd_per_unit:null,max_usd_per_call:e.max_usd_per_call}}:e.mode==="unit"&&typeof e.unit=="string"&&typeof e.usd_per_unit=="number"&&Number.isFinite(e.usd_per_unit)&&e.usd_per_unit>=0?{status:r,price:{mode:"unit",unit:e.unit,usd_per_unit:e.usd_per_unit,max_usd_per_call:e.max_usd_per_call}}:{status:r}}i(x,"parseSpendAnswer");async function T(t,n){const{privateKey:r}=t,e=typeof r=="string";let o=!e&&r.kty==="RSA"?"RS256":"ES256";if(!e&&r.kty!=="RSA"&&r.kty!=="EC")throw new c("Ledger private key must be an ES256 or RS256 PEM or JWK",!0);const u={name:"ECDSA",namedCurve:"P-256"},a={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};let s;try{if(e){const p=/^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/.exec(r);if(!p)throw new Error("Expected a PKCS#8 PEM private key");const y=Uint8Array.from(atob(p[1].replace(/\s/g,"")),E=>E.charCodeAt(0));try{s=await crypto.subtle.importKey("pkcs8",y,u,!1,["sign"])}catch{o="RS256",s=await crypto.subtle.importKey("pkcs8",y,a,!1,["sign"])}}else{if(r.alg!==void 0&&r.alg!==o)throw new Error(`JWK alg must be ${o}`);s=await crypto.subtle.importKey("jwk",r,o==="ES256"?u:a,!1,["sign"])}}catch(p){throw new c(`Invalid ledger private key: ${String(p)}`,!0)}const d=Math.floor(Date.now()/1e3),h=i(p=>g(new TextEncoder().encode(JSON.stringify(p))),"encode"),f=t.keyId??(e?void 0:r.kid),S=h({alg:o,typ:"JWT",...f?{kid:f}:{}}),_=h({iss:t.clientId,sub:t.clientId,aud:n,iat:d,exp:d+60,jti:crypto.randomUUID()}),w=`${S}.${_}`,k=await crypto.subtle.sign(o==="ES256"?{name:"ECDSA",hash:"SHA-256"}:"RSASSA-PKCS1-v1_5",s,new TextEncoder().encode(w));return`${w}.${g(new Uint8Array(k))}`}i(T,"clientAssertion");function g(t){let n="";for(const r of t)n+=String.fromCharCode(r);return btoa(n).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}i(g,"base64url");function l(t){return t>=400&&t<500&&t!==408&&t!==429}i(l,"isPermanent");export{c as ReceiptPostError,A as SpendRefusedError,C as postReceipt,$ as requestSpendCheck};
1
+ var A=Object.defineProperty;var i=(t,e)=>A(t,"name",{value:e,configurable:!0});class u extends Error{static{i(this,"ReceiptPostError")}permanent;status;constructor(e,r,s){super(e),this.permanent=r,this.status=s,this.name="ReceiptPostError"}}class b extends Error{static{i(this,"SpendRefusedError")}code;next;constructor(e,r,s){super(r),this.code=e,this.next=s,this.name="SpendRefusedError"}}async function $(t,e){const r=await g(e);let s;try{s=await fetch(e.url,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(t)})}catch(n){throw new u(`Could not post receipt: ${String(n)}`,!1)}if(!s.ok)throw new u(`Ledger receipt request failed: HTTP ${s.status}`,l(s.status),s.status)}i($,"postReceipt");async function g(t,e){const r=new URL("/token",t.url),s=await P(t,r.href);let n;try{n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_assertion_type:"urn:ietf:params:oauth:client-assertion-type:jwt-bearer",client_assertion:s}),...e===void 0?{}:{signal:e}})}catch(a){throw new u(`Could not obtain a ledger token: ${String(a)}`,!1)}if(!n.ok)throw new u(`Ledger token request failed: HTTP ${n.status}`,l(n.status),n.status);let c;try{c=(await n.json()).access_token}catch{throw new u("Ledger token response was not JSON",!1)}if(typeof c!="string"||c.length===0)throw new u("Ledger token response has no access_token",!1);return c}i(g,"ledgerToken");async function R(t,e,r,s){const n=AbortSignal.timeout(1e4),c=await g({...s,url:t},n);let a;try{a=await fetch(`${t.replace(/\/+$/,"")}/v1/billing/check`,{method:"POST",headers:{Authorization:`Bearer ${c}`,"Content-Type":"application/json"},body:JSON.stringify({token:e,tool:r}),signal:n})}catch(o){throw new u(`Could not reach the billing check: ${String(o)}`,!1)}if(a.ok)return x(await a.json().catch(()=>{}));if(a.status===402){let o;try{o=(await a.json()).error}catch{}throw typeof o?.code=="string"&&typeof o.message=="string"?new b(o.code,o.message,typeof o.details?.next=="string"?o.details.next:""):new u("Billing check answered 402 without a code and message",!0,402)}throw new u(`Billing check request failed: HTTP ${a.status}`,l(a.status),a.status)}i(R,"requestSpendCheck");function x(t){const e=typeof t=="object"&&t!==null?t:{},r=typeof e.status=="string"?e.status:"ok",n=(Array.isArray(e.prices)?e.prices:[e.price]).flatMap(c=>T(c)??[]);return{status:r,prices:n,...n.length===1?{price:n[0]}:{}}}i(x,"parseSpendAnswer");function T(t){const e=t;if(!(typeof e!="object"||e===null||typeof e.max_usd_per_call!="number")){if(e.mode==="reported")return{mode:"reported",unit:null,usd_per_unit:null,max_usd_per_call:e.max_usd_per_call};if(e.mode==="unit"&&typeof e.unit=="string"&&typeof e.usd_per_unit=="number"&&Number.isFinite(e.usd_per_unit)&&e.usd_per_unit>=0)return{mode:"unit",unit:e.unit,usd_per_unit:e.usd_per_unit,max_usd_per_call:e.max_usd_per_call}}}i(T,"parseSpendPrice");async function P(t,e){const{privateKey:r}=t,s=typeof r=="string";let n=!s&&r.kty==="RSA"?"RS256":"ES256";if(!s&&r.kty!=="RSA"&&r.kty!=="EC")throw new u("Ledger private key must be an ES256 or RS256 PEM or JWK",!0);const c={name:"ECDSA",namedCurve:"P-256"},a={name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"};let o;try{if(s){const p=/^-----BEGIN PRIVATE KEY-----\s*([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----\s*$/.exec(r);if(!p)throw new Error("Expected a PKCS#8 PEM private key");const y=Uint8Array.from(atob(p[1].replace(/\s/g,"")),E=>E.charCodeAt(0));try{o=await crypto.subtle.importKey("pkcs8",y,c,!1,["sign"])}catch{n="RS256",o=await crypto.subtle.importKey("pkcs8",y,a,!1,["sign"])}}else{if(r.alg!==void 0&&r.alg!==n)throw new Error(`JWK alg must be ${n}`);o=await crypto.subtle.importKey("jwk",r,n==="ES256"?c:a,!1,["sign"])}}catch(p){throw new u(`Invalid ledger private key: ${String(p)}`,!0)}const d=Math.floor(Date.now()/1e3),f=i(p=>m(new TextEncoder().encode(JSON.stringify(p))),"encode"),h=t.keyId??(s?void 0:r.kid),S=f({alg:n,typ:"JWT",...h?{kid:h}:{}}),_=f({iss:t.clientId,sub:t.clientId,aud:e,iat:d,exp:d+60,jti:crypto.randomUUID()}),w=`${S}.${_}`,k=await crypto.subtle.sign(n==="ES256"?{name:"ECDSA",hash:"SHA-256"}:"RSASSA-PKCS1-v1_5",o,new TextEncoder().encode(w));return`${w}.${m(new Uint8Array(k))}`}i(P,"clientAssertion");function m(t){let e="";for(const r of t)e+=String.fromCharCode(r);return btoa(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}i(m,"base64url");function l(t){return t>=400&&t<500&&t!==408&&t!==429}i(l,"isPermanent");export{u as ReceiptPostError,b as SpendRefusedError,$ as postReceipt,R as requestSpendCheck};
package/dist/serve.d.ts CHANGED
@@ -18,7 +18,7 @@ export interface FetchHandlerOptions {
18
18
  */
19
19
  readonly baseUrl?: string;
20
20
  /** Receives an unhandled leaf exception before a 500 response is returned. */
21
- readonly onError?: (error: unknown, commandPath: readonly string[], receipt?: Receipt) => void;
21
+ readonly onError?: (error: unknown, commandPath: readonly string[], receipt?: Receipt, receipts?: readonly Receipt[]) => void;
22
22
  readonly receipts?: ReceiptOptions;
23
23
  readonly requests?: RequestStore;
24
24
  /** One metadata-only event for each answered, recognized leaf POST; exceptions are ignored. */
@@ -40,28 +40,34 @@ export interface LeafAnswerEvent {
40
40
  readonly tool: string;
41
41
  readonly status: number;
42
42
  readonly durationMs: number;
43
+ /** The first receipt's id. */
43
44
  readonly receiptId?: string;
45
+ /** Every receipt's id; set only when the call metered more than one. */
46
+ readonly receiptIds?: string[];
44
47
  readonly replayed: boolean;
45
48
  }
49
+ /**
50
+ * The answer a store keeps. `receipt` is the call's first receipt, exactly as when a call meters
51
+ * one. `receipts` is set only when the call metered more than one and then lists all of them,
52
+ * the first included; a store that keeps it must return it from `read`. Replay rebuilds
53
+ * `Crtr-Receipt` from `receipts` when present, else from `receipt`.
54
+ */
55
+ interface StoredRequestAnswer {
56
+ status: number;
57
+ body: string;
58
+ receipt?: Receipt;
59
+ receipts?: readonly Receipt[];
60
+ headers?: Record<string, string>;
61
+ }
46
62
  /** Persistence is owned by the provider, including an atomic answer + receipt outbox write. */
47
63
  export interface RequestStore {
48
64
  /** Persist the identity atomically with the request id. False means that id already exists. */
49
65
  record(requestId: string, identity: RequestIdentity): Promise<boolean>;
50
- store(requestId: string, answer: {
51
- status: number;
52
- body: string;
53
- receipt?: Receipt;
54
- headers?: Record<string, string>;
55
- }): Promise<void>;
66
+ store(requestId: string, answer: StoredRequestAnswer): Promise<void>;
56
67
  read(requestId: string): Promise<{
57
68
  identity: RequestIdentity;
58
69
  recordedAt: Date | string | number;
59
- answer: {
60
- status: number;
61
- body: string;
62
- receipt?: Receipt;
63
- headers?: Record<string, string>;
64
- } | null;
70
+ answer: StoredRequestAnswer | null;
65
71
  } | null>;
66
72
  delete(requestId: string): Promise<void>;
67
73
  }
package/dist/serve.js CHANGED
@@ -1,3 +1,3 @@
1
- var Z=Object.defineProperty;var c=(n,e)=>Z(n,"name",{value:e,configurable:!0});import{approvalFor as K}from"./approval.js";import{requestSpendCheck as Q}from"./receipts.js";import{validateDeclaredResult as X}from"@north-light/api/command-manifest";import{errorResponse as $,LeafError as _,leafErrorResponse as P,storedAnswerHeaders as Y}from"./errors.js";import{buildCommandManifest as ee}from"./manifest.js";import{buildBundle as ne}from"./bundle.js";import{parseCrtrCaller as te}from"./caller.js";import{createCallerVerifier as re,normalizeProviderId as ie,scopeMissing as oe}from"./verify.js";const D=/^v([1-9][0-9]*)$/;function Re(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:ie(e.auth),t=Array.isArray(n)||n.version!==void 0,r=se(Array.isArray(n)?n:[n],Array.isArray(n),i),o=r[0].plugin.name;for(const u of r)for(const g of u.commands.values())if(g.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${g.path.join(" ")}`);const f=e.auth===void 0?void 0:re(e.auth);if(f!==void 0){for(const u of r)for(const g of u.commands.values())if(g.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${g.path.join(" ")} has none`)}const d=new Map,k=e.baseUrl===void 0?void 0:J(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${o} is serving without bearer authentication`);const p=c(async(u,g,O)=>{const s=`${g.version}\0${O}`;let l=d.get(s);if(l===void 0){const A=await ne(g.plugin,{mountPath:O,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:A.tar,etag:A.etag},d.set(s,l)}const w={ETag:l.etag};return u.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:w}):new Response(new Uint8Array(l.tar).buffer,{headers:{...w,"Content-Type":"application/x-tar"}})},"archiveResponse");return async u=>{if(u.method!=="POST"&&e.token!==void 0&&!W(u.headers.get("authorization")??"",`Bearer ${e.token}`))return $(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const g=new URL(u.url).pathname;if(u.method==="GET"){if(!t)return p(u,h,k??J(g));const m=U(g),S=m[m.length-1],R=k??J(`/${m.slice(0,-1).join("/")}`);if(S==="versions")return Response.json({latest:h.version,supported:r.map(b=>b.version)});const x=S===void 0?null:D.exec(S),I=x===null?void 0:r.find(b=>b.version===Number(x[1]));return I===void 0?F():p(u,I,`${R}/v${I.version}`)}if(u.method!=="POST")return F();const O=performance.now();let s,l,w,A=!1,M=!1;const E=c(m=>{if(l!==void 0)try{e.onAnswer?.({...s===void 0?{}:{sub:s.sub,grantee:s.grantee,initiatingApp:s.initiatingApp,act:s.act,jti:s.jti,requestId:s.requestId,...s.runId===void 0?{}:{runId:s.runId}},...s===void 0&&y!==null&&y!==""?{requestId:y}:{},tool:l.path.slice(1).join(" "),status:m.status,durationMs:performance.now()-O,...w===void 0?{}:{receiptId:w.receipt_id},replayed:M})}catch{}return m},"answer");let y=u.headers.get("crtr-request-id");try{if(l=t?fe(r,g):ue(h.commands,g),e.token!==void 0&&!W(u.headers.get("authorization")??"",`Bearer ${e.token}`))return E($(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const m=f===void 0?void 0:await f(u);if(l===void 0)return F();if(m!==void 0&&!m.scope.includes(l.scope)){s=Object.freeze({...m,requestId:y??"",...u.headers.get("crtr-run-id")?{runId:u.headers.get("crtr-run-id")}:{}});const a=l.leaf.group,v=i===void 0&&a!==void 0?m.scope.find(j=>j.endsWith(`:${a}`)&&j.length>a.length+1)?.slice(0,-(a.length+1)):void 0;throw oe(l.scope,v)}if(m!==void 0){if(y===null||y==="")return E($(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=u.headers.get("crtr-run-id"),v=te(u.headers.get("crtr-caller"));s=Object.freeze({...m,requestId:y,...a!==null&&a!==""?{runId:a}:{},...Object.keys(v).length>0?{crtr:Object.freeze(v)}:{}})}const S=await le(u,l.manifest,m!==void 0);if(l.leaf.sideEffect){if(y===null||y==="")return E($(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const a=s===void 0?null:{sub:s.sub,grantee:s.grantee};if(!await e.requests.record(y,a)){M=!0;const j=await ae(e.requests,y,a,l.plugin.timeouts?.requestMs??3e4);if(j!==!0){const B=j.headers.get("Crtr-Receipt");if(B!==null)try{w=JSON.parse(B)}catch{}return E(j)}M=!1}A=!0}const R=l;let x;const I={request:u,...s!==void 0?{caller:s}:{},approval:K(u),meter(a){if(s===void 0)throw new Error("ctx.meter needs an authenticated caller");if(w!==void 0)throw new Error("ctx.meter may be called only once");if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const v=R.path.slice(1).join(" "),j=a.usdEquivalent??(x?.mode==="unit"&&x.usd_per_unit!==null?a.units*x.usd_per_unit:0);return w={receipt_id:s.requestId,provider:e.receipts.provider,tool:v,sub:s.sub,grantee:s.grantee,payer:s.payer,units:a.units,unit:a.unit,usd_equivalent:j,request_id:s.requestId,...s.runId!==void 0?{run_id:s.runId}:{},time:new Date().toISOString()},w},async checkSpend(){if(s===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const a=/^Bearer ([^\s]+)$/.exec(u.headers.get("authorization")??"")?.[1];if(a===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");x=(await Q(e.auth.issuer,a,R.path.slice(1).join(" "),e.receipts.ledger)).price}};let b,H;try{const a=await l.leaf.run(S,I);b=l.leaf.streaming?await we(a,e.onError,l.path):pe(a,l.manifest)}catch(a){a instanceof _?(b=P(a),H=a.headers):(q(e.onError,a,l.path),b=T(a))}if(A&&b.status===403&&await de(b))return await e.requests.delete(y),E(G(b,w));try{if(A)await e.requests.store(y,{status:b.status,body:await b.clone().text(),...H!==void 0?{headers:{...H}}:{},...w!==void 0?{receipt:w}:{}});else if(w!==void 0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);await e.receipts.outbox.save(w)}}catch(a){return q(e.onError,a,l.path,w),E(T(a))}return E(G(b,w))}catch(m){return m instanceof _?E(P(m)):(q(e.onError,m,l?.path??[]),E(T(m)))}}}c(Re,"createFetchHandler");function T(n){return $(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}c(T,"handlerFailed");function G(n,e){if(e===void 0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",JSON.stringify(e)),new Response(n.body,{status:n.status,headers:i})}c(G,"responseWithReceipt");async function de(n){try{const e=await n.clone().json();return z(e)&&z(e.error)&&e.error.code==="approval_required"}catch{return!1}}c(de,"isApprovalRequired");async function ae(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return $(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const o=Y(r.answer.headers);return o.set("Content-Type","application/json"),r.answer.receipt!==void 0&&o.set("Crtr-Receipt",JSON.stringify(r.answer.receipt)),new Response(r.answer.body,{status:r.answer.status,headers:o})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return T(new Error("The earlier request has no stored answer."));await new Promise(o=>setTimeout(o,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}c(ae,"replay");function se(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const o of n){if(o.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${o.name}`);if(e&&o.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const f=o.version??1;if(r.has(f))throw new Error(`createFetchHandler got two definitions of ${t} major ${f}`);r.set(f,{version:f,plugin:o,commands:ce(o,i)})}return[...r.values()].sort((o,f)=>o.version-f.version)}c(se,"servedMajors");function ce(n,e){const t=ee(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return L(t.children,n.commands,[t.name],n,r,e),r}c(ce,"commandMap");function L(n,e,i,t,r,o){const f=Object.entries(e);if(n.length!==f.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[d,[k,h]]of f.entries()){const p=n[d];if(p===void 0||p.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${k}`);const u=[...i,p.name];if(p.kind==="branch"&&h.kind==="branch"){L(p.children,h.children,u,t,r,o);continue}if(p.kind==="leaf"&&h.kind==="leaf"){r.set(u.join("/"),{path:u,leaf:h,plugin:t,manifest:p,...h.group!==void 0?{scope:`${o??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${k}`)}}c(L,"collectCommands");function ue(n,e){const i=U(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}c(ue,"findCommand");function fe(n,e){const i=U(e);for(let t=i.length-2;t>=0;t-=1){const r=D.exec(i[t]);if(r===null)continue;const f=n.find(d=>d.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(f!==void 0)return f}}c(fe,"findVersionedCommand");function U(n){return n.split("/").filter(e=>e.length>0)}c(U,"pathSegments");async function le(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const d=JSON.parse(t);if(!z(d))throw new Error("not an object");r=d}catch{throw N("Request body must be a JSON object.",i?"body":void 0,i,t)}const o=new Map(e.params.map(d=>[d.name,d]));for(const d of Object.keys(r))if(!o.has(d))throw i?N(`Unknown parameter ${d}.`,d,!0,r[d]):new _({code:"unknown_parameter",message:`Unknown parameter ${d}.`,field:d});const f={};for(const d of e.params){if(!Object.hasOwn(r,d.name)){if(d.required)throw N(`Missing required parameter ${d.name}.`,d.name,i,null);continue}const k=r[d.name],h=he(k,d);if(h===void 0)throw N(`Invalid value for parameter ${d.name}.`,d.name,i,k);f[ge(d.name)]=h}return f}c(le,"decodeInput");function he(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>V(t,e));return i.some(t=>t===void 0)?void 0:i}return V(n,e)}c(he,"decodeParameter");function V(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?me(n):n}}c(V,"decodeScalar");function me(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}c(me,"decodeBase64");function pe(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw C("result")}if(!z(t))throw C("result");const r=X(e.output,t);if(r!==null)throw C(r.field,r.receivedType);for(const o of Object.keys(t))if(!e.output.some(f=>f.name===o))throw C(o);return new Response(i,{headers:{"Content-Type":"application/json"}})}c(pe,"resultResponse");async function we(n,e,i){if(!ye(n))throw C("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,o=await t.next();let f=o.done,d=f?void 0:r.encode(`${JSON.stringify(o.value)}
2
- `);const k=new ReadableStream({async pull(h){if(d!==void 0){h.enqueue(d),d=void 0;return}if(f){h.close();return}try{const p=await t.next();p.done?(f=!0,h.close()):h.enqueue(r.encode(`${JSON.stringify(p.value)}
3
- `))}catch(p){q(e,p,i),h.error(p)}},async cancel(h){await t.return?.(h)}});return new Response(k,{headers:{"Content-Type":"application/x-ndjson"}})}c(we,"streamResponse");function q(n,e,i,t){try{n?.(e,i,t)}catch{}}c(q,"reportUnhandledError");function C(n,e){return new _({code:"handler_output_invalid",message:`Handler returned an invalid value for ${n}.`,status:500,field:n,...e!==void 0?{received:e}:{}})}c(C,"outputInvalid");function N(n,e,i=!1,t){return new _({code:i?"invalid_argument":"invalid_input",message:n,...e!==void 0?{field:e}:{},...i?{received:t}:{}})}c(N,"invalidInput");function F(){return $(404,{code:"no_such_command",message:"No command matches this request."})}c(F,"noSuchCommand");function J(n){return n==="/"?"":n.replace(/\/+$/,"")}c(J,"mountPath");function ge(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}c(ge,"camel");function W(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let o=0;o<Math.min(i.length,t.length);o+=1)r|=i[o]^t[o];return r===0}c(W,"constantTimeEqual");function z(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}c(z,"isRecord");function ye(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}c(ye,"isAsyncIterable");export{Re as createFetchHandler};
1
+ var Y=Object.defineProperty;var s=(n,e)=>Y(n,"name",{value:e,configurable:!0});import{approvalFor as ee}from"./approval.js";import{requestSpendCheck as ne}from"./receipts.js";import{validateDeclaredResult as te}from"@north-light/api/command-manifest";import{errorResponse as A,LeafError as O,leafErrorResponse as L,storedAnswerHeaders as re}from"./errors.js";import{buildCommandManifest as ie}from"./manifest.js";import{buildBundle as oe}from"./bundle.js";import{parseCrtrCaller as de}from"./caller.js";import{createCallerVerifier as ae,normalizeProviderId as se,scopeMissing as ce}from"./verify.js";const V=/^v([1-9][0-9]*)$/;function Oe(n,e={}){if(e.token!==void 0&&e.auth!==void 0)throw new Error("createFetchHandler takes either token or auth, not both");if(e.token!==void 0&&e.receipts!==void 0)throw new Error("createFetchHandler cannot meter with a static token");if(e.receipts!==void 0&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(e.receipts.provider))throw new Error("createFetchHandler receipts.provider must be an app principal (app:<id>)");const i=e.auth===void 0?void 0:se(e.auth),t=Array.isArray(n)||n.version!==void 0,r=le(Array.isArray(n)?n:[n],Array.isArray(n),i),d=r[0].plugin.name;for(const f of r)for(const g of f.commands.values())if(g.leaf.sideEffect&&e.requests===void 0)throw new Error(`createFetchHandler needs requests for side-effect leaf ${g.path.join(" ")}`);const u=e.auth===void 0?void 0:ae(e.auth);if(u!==void 0){for(const f of r)for(const g of f.commands.values())if(g.scope===void 0)throw new Error(`createFetchHandler auth needs a group on every leaf; ${g.path.join(" ")} has none`)}const a=new Map,k=e.baseUrl===void 0?void 0:D(new URL(e.baseUrl).pathname),h=r[r.length-1];e.token===void 0&&e.auth===void 0&&console.warn(`crouter plugin ${d} is serving without bearer authentication`);const w=s(async(f,g,q)=>{const c=`${g.version}\0${q}`;let l=a.get(c);if(l===void 0){const I=await oe(g.plugin,{mountPath:q,...i!==void 0?{providerId:i}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{}});l={tar:I.tar,etag:I.etag},a.set(c,l)}const m={ETag:l.etag};return f.headers.get("if-none-match")===l.etag?new Response(null,{status:304,headers:m}):new Response(new Uint8Array(l.tar).buffer,{headers:{...m,"Content-Type":"application/x-tar"}})},"archiveResponse");return async f=>{if(f.method!=="POST"&&e.token!==void 0&&!X(f.headers.get("authorization")??"",`Bearer ${e.token}`))return A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."});const g=new URL(f.url).pathname;if(f.method==="GET"){if(!t)return w(f,h,k??D(g));const p=J(g),$=p[p.length-1],R=k??D(`/${p.slice(0,-1).join("/")}`);if($==="versions")return Response.json({latest:h.version,supported:r.map(v=>v.version)});const z=$===void 0?null:V.exec($),b=z===null?void 0:r.find(v=>v.version===Number(z[1]));return b===void 0?P():w(f,b,`${R}/v${b.version}`)}if(f.method!=="POST")return P();const q=performance.now();let c,l;const m=[];let I=[],F=!1,B=!1;const E=s(p=>{if(l!==void 0)try{e.onAnswer?.({...c===void 0?{}:{sub:c.sub,grantee:c.grantee,initiatingApp:c.initiatingApp,act:c.act,jti:c.jti,requestId:c.requestId,...c.runId===void 0?{}:{runId:c.runId}},...c===void 0&&y!==null&&y!==""?{requestId:y}:{},tool:l.path.slice(1).join(" "),status:p.status,durationMs:performance.now()-q,...m.length===0?{}:{receiptId:m[0].receipt_id},...m.length>1?{receiptIds:m.map($=>$.receipt_id)}:{},replayed:B})}catch{}return p},"answer");let y=f.headers.get("crtr-request-id");try{if(l=t?pe(r,g):me(h.commands,g),e.token!==void 0&&!X(f.headers.get("authorization")??"",`Bearer ${e.token}`))return E(A(401,{code:"unauthorized",message:"A valid bearer token is required.",next:"Send Authorization: Bearer <token>."}));const p=u===void 0?void 0:await u(f);if(l===void 0)return P();if(p!==void 0&&!p.scope.includes(l.scope)){c=Object.freeze({...p,requestId:y??"",...f.headers.get("crtr-run-id")?{runId:f.headers.get("crtr-run-id")}:{}});const o=l.leaf.group,x=i===void 0&&o!==void 0?p.scope.find(j=>j.endsWith(`:${o}`)&&j.length>o.length+1)?.slice(0,-(o.length+1)):void 0;throw ce(l.scope,x)}if(p!==void 0){if(y===null||y==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=f.headers.get("crtr-run-id"),x=de(f.headers.get("crtr-caller"));c=Object.freeze({...p,requestId:y,...o!==null&&o!==""?{runId:o}:{},...Object.keys(x).length>0?{crtr:Object.freeze(x)}:{}})}const $=await we(f,l.manifest,p!==void 0);if(l.leaf.sideEffect){if(y===null||y==="")return E(A(400,{code:"invalid_request",message:"The request carries no Crtr-Request-Id header."}));const o=c===void 0?null:{sub:c.sub,grantee:c.grantee};if(!await e.requests.record(y,o)){B=!0;const j=await fe(e.requests,y,o,l.plugin.timeouts?.requestMs??3e4);if(j!==!0){const _=j.headers.get("Crtr-Receipt");if(_!==null)try{const C=JSON.parse(_);m.push(...Array.isArray(C)?C:[C])}catch{}return E(j)}B=!1}F=!0}const R=l,z={request:f,...c!==void 0?{caller:c}:{},approval:ee(f),meter(o){if(c===void 0)throw new Error("ctx.meter needs an authenticated caller");if(m.some(S=>S.unit===o.unit))throw new Error(`ctx.meter may be called only once for unit ${o.unit}`);if(e.receipts===void 0)throw new Error("ctx.meter needs receipts with a provider and outbox");const x=o.receiptId??c.requestId;if(m.some(S=>S.receipt_id===x))throw new Error(`ctx.meter needs a distinct receiptId for each unit; ${x} is taken`);const j=R.path.slice(1).join(" "),_=I.find(S=>S.mode==="unit"&&S.unit===o.unit),C=o.usdEquivalent??(_?.usd_per_unit!=null?o.units*_.usd_per_unit:0),G={receipt_id:x,provider:e.receipts.provider,tool:j,sub:c.sub,grantee:c.grantee,payer:c.payer,units:o.units,unit:o.unit,usd_equivalent:C,request_id:c.requestId,...c.runId!==void 0?{run_id:c.runId}:{},time:new Date().toISOString()};return m.push(G),G},async checkSpend(){if(c===void 0)throw new Error("ctx.checkSpend needs an authenticated caller");if(e.receipts===void 0)throw new Error("ctx.checkSpend needs receipts with a provider and outbox");if(e.receipts.ledger===void 0)throw new Error("ctx.checkSpend needs receipts.ledger (the provider's directory client credentials)");const o=/^Bearer ([^\s]+)$/.exec(f.headers.get("authorization")??"")?.[1];if(o===void 0)throw new Error("ctx.checkSpend needs the request's bearer token");return I=(await ne(e.auth.issuer,o,R.path.slice(1).join(" "),e.receipts.ledger)).prices,{prices:I}}};let b,v;try{const o=await l.leaf.run($,z);b=l.leaf.streaming?await ke(o,e.onError,l.path):be(o,l.manifest)}catch(o){o instanceof O?(b=L(o),v=o.headers):(M(e.onError,o,l.path),b=H(o))}if(F&&b.status===403&&await ue(b))return await e.requests.delete(y),E(W(b,m));try{if(F)await e.requests.store(y,{status:b.status,body:await b.clone().text(),...v!==void 0?{headers:{...v}}:{},...m.length>0?{receipt:m[0]}:{},...m.length>1?{receipts:[...m]}:{}});else if(m.length>0){if(e.receipts===void 0)throw new Error(`No receipt outbox for ${R.path.join(" ")}`);for(const o of m)await e.receipts.outbox.save(o)}}catch(o){return M(e.onError,o,l.path,m),E(H(o))}return E(W(b,m))}catch(p){return p instanceof O?E(L(p)):(M(e.onError,p,l?.path??[]),E(H(p)))}}}s(Oe,"createFetchHandler");function H(n){return A(500,{code:"handler_failed",message:n instanceof Error?n.message:String(n)})}s(H,"handlerFailed");function W(n,e){if(e.length===0)return n;const i=new Headers(n.headers);return i.set("Crtr-Receipt",Z(e)),new Response(n.body,{status:n.status,headers:i})}s(W,"responseWithReceipts");function Z(n){return JSON.stringify(n.length===1?n[0]:n)}s(Z,"receiptHeader");async function ue(n){try{const e=await n.clone().json();return U(e)&&U(e.error)&&e.error.code==="approval_required"}catch{return!1}}s(ue,"isApprovalRequired");async function fe(n,e,i,t){for(;;){const r=await n.read(e);if(r===null){if(await n.record(e,i))return!0;continue}if(r.identity?.sub!==i?.sub||r.identity?.grantee!==i?.grantee)return A(403,{code:"provider_refused",message:"This request id belongs to a different caller."});if(r.answer!==null){const d=re(r.answer.headers);d.set("Content-Type","application/json");const u=r.answer.receipts??(r.answer.receipt===void 0?[]:[r.answer.receipt]);return u.length>0&&d.set("Crtr-Receipt",Z(u)),new Response(r.answer.body,{status:r.answer.status,headers:d})}if(Date.now()>=new Date(r.recordedAt).getTime()+t)return H(new Error("The earlier request has no stored answer."));await new Promise(d=>setTimeout(d,Math.min(25,Math.max(1,new Date(r.recordedAt).getTime()+t-Date.now()))))}}s(fe,"replay");function le(n,e,i){if(n.length===0)throw new Error("createFetchHandler needs at least one plugin definition");const t=n[0].name,r=new Map;for(const d of n){if(d.name!==t)throw new Error(`createFetchHandler serves one plugin; got ${t} and ${d.name}`);if(e&&d.version===void 0)throw new Error(`createFetchHandler needs an explicit version on every definition in an array; ${t} has none`);const u=d.version??1;if(r.has(u))throw new Error(`createFetchHandler got two definitions of ${t} major ${u}`);r.set(u,{version:u,plugin:d,commands:he(d,i)})}return[...r.values()].sort((d,u)=>d.version-u.version)}s(le,"servedMajors");function he(n,e){const t=ie(n,{mountPath:""}).mounts[0]?.node;if(t===void 0||t.kind!=="branch")throw new Error("Generated plugin manifest has no root branch");const r=new Map;return K(t.children,n.commands,[t.name],n,r,e),r}s(he,"commandMap");function K(n,e,i,t,r,d){const u=Object.entries(e);if(n.length!==u.length)throw new Error("Generated plugin manifest does not match the command definition");for(const[a,[k,h]]of u.entries()){const w=n[a];if(w===void 0||w.kind!==h.kind)throw new Error(`Generated plugin manifest does not match command ${k}`);const f=[...i,w.name];if(w.kind==="branch"&&h.kind==="branch"){K(w.children,h.children,f,t,r,d);continue}if(w.kind==="leaf"&&h.kind==="leaf"){r.set(f.join("/"),{path:f,leaf:h,plugin:t,manifest:w,...h.group!==void 0?{scope:`${d??t.name}:${h.group}`}:{}});continue}throw new Error(`Generated plugin manifest does not match command ${k}`)}}s(K,"collectCommands");function me(n,e){const i=J(e);for(let t=0;t<i.length;t+=1){const r=n.get(i.slice(t).join("/"));if(r!==void 0)return r}}s(me,"findCommand");function pe(n,e){const i=J(e);for(let t=i.length-2;t>=0;t-=1){const r=V.exec(i[t]);if(r===null)continue;const u=n.find(a=>a.version===Number(r[1]))?.commands.get(i.slice(t+1).join("/"));if(u!==void 0)return u}}s(pe,"findVersionedCommand");function J(n){return n.split("/").filter(e=>e.length>0)}s(J,"pathSegments");async function we(n,e,i){const t=n.body===null?"":await n.text();let r;if(t.length===0)r={};else try{const a=JSON.parse(t);if(!U(a))throw new Error("not an object");r=a}catch{throw N("Request body must be a JSON object.",i?"body":void 0,i,t)}const d=new Map(e.params.map(a=>[a.name,a]));for(const a of Object.keys(r))if(!d.has(a))throw i?N(`Unknown parameter ${a}.`,a,!0,r[a]):new O({code:"unknown_parameter",message:`Unknown parameter ${a}.`,field:a});const u={};for(const a of e.params){if(!Object.hasOwn(r,a.name)){if(a.required)throw N(`Missing required parameter ${a.name}.`,a.name,i,null);continue}const k=r[a.name],h=ge(k,a);if(h===void 0)throw N(`Invalid value for parameter ${a.name}.`,a.name,i,k);u[Ee(a.name)]=h}return u}s(we,"decodeInput");function ge(n,e){if(e.kind!=="stdin"&&e.kind!=="context-file"&&e.repeatable){if(!Array.isArray(n))return;const i=n.map(t=>Q(t,e));return i.some(t=>t===void 0)?void 0:i}return Q(n,e)}s(ge,"decodeParameter");function Q(n,e){if(e.kind==="stdin"||e.kind==="positional")return typeof n=="string"?n:void 0;if(e.kind!=="context-file"){if(e.type==="string")return typeof n=="string"?n:void 0;if(e.type==="int")return typeof n=="number"&&Number.isInteger(n)?n:void 0;if(e.type==="bool")return typeof n=="boolean"?n:void 0;if(e.type==="enum")return typeof n=="string"&&Array.isArray(e.choices)&&e.choices.includes(n)?n:void 0;if(e.type==="file")return typeof n=="string"?n:void 0;if(e.type==="path")return typeof n!="string"?void 0:e.encoding==="base64"?ye(n):n}}s(Q,"decodeScalar");function ye(n){if(!(!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4!==0))try{const e=atob(n);return Uint8Array.from(e,i=>i.charCodeAt(0))}catch{return}}s(ye,"decodeBase64");function be(n,e){let i,t;try{i=JSON.stringify(n),t=JSON.parse(i)}catch{throw T("result")}if(!U(t))throw T("result");const r=te(e.output,t);if(r!==null)throw T(r.field,r.receivedType);for(const d of Object.keys(t))if(!e.output.some(u=>u.name===d))throw T(d);return new Response(i,{headers:{"Content-Type":"application/json"}})}s(be,"resultResponse");async function ke(n,e,i){if(!xe(n))throw T("result");const t=n[Symbol.asyncIterator](),r=new TextEncoder,d=await t.next();let u=d.done,a=u?void 0:r.encode(`${JSON.stringify(d.value)}
2
+ `);const k=new ReadableStream({async pull(h){if(a!==void 0){h.enqueue(a),a=void 0;return}if(u){h.close();return}try{const w=await t.next();w.done?(u=!0,h.close()):h.enqueue(r.encode(`${JSON.stringify(w.value)}
3
+ `))}catch(w){M(e,w,i),h.error(w)}},async cancel(h){await t.return?.(h)}});return new Response(k,{headers:{"Content-Type":"application/x-ndjson"}})}s(ke,"streamResponse");function M(n,e,i,t=[]){try{t.length>1?n?.(e,i,t[0],t):n?.(e,i,t[0])}catch{}}s(M,"reportUnhandledError");function T(n,e){return new O({code:"handler_output_invalid",message:`Handler returned an invalid value for ${n}.`,status:500,field:n,...e!==void 0?{received:e}:{}})}s(T,"outputInvalid");function N(n,e,i=!1,t){return new O({code:i?"invalid_argument":"invalid_input",message:n,...e!==void 0?{field:e}:{},...i?{received:t}:{}})}s(N,"invalidInput");function P(){return A(404,{code:"no_such_command",message:"No command matches this request."})}s(P,"noSuchCommand");function D(n){return n==="/"?"":n.replace(/\/+$/,"")}s(D,"mountPath");function Ee(n){return n.replace(/-([a-z])/g,(e,i)=>i.toUpperCase())}s(Ee,"camel");function X(n,e){const i=new TextEncoder().encode(n),t=new TextEncoder().encode(e);let r=i.length^t.length;for(let d=0;d<Math.min(i.length,t.length);d+=1)r|=i[d]^t[d];return r===0}s(X,"constantTimeEqual");function U(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}s(U,"isRecord");function xe(n){return typeof n=="object"&&n!==null&&Symbol.asyncIterator in n}s(xe,"isAsyncIterable");export{Oe as createFetchHandler};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.497",
3
+ "version": "0.3.499",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -23,8 +23,8 @@
23
23
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
24
24
  },
25
25
  "dependencies": {
26
- "@north-light/api": "0.3.497",
27
- "@north-light/identity": "0.3.497"
26
+ "@north-light/api": "0.3.499",
27
+ "@north-light/identity": "0.3.499"
28
28
  },
29
29
  "license": "UNLICENSED",
30
30
  "publishConfig": {