eve 0.27.0 → 0.27.2
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/CHANGELOG.md +31 -0
- package/dist/src/channel/resolve-active-session.d.ts +4 -0
- package/dist/src/channel/resolve-active-session.js +1 -0
- package/dist/src/channel/routes.d.ts +11 -0
- package/dist/src/chunks/{use-eve-agent-PMY2WkAt.js → use-eve-agent-CbF0l_Fp.js} +66 -27
- package/dist/src/chunks/{use-eve-agent-AeQLLhu9.js → use-eve-agent-CgxB9WQv.js} +66 -27
- package/dist/src/cli/dev/tui/vercel-trusted-sources-policy.d.ts +1 -1
- package/dist/src/cli/dev/tui/vercel-trusted-sources.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/open-stream.d.ts +15 -2
- package/dist/src/client/open-stream.js +1 -1
- package/dist/src/client/session.d.ts +3 -2
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +32 -0
- package/dist/src/compiled/.vendor-stamp.json +16 -16
- package/dist/src/compiled/@ai-sdk/anthropic/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/google/index.d.ts +9 -2
- package/dist/src/compiled/@ai-sdk/google/index.js +6 -6
- package/dist/src/compiled/@ai-sdk/mcp/index.d.ts +18 -3
- package/dist/src/compiled/@ai-sdk/mcp/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/openai/index.d.ts +285 -24
- package/dist/src/compiled/@ai-sdk/openai/index.js +2 -2
- package/dist/src/compiled/@ai-sdk/otel/index.js +1 -1
- package/dist/src/compiled/@ai-sdk/provider-utils/index.d.ts +7 -3
- package/dist/src/compiled/@vercel/oidc/index.js +28 -2
- package/dist/src/compiled/@vercel/sandbox/api-client/api-client.d.ts +11 -0
- package/dist/src/compiled/@vercel/sandbox/api-client/validators.d.ts +7 -0
- package/dist/src/compiled/@vercel/sandbox/command.d.ts +8 -0
- package/dist/src/compiled/@vercel/sandbox/execution-context.d.ts +116 -0
- package/dist/src/compiled/@vercel/sandbox/index.d.ts +3 -1
- package/dist/src/compiled/@vercel/sandbox/index.js +20 -19
- package/dist/src/compiled/@vercel/sandbox/network-policy.d.ts +13 -5
- package/dist/src/compiled/@vercel/sandbox/sandbox-user.d.ts +212 -0
- package/dist/src/compiled/@vercel/sandbox/sandbox.d.ts +133 -2
- package/dist/src/compiled/@vercel/sandbox/session.d.ts +2 -1
- package/dist/src/compiled/@vercel/sandbox/snapshot.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/create-hook.d.ts +41 -22
- package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +29 -0
- package/dist/src/compiled/@workflow/core/global.d.ts +2 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/private.d.ts +6 -17
- package/dist/src/compiled/@workflow/core/private.js +1 -1
- package/dist/src/compiled/@workflow/core/replay-payload-cache.d.ts +56 -0
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +11 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +6 -4
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +4 -1
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +39 -0
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/serialization.d.ts +44 -4
- package/dist/src/compiled/@workflow/core/symbols.d.ts +13 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/error-codes.d.ts +2 -0
- package/dist/src/compiled/@workflow/errors/index.d.ts +14 -0
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/events.d.ts +15 -0
- package/dist/src/compiled/@workflow/world/hooks.d.ts +2 -1
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +77 -4
- package/dist/src/compiled/@workflow/world-local/index.js +4 -4
- package/dist/src/compiled/@workflow/world-vercel/index.js +16 -16
- package/dist/src/compiled/_chunks/node/{auth-BuQkq4Gr.js → auth-l7F2PF2b.js} +2 -2
- package/dist/src/compiled/_chunks/node/{version-DD-FX9rK.js → version-CjHTLx2a.js} +1 -1
- package/dist/src/compiled/_chunks/node/virtual-loader-Cwgujv7l.js +1 -0
- package/dist/src/compiled/_chunks/workflow/attribute-changes-Dk1fP6vt.js +20 -0
- package/dist/src/compiled/_chunks/workflow/{chunk-BHKSVoKr.js → chunk-BTyA9uPd.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/dist-B3qkUnLJ.js +3 -0
- package/dist/src/compiled/_chunks/workflow/{dist-CSfKNxQW.js → dist-BX517Nmz.js} +2 -2
- package/dist/src/compiled/_chunks/workflow/{dist-zLevmMyU.js → dist-C_VDTghO.js} +10 -10
- package/dist/src/compiled/_chunks/workflow/{dist-CttsoN4D.js → dist-CrxV2rsR.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{functions-PT9ri9Hu.js → functions-Dv8dc_-I.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/resume-hook-czpG5xnP.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-6zaMjFY6.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-B2u06FWc.js +1 -0
- package/dist/src/compiled/_chunks/workflow/{src-CQuMexnO.js → src-D1EltLDA.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{token-CaY0nA5J.js → token-Cz223z3C.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/token-DWqA5-DA.js +1 -0
- package/dist/src/compiled/_chunks/workflow/token-util-B6qBs3-0.js +27 -0
- package/dist/src/compiled/_chunks/workflow/{undici-fb54XL8i.js → undici-C2ZhYnV9.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/wrapper-Cc2otuUR.js +6 -0
- package/dist/src/compiled/env-runner/index.js +1 -1
- package/dist/src/compiled/env-runner/node-worker.js +1 -1
- package/dist/src/compiled/eventsource-parser/stream/index.d.ts +16 -3
- package/dist/src/compiled/jose/index.js +1 -1
- package/dist/src/compiler/compile-from-memory.d.ts +5 -0
- package/dist/src/compiler/compile-from-memory.js +1 -1
- package/dist/src/compiler/extension-compatibility.d.ts +10 -10
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/execution/deliver-payloads.d.ts +1 -1
- package/dist/src/execution/deliver-payloads.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/session-limit-continuation.d.ts +8 -0
- package/dist/src/harness/session-limit-continuation.js +1 -1
- package/dist/src/harness/session-limit-enforcement.d.ts +9 -6
- package/dist/src/harness/session-limit-enforcement.js +1 -1
- package/dist/src/harness/stale-input-responses.d.ts +21 -3
- package/dist/src/harness/stale-input-responses.js +2 -2
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/turn-cancellation.d.ts +13 -0
- package/dist/src/harness/turn-cancellation.js +1 -1
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-module-evaluation-error.d.ts +2 -0
- package/dist/src/internal/authored-module-evaluation-error.js +4 -0
- package/dist/src/internal/authored-module-loader.js +2 -2
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/workflow-bundle/vercel-workflow-output.js +1 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/updateprojectblock.js +1 -0
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.8/node_modules/@vercel/sdk/esm/models/updateprojectprojectsbranchmatcher.js +1 -0
- package/dist/src/packages/eve-catalog/src/index.js +1 -1
- package/dist/src/public/channels/discord/defaults.js +1 -1
- package/dist/src/public/channels/eve.js +2 -1
- package/dist/src/public/channels/linear/api.d.ts +2 -0
- package/dist/src/public/channels/linear/api.js +3 -1
- package/dist/src/public/channels/linear/defaults.js +2 -2
- package/dist/src/public/channels/linear/hitl.d.ts +8 -13
- package/dist/src/public/channels/linear/hitl.js +3 -3
- package/dist/src/public/channels/linear/index.d.ts +1 -1
- package/dist/src/public/channels/linear/index.js +1 -1
- package/dist/src/public/channels/linear/linearChannel.js +1 -1
- package/dist/src/public/channels/slack/api.d.ts +46 -2
- package/dist/src/public/channels/slack/api.js +1 -1
- package/dist/src/public/channels/slack/attachments.d.ts +6 -5
- package/dist/src/public/channels/slack/defaults.js +1 -1
- package/dist/src/public/channels/slack/inbound.d.ts +31 -0
- package/dist/src/public/channels/slack/inbound.js +1 -1
- package/dist/src/public/channels/slack/index.d.ts +2 -2
- package/dist/src/public/channels/slack/interactions.d.ts +2 -1
- package/dist/src/public/channels/slack/interactions.js +1 -1
- package/dist/src/public/channels/slack/slackChannel.d.ts +118 -13
- package/dist/src/public/channels/slack/slackChannel.js +1 -1
- package/dist/src/public/channels/slack/thread.d.ts +4 -3
- package/dist/src/public/channels/slack/thread.js +1 -1
- package/dist/src/public/channels/teams/defaults.js +2 -2
- package/dist/src/public/channels/teams/index.d.ts +1 -1
- package/dist/src/public/channels/teams/teamsChannel.d.ts +7 -2
- package/dist/src/public/channels/teams/teamsChannel.js +1 -1
- package/dist/src/public/channels/telegram/defaults.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -1
- package/dist/src/setup/scaffold/create/add-to-project.js +1 -1
- package/dist/src/setup/scaffold/create/project.js +2 -2
- package/dist/src/setup/scaffold/create/web-template.d.ts +1 -1
- package/dist/src/setup/scaffold/create/web-template.js +90 -5
- package/dist/src/setup/scaffold/update/channels.js +2 -2
- package/dist/src/setup/scaffold/update/connections.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/agent-config.md +10 -5
- package/docs/channels/slack.mdx +115 -12
- package/docs/channels/teams.mdx +10 -3
- package/docs/guides/client/streaming.mdx +15 -0
- package/docs/guides/deployment/vercel.mdx +1 -1
- package/docs/guides/frontend/overview.mdx +2 -0
- package/package.json +22 -22
- package/dist/src/compiled/@workflow/core/step-hydration-cache.d.ts +0 -148
- package/dist/src/compiled/_chunks/node/virtual-loader-B8K8w9cr.js +0 -1
- package/dist/src/compiled/_chunks/workflow/attribute-changes-CXiYB8h9.js +0 -20
- package/dist/src/compiled/_chunks/workflow/dist-BYo8Gno2.js +0 -3
- package/dist/src/compiled/_chunks/workflow/resume-hook-CHXbXuRZ.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-BjtAGa3_.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-BJAv0MFP.js +0 -1
- package/dist/src/compiled/_chunks/workflow/token-D4VIwGlD.js +0 -1
- package/dist/src/compiled/_chunks/workflow/wrapper-ulTvoTdW.js +0 -6
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.1/node_modules/@vercel/sdk/esm/models/updateprojectprojectsaction.js +0 -1
- package/dist/src/node_modules/.pnpm/@vercel_sdk@1.28.1/node_modules/@vercel/sdk/esm/models/updateprojectprojectsoptionsallowlist.js +0 -1
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/lib/primitives.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/lib/schemas.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/models/aclaction.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/models/sdkvalidationerror.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/defaultToZeroValue.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/fp.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/primitives.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/rfcdate.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/smartUnion.js +0 -0
- /package/dist/src/node_modules/.pnpm/{@vercel_sdk@1.28.1 → @vercel_sdk@1.28.8}/node_modules/@vercel/sdk/esm/types/unrecognized.js +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as e}from"../_chunks/workflow/chunk-BHKSVoKr.js";const t=new TextEncoder,n=new TextDecoder,r=2**32;function i(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function a(e,t,n){if(t<0||t>=r)throw RangeError(`value must be >= 0 and <= ${r-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function o(e){let t=Math.floor(e/r),n=e%r,i=new Uint8Array(8);return a(i,t,0),a(i,n,4),i}function s(e){let t=new Uint8Array(4);return a(t,e),t}function c(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function l(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function u(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var d=e({decode:()=>f,encode:()=>p});function f(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:n.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=n.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return u(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function p(e){let n=e;return typeof n==`string`&&(n=t.encode(n)),Uint8Array.prototype.toBase64?n.toBase64({alphabet:`base64url`,omitPadding:!0}):l(n).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}const m=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),h=(e,t)=>e.name===t;function g(e){return parseInt(e.name.slice(4),10)}function _(e,t){if(g(e.hash)!==t)throw m(`SHA-${t}`,`algorithm.hash`)}function v(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function y(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ee(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!h(e.algorithm,`HMAC`))throw m(`HMAC`);_(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!h(e.algorithm,`RSASSA-PKCS1-v1_5`))throw m(`RSASSA-PKCS1-v1_5`);_(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!h(e.algorithm,`RSA-PSS`))throw m(`RSA-PSS`);_(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!h(e.algorithm,`Ed25519`))throw m(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!h(e.algorithm,t))throw m(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!h(e.algorithm,`ECDSA`))throw m(`ECDSA`);let n=v(t);if(e.algorithm.namedCurve!==n)throw m(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function b(e,t,n){switch(t){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!h(e.algorithm,`AES-GCM`))throw m(`AES-GCM`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!h(e.algorithm,`AES-KW`))throw m(`AES-KW`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:break;default:throw m(`ECDH or X25519`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!h(e.algorithm,`PBKDF2`))throw m(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(!h(e.algorithm,`RSA-OAEP`))throw m(`RSA-OAEP`);_(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function x(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const S=(e,...t)=>x(`Key must be `,e,...t),te=(e,t,...n)=>x(`Key for the ${e} algorithm must be `,t,...n);var ne=e({JOSEAlgNotAllowed:()=>ie,JOSEError:()=>C,JOSENotSupported:()=>T,JWEDecryptionFailed:()=>E,JWEInvalid:()=>D,JWKInvalid:()=>ae,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>ce,JWKSNoMatchingKey:()=>se,JWKSTimeout:()=>le,JWSInvalid:()=>O,JWSSignatureVerificationFailed:()=>ue,JWTClaimValidationFailed:()=>w,JWTExpired:()=>re,JWTInvalid:()=>k}),C=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},w=class extends C{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},re=class extends C{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ie=class extends C{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},T=class extends C{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},E=class extends C{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},D=class extends C{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},O=class extends C{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},k=class extends C{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},ae=class extends C{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},oe=class extends C{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},se=class extends C{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},ce=class extends C{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},le=class extends C{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},ue=class extends C{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function A(e){if(!j(e))throw Error(`CryptoKey instance expected`)}const j=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},de=e=>e?.[Symbol.toStringTag]===`KeyObject`,fe=e=>j(e)||de(e);function pe(e){switch(e){case`A128GCM`:return 128;case`A192GCM`:return 192;case`A256GCM`:case`A128CBC-HS256`:return 256;case`A192CBC-HS384`:return 384;case`A256CBC-HS512`:return 512;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const M=e=>crypto.getRandomValues(new Uint8Array(pe(e)>>3));function me(e,t){let n=e.byteLength<<3;if(n!==t)throw new D(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}function he(e){switch(e){case`A128GCM`:case`A128GCMKW`:case`A192GCM`:case`A192GCMKW`:case`A256GCM`:case`A256GCMKW`:return 96;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return 128;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const ge=e=>crypto.getRandomValues(new Uint8Array(he(e)>>3));function _e(e,t){if(t.length<<3!==he(e))throw new D(`Invalid Initialization Vector length`)}async function ve(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(S(t,`Uint8Array`));let r=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),macKey:await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),keySize:r}}async function ye(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function be(e,t,n,r,a){let{encKey:s,macKey:c,keySize:l}=await ve(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},s,t));return{ciphertext:u,tag:await ye(c,i(a,r,u,o(a.length<<3)),l),iv:r}}async function xe(e,t){if(!(e instanceof Uint8Array))throw TypeError(`First argument must be a buffer`);if(!(t instanceof Uint8Array))throw TypeError(`Second argument must be a buffer`);let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`]),i=new Uint8Array(await crypto.subtle.sign(n,r,e)),a=new Uint8Array(await crypto.subtle.sign(n,r,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return o===0}async function Se(e,t,n,r,a,s){let{encKey:c,macKey:l,keySize:u}=await ve(e,t,`decrypt`),d=await ye(l,i(s,r,n,o(s.length<<3)),u),f;try{f=await xe(a,d)}catch{}if(!f)throw new E;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}if(!p)throw new E;return p}async function Ce(e,t,n,r,i){let a;n instanceof Uint8Array?a=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`encrypt`]):(b(n,e,`encrypt`),a=n);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:r}}async function we(e,t,n,r,a,o){let s;t instanceof Uint8Array?s=await crypto.subtle.importKey(`raw`,t,`AES-GCM`,!1,[`decrypt`]):(b(t,e,`decrypt`),s=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:`AES-GCM`,tagLength:128},s,i(n,a)))}catch{throw new E}}const Te=`Unsupported JWE Content Encryption Algorithm`;async function Ee(e,t,n,r,i){if(!j(n)&&!(n instanceof Uint8Array))throw TypeError(S(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));switch(r?_e(e,r):r=ge(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(-3),10)),be(e,t,n,r,i);case`A128GCM`:case`A192GCM`:case`A256GCM`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(1,4),10)),Ce(e,t,n,r,i);default:throw new T(Te)}}async function De(e,t,n,r,i,a){if(!j(t)&&!(t instanceof Uint8Array))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new D(`JWE Initialization Vector missing`);if(!i)throw new D(`JWE Authentication Tag missing`);switch(_e(e,r),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(-3),10)),Se(e,t,n,r,i,a);case`A128GCM`:case`A192GCM`:case`A256GCM`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(1,4),10)),we(e,t,n,r,i,a);default:throw new T(Te)}}const Oe=Symbol();function N(e,t){if(e)throw TypeError(`${t} can only be called once`)}function P(e,t,n){try{return f(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}async function ke(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}const Ae=e=>typeof e==`object`&&!!e;function F(e){if(!Ae(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function I(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const L=e=>F(e)&&typeof e.kty==`string`,je=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Me=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Ne=e=>e.kty===`oct`&&typeof e.k==`string`;function Pe(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function Fe(e,t,n){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):(b(e,t,n),e)}async function Ie(e,t,n){let r=await Fe(t,e,`wrapKey`);Pe(r,e);let i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Le(e,t,n){let r=await Fe(t,e,`unwrapKey`);Pe(r,e);let i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Re(e){return i(s(e.length),e)}async function ze(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=new Uint8Array(4+e.length+n.length);r.set(s(t),0),r.set(e,4),r.set(n,4+e.length);let i=await ke(`sha256`,r);a.set(i,(t-1)*32)}return a.slice(0,r)}async function Be(e,t,n,r,a=new Uint8Array,o=new Uint8Array){b(e,`ECDH`),b(t,`ECDH`,`deriveBits`);let l=i(Re(c(n)),Re(a),Re(o),s(r),new Uint8Array);return ze(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,Ve(e))),r,l)}function Ve(e){return e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function He(e){switch(e.algorithm.namedCurve){case`P-256`:case`P-384`:case`P-521`:return!0;default:return e.algorithm.name===`X25519`}}function Ue(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(b(e,t,`deriveBits`),e)}const We=(e,t)=>i(c(e),Uint8Array.of(0),t);async function Ge(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new D(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new D(`PBES2 Count Input must be a positive integer`);let i=We(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Ue(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function Ke(e,t,n,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await Ge(i,e,r,t);return{encryptedKey:await Ie(e.slice(-6),a,n),p2c:r,p2s:p(i)}}async function qe(e,t,n,r,i){let a=await Ge(i,e,r,t);return Le(e.slice(-6),a,n)}function R(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Je(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ye(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return ee(t,e,n),t}async function Xe(e,t,n){let r=await Ye(e,t,`sign`);R(e,r);let i=await crypto.subtle.sign(Je(e,r.algorithm),r,n);return new Uint8Array(i)}async function Ze(e,t,n,r){let i=await Ye(e,t,`verify`);R(e,i);let a=Je(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Qe=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return`RSA-OAEP`;default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function $e(e,t,n){return b(t,e,`encrypt`),R(e,t),new Uint8Array(await crypto.subtle.encrypt(Qe(e),t,n))}async function et(e,t,n){return b(t,e,`decrypt`),R(e,t),new Uint8Array(await crypto.subtle.decrypt(Qe(e),t,n))}const z=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function tt(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new T(z)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new T(z)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;default:throw new T(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function B(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=tt(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const V=`given KeyObject instance cannot be used for this algorithm`;let H;const nt=async(e,t,n,r=!1)=>{H||=new WeakMap;let i=H.get(e);if(i?.[n])return i[n];let a=await B({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:H.set(e,{[n]:a}),a},rt=(e,t)=>{H||=new WeakMap;let n=H.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(V)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(V)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(V);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(V);return n?n[t]=a:H.set(e,{[t]:a}),a};async function U(e,t){if(e instanceof Uint8Array||j(e))return e;if(de(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return rt(e,t)}catch(e){if(e instanceof TypeError)throw e}return nt(e,e.export({format:`jwk`}),t)}if(L(e))return e.k?f(e.k):nt(e,e,t,!0);throw Error(`unreachable`)}const it=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join(`
|
|
1
|
+
import{r as e}from"../_chunks/workflow/chunk-BTyA9uPd.js";const t=new TextEncoder,n=new TextDecoder,r=2**32;function i(...e){let t=e.reduce((e,{length:t})=>e+t,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function a(e,t,n){if(t<0||t>=r)throw RangeError(`value must be >= 0 and <= ${r-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function o(e){let t=Math.floor(e/r),n=e%r,i=new Uint8Array(8);return a(i,t,0),a(i,n,4),i}function s(e){let t=new Uint8Array(4);return a(t,e),t}function c(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);if(r>127)throw TypeError(`non-ASCII string encountered in encode()`);t[n]=r}return t}function l(e){if(Uint8Array.prototype.toBase64)return e.toBase64();let t=32768,n=[];for(let r=0;r<e.length;r+=t)n.push(String.fromCharCode.apply(null,e.subarray(r,r+t)));return btoa(n.join(``))}function u(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(e);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var d=e({decode:()=>f,encode:()=>p});function f(e){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof e==`string`?e:n.decode(e),{alphabet:`base64url`});let t=e;t instanceof Uint8Array&&(t=n.decode(t)),t=t.replace(/-/g,`+`).replace(/_/g,`/`);try{return u(t)}catch{throw TypeError(`The input to be decoded is not correctly encoded.`)}}function p(e){let n=e;return typeof n==`string`&&(n=t.encode(n)),Uint8Array.prototype.toBase64?n.toBase64({alphabet:`base64url`,omitPadding:!0}):l(n).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`)}const m=(e,t=`algorithm.name`)=>TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`),h=(e,t)=>e.name===t;function g(e){return parseInt(e.name.slice(4),10)}function _(e,t){if(g(e.hash)!==t)throw m(`SHA-${t}`,`algorithm.hash`)}function v(e){switch(e){case`ES256`:return`P-256`;case`ES384`:return`P-384`;case`ES512`:return`P-521`;default:throw Error(`unreachable`)}}function y(e,t){if(t&&!e.usages.includes(t))throw TypeError(`CryptoKey does not support this operation, its usages must include ${t}.`)}function ee(e,t,n){switch(t){case`HS256`:case`HS384`:case`HS512`:if(!h(e.algorithm,`HMAC`))throw m(`HMAC`);_(e.algorithm,parseInt(t.slice(2),10));break;case`RS256`:case`RS384`:case`RS512`:if(!h(e.algorithm,`RSASSA-PKCS1-v1_5`))throw m(`RSASSA-PKCS1-v1_5`);_(e.algorithm,parseInt(t.slice(2),10));break;case`PS256`:case`PS384`:case`PS512`:if(!h(e.algorithm,`RSA-PSS`))throw m(`RSA-PSS`);_(e.algorithm,parseInt(t.slice(2),10));break;case`Ed25519`:case`EdDSA`:if(!h(e.algorithm,`Ed25519`))throw m(`Ed25519`);break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:if(!h(e.algorithm,t))throw m(t);break;case`ES256`:case`ES384`:case`ES512`:{if(!h(e.algorithm,`ECDSA`))throw m(`ECDSA`);let n=v(t);if(e.algorithm.namedCurve!==n)throw m(n,`algorithm.namedCurve`);break}default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function b(e,t,n){switch(t){case`A128GCM`:case`A192GCM`:case`A256GCM`:{if(!h(e.algorithm,`AES-GCM`))throw m(`AES-GCM`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`A128KW`:case`A192KW`:case`A256KW`:{if(!h(e.algorithm,`AES-KW`))throw m(`AES-KW`);let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw m(n,`algorithm.length`);break}case`ECDH`:switch(e.algorithm.name){case`ECDH`:case`X25519`:break;default:throw m(`ECDH or X25519`)}break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:if(!h(e.algorithm,`PBKDF2`))throw m(`PBKDF2`);break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:if(!h(e.algorithm,`RSA-OAEP`))throw m(`RSA-OAEP`);_(e.algorithm,parseInt(t.slice(9),10)||1);break;default:throw TypeError(`CryptoKey does not support this operation`)}y(e,n)}function x(e,t,...n){if(n=n.filter(Boolean),n.length>2){let t=n.pop();e+=`one of type ${n.join(`, `)}, or ${t}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t==`function`&&t.name?e+=` Received function ${t.name}`:typeof t==`object`&&t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}const S=(e,...t)=>x(`Key must be `,e,...t),te=(e,t,...n)=>x(`Key for the ${e} algorithm must be `,t,...n);var ne=e({JOSEAlgNotAllowed:()=>ie,JOSEError:()=>C,JOSENotSupported:()=>T,JWEDecryptionFailed:()=>E,JWEInvalid:()=>D,JWKInvalid:()=>ae,JWKSInvalid:()=>oe,JWKSMultipleMatchingKeys:()=>ce,JWKSNoMatchingKey:()=>se,JWKSTimeout:()=>le,JWSInvalid:()=>O,JWSSignatureVerificationFailed:()=>ue,JWTClaimValidationFailed:()=>w,JWTExpired:()=>re,JWTInvalid:()=>k}),C=class extends Error{static code=`ERR_JOSE_GENERIC`;code=`ERR_JOSE_GENERIC`;constructor(e,t){super(e,t),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}},w=class extends C{static code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;code=`ERR_JWT_CLAIM_VALIDATION_FAILED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},re=class extends C{static code=`ERR_JWT_EXPIRED`;code=`ERR_JWT_EXPIRED`;claim;reason;payload;constructor(e,t,n=`unspecified`,r=`unspecified`){super(e,{cause:{claim:n,reason:r,payload:t}}),this.claim=n,this.reason=r,this.payload=t}},ie=class extends C{static code=`ERR_JOSE_ALG_NOT_ALLOWED`;code=`ERR_JOSE_ALG_NOT_ALLOWED`},T=class extends C{static code=`ERR_JOSE_NOT_SUPPORTED`;code=`ERR_JOSE_NOT_SUPPORTED`},E=class extends C{static code=`ERR_JWE_DECRYPTION_FAILED`;code=`ERR_JWE_DECRYPTION_FAILED`;constructor(e=`decryption operation failed`,t){super(e,t)}},D=class extends C{static code=`ERR_JWE_INVALID`;code=`ERR_JWE_INVALID`},O=class extends C{static code=`ERR_JWS_INVALID`;code=`ERR_JWS_INVALID`},k=class extends C{static code=`ERR_JWT_INVALID`;code=`ERR_JWT_INVALID`},ae=class extends C{static code=`ERR_JWK_INVALID`;code=`ERR_JWK_INVALID`},oe=class extends C{static code=`ERR_JWKS_INVALID`;code=`ERR_JWKS_INVALID`},se=class extends C{static code=`ERR_JWKS_NO_MATCHING_KEY`;code=`ERR_JWKS_NO_MATCHING_KEY`;constructor(e=`no applicable key found in the JSON Web Key Set`,t){super(e,t)}},ce=class extends C{[Symbol.asyncIterator];static code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;code=`ERR_JWKS_MULTIPLE_MATCHING_KEYS`;constructor(e=`multiple matching keys found in the JSON Web Key Set`,t){super(e,t)}},le=class extends C{static code=`ERR_JWKS_TIMEOUT`;code=`ERR_JWKS_TIMEOUT`;constructor(e=`request timed out`,t){super(e,t)}},ue=class extends C{static code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;code=`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`;constructor(e=`signature verification failed`,t){super(e,t)}};function A(e){if(!j(e))throw Error(`CryptoKey instance expected`)}const j=e=>{if(e?.[Symbol.toStringTag]===`CryptoKey`)return!0;try{return e instanceof CryptoKey}catch{return!1}},de=e=>e?.[Symbol.toStringTag]===`KeyObject`,fe=e=>j(e)||de(e);function pe(e){switch(e){case`A128GCM`:return 128;case`A192GCM`:return 192;case`A256GCM`:case`A128CBC-HS256`:return 256;case`A192CBC-HS384`:return 384;case`A256CBC-HS512`:return 512;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const M=e=>crypto.getRandomValues(new Uint8Array(pe(e)>>3));function me(e,t){let n=e.byteLength<<3;if(n!==t)throw new D(`Invalid Content Encryption Key length. Expected ${t} bits, got ${n} bits`)}function he(e){switch(e){case`A128GCM`:case`A128GCMKW`:case`A192GCM`:case`A192GCMKW`:case`A256GCM`:case`A256GCMKW`:return 96;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return 128;default:throw new T(`Unsupported JWE Algorithm: ${e}`)}}const ge=e=>crypto.getRandomValues(new Uint8Array(he(e)>>3));function _e(e,t){if(t.length<<3!==he(e))throw new D(`Invalid Initialization Vector length`)}async function ve(e,t,n){if(!(t instanceof Uint8Array))throw TypeError(S(t,`Uint8Array`));let r=parseInt(e.slice(1,4),10);return{encKey:await crypto.subtle.importKey(`raw`,t.subarray(r>>3),`AES-CBC`,!1,[n]),macKey:await crypto.subtle.importKey(`raw`,t.subarray(0,r>>3),{hash:`SHA-${r<<1}`,name:`HMAC`},!1,[`sign`]),keySize:r}}async function ye(e,t,n){return new Uint8Array((await crypto.subtle.sign(`HMAC`,e,t)).slice(0,n>>3))}async function be(e,t,n,r,a){let{encKey:s,macKey:c,keySize:l}=await ve(e,n,`encrypt`),u=new Uint8Array(await crypto.subtle.encrypt({iv:r,name:`AES-CBC`},s,t));return{ciphertext:u,tag:await ye(c,i(a,r,u,o(a.length<<3)),l),iv:r}}async function xe(e,t){if(!(e instanceof Uint8Array))throw TypeError(`First argument must be a buffer`);if(!(t instanceof Uint8Array))throw TypeError(`Second argument must be a buffer`);let n={name:`HMAC`,hash:`SHA-256`},r=await crypto.subtle.generateKey(n,!1,[`sign`]),i=new Uint8Array(await crypto.subtle.sign(n,r,e)),a=new Uint8Array(await crypto.subtle.sign(n,r,t)),o=0,s=-1;for(;++s<32;)o|=i[s]^a[s];return o===0}async function Se(e,t,n,r,a,s){let{encKey:c,macKey:l,keySize:u}=await ve(e,t,`decrypt`),d=await ye(l,i(s,r,n,o(s.length<<3)),u),f;try{f=await xe(a,d)}catch{}if(!f)throw new E;let p;try{p=new Uint8Array(await crypto.subtle.decrypt({iv:r,name:`AES-CBC`},c,n))}catch{}if(!p)throw new E;return p}async function Ce(e,t,n,r,i){let a;n instanceof Uint8Array?a=await crypto.subtle.importKey(`raw`,n,`AES-GCM`,!1,[`encrypt`]):(b(n,e,`encrypt`),a=n);let o=new Uint8Array(await crypto.subtle.encrypt({additionalData:i,iv:r,name:`AES-GCM`,tagLength:128},a,t)),s=o.slice(-16);return{ciphertext:o.slice(0,-16),tag:s,iv:r}}async function we(e,t,n,r,a,o){let s;t instanceof Uint8Array?s=await crypto.subtle.importKey(`raw`,t,`AES-GCM`,!1,[`decrypt`]):(b(t,e,`decrypt`),s=t);try{return new Uint8Array(await crypto.subtle.decrypt({additionalData:o,iv:r,name:`AES-GCM`,tagLength:128},s,i(n,a)))}catch{throw new E}}const Te=`Unsupported JWE Content Encryption Algorithm`;async function Ee(e,t,n,r,i){if(!j(n)&&!(n instanceof Uint8Array))throw TypeError(S(n,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));switch(r?_e(e,r):r=ge(e),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(-3),10)),be(e,t,n,r,i);case`A128GCM`:case`A192GCM`:case`A256GCM`:return n instanceof Uint8Array&&me(n,parseInt(e.slice(1,4),10)),Ce(e,t,n,r,i);default:throw new T(Te)}}async function De(e,t,n,r,i,a){if(!j(t)&&!(t instanceof Uint8Array))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`Uint8Array`,`JSON Web Key`));if(!r)throw new D(`JWE Initialization Vector missing`);if(!i)throw new D(`JWE Authentication Tag missing`);switch(_e(e,r),e){case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(-3),10)),Se(e,t,n,r,i,a);case`A128GCM`:case`A192GCM`:case`A256GCM`:return t instanceof Uint8Array&&me(t,parseInt(e.slice(1,4),10)),we(e,t,n,r,i,a);default:throw new T(Te)}}const Oe=Symbol();function N(e,t){if(e)throw TypeError(`${t} can only be called once`)}function P(e,t,n){try{return f(e)}catch{throw new n(`Failed to base64url decode the ${t}`)}}async function ke(e,t){let n=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto.subtle.digest(n,t))}const Ae=e=>typeof e==`object`&&!!e;function F(e){if(!Ae(e)||Object.prototype.toString.call(e)!==`[object Object]`)return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function I(...e){let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let e of t){let t=Object.keys(e);if(!n||n.size===0){n=new Set(t);continue}for(let e of t){if(n.has(e))return!1;n.add(e)}}return!0}const L=e=>F(e)&&typeof e.kty==`string`,je=e=>e.kty!==`oct`&&(e.kty===`AKP`&&typeof e.priv==`string`||typeof e.d==`string`),Me=e=>e.kty!==`oct`&&e.d===void 0&&e.priv===void 0,Ne=e=>e.kty===`oct`&&typeof e.k==`string`;function Pe(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw TypeError(`Invalid key size for alg: ${t}`)}function Fe(e,t,n){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`AES-KW`,!0,[n]):(b(e,t,n),e)}async function Ie(e,t,n){let r=await Fe(t,e,`wrapKey`);Pe(r,e);let i=await crypto.subtle.importKey(`raw`,n,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.wrapKey(`raw`,i,r,`AES-KW`))}async function Le(e,t,n){let r=await Fe(t,e,`unwrapKey`);Pe(r,e);let i=await crypto.subtle.unwrapKey(`raw`,n,r,`AES-KW`,{hash:`SHA-256`,name:`HMAC`},!0,[`sign`]);return new Uint8Array(await crypto.subtle.exportKey(`raw`,i))}function Re(e){return i(s(e.length),e)}async function ze(e,t,n){let r=t>>3,i=Math.ceil(r/32),a=new Uint8Array(i*32);for(let t=1;t<=i;t++){let r=new Uint8Array(4+e.length+n.length);r.set(s(t),0),r.set(e,4),r.set(n,4+e.length);let i=await ke(`sha256`,r);a.set(i,(t-1)*32)}return a.slice(0,r)}async function Be(e,t,n,r,a=new Uint8Array,o=new Uint8Array){b(e,`ECDH`),b(t,`ECDH`,`deriveBits`);let l=i(Re(c(n)),Re(a),Re(o),s(r),new Uint8Array);return ze(new Uint8Array(await crypto.subtle.deriveBits({name:e.algorithm.name,public:e},t,Ve(e))),r,l)}function Ve(e){return e.algorithm.name===`X25519`?256:Math.ceil(parseInt(e.algorithm.namedCurve.slice(-3),10)/8)<<3}function He(e){switch(e.algorithm.namedCurve){case`P-256`:case`P-384`:case`P-521`:return!0;default:return e.algorithm.name===`X25519`}}function Ue(e,t){return e instanceof Uint8Array?crypto.subtle.importKey(`raw`,e,`PBKDF2`,!1,[`deriveBits`]):(b(e,t,`deriveBits`),e)}const We=(e,t)=>i(c(e),Uint8Array.of(0),t);async function Ge(e,t,n,r){if(!(e instanceof Uint8Array)||e.length<8)throw new D(`PBES2 Salt Input must be 8 or more octets`);if(!Number.isSafeInteger(n)||Math.sign(n)!==1)throw new D(`PBES2 Count Input must be a positive integer`);let i=We(t,e),a=parseInt(t.slice(13,16),10),o={hash:`SHA-${t.slice(8,11)}`,iterations:n,name:`PBKDF2`,salt:i},s=await Ue(r,t);return new Uint8Array(await crypto.subtle.deriveBits(o,s,a))}async function Ke(e,t,n,r=2048,i=crypto.getRandomValues(new Uint8Array(16))){let a=await Ge(i,e,r,t);return{encryptedKey:await Ie(e.slice(-6),a,n),p2c:r,p2s:p(i)}}async function qe(e,t,n,r,i){let a=await Ge(i,e,r,t);return Le(e.slice(-6),a,n)}function R(e,t){if(e.startsWith(`RS`)||e.startsWith(`PS`)){let{modulusLength:n}=t.algorithm;if(typeof n!=`number`||n<2048)throw TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}}function Je(e,t){let n=`SHA-${e.slice(-3)}`;switch(e){case`HS256`:case`HS384`:case`HS512`:return{hash:n,name:`HMAC`};case`PS256`:case`PS384`:case`PS512`:return{hash:n,name:`RSA-PSS`,saltLength:parseInt(e.slice(-3),10)>>3};case`RS256`:case`RS384`:case`RS512`:return{hash:n,name:`RSASSA-PKCS1-v1_5`};case`ES256`:case`ES384`:case`ES512`:return{hash:n,name:`ECDSA`,namedCurve:t.namedCurve};case`Ed25519`:case`EdDSA`:return{name:`Ed25519`};case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:return{name:e};default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Ye(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith(`HS`))throw TypeError(S(t,`CryptoKey`,`KeyObject`,`JSON Web Key`));return crypto.subtle.importKey(`raw`,t,{hash:`SHA-${e.slice(-3)}`,name:`HMAC`},!1,[n])}return ee(t,e,n),t}async function Xe(e,t,n){let r=await Ye(e,t,`sign`);R(e,r);let i=await crypto.subtle.sign(Je(e,r.algorithm),r,n);return new Uint8Array(i)}async function Ze(e,t,n,r){let i=await Ye(e,t,`verify`);R(e,i);let a=Je(e,i.algorithm);try{return await crypto.subtle.verify(a,i,n,r)}catch{return!1}}const Qe=e=>{switch(e){case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return`RSA-OAEP`;default:throw new T(`alg ${e} is not supported either by JOSE or your javascript runtime`)}};async function $e(e,t,n){return b(t,e,`encrypt`),R(e,t),new Uint8Array(await crypto.subtle.encrypt(Qe(e),t,n))}async function et(e,t,n){return b(t,e,`decrypt`),R(e,t),new Uint8Array(await crypto.subtle.decrypt(Qe(e),t,n))}const z=`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`;function tt(e){let t,n;switch(e.kty){case`AKP`:switch(e.alg){case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:t={name:e.alg},n=e.priv?[`sign`]:[`verify`];break;default:throw new T(z)}break;case`RSA`:switch(e.alg){case`PS256`:case`PS384`:case`PS512`:t={name:`RSA-PSS`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RS256`:case`RS384`:case`RS512`:t={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.alg.slice(-3)}`},n=e.d?[`sign`]:[`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:t={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},n=e.d?[`decrypt`,`unwrapKey`]:[`encrypt`,`wrapKey`];break;default:throw new T(z)}break;case`EC`:switch(e.alg){case`ES256`:case`ES384`:case`ES512`:t={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[e.alg]},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:`ECDH`,namedCurve:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;case`OKP`:switch(e.alg){case`Ed25519`:case`EdDSA`:t={name:`Ed25519`},n=e.d?[`sign`]:[`verify`];break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:t={name:e.crv},n=e.d?[`deriveBits`]:[];break;default:throw new T(z)}break;default:throw new T(`Invalid or unsupported JWK "kty" (Key Type) Parameter value`)}return{algorithm:t,keyUsages:n}}async function B(e){if(!e.alg)throw TypeError(`"alg" argument is required when "jwk.alg" is not present`);let{algorithm:t,keyUsages:n}=tt(e),r={...e};return r.kty!==`AKP`&&delete r.alg,delete r.use,crypto.subtle.importKey(`jwk`,r,t,e.ext??!(e.d||e.priv),e.key_ops??n)}const V=`given KeyObject instance cannot be used for this algorithm`;let H;const nt=async(e,t,n,r=!1)=>{H||=new WeakMap;let i=H.get(e);if(i?.[n])return i[n];let a=await B({...t,alg:n});return r&&Object.freeze(e),i?i[n]=a:H.set(e,{[n]:a}),a},rt=(e,t)=>{H||=new WeakMap;let n=H.get(e);if(n?.[t])return n[t];let r=e.type===`public`,i=!!r,a;if(e.asymmetricKeyType===`x25519`){switch(t){case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:break;default:throw TypeError(V)}a=e.toCryptoKey(e.asymmetricKeyType,i,r?[]:[`deriveBits`])}if(e.asymmetricKeyType===`ed25519`){if(t!==`EdDSA`&&t!==`Ed25519`)throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}switch(e.asymmetricKeyType){case`ml-dsa-44`:case`ml-dsa-65`:case`ml-dsa-87`:if(t!==e.asymmetricKeyType.toUpperCase())throw TypeError(V);a=e.toCryptoKey(e.asymmetricKeyType,i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`rsa`){let n;switch(t){case`RSA-OAEP`:n=`SHA-1`;break;case`RS256`:case`PS256`:case`RSA-OAEP-256`:n=`SHA-256`;break;case`RS384`:case`PS384`:case`RSA-OAEP-384`:n=`SHA-384`;break;case`RS512`:case`PS512`:case`RSA-OAEP-512`:n=`SHA-512`;break;default:throw TypeError(V)}if(t.startsWith(`RSA-OAEP`))return e.toCryptoKey({name:`RSA-OAEP`,hash:n},i,r?[`encrypt`]:[`decrypt`]);a=e.toCryptoKey({name:t.startsWith(`PS`)?`RSA-PSS`:`RSASSA-PKCS1-v1_5`,hash:n},i,[r?`verify`:`sign`])}if(e.asymmetricKeyType===`ec`){let n=new Map([[`prime256v1`,`P-256`],[`secp384r1`,`P-384`],[`secp521r1`,`P-521`]]).get(e.asymmetricKeyDetails?.namedCurve);if(!n)throw TypeError(V);let o={ES256:`P-256`,ES384:`P-384`,ES512:`P-521`};o[t]&&n===o[t]&&(a=e.toCryptoKey({name:`ECDSA`,namedCurve:n},i,[r?`verify`:`sign`])),t.startsWith(`ECDH-ES`)&&(a=e.toCryptoKey({name:`ECDH`,namedCurve:n},i,r?[]:[`deriveBits`]))}if(!a)throw TypeError(V);return n?n[t]=a:H.set(e,{[t]:a}),a};async function U(e,t){if(e instanceof Uint8Array||j(e))return e;if(de(e)){if(e.type===`secret`)return e.export();if(`toCryptoKey`in e&&typeof e.toCryptoKey==`function`)try{return rt(e,t)}catch(e){if(e instanceof TypeError)throw e}return nt(e,e.export({format:`jwk`}),t)}if(L(e))return e.k?f(e.k):nt(e,e,t,!0);throw Error(`unreachable`)}const it=(e,t)=>`-----BEGIN ${t}-----\n${(e.match(/.{1,64}/g)||[]).join(`
|
|
2
2
|
`)}\n-----END ${t}-----`,at=async(e,t,n)=>{if(de(n)){if(n.type!==e)throw TypeError(`key is not a ${e} key`);return n.export({format:`pem`,type:t})}if(!j(n))throw TypeError(S(n,`CryptoKey`,`KeyObject`));if(!n.extractable)throw TypeError(`CryptoKey is not extractable`);if(n.type!==e)throw TypeError(`key is not a ${e} key`);return it(l(new Uint8Array(await crypto.subtle.exportKey(t,n))),`${e.toUpperCase()} KEY`)},ot=e=>at(`public`,`spki`,e),st=e=>at(`private`,`pkcs8`,e),ct=(e,t)=>{if(e.byteLength!==t.length)return!1;for(let n=0;n<e.byteLength;n++)if(e[n]!==t[n])return!1;return!0},lt=e=>({data:e,pos:0}),W=e=>{let t=e.data[e.pos++];if(t&128){let n=t&127,r=0;for(let t=0;t<n;t++)r=r<<8|e.data[e.pos++];return r}return t},ut=(e,t=1)=>{if(t<=0)return;e.pos++;let n=W(e);e.pos+=n,t>1&&ut(e,t-1)},G=(e,t,n)=>{if(e.data[e.pos++]!==t)throw Error(n)},dt=(e,t)=>{let n=e.data.subarray(e.pos,e.pos+t);return e.pos+=t,n},ft=e=>(G(e,6,`Expected algorithm OID`),dt(e,W(e)));function pt(e){G(e,48,`Invalid PKCS#8 structure`),W(e),G(e,2,`Expected version field`);let t=W(e);e.pos+=t,G(e,48,`Expected algorithm identifier`);let n=W(e);return{algIdStart:e.pos,algIdLength:n}}function mt(e){G(e,48,`Invalid SPKI structure`),W(e),G(e,48,`Expected algorithm identifier`);let t=W(e);return{algIdStart:e.pos,algIdLength:t}}const ht=e=>{let t=ft(e);if(ct(t,[43,101,110]))return`X25519`;if(!ct(t,[42,134,72,206,61,2,1]))throw Error(`Unsupported key algorithm`);G(e,6,`Expected curve OID`);let n=dt(e,W(e));for(let{name:e,oid:t}of[{name:`P-256`,oid:[42,134,72,206,61,3,1,7]},{name:`P-384`,oid:[43,129,4,0,34]},{name:`P-521`,oid:[43,129,4,0,35]}])if(ct(n,t))return e;throw Error(`Unsupported named curve`)},gt=async(e,t,n,r)=>{let i,a,o=e===`spki`,s=()=>o?[`verify`]:[`sign`],c=()=>o?[`encrypt`,`wrapKey`]:[`decrypt`,`unwrapKey`];switch(n){case`PS256`:case`PS384`:case`PS512`:i={name:`RSA-PSS`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RS256`:case`RS384`:case`RS512`:i={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${n.slice(-3)}`},a=s();break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:i={name:`RSA-OAEP`,hash:`SHA-${parseInt(n.slice(-3),10)||1}`},a=c();break;case`ES256`:case`ES384`:case`ES512`:i={name:`ECDSA`,namedCurve:{ES256:`P-256`,ES384:`P-384`,ES512:`P-521`}[n]},a=s();break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:try{let e=r.getNamedCurve(t);i=e===`X25519`?{name:`X25519`}:{name:`ECDH`,namedCurve:e}}catch{throw new T(`Invalid or unsupported key format`)}a=o?[]:[`deriveBits`];break;case`Ed25519`:case`EdDSA`:i={name:`Ed25519`},a=s();break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:i={name:n},a=s();break;default:throw new T(`Invalid or unsupported "alg" (Algorithm) value`)}return crypto.subtle.importKey(e,t,i,r?.extractable??!!o,a)},_t=(e,t)=>u(e.replace(t,``)),vt=(e,t,n)=>{let r=_t(e,/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=lt(e);return pt(t),ht(t)}),gt(`pkcs8`,r,t,i)},yt=(e,t,n)=>{let r=_t(e,/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g),i=n;return t?.startsWith?.(`ECDH-ES`)&&(i||={},i.getNamedCurve=e=>{let t=lt(e);return mt(t),ht(t)}),gt(`spki`,r,t,i)};function bt(e){let t=lt(e);G(t,48,`Invalid certificate structure`),W(t),G(t,48,`Invalid tbsCertificate structure`),W(t),e[t.pos]===160?ut(t,6):ut(t,5);let n=t.pos;G(t,48,`Invalid SPKI structure`);let r=W(t);return e.subarray(n,n+r+(t.pos-n))}function xt(e){return bt(_t(e,/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g))}const St=(e,t,n)=>{let r;try{r=xt(e)}catch(e){throw TypeError(`Failed to parse the X.509 certificate`,{cause:e})}return yt(it(l(r),`PUBLIC KEY`),t,n)};async function Ct(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PUBLIC KEY-----`)!==0)throw TypeError(`"spki" must be SPKI formatted string`);return yt(e,t,n)}async function wt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN CERTIFICATE-----`)!==0)throw TypeError(`"x509" must be X.509 formatted string`);return St(e,t,n)}async function Tt(e,t,n){if(typeof e!=`string`||e.indexOf(`-----BEGIN PRIVATE KEY-----`)!==0)throw TypeError(`"pkcs8" must be PKCS#8 formatted string`);return vt(e,t,n)}async function Et(e,t,n){if(!F(e))throw TypeError(`JWK must be an object`);let r;switch(t??=e.alg,r??=n?.extractable??e.ext,e.kty){case`oct`:if(typeof e.k!=`string`||!e.k)throw TypeError(`missing "k" (Key Value) Parameter value`);return f(e.k);case`RSA`:if(`oth`in e&&e.oth!==void 0)throw new T(`RSA JWK "oth" (Other Primes Info) Parameter value is not supported`);return B({...e,alg:t,ext:r});case`AKP`:if(typeof e.alg!=`string`||!e.alg)throw TypeError(`missing "alg" (Algorithm) Parameter value`);if(t!==void 0&&t!==e.alg)throw TypeError(`JWK alg and alg option value mismatch`);return B({...e,ext:r});case`EC`:case`OKP`:return B({...e,alg:t,ext:r});default:throw new T(`Unsupported "kty" (Key Type) Parameter value`)}}async function Dt(e){if(de(e))if(e.type===`secret`)e=e.export();else return e.export({format:`jwk`});if(e instanceof Uint8Array)return{kty:`oct`,k:p(e)};if(!j(e))throw TypeError(S(e,`CryptoKey`,`KeyObject`,`Uint8Array`));if(!e.extractable)throw TypeError(`non-extractable CryptoKey cannot be exported as a JWK`);let{ext:t,key_ops:n,alg:r,use:i,...a}=await crypto.subtle.exportKey(`jwk`,e);return a.kty===`AKP`&&(a.alg=r),a}async function Ot(e){return ot(e)}async function kt(e){return st(e)}async function At(e){return Dt(e)}async function jt(e,t,n,r){let i=await Ee(e.slice(0,7),n,t,r,new Uint8Array);return{encryptedKey:i.ciphertext,iv:p(i.iv),tag:p(i.tag)}}async function Mt(e,t,n,r,i){return De(e.slice(0,7),t,n,r,i,new Uint8Array)}const Nt=`Invalid or unsupported "alg" (JWE Algorithm) header value`;function K(e){if(e===void 0)throw new D(`JWE Encrypted Key missing`)}async function Pt(e,t,n,r,i){switch(e){case`dir`:if(n!==void 0)throw new D(`Encountered unexpected JWE Encrypted Key`);return t;case`ECDH-ES`:if(n!==void 0)throw new D(`Encountered unexpected JWE Encrypted Key`);case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(!F(r.epk))throw new D(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);if(A(t),!He(t))throw new T(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let i=await Et(r.epk,e);A(i);let a,o;if(r.apu!==void 0){if(typeof r.apu!=`string`)throw new D(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);a=P(r.apu,`apu`,D)}if(r.apv!==void 0){if(typeof r.apv!=`string`)throw new D(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);o=P(r.apv,`apv`,D)}let s=await Be(i,t,e===`ECDH-ES`?r.enc:e,e===`ECDH-ES`?pe(r.enc):parseInt(e.slice(-5,-2),10),a,o);return e===`ECDH-ES`?s:(K(n),Le(e.slice(-6),s,n))}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:return K(n),A(t),et(e,t,n);case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{if(K(n),typeof r.p2c!=`number`)throw new D(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);let a=i?.maxPBES2Count||1e4;if(r.p2c>a)throw new D(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);if(typeof r.p2s!=`string`)throw new D(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);let o;return o=P(r.p2s,`p2s`,D),qe(e,t,n,r.p2c,o)}case`A128KW`:case`A192KW`:case`A256KW`:return K(n),Le(e,t,n);case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{if(K(n),typeof r.iv!=`string`)throw new D(`JOSE Header "iv" (Initialization Vector) missing or invalid`);if(typeof r.tag!=`string`)throw new D(`JOSE Header "tag" (Authentication Tag) missing or invalid`);let i;i=P(r.iv,`iv`,D);let a;return a=P(r.tag,`tag`,D),Mt(e,t,n,i,a)}default:throw new T(Nt)}}async function Ft(e,t,n,r,i={}){let a,o,s;switch(e){case`dir`:s=n;break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{if(A(n),!He(n))throw new T(`ECDH with the provided key is not allowed or not supported by your javascript runtime`);let{apu:c,apv:l}=i,u;u=i.epk?await U(i.epk,e):(await crypto.subtle.generateKey(n.algorithm,!0,[`deriveBits`])).privateKey;let{x:d,y:f,crv:m,kty:h}=await At(u),g=await Be(n,u,e===`ECDH-ES`?t:e,e===`ECDH-ES`?pe(t):parseInt(e.slice(-5,-2),10),c,l);if(o={epk:{x:d,crv:m,kty:h}},h===`EC`&&(o.epk.y=f),c&&(o.apu=p(c)),l&&(o.apv=p(l)),e===`ECDH-ES`){s=g;break}s=r||M(t),a=await Ie(e.slice(-6),g,s);break}case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:s=r||M(t),A(n),a=await $e(e,n,s);break;case`PBES2-HS256+A128KW`:case`PBES2-HS384+A192KW`:case`PBES2-HS512+A256KW`:{s=r||M(t);let{p2c:c,p2s:l}=i;({encryptedKey:a,...o}=await Ke(e,n,s,c,l));break}case`A128KW`:case`A192KW`:case`A256KW`:s=r||M(t),a=await Ie(e,n,s);break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:{s=r||M(t);let{iv:c}=i;({encryptedKey:a,...o}=await jt(e,n,s,c));break}default:throw new T(Nt)}return{cek:s,encryptedKey:a,parameters:o}}function q(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e(`"crit" (Critical) Header Parameter MUST be integrity protected`);if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(e=>typeof e!=`string`||e.length===0))throw new e(`"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present`);let a;a=n===void 0?t:new Map([...Object.entries(n),...t.entries()]);for(let t of r.crit){if(!a.has(t))throw new T(`Extension Header Parameter "${t}" is not recognized`);if(i[t]===void 0)throw new e(`Extension Header Parameter "${t}" is missing`);if(a.get(t)&&r[t]===void 0)throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(r.crit)}function It(e,t){if(t!==void 0&&(!Array.isArray(t)||t.some(e=>typeof e!=`string`)))throw TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)}const J=e=>e?.[Symbol.toStringTag],Lt=(e,t,n)=>{if(t.use!==void 0){let e;switch(n){case`sign`:case`verify`:e=`sig`;break;case`encrypt`:case`decrypt`:e=`enc`;break}if(t.use!==e)throw TypeError(`Invalid key for this operation, its "use" must be "${e}" when present`)}if(t.alg!==void 0&&t.alg!==e)throw TypeError(`Invalid key for this operation, its "alg" must be "${e}" when present`);if(Array.isArray(t.key_ops)){let r;switch(!0){case n===`sign`||n===`verify`:case e===`dir`:case e.includes(`CBC-HS`):r=n;break;case e.startsWith(`PBES2`):r=`deriveBits`;break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(e):r=!e.includes(`GCM`)&&e.endsWith(`KW`)?n===`encrypt`?`wrapKey`:`unwrapKey`:n;break;case n===`encrypt`&&e.startsWith(`RSA`):r=`wrapKey`;break;case n===`decrypt`:r=e.startsWith(`RSA`)?`unwrapKey`:`deriveBits`;break}if(r&&t.key_ops?.includes?.(r)===!1)throw TypeError(`Invalid key for this operation, its "key_ops" must include "${r}" when present`)}return!0},Rt=(e,t,n)=>{if(!(t instanceof Uint8Array)){if(L(t)){if(Ne(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`)}if(!fe(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`,`Uint8Array`));if(t.type!==`secret`)throw TypeError(`${J(t)} instances for symmetric algorithms must be of type "secret"`)}},zt=(e,t,n)=>{if(L(t))switch(n){case`decrypt`:case`sign`:if(je(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a private JWK`);case`encrypt`:case`verify`:if(Me(t)&&Lt(e,t,n))return;throw TypeError(`JSON Web Key for this operation must be a public JWK`)}if(!fe(t))throw TypeError(te(e,t,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t.type===`secret`)throw TypeError(`${J(t)} instances for asymmetric algorithms must not be of type "secret"`);if(t.type===`public`)switch(n){case`sign`:throw TypeError(`${J(t)} instances for asymmetric algorithm signing must be of type "private"`);case`decrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm decryption must be of type "private"`)}if(t.type===`private`)switch(n){case`verify`:throw TypeError(`${J(t)} instances for asymmetric algorithm verifying must be of type "public"`);case`encrypt`:throw TypeError(`${J(t)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Y(e,t,n){switch(e.substring(0,2)){case`A1`:case`A2`:case`di`:case`HS`:case`PB`:Rt(e,t,n);break;default:zt(e,t,n)}}function Bt(e){if(globalThis[e]===void 0)throw new T(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${e} API.`)}async function Vt(e){Bt(`CompressionStream`);let t=new CompressionStream(`deflate-raw`),n=t.writable.getWriter();n.write(e).catch(()=>{}),n.close().catch(()=>{});let r=[],a=t.readable.getReader();for(;;){let{value:e,done:t}=await a.read();if(t)break;r.push(e)}return i(...r)}async function Ht(e,t){Bt(`DecompressionStream`);let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();r.write(e).catch(()=>{}),r.close().catch(()=>{});let a=[],o=0,s=n.readable.getReader();for(;;){let{value:e,done:n}=await s.read();if(n)break;if(a.push(e),o+=e.byteLength,t!==1/0&&o>t)throw new D(`Decompressed plaintext exceeded the configured limit`)}return i(...a)}async function Ut(e,t,r){if(!F(e))throw new D(`Flattened JWE must be an object`);if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new D(`JOSE Header missing`);if(e.iv!==void 0&&typeof e.iv!=`string`)throw new D(`JWE Initialization Vector incorrect type`);if(typeof e.ciphertext!=`string`)throw new D(`JWE Ciphertext missing or incorrect type`);if(e.tag!==void 0&&typeof e.tag!=`string`)throw new D(`JWE Authentication Tag incorrect type`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new D(`JWE Protected Header incorrect type`);if(e.encrypted_key!==void 0&&typeof e.encrypted_key!=`string`)throw new D(`JWE Encrypted Key incorrect type`);if(e.aad!==void 0&&typeof e.aad!=`string`)throw new D(`JWE AAD incorrect type`);if(e.header!==void 0&&!F(e.header))throw new D(`JWE Shared Unprotected Header incorrect type`);if(e.unprotected!==void 0&&!F(e.unprotected))throw new D(`JWE Per-Recipient Unprotected Header incorrect type`);let a;if(e.protected)try{let t=f(e.protected);a=JSON.parse(n.decode(t))}catch{throw new D(`JWE Protected Header is invalid`)}if(!I(a,e.header,e.unprotected))throw new D(`JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint`);let o={...a,...e.header,...e.unprotected};if(q(D,new Map,r?.crit,a,o),o.zip!==void 0&&o.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(o.zip!==void 0&&!a?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:s,enc:l}=o;if(typeof s!=`string`||!s)throw new D(`missing JWE Algorithm (alg) in JWE Header`);if(typeof l!=`string`||!l)throw new D(`missing JWE Encryption Algorithm (enc) in JWE Header`);let u=r&&It(`keyManagementAlgorithms`,r.keyManagementAlgorithms),d=r&&It(`contentEncryptionAlgorithms`,r.contentEncryptionAlgorithms);if(u&&!u.has(s)||!u&&s.startsWith(`PBES2`))throw new ie(`"alg" (Algorithm) Header Parameter value not allowed`);if(d&&!d.has(l))throw new ie(`"enc" (Encryption Algorithm) Header Parameter value not allowed`);let p;e.encrypted_key!==void 0&&(p=P(e.encrypted_key,`encrypted_key`,D));let m=!1;typeof t==`function`&&(t=await t(a,e),m=!0),Y(s===`dir`?l:s,t,`decrypt`);let h=await U(t,s),g;try{g=await Pt(s,h,p,o,r)}catch(e){if(e instanceof TypeError||e instanceof D||e instanceof T)throw e;g=M(l)}let _,v;e.iv!==void 0&&(_=P(e.iv,`iv`,D)),e.tag!==void 0&&(v=P(e.tag,`tag`,D));let y=e.protected===void 0?new Uint8Array:c(e.protected),ee;ee=e.aad===void 0?y:i(y,c(`.`),c(e.aad));let b=P(e.ciphertext,`ciphertext`,D),x=await De(l,g,b,_,v,ee),S={plaintext:x};if(o.zip===`DEF`){let e=r?.maxDecompressedLength??25e4;if(e===0)throw new T(`JWE "zip" (Compression Algorithm) Header Parameter is not supported.`);if(e!==1/0&&(!Number.isSafeInteger(e)||e<1))throw TypeError(`maxDecompressedLength must be 0, a positive safe integer, or Infinity`);S.plaintext=await Ht(x,e).catch(e=>{throw e instanceof D?e:new D(`Failed to decompress plaintext`,{cause:e})})}return e.protected!==void 0&&(S.protectedHeader=a),e.aad!==void 0&&(S.additionalAuthenticatedData=P(e.aad,`aad`,D)),e.unprotected!==void 0&&(S.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(S.unprotectedHeader=e.header),m?{...S,key:h}:S}async function Wt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new D(`Compact JWE must be a string or Uint8Array`);let{0:i,1:a,2:o,3:s,4:c,length:l}=e.split(`.`);if(l!==5)throw new D(`Invalid Compact JWE`);let u=await Ut({ciphertext:s,iv:o||void 0,protected:i,tag:c||void 0,encrypted_key:a||void 0},t,r),d={plaintext:u.plaintext,protectedHeader:u.protectedHeader};return typeof t==`function`?{...d,key:u.key}:d}async function Gt(e,t,n){if(!F(e))throw new D(`General JWE must be an object`);if(!Array.isArray(e.recipients)||!e.recipients.every(F))throw new D(`JWE Recipients missing or incorrect type`);if(!e.recipients.length)throw new D(`JWE Recipients has no members`);for(let r of e.recipients)try{return await Ut({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,n)}catch{}throw new E}var Kt=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`plaintext must be an instance of Uint8Array`);this.#e=e}setKeyManagementParameters(e){return N(this.#s,`setKeyManagementParameters`),this.#s=e,this}setProtectedHeader(e){return N(this.#t,`setProtectedHeader`),this.#t=e,this}setSharedUnprotectedHeader(e){return N(this.#n,`setSharedUnprotectedHeader`),this.#n=e,this}setUnprotectedHeader(e){return N(this.#r,`setUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}setContentEncryptionKey(e){return N(this.#a,`setContentEncryptionKey`),this.#a=e,this}setInitializationVector(e){return N(this.#o,`setInitializationVector`),this.#o=e,this}async encrypt(e,t){if(!this.#t&&!this.#r&&!this.#n)throw new D(`either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()`);if(!I(this.#t,this.#r,this.#n))throw new D(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let n={...this.#t,...this.#r,...this.#n};if(q(D,new Map,t?.crit,this.#t,n),n.zip!==void 0&&n.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(n.zip!==void 0&&!this.#t?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`);let{alg:r,enc:a}=n;if(typeof r!=`string`||!r)throw new D(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(typeof a!=`string`||!a)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);let o;if(this.#a&&(r===`dir`||r===`ECDH-ES`))throw TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${r}`);Y(r===`dir`?a:r,e,`encrypt`);let s;{let n,i=await U(e,r);({cek:s,encryptedKey:o,parameters:n}=await Ft(r,a,i,this.#a,this.#s)),n&&(t&&Oe in t?this.#r?this.#r={...this.#r,...n}:this.setUnprotectedHeader(n):this.#t?this.#t={...this.#t,...n}:this.setProtectedHeader(n))}let l,u,d,f;if(this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array),this.#i){f=p(this.#i);let e=c(f);l=i(d,c(`.`),e)}else l=d;let m=this.#e;n.zip===`DEF`&&(m=await Vt(m).catch(e=>{throw new D(`Failed to compress plaintext`,{cause:e})}));let{ciphertext:h,tag:g,iv:_}=await Ee(a,m,s,this.#o,l),v={ciphertext:p(h)};return _&&(v.iv=p(_)),g&&(v.tag=p(g)),o&&(v.encrypted_key=p(o)),f&&(v.aad=f),this.#t&&(v.protected=u),this.#n&&(v.unprotected=this.#n),this.#r&&(v.header=this.#r),v}},qt=class{#e;unprotectedHeader;keyManagementParameters;key;options;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setUnprotectedHeader(e){return N(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}setKeyManagementParameters(e){return N(this.keyManagementParameters,`setKeyManagementParameters`),this.keyManagementParameters=e,this}addRecipient(...e){return this.#e.addRecipient(...e)}encrypt(...e){return this.#e.encrypt(...e)}done(){return this.#e}},Jt=class{#e;#t=[];#n;#r;#i;constructor(e){this.#e=e}addRecipient(e,t){let n=new qt(this,e,{crit:t?.crit});return this.#t.push(n),n}setProtectedHeader(e){return N(this.#n,`setProtectedHeader`),this.#n=e,this}setSharedUnprotectedHeader(e){return N(this.#r,`setSharedUnprotectedHeader`),this.#r=e,this}setAdditionalAuthenticatedData(e){return this.#i=e,this}async encrypt(){if(!this.#t.length)throw new D(`at least one recipient must be added`);if(this.#t.length===1){let[e]=this.#t,t=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(e.unprotectedHeader).encrypt(e.key,{...e.options}),n={ciphertext:t.ciphertext,iv:t.iv,recipients:[{}],tag:t.tag};return t.aad&&(n.aad=t.aad),t.protected&&(n.protected=t.protected),t.unprotected&&(n.unprotected=t.unprotected),t.encrypted_key&&(n.recipients[0].encrypted_key=t.encrypted_key),t.header&&(n.recipients[0].header=t.header),n}let e;for(let t=0;t<this.#t.length;t++){let n=this.#t[t];if(!I(this.#n,this.#r,n.unprotectedHeader))throw new D(`JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint`);let r={...this.#n,...this.#r,...n.unprotectedHeader},{alg:i}=r;if(typeof i!=`string`||!i)throw new D(`JWE "alg" (Algorithm) Header Parameter missing or invalid`);if(i===`dir`||i===`ECDH-ES`)throw new D(`"dir" and "ECDH-ES" alg may only be used with a single recipient`);if(typeof r.enc!=`string`||!r.enc)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid`);if(!e)e=r.enc;else if(e!==r.enc)throw new D(`JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients`);if(q(D,new Map,n.options.crit,this.#n,r),r.zip!==void 0&&r.zip!==`DEF`)throw new T(`Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.`);if(r.zip!==void 0&&!this.#n?.zip)throw new D(`JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.`)}let t=M(e),n={ciphertext:``,recipients:[]};for(let r=0;r<this.#t.length;r++){let i=this.#t[r],a={};if(n.recipients.push(a),r===0){let e=await new Kt(this.#e).setAdditionalAuthenticatedData(this.#i).setContentEncryptionKey(t).setProtectedHeader(this.#n).setSharedUnprotectedHeader(this.#r).setUnprotectedHeader(i.unprotectedHeader).setKeyManagementParameters(i.keyManagementParameters).encrypt(i.key,{...i.options,[Oe]:!0});n.ciphertext=e.ciphertext,n.iv=e.iv,n.tag=e.tag,e.aad&&(n.aad=e.aad),e.protected&&(n.protected=e.protected),e.unprotected&&(n.unprotected=e.unprotected),a.encrypted_key=e.encrypted_key,e.header&&(a.header=e.header);continue}let o=i.unprotectedHeader?.alg||this.#n?.alg||this.#r?.alg;Y(o===`dir`?e:o,i.key,`encrypt`);let s=await U(i.key,o),{encryptedKey:c,parameters:l}=await Ft(o,e,s,t,i.keyManagementParameters);a.encrypted_key=p(c),(i.unprotectedHeader||l)&&(a.header={...i.unprotectedHeader,...l})}return n}};async function Yt(e,r,a){if(!F(e))throw new O(`Flattened JWS must be an object`);if(e.protected===void 0&&e.header===void 0)throw new O(`Flattened JWS must have either of the "protected" or "header" members`);if(e.protected!==void 0&&typeof e.protected!=`string`)throw new O(`JWS Protected Header incorrect type`);if(e.payload===void 0)throw new O(`JWS Payload missing`);if(typeof e.signature!=`string`)throw new O(`JWS Signature missing or incorrect type`);if(e.header!==void 0&&!F(e.header))throw new O(`JWS Unprotected Header incorrect type`);let o={};if(e.protected)try{let t=f(e.protected);o=JSON.parse(n.decode(t))}catch{throw new O(`JWS Protected Header is invalid`)}if(!I(o,e.header))throw new O(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let s={...o,...e.header},l=q(O,new Map([[`b64`,!0]]),a?.crit,o,s),u=!0;if(l.has(`b64`)&&(u=o.b64,typeof u!=`boolean`))throw new O(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:d}=s;if(typeof d!=`string`||!d)throw new O(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);let p=a&&It(`algorithms`,a.algorithms);if(p&&!p.has(d))throw new ie(`"alg" (Algorithm) Header Parameter value not allowed`);if(u){if(typeof e.payload!=`string`)throw new O(`JWS Payload must be a string`)}else if(typeof e.payload!=`string`&&!(e.payload instanceof Uint8Array))throw new O(`JWS Payload must be a string or an Uint8Array instance`);let m=!1;typeof r==`function`&&(r=await r(o,e),m=!0),Y(d,r,`verify`);let h=i(e.protected===void 0?new Uint8Array:c(e.protected),c(`.`),typeof e.payload==`string`?u?c(e.payload):t.encode(e.payload):e.payload),g=P(e.signature,`signature`,O),_=await U(r,d);if(!await Ze(d,_,g,h))throw new ue;let v;v=u?P(e.payload,`payload`,O):typeof e.payload==`string`?t.encode(e.payload):e.payload;let y={payload:v};return e.protected!==void 0&&(y.protectedHeader=o),e.header!==void 0&&(y.unprotectedHeader=e.header),m?{...y,key:_}:y}async function Xt(e,t,r){if(e instanceof Uint8Array&&(e=n.decode(e)),typeof e!=`string`)throw new O(`Compact JWS must be a string or Uint8Array`);let{0:i,1:a,2:o,length:s}=e.split(`.`);if(s!==3)throw new O(`Invalid Compact JWS`);let c=await Yt({payload:a,protected:i,signature:o},t,r),l={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t==`function`?{...l,key:c.key}:l}async function Zt(e,t,n){if(!F(e))throw new O(`General JWS must be an object`);if(!Array.isArray(e.signatures)||!e.signatures.every(F))throw new O(`JWS Signatures missing or incorrect type`);for(let r of e.signatures)try{return await Yt({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,n)}catch{}throw new ue}const X=e=>Math.floor(e.getTime()/1e3),Qt=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Z(e){let t=Qt.exec(e);if(!t||t[4]&&t[1])throw TypeError(`Invalid time period format`);let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case`sec`:case`secs`:case`second`:case`seconds`:case`s`:i=Math.round(n);break;case`minute`:case`minutes`:case`min`:case`mins`:case`m`:i=Math.round(n*60);break;case`hour`:case`hours`:case`hr`:case`hrs`:case`h`:i=Math.round(n*3600);break;case`day`:case`days`:case`d`:i=Math.round(n*86400);break;case`week`:case`weeks`:case`w`:i=Math.round(n*604800);break;default:i=Math.round(n*31557600);break}return t[1]===`-`||t[4]===`ago`?-i:i}function Q(e,t){if(!Number.isFinite(t))throw TypeError(`Invalid ${e} input`);return t}const $t=e=>e.includes(`/`)?e.toLowerCase():`application/${e.toLowerCase()}`,en=(e,t)=>typeof e==`string`?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;function tn(e,t,r={}){let i;try{i=JSON.parse(n.decode(t))}catch{}if(!F(i))throw new k(`JWT Claims Set must be a top-level JSON object`);let{typ:a}=r;if(a&&(typeof e.typ!=`string`||$t(e.typ)!==$t(a)))throw new w(`unexpected "typ" JWT header value`,i,`typ`,`check_failed`);let{requiredClaims:o=[],issuer:s,subject:c,audience:l,maxTokenAge:u}=r,d=[...o];u!==void 0&&d.push(`iat`),l!==void 0&&d.push(`aud`),c!==void 0&&d.push(`sub`),s!==void 0&&d.push(`iss`);for(let e of new Set(d.reverse()))if(!(e in i))throw new w(`missing required "${e}" claim`,i,e,`missing`);if(s&&!(Array.isArray(s)?s:[s]).includes(i.iss))throw new w(`unexpected "iss" claim value`,i,`iss`,`check_failed`);if(c&&i.sub!==c)throw new w(`unexpected "sub" claim value`,i,`sub`,`check_failed`);if(l&&!en(i.aud,typeof l==`string`?[l]:l))throw new w(`unexpected "aud" claim value`,i,`aud`,`check_failed`);let f;switch(typeof r.clockTolerance){case`string`:f=Z(r.clockTolerance);break;case`number`:f=r.clockTolerance;break;case`undefined`:f=0;break;default:throw TypeError(`Invalid clockTolerance option type`)}let{currentDate:p}=r,m=X(p||new Date);if((i.iat!==void 0||u)&&typeof i.iat!=`number`)throw new w(`"iat" claim must be a number`,i,`iat`,`invalid`);if(i.nbf!==void 0){if(typeof i.nbf!=`number`)throw new w(`"nbf" claim must be a number`,i,`nbf`,`invalid`);if(i.nbf>m+f)throw new w(`"nbf" claim timestamp check failed`,i,`nbf`,`check_failed`)}if(i.exp!==void 0){if(typeof i.exp!=`number`)throw new w(`"exp" claim must be a number`,i,`exp`,`invalid`);if(i.exp<=m-f)throw new re(`"exp" claim timestamp check failed`,i,`exp`,`check_failed`)}if(u){let e=m-i.iat,t=typeof u==`number`?u:Z(u);if(e-f>t)throw new re(`"iat" claim timestamp check failed (too far in the past)`,i,`iat`,`check_failed`);if(e<0-f)throw new w(`"iat" claim timestamp check failed (it should be in the past)`,i,`iat`,`check_failed`)}return i}var nn=class{#e;constructor(e){if(!F(e))throw TypeError(`JWT Claims Set MUST be an object`);this.#e=structuredClone(e)}data(){return t.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e==`number`?this.#e.nbf=Q(`setNotBefore`,e):e instanceof Date?this.#e.nbf=Q(`setNotBefore`,X(e)):this.#e.nbf=X(new Date)+Z(e)}set exp(e){typeof e==`number`?this.#e.exp=Q(`setExpirationTime`,e):e instanceof Date?this.#e.exp=Q(`setExpirationTime`,X(e)):this.#e.exp=X(new Date)+Z(e)}set iat(e){e===void 0?this.#e.iat=X(new Date):e instanceof Date?this.#e.iat=Q(`setIssuedAt`,X(e)):typeof e==`string`?this.#e.iat=Q(`setIssuedAt`,X(new Date)+Z(e)):this.#e.iat=Q(`setIssuedAt`,e)}};async function rn(e,t,n){let r=await Xt(e,t,n);if(r.protectedHeader.crit?.includes(`b64`)&&r.protectedHeader.b64===!1)throw new k(`JWTs MUST NOT use unencoded payload`);let i={payload:tn(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t==`function`?{...i,key:r.key}:i}async function an(e,t,n){let r=await Wt(e,t,n),i=tn(r.protectedHeader,r.plaintext,n),{protectedHeader:a}=r;if(a.iss!==void 0&&a.iss!==i.iss)throw new w(`replicated "iss" claim header parameter mismatch`,i,`iss`,`mismatch`);if(a.sub!==void 0&&a.sub!==i.sub)throw new w(`replicated "sub" claim header parameter mismatch`,i,`sub`,`mismatch`);if(a.aud!==void 0&&JSON.stringify(a.aud)!==JSON.stringify(i.aud))throw new w(`replicated "aud" claim header parameter mismatch`,i,`aud`,`mismatch`);let o={payload:i,protectedHeader:a};return typeof t==`function`?{...o,key:r.key}:o}var on=class{#e;constructor(e){this.#e=new Kt(e)}setContentEncryptionKey(e){return this.#e.setContentEncryptionKey(e),this}setInitializationVector(e){return this.#e.setInitializationVector(e),this}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}setKeyManagementParameters(e){return this.#e.setKeyManagementParameters(e),this}async encrypt(e,t){let n=await this.#e.encrypt(e,t);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(`.`)}},sn=class{#e;#t;#n;constructor(e){if(!(e instanceof Uint8Array))throw TypeError(`payload must be an instance of Uint8Array`);this.#e=e}setProtectedHeader(e){return N(this.#t,`setProtectedHeader`),this.#t=e,this}setUnprotectedHeader(e){return N(this.#n,`setUnprotectedHeader`),this.#n=e,this}async sign(e,t){if(!this.#t&&!this.#n)throw new O(`either setProtectedHeader or setUnprotectedHeader must be called before #sign()`);if(!I(this.#t,this.#n))throw new O(`JWS Protected and JWS Unprotected Header Parameter names must be disjoint`);let n={...this.#t,...this.#n},r=q(O,new Map([[`b64`,!0]]),t?.crit,this.#t,n),a=!0;if(r.has(`b64`)&&(a=this.#t.b64,typeof a!=`boolean`))throw new O(`The "b64" (base64url-encode payload) Header Parameter must be a boolean`);let{alg:o}=n;if(typeof o!=`string`||!o)throw new O(`JWS "alg" (Algorithm) Header Parameter missing or invalid`);Y(o,e,`sign`);let s,l;a?(s=p(this.#e),l=c(s)):(l=this.#e,s=``);let u,d;this.#t?(u=p(JSON.stringify(this.#t)),d=c(u)):(u=``,d=new Uint8Array);let f=i(d,c(`.`),l),m={signature:p(await Xe(o,await U(e,o),f)),payload:s};return this.#n&&(m.header=this.#n),this.#t&&(m.protected=u),m}},cn=class{#e;constructor(e){this.#e=new sn(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,t){let n=await this.#e.sign(e,t);if(n.payload===void 0)throw TypeError(`use the flattened module for creating JWS with b64: false`);return`${n.protected}.${n.payload}.${n.signature}`}},ln=class{#e;protectedHeader;unprotectedHeader;options;key;constructor(e,t,n){this.#e=e,this.key=t,this.options=n}setProtectedHeader(e){return N(this.protectedHeader,`setProtectedHeader`),this.protectedHeader=e,this}setUnprotectedHeader(e){return N(this.unprotectedHeader,`setUnprotectedHeader`),this.unprotectedHeader=e,this}addSignature(...e){return this.#e.addSignature(...e)}sign(...e){return this.#e.sign(...e)}done(){return this.#e}},un=class{#e;#t=[];constructor(e){this.#e=e}addSignature(e,t){let n=new ln(this,e,t);return this.#t.push(n),n}async sign(){if(!this.#t.length)throw new O(`at least one signature must be added`);let e={signatures:[],payload:``};for(let t=0;t<this.#t.length;t++){let n=this.#t[t],r=new sn(this.#e);r.setProtectedHeader(n.protectedHeader),r.setUnprotectedHeader(n.unprotectedHeader);let{payload:i,...a}=await r.sign(n.key,n.options);if(t===0)e.payload=i;else if(e.payload!==i)throw new O(`inconsistent use of JWS Unencoded Payload (RFC7797)`);e.signatures.push(a)}return e}},dn=class{#e;#t;constructor(e={}){this.#t=new nn(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,t){let n=new cn(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes(`b64`)&&this.#e.b64===!1)throw new k(`JWTs MUST NOT use unencoded payload`);return n.sign(e,t)}},fn=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#s=new nn(e)}setIssuer(e){return this.#s.iss=e,this}setSubject(e){return this.#s.sub=e,this}setAudience(e){return this.#s.aud=e,this}setJti(e){return this.#s.jti=e,this}setNotBefore(e){return this.#s.nbf=e,this}setExpirationTime(e){return this.#s.exp=e,this}setIssuedAt(e){return this.#s.iat=e,this}setProtectedHeader(e){return N(this.#r,`setProtectedHeader`),this.#r=e,this}setKeyManagementParameters(e){return N(this.#n,`setKeyManagementParameters`),this.#n=e,this}setContentEncryptionKey(e){return N(this.#e,`setContentEncryptionKey`),this.#e=e,this}setInitializationVector(e){return N(this.#t,`setInitializationVector`),this.#t=e,this}replicateIssuerAsHeader(){return this.#i=!0,this}replicateSubjectAsHeader(){return this.#a=!0,this}replicateAudienceAsHeader(){return this.#o=!0,this}async encrypt(e,t){let n=new on(this.#s.data());return this.#r&&(this.#i||this.#a||this.#o)&&(this.#r={...this.#r,iss:this.#i?this.#s.iss:void 0,sub:this.#a?this.#s.sub:void 0,aud:this.#o?this.#s.aud:void 0}),n.setProtectedHeader(this.#r),this.#t&&n.setInitializationVector(this.#t),this.#e&&n.setContentEncryptionKey(this.#e),this.#n&&n.setKeyManagementParameters(this.#n),n.encrypt(e,t)}};const $=(e,t)=>{if(typeof e!=`string`||!e)throw new ae(`${t} missing or invalid`)};async function pn(e,t){let n;if(L(e))n=e;else if(fe(e))n=await At(e);else throw TypeError(S(e,`CryptoKey`,`KeyObject`,`JSON Web Key`));if(t??=`sha256`,t!==`sha256`&&t!==`sha384`&&t!==`sha512`)throw TypeError(`digestAlgorithm must one of "sha256", "sha384", or "sha512"`);let r;switch(n.kty){case`AKP`:$(n.alg,`"alg" (Algorithm) Parameter`),$(n.pub,`"pub" (Public key) Parameter`),r={alg:n.alg,kty:n.kty,pub:n.pub};break;case`EC`:$(n.crv,`"crv" (Curve) Parameter`),$(n.x,`"x" (X Coordinate) Parameter`),$(n.y,`"y" (Y Coordinate) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x,y:n.y};break;case`OKP`:$(n.crv,`"crv" (Subtype of Key Pair) Parameter`),$(n.x,`"x" (Public Key) Parameter`),r={crv:n.crv,kty:n.kty,x:n.x};break;case`RSA`:$(n.e,`"e" (Exponent) Parameter`),$(n.n,`"n" (Modulus) Parameter`),r={e:n.e,kty:n.kty,n:n.n};break;case`oct`:$(n.k,`"k" (Key Value) Parameter`),r={k:n.k,kty:n.kty};break;default:throw new T(`"kty" (Key Type) Parameter missing or unsupported`)}let i=c(JSON.stringify(r));return p(await ke(t,i))}async function mn(e,t){t??=`sha256`;let n=await pn(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}async function hn(e,t){let n={...e,...t?.header};if(!F(n.jwk))throw new O(`"jwk" (JSON Web Key) Header Parameter must be a JSON object`);let r=await Et({...n.jwk,ext:!0},n.alg);if(r instanceof Uint8Array||r.type!==`public`)throw new O(`"jwk" (JSON Web Key) Header Parameter must be a public key`);return r}function gn(e){switch(typeof e==`string`&&e.slice(0,2)){case`RS`:case`PS`:return`RSA`;case`ES`:return`EC`;case`Ed`:return`OKP`;case`ML`:return`AKP`;default:throw new T(`Unsupported "alg" value for a JSON Web Key Set`)}}function _n(e){return e&&typeof e==`object`&&Array.isArray(e.keys)&&e.keys.every(vn)}function vn(e){return F(e)}var yn=class{#e;#t=new WeakMap;constructor(e){if(!_n(e))throw new oe(`JSON Web Key Set malformed`);this.#e=structuredClone(e)}jwks(){return this.#e}async getKey(e,t){let{alg:n,kid:r}={...e,...t?.header},i=gn(n),a=this.#e.keys.filter(e=>{let t=i===e.kty;if(t&&typeof r==`string`&&(t=r===e.kid),t&&(typeof e.alg==`string`||i===`AKP`)&&(t=n===e.alg),t&&typeof e.use==`string`&&(t=e.use===`sig`),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes(`verify`)),t)switch(n){case`ES256`:t=e.crv===`P-256`;break;case`ES384`:t=e.crv===`P-384`;break;case`ES512`:t=e.crv===`P-521`;break;case`Ed25519`:case`EdDSA`:t=e.crv===`Ed25519`;break}return t}),{0:o,length:s}=a;if(s===0)throw new se;if(s!==1){let e=new ce,t=this.#t;throw e[Symbol.asyncIterator]=async function*(){for(let e of a)try{yield await bn(t,e,n)}catch{}},e}return bn(this.#t,o,n)}};async function bn(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let e=await Et({...t,ext:!0},n);if(e instanceof Uint8Array||e.type!==`public`)throw new oe(`JSON Web Key Set members must be public keys`);r[n]=e}return r[n]}function xn(e){let t=new yn(e),n=async(e,n)=>t.getKey(e,n);return Object.defineProperties(n,{jwks:{value:()=>structuredClone(t.jwks()),enumerable:!1,configurable:!1,writable:!1}}),n}function Sn(){return typeof WebSocketPair<`u`||typeof navigator<`u`&&navigator.userAgent===`Cloudflare-Workers`||typeof EdgeRuntime<`u`&&EdgeRuntime===`vercel`}let Cn;(typeof navigator>`u`||!navigator.userAgent?.startsWith?.(`Mozilla/5.0 `))&&(Cn=`jose/v6.2.3`);const wn=Symbol();async function Tn(e,t,n,r=fetch){let i=await r(e,{method:`GET`,signal:n,redirect:`manual`,headers:t}).catch(e=>{throw e.name===`TimeoutError`?new le:e});if(i.status!==200)throw new C(`Expected 200 OK from the JSON Web Key Set HTTP response`);try{return await i.json()}catch{throw new C(`Failed to parse the JSON Web Key Set HTTP response as JSON`)}}const En=Symbol();function Dn(e,t){return!(typeof e!=`object`||!e||!(`uat`in e)||typeof e.uat!=`number`||Date.now()-e.uat>=t||!(`jwks`in e)||!F(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,F))}var On=class{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l;constructor(e,t){if(!(e instanceof URL))throw TypeError(`url must be an instance of URL`);this.#e=new URL(e.href),this.#t=typeof t?.timeoutDuration==`number`?t?.timeoutDuration:5e3,this.#n=typeof t?.cooldownDuration==`number`?t?.cooldownDuration:3e4,this.#r=typeof t?.cacheMaxAge==`number`?t?.cacheMaxAge:6e5,this.#o=new Headers(t?.headers),Cn&&!this.#o.has(`User-Agent`)&&this.#o.set(`User-Agent`,Cn),this.#o.has(`accept`)||(this.#o.set(`accept`,`application/json`),this.#o.append(`accept`,`application/jwk-set+json`)),this.#s=t?.[wn],t?.[En]!==void 0&&(this.#l=t?.[En],Dn(t?.[En],this.#r)&&(this.#i=this.#l.uat,this.#c=xn(this.#l.jwks)))}pendingFetch(){return!!this.#a}coolingDown(){return typeof this.#i==`number`?Date.now()<this.#i+this.#n:!1}fresh(){return typeof this.#i==`number`?Date.now()<this.#i+this.#r:!1}jwks(){return this.#c?.jwks()}async getKey(e,t){(!this.#c||!this.fresh())&&await this.reload();try{return await this.#c(e,t)}catch(n){if(n instanceof se&&this.coolingDown()===!1)return await this.reload(),this.#c(e,t);throw n}}async reload(){this.#a&&Sn()&&(this.#a=void 0),this.#a||=Tn(this.#e.href,this.#o,AbortSignal.timeout(this.#t),this.#s).then(e=>{this.#c=xn(e),this.#l&&(this.#l.uat=Date.now(),this.#l.jwks=e),this.#i=Date.now(),this.#a=void 0}).catch(e=>{throw this.#a=void 0,e}),await this.#a}};function kn(e,t){let n=new On(e,t),r=async(e,t)=>n.getKey(e,t);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>n.pendingFetch(),enumerable:!0,configurable:!1},jwks:{value:()=>n.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}var An=class{#e;constructor(e={}){this.#e=new nn(e)}encode(){return`${p(JSON.stringify({alg:`none`}))}.${p(this.#e.data())}.`}setIssuer(e){return this.#e.iss=e,this}setSubject(e){return this.#e.sub=e,this}setAudience(e){return this.#e.aud=e,this}setJti(e){return this.#e.jti=e,this}setNotBefore(e){return this.#e.nbf=e,this}setExpirationTime(e){return this.#e.exp=e,this}setIssuedAt(e){return this.#e.iat=e,this}static decode(e,t){if(typeof e!=`string`)throw new k(`Unsecured JWT must be a string`);let{0:r,1:i,2:a,length:o}=e.split(`.`);if(o!==3||a!==``)throw new k(`Invalid Unsecured JWT`);let s;try{if(s=JSON.parse(n.decode(f(r))),s.alg!==`none`)throw Error()}catch{throw new k(`Invalid Unsecured JWT`)}return{payload:tn(s,f(i),t),header:s}}};function jn(e){let t;if(typeof e==`string`){let n=e.split(`.`);(n.length===3||n.length===5)&&([t]=n)}else if(typeof e==`object`&&e)if(`protected`in e)t=e.protected;else throw TypeError(`Token does not contain a Protected Header`);try{if(typeof t!=`string`||!t)throw Error();let e=JSON.parse(n.decode(f(t)));if(!F(e))throw Error();return e}catch{throw TypeError(`Invalid Token or Protected Header formatting`)}}function Mn(e){if(typeof e!=`string`)throw new k(`JWTs must use Compact JWS serialization, JWT must be a string`);let{1:t,length:r}=e.split(`.`);if(r===5)throw new k(`Only JWTs using Compact JWS serialization can be decoded`);if(r!==3)throw new k(`Invalid JWT`);if(!t)throw new k(`JWTs must contain a payload`);let i;try{i=f(t)}catch{throw new k(`Failed to base64url decode the payload`)}let a;try{a=JSON.parse(n.decode(i))}catch{throw new k(`Failed to parse the decoded payload as JSON`)}if(!F(a))throw new k(`Invalid JWT Claims Set`);return a}function Nn(e){let t=e?.modulusLength??2048;if(typeof t!=`number`||t<2048)throw new T(`Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used`);return t}async function Pn(e,t){let n,r;switch(e){case`PS256`:case`PS384`:case`PS512`:n={name:`RSA-PSS`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Nn(t)},r=[`sign`,`verify`];break;case`RS256`:case`RS384`:case`RS512`:n={name:`RSASSA-PKCS1-v1_5`,hash:`SHA-${e.slice(-3)}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Nn(t)},r=[`sign`,`verify`];break;case`RSA-OAEP`:case`RSA-OAEP-256`:case`RSA-OAEP-384`:case`RSA-OAEP-512`:n={name:`RSA-OAEP`,hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:Uint8Array.of(1,0,1),modulusLength:Nn(t)},r=[`decrypt`,`unwrapKey`,`encrypt`,`wrapKey`];break;case`ES256`:n={name:`ECDSA`,namedCurve:`P-256`},r=[`sign`,`verify`];break;case`ES384`:n={name:`ECDSA`,namedCurve:`P-384`},r=[`sign`,`verify`];break;case`ES512`:n={name:`ECDSA`,namedCurve:`P-521`},r=[`sign`,`verify`];break;case`Ed25519`:case`EdDSA`:r=[`sign`,`verify`],n={name:`Ed25519`};break;case`ML-DSA-44`:case`ML-DSA-65`:case`ML-DSA-87`:r=[`sign`,`verify`],n={name:e};break;case`ECDH-ES`:case`ECDH-ES+A128KW`:case`ECDH-ES+A192KW`:case`ECDH-ES+A256KW`:{r=[`deriveBits`];let e=t?.crv??`P-256`;switch(e){case`P-256`:case`P-384`:case`P-521`:n={name:`ECDH`,namedCurve:e};break;case`X25519`:n={name:`X25519`};break;default:throw new T(`Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, and X25519`)}break}default:throw new T(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(n,t?.extractable??!1,r)}async function Fn(e,t){let n,r,i;switch(e){case`HS256`:case`HS384`:case`HS512`:n=parseInt(e.slice(-3),10),r={name:`HMAC`,hash:`SHA-${n}`,length:n},i=[`sign`,`verify`];break;case`A128CBC-HS256`:case`A192CBC-HS384`:case`A256CBC-HS512`:return n=parseInt(e.slice(-3),10),crypto.getRandomValues(new Uint8Array(n>>3));case`A128KW`:case`A192KW`:case`A256KW`:n=parseInt(e.slice(1,4),10),r={name:`AES-KW`,length:n},i=[`wrapKey`,`unwrapKey`];break;case`A128GCMKW`:case`A192GCMKW`:case`A256GCMKW`:case`A128GCM`:case`A192GCM`:case`A256GCM`:n=parseInt(e.slice(1,4),10),r={name:`AES-GCM`,length:n},i=[`encrypt`,`decrypt`];break;default:throw new T(`Invalid or unsupported JWK "alg" (Algorithm) Parameter value`)}return crypto.subtle.generateKey(r,t?.extractable??!1,i)}const In=`WebCryptoAPI`;export{on as CompactEncrypt,cn as CompactSign,hn as EmbeddedJWK,fn as EncryptJWT,Kt as FlattenedEncrypt,sn as FlattenedSign,Jt as GeneralEncrypt,un as GeneralSign,dn as SignJWT,An as UnsecuredJWT,d as base64url,pn as calculateJwkThumbprint,mn as calculateJwkThumbprintUri,Wt as compactDecrypt,Xt as compactVerify,xn as createLocalJWKSet,kn as createRemoteJWKSet,In as cryptoRuntime,wn as customFetch,Mn as decodeJwt,jn as decodeProtectedHeader,ne as errors,At as exportJWK,kt as exportPKCS8,Ot as exportSPKI,Ut as flattenedDecrypt,Yt as flattenedVerify,Gt as generalDecrypt,Zt as generalVerify,Pn as generateKeyPair,Fn as generateSecret,Et as importJWK,Tt as importPKCS8,Ct as importSPKI,wt as importX509,En as jwksCache,an as jwtDecrypt,rn as jwtVerify};
|
|
@@ -19,6 +19,11 @@ export interface CompileFromMemoryInput {
|
|
|
19
19
|
readonly agentRoot?: string;
|
|
20
20
|
/** Model id assigned to the synthetic agent config. */
|
|
21
21
|
readonly model: string;
|
|
22
|
+
/** Session token limits assigned to the synthetic agent config. */
|
|
23
|
+
readonly limits?: {
|
|
24
|
+
readonly maxInputTokensPerSession?: number | false;
|
|
25
|
+
readonly maxOutputTokensPerSession?: number | false;
|
|
26
|
+
};
|
|
22
27
|
readonly outputSchema?: JsonObject;
|
|
23
28
|
/**
|
|
24
29
|
* Authored tools to project into the compiled manifest and module map.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{classifyModelRouting}from"#internal/classify-model-routing.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest}from"#compiler/manifest.js";function compileFromMemory(t){let n=t.appRoot??`/virtual/eve-memory-app`,r=t.agentRoot??`${n}/agent`,i=t.name??`memory-agent`,a={model:{id:t.model,routing:classifyModelRouting(t.model)},name:i};t.outputSchema!==void 0&&(a.outputSchema=t.outputSchema);let o=(t.tools??[]).map(e=>({description:e.description??`${e.name} test tool.`,inputSchema:e.inputSchema??null,logicalPath:`tools/${e.name}.ts`,name:e.name,outputSchema:e.outputSchema,sourceId:createMemorySourceId(`tools/${e.name}.ts`),sourceKind:`module`}));return{manifest:createCompiledAgentManifest({agentRoot:r,appRoot:n,config:a,skills:(t.skills??[]).map(e=>({description:e.description,logicalPath:`skills/${e.name}.md`,markdown:e.markdown??`# ${e.name}\n`,name:e.name,sourceId:createMemorySourceId(`skills/${e.name}.md`),sourceKind:`markdown`})),tools:o}),moduleMap:{nodes:{[ROOT_COMPILED_AGENT_NODE_ID]:{modules:Object.fromEntries(o.map(e=>[e.sourceId,Object.freeze({})]))}}}}}function createMemorySourceId(e){return`memory::${e}`}export{compileFromMemory};
|
|
1
|
+
import{classifyModelRouting}from"#internal/classify-model-routing.js";import{ROOT_COMPILED_AGENT_NODE_ID,createCompiledAgentManifest}from"#compiler/manifest.js";function compileFromMemory(t){let n=t.appRoot??`/virtual/eve-memory-app`,r=t.agentRoot??`${n}/agent`,i=t.name??`memory-agent`,a={model:{id:t.model,routing:classifyModelRouting(t.model)},name:i};t.limits!==void 0&&(a.limits=t.limits),t.outputSchema!==void 0&&(a.outputSchema=t.outputSchema);let o=(t.tools??[]).map(e=>({description:e.description??`${e.name} test tool.`,inputSchema:e.inputSchema??null,logicalPath:`tools/${e.name}.ts`,name:e.name,outputSchema:e.outputSchema,sourceId:createMemorySourceId(`tools/${e.name}.ts`),sourceKind:`module`}));return{manifest:createCompiledAgentManifest({agentRoot:r,appRoot:n,config:a,skills:(t.skills??[]).map(e=>({description:e.description,logicalPath:`skills/${e.name}.md`,markdown:e.markdown??`# ${e.name}\n`,name:e.name,sourceId:createMemorySourceId(`skills/${e.name}.md`),sourceKind:`markdown`})),tools:o}),moduleMap:{nodes:{[ROOT_COMPILED_AGENT_NODE_ID]:{modules:Object.fromEntries(o.map(e=>[e.sourceId,Object.freeze({})]))}}}}}function createMemorySourceId(e){return`memory::${e}`}export{compileFromMemory};
|
|
@@ -11,23 +11,23 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
11
11
|
readonly dropped: {};
|
|
12
12
|
};
|
|
13
13
|
readonly tool: {
|
|
14
|
-
readonly current:
|
|
15
|
-
readonly supported: readonly [1];
|
|
14
|
+
readonly current: 2;
|
|
15
|
+
readonly supported: readonly [1, 2];
|
|
16
16
|
readonly dropped: {};
|
|
17
17
|
};
|
|
18
18
|
readonly dynamicTool: {
|
|
19
|
-
readonly current:
|
|
20
|
-
readonly supported: readonly [1, 2];
|
|
19
|
+
readonly current: 3;
|
|
20
|
+
readonly supported: readonly [1, 2, 3];
|
|
21
21
|
readonly dropped: {};
|
|
22
22
|
};
|
|
23
23
|
readonly connection: {
|
|
24
|
-
readonly current:
|
|
25
|
-
readonly supported: readonly [1];
|
|
24
|
+
readonly current: 2;
|
|
25
|
+
readonly supported: readonly [1, 2];
|
|
26
26
|
readonly dropped: {};
|
|
27
27
|
};
|
|
28
28
|
readonly hook: {
|
|
29
|
-
readonly current:
|
|
30
|
-
readonly supported: readonly [1];
|
|
29
|
+
readonly current: 2;
|
|
30
|
+
readonly supported: readonly [1, 2];
|
|
31
31
|
readonly dropped: {};
|
|
32
32
|
};
|
|
33
33
|
readonly skill: {
|
|
@@ -56,8 +56,8 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
|
|
|
56
56
|
readonly dropped: {};
|
|
57
57
|
};
|
|
58
58
|
readonly state: {
|
|
59
|
-
readonly current:
|
|
60
|
-
readonly supported: readonly [1];
|
|
59
|
+
readonly current: 2;
|
|
60
|
+
readonly supported: readonly [1, 2];
|
|
61
61
|
readonly dropped: {};
|
|
62
62
|
};
|
|
63
63
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{readFile,writeFile}from"node:fs/promises";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:
|
|
1
|
+
import{z}from"#compiled/zod/index.js";import{join}from"node:path";import{readFile,writeFile}from"node:fs/promises";import{formatValidationError}from"#runtime/validation.js";const EXTENSION_COMPATIBILITY_MANIFEST_KIND=`eve-extension`,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION=1,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME=`_manifest.json`,EXTENSION_CAPABILITY_CONTRACTS={extension:{current:1,supported:[1],dropped:{}},tool:{current:2,supported:[1,2],dropped:{}},dynamicTool:{current:3,supported:[1,2,3],dropped:{}},connection:{current:2,supported:[1,2],dropped:{}},hook:{current:2,supported:[1,2],dropped:{}},skill:{current:1,supported:[1],dropped:{}},dynamicSkill:{current:1,supported:[1],dropped:{}},instructions:{current:1,supported:[1],dropped:{}},dynamicInstructions:{current:1,supported:[1],dropped:{}},config:{current:1,supported:[1],dropped:{}},state:{current:2,supported:[1,2],dropped:{}}},EXTENSION_CAPABILITY_VERSIONS=Object.fromEntries(Object.entries(EXTENSION_CAPABILITY_CONTRACTS).map(([e,t])=>[e,t.current])),EXTENSION_CAPABILITY_SUPPORT=Object.keys(EXTENSION_CAPABILITY_CONTRACTS).reduce((e,t)=>(e[t]=EXTENSION_CAPABILITY_CONTRACTS[t].supported,e),{}),extensionCompatibilityManifestSchema=z.object({kind:z.literal(EXTENSION_COMPATIBILITY_MANIFEST_KIND),formatVersion:z.literal(1),builtWithEve:z.string().min(1),requires:z.record(z.string(),z.number().int().positive())}).strict();function serializeExtensionCompatibilityManifest(e){return`${JSON.stringify(e,null,2)}\n`}function parseExtensionCompatibilityManifest(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`Extension compatibility manifest "${t}" is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}let r=extensionCompatibilityManifestSchema.safeParse(n);if(!r.success)throw Error(`Extension compatibility manifest "${t}" is invalid. ${formatValidationError(r.error)}`);return r.data}async function readExtensionCompatibilityManifest(e){return parseExtensionCompatibilityManifest(await readFile(e,`utf8`),e)}async function writeExtensionCompatibilityManifest(e,n){await writeFile(join(e,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME),serializeExtensionCompatibilityManifest(n),`utf8`)}function findUnsupportedExtensionCapabilities(e,t=EXTENSION_CAPABILITY_SUPPORT){return Object.entries(e.requires).flatMap(([e,n])=>{let r=Object.hasOwn(t,e)?t[e]??[]:[];return r.includes(n)?[]:[{capability:e,requiredVersion:n,supportedVersions:r}]}).sort((e,t)=>e.capability.localeCompare(t.capability))}export{EXTENSION_CAPABILITY_SUPPORT,EXTENSION_CAPABILITY_VERSIONS,EXTENSION_COMPATIBILITY_MANIFEST_FILENAME,EXTENSION_COMPATIBILITY_MANIFEST_FORMAT_VERSION,EXTENSION_COMPATIBILITY_MANIFEST_KIND,findUnsupportedExtensionCapabilities,parseExtensionCompatibilityManifest,readExtensionCompatibilityManifest,serializeExtensionCompatibilityManifest,writeExtensionCompatibilityManifest};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { DeliverPayload } from "#channel/types.js";
|
|
2
|
-
/** Coalesces channel payloads while preserving
|
|
2
|
+
/** Coalesces channel payloads while preserving turn input and adapter-specific fields. */
|
|
3
3
|
export declare function coalesceDeliverPayloads(payloads: readonly DeliverPayload[]): DeliverPayload;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function coalesceDeliverPayloads(
|
|
1
|
+
import{coalesceTurnInputs}from"#harness/messages.js";const COALESCED_DELIVER_FIELDS=[`context`,`inputResponses`,`message`,`outputSchema`];function coalesceDeliverPayloads(n){if(n.length===0)return{};if(n.length===1)return n[0]??{};let r={},i={};for(let t of n){for(let[e,n]of Object.entries(t))n!==void 0&&(r[e]=n);i=coalesceTurnInputs(i,t)}for(let e of COALESCED_DELIVER_FIELDS)delete r[e];return Object.assign(r,i)}export{coalesceDeliverPayloads};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{
|
|
1
|
+
import{coalesceDeliveries}from"#harness/messages.js";import{readSerializedSubagentDepth}from"#harness/subagent-depth.js";import{createHook,getWorkflowMetadata,getWritable}from"#compiled/@workflow/core/index.js";import{disposeHook}from"#execution/hook-ownership.js";import{normalizeSerializableError}from"#execution/workflow-errors.js";import{routeDeliverToChildren}from"#execution/route-child-delivery.js";import{readChannelRequestId,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{notifyDelegatedParentStep}from"#execution/delegated-parent-notification.js";import{createDelegatedSubagentErrorResult,createDelegatedSubagentSuccessResult}from"#execution/delegated-parent-result.js";import{dispatchAndAwaitTurn}from"#execution/turn-dispatch.js";import{createSessionStep}from"#execution/create-session-step.js";import{settleCancelledTurnStep}from"#execution/settle-cancelled-turn-step.js";import{emitTerminalSessionFailureStep}from"#execution/terminal-session-failure-step.js";import{fireSessionCallbackStep}from"#execution/session-callback-step.js";import{createSessionDeliveryHook}from"#execution/session-delivery-hook.js";async function workflowEntry(e){"use workflow";let{workflowRunId:n}=getWorkflowMetadata(),a=e.serializedContext[`eve.continuationToken`]||``,s=e.serializedContext[`eve.mode`],u=e.serializedContext[`eve.capabilities`],d=e.serializedContext[`eve.bundle`];e.serializedContext[`eve.sessionId`]=n;let f=getWritable();try{let r=readRootSessionId(e.serializedContext),i=readSerializedSubagentDepth(e.serializedContext),{state:o}=await createSessionStep({compiledArtifactsSource:d.source,continuationToken:a,inheritedLimits:e.limits,nodeId:d.nodeId,outputSchema:e.input.outputSchema,rootSessionId:r,sessionId:n,subagentDepth:i});return await runDriverLoop({capabilities:u,driverWritable:f,initialInput:{kind:`deliver`,payloads:[{message:e.input.message,context:e.input.context,outputSchema:e.input.outputSchema}],requestId:readChannelRequestId(e.serializedContext)},mode:s,serializedContext:e.serializedContext,sessionState:o})}catch(t){throw await emitTerminalSessionFailureStep({error:normalizeSerializableError(t),parentWritable:f,serializedContext:e.serializedContext}),await fireSessionCallbackStep({error:normalizeSerializableError(t),serializedContext:e.serializedContext,status:`failed`}),await notifyDelegatedParentStep({result:createDelegatedSubagentErrorResult(e.serializedContext,t),serializedContext:e.serializedContext}),t}}async function runDriverLoop(e){let t=createHook({token:`${e.sessionState.sessionId}:auth`}),r=t[Symbol.asyncIterator](),i=0,nextTurnControlToken=()=>`${e.sessionState.sessionId}:turn-control:${String(i++)}`,o=[],c=createSessionDeliveryHook(o),l,runTurn=async t=>{let n=await dispatchAndAwaitTurn({bufferedDeliveries:o,capabilities:e.capabilities,controlToken:nextTurnControlToken(),delivery:t.delivery,deliveryHook:c,mode:e.mode,parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState});return await l?.(),l=n.dispose,n.action};try{e.sessionState.continuationToken&&await c.rekey(e.sessionState.continuationToken);let t=await runTurn({delivery:e.initialInput,serializedContext:e.serializedContext,sessionState:e.sessionState});for(;;){if(t.kind===`done`)return await finalizeDone({action:t,driverWritable:e.driverWritable});if(t.kind!==`park`)throw Error(`Driver received unexpected turn action "${t.kind}".`);if(t.cancelled===!0){let n=await settleCancelledTurnStep({parentWritable:e.driverWritable,serializedContext:t.serializedContext,sessionState:t.sessionState});t={...t,serializedContext:n.serializedContext,sessionState:n.sessionState}}if(!t.sessionState.continuationToken)throw Error("Cannot park: no continuation token available. The channel must post the first message during the initial turn (anchoring the session) or `send()` must be called with an explicit continuationToken.");if(await c.rekey(t.sessionState.continuationToken),t.authorizationNames&&t.authorizationNames.length>0){let e=t.authorizationNames.length,n=[];for(;n.length<e;){let e=await r.next();if(e.done)break;e.value.kind===`deliver`&&n.push(...e.value.payloads)}t=await runTurn({delivery:{kind:`deliver`,payloads:n},serializedContext:t.serializedContext,sessionState:t.sessionState});continue}let n=await waitForNextDeliver({bufferedDeliveries:o,deliveryHook:c});if(n===null)return{output:``};let i=await routeDeliverToChildren({auth:n.auth,parentWritable:e.driverWritable,payloads:n.payloads,sessionState:t.sessionState});i!==void 0&&(t=await runTurn({delivery:{auth:n.auth,kind:`deliver`,payloads:[i],requestId:n.requestId},serializedContext:t.serializedContext,sessionState:t.sessionState}))}}finally{await l?.(),await c.dispose(),await disposeHook(t)}}async function finalizeDone(e){let{output:t,serializedContext:n}=e.action,r=e.action.isError===!0;return await fireSessionCallbackStep({error:r?t:void 0,output:r?void 0:t,serializedContext:n,status:r?`failed`:`completed`,usage:r?void 0:e.action.usage}),await notifyDelegatedParentStep({result:r?createDelegatedSubagentErrorResult(n,t):createDelegatedSubagentSuccessResult(n,t),serializedContext:n,usage:r?void 0:e.action.usage}),{output:t}}async function waitForNextDeliver(t){if(t.bufferedDeliveries.length>0)return coalesceDeliveries(t.bufferedDeliveries.splice(0));for(;;){let n=await t.deliveryHook.next();if(t.deliveryHook.consumeNext(),n.done)return null;if(n.value.kind!==`deliver`)continue;let r=n.value;for(;;){let n=await takeReadyPayload(t.deliveryHook.next());if(n===NO_READY_MESSAGE||(t.deliveryHook.consumeNext(),n.done))break;n.value.kind===`deliver`&&(r=coalesceDeliveries([r,n.value]))}return r}}const NO_READY_MESSAGE=Symbol(`no-ready-message`);async function takeReadyPayload(e){return await Promise.resolve(),await Promise.race([e,Promise.resolve(NO_READY_MESSAGE)])}export{workflowEntry};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{createWorkflowRuntime,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resumeHook}from"#internal/workflow/runtime.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{
|
|
1
|
+
import{callAdapterEventHandler,defaultDeliverResult}from"#channel/adapter.js";import{AuthKey,CapabilitiesKey,ModeKey}from"#context/keys.js";import{createAuthorizationCompletedEvent,encodeMessageStreamEvent,timestampHandleMessageStreamEvent}from"#protocol/message.js";import{BundleKey,ChannelKey}from"#runtime/sessions/runtime-context-keys.js";import{getHarnessEmissionState}from"#harness/emission.js";import{deserializeContext,serializeContext}from"#context/serialize.js";import{createDurableSessionState,readDurableSession}from"#execution/durable-session-store.js";import{createWorkflowRuntime,requestWorkflowTurnCancellation,startWorkflowPreferLatest,turnWorkflowReference}from"#execution/workflow-runtime.js";import{getPendingRuntimeActionBatch}from"#harness/runtime-actions.js";import{hydrateDurableSession,refreshSessionFromTurnAgent}from"#execution/session.js";import{resumeHook}from"#internal/workflow/runtime.js";import{coalesceTurnInputs}from"#harness/messages.js";import{buildAdapterContext}from"#channel/adapter-context.js";import{getPendingWorkflowInterrupt}from"#harness/workflow-interrupt-state.js";import{getRuntimeActionKeysFromWorkflowInterrupt,isWorkflowRuntimeActionInterrupt}from"#harness/workflow-runtime-action-state.js";import{dispatchDynamicModelEvent}from"#context/dynamic-model-lifecycle.js";import{resolveWorkflowCallbackBaseUrl}from"#execution/workflow-callback-url.js";import{setChannelContext}from"#execution/channel-context.js";import{dispatchStreamEventHooks}from"#context/hook-lifecycle.js";import{runStep}from"#context/run-step.js";import{reconcileSessionContinuationToken}from"#execution/reconcile-session-continuation-token.js";import{routeDeliverPayload}from"#execution/subagent-hitl-proxy.js";import{CallbackBaseUrlKey,PendingAuthorizationResultKey,clearPendingAuthorization,getPendingAuthorization}from"#harness/authorization.js";import{isSessionLimitDecline,isTurnCancellation,throwIfTurnAborted}from"#harness/turn-cancellation.js";import{createTurnWorkflowInput}from"#execution/durable-session-migrations/turn-workflow.js";import{buildTurnAttributes,readRootSessionId}from"#execution/eve-workflow-attributes.js";import{normalizeEveAttributes}from"#runtime/attributes/normalize.js";import{dispatchDynamicInstructionEvent}from"#context/dynamic-instruction-lifecycle.js";import{dispatchDynamicSkillEvent}from"#context/dynamic-skill-lifecycle.js";import{dispatchDynamicToolEvent}from"#context/dynamic-tool-lifecycle.js";import{hasPendingInputBatch}from"#harness/input-requests.js";import{getTurnUsageState,toUsage}from"#harness/turn-tag-state.js";import{getRuntimeActionRequestKey}from"#runtime/actions/keys.js";import{createExecutionNodeStep}from"#execution/node-step.js";import{recordSubagentUsageSpans}from"#execution/subagent-usage-span.js";async function turnStep(a){"use step";let o=a,s=await readDurableSession(o.sessionState),c=await deserializeContext(o.serializedContext),l=c.require(ChannelKey),u=c.require(BundleKey);try{let{getWorkflowMetadata:e}=await import(`#compiled/@workflow/core/index.js`),t=e();typeof t.url==`string`&&c.set(CallbackBaseUrlKey,resolveWorkflowCallbackBaseUrl(t.url))}catch{}let d=getPendingAuthorization(s.state),f;if(d&&o.input?.kind===`deliver`){let e=[],t=[],n=[];for(let r of o.input.payloads){let i=r.authorizationCallback;if(i){let n=d.challenges.find(e=>e.name===i.connectionName);n&&(e.push({name:n.name,resume:n.resume,callback:i.callback,hookUrl:n.hookUrl}),t.push({name:n.name,authorization:n.challenge}))}else n.push(r)}e.length>0&&(c.set(PendingAuthorizationResultKey,e),s={...s,state:clearPendingAuthorization(s.state,e.map(e=>e.name))},f=t,o=n.length>0?{...o,input:{...o.input,payloads:n}}:{...o,input:void 0})}o.input?.kind===`deliver`&&o.input.auth!==void 0&&c.set(AuthKey,o.input.auth??null);let p=hydrateDurableSession({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},durable:s,turnAgent:u.turnAgent}),m=buildAdapterContext(l,c),h;if(o.input?.kind===`deliver`){let e=[];for(let n of o.input.payloads){let r=l.deliver?await l.deliver(n,m):defaultDeliverResult(n);r!=null&&e.push(r)}h=e.length===0?void 0:e.reduce(coalesceTurnInputs)}else o.input?.kind===`runtime-action-result`&&(recordSubagentUsageSpans(o.input.results),h={runtimeActionResults:o.input.results});if(o.input?.kind===`deliver`&&setChannelContext(c,{...l,state:{...m.state}}),o.input?.kind===`deliver`&&h===void 0){let e=reconcileSessionContinuationToken(c,p),t=serializeContext(c),n=e===p?o.sessionState:createDurableSessionState({session:e});return{action:`park`,...derivePendingState(e),serializedContext:t,sessionState:n}}let g=o.parentWritable.getWriter(),_=u.hookRegistry,v=u.resolvedAgent.dynamicInstructionsResolvers??[],y=u.resolvedAgent.dynamicSkillResolvers??[],b=u.resolvedAgent.dynamicToolResolvers??[],emit=async t=>{let n=await callAdapterEventHandler(l,t,m);return setChannelContext(c,{...l,state:{...m.state}}),await g.write(encodeMessageStreamEvent(timestampHandleMessageStreamEvent(n))),n},handleEvent=async(e,t)=>{let n=await emit(e);await dispatchStreamEventHooks({ctx:c,registry:_,event:n}),n.type!==`step.started`&&await dispatchDynamicModelEvent({ctx:c,dynamicModel:u.turnAgent.dynamicModel,event:n,fallback:u.turnAgent.model,messages:t??[],scope:{moduleMap:u.moduleMap,nodeId:u.nodeId}}),await dispatchDynamicToolEvent({ctx:c,resolvers:b,event:n,messages:t??[]}),await dispatchDynamicSkillEvent({ctx:c,resolvers:y,event:n,messages:t??[]}),await dispatchDynamicInstructionEvent({ctx:c,resolvers:v,event:n,messages:t??[]})},x=c.require(ModeKey),S;try{throwIfTurnAborted(o.abortSignal),S=await runStep(c,p,async e=>{let t=resolveEffectiveOutputSchema({agentOutputSchema:u.turnAgent.outputSchema,input:h,mode:x,session:e});if(f){let e=getHarnessEmissionState(t.state);for(let{name:t,authorization:n}of f)await handleEvent(createAuthorizationCompletedEvent({authorization:n,name:t,outcome:`authorized`,sequence:e.sequence,stepIndex:e.stepIndex,turnId:e.turnId}))}let n=c.get(CapabilitiesKey);return(async(e,t)=>{let r=refreshSessionFromTurnAgent({compactionOverrides:{thresholdPercent:u.resolvedAgent.config.compaction?.thresholdPercent},session:e,turnAgent:u.turnAgent});return createExecutionNodeStep({abortSignal:o.abortSignal,capabilities:n,createRuntime:createWorkflowRuntime,handleEvent,mode:x,modelResolutionScope:{moduleMap:u.moduleMap,nodeId:u.nodeId},node:u.graph.root,workflowMaxSubagents:r.workflowMaxSubagents})(r,t)})(t,h)})}catch(e){if(!isTurnCancellation(e))throw e;if(g.releaseLock(),isSessionLimitDecline(e)){let e=readRootSessionId(o.serializedContext);e!==void 0&&await requestWorkflowTurnCancellation({sessionId:e})}return{action:`cancelled`,serializedContext:o.serializedContext,sessionState:o.sessionState}}let C=reconcileSessionContinuationToken(c,S.session),w=serializeContext(c);S={...S,session:C};let T=createDurableSessionState({session:S.session});if(S.next!==null&&typeof S.next==`object`&&`done`in S.next){await g.close();let e=getTurnUsageState(S.session.state)?.session;return{action:`done`,output:S.next.output,isError:S.next.isError,serializedContext:w,sessionState:T,usage:e===void 0?void 0:toUsage(e)}}if(S.next===null){g.releaseLock();let e=getPendingWorkflowInterrupt(S.session.state);return e!==void 0&&isWorkflowRuntimeActionInterrupt(e.interrupt)?{action:`dispatch-workflow-runtime-actions`,pendingRuntimeActionKeys:getRuntimeActionKeysFromWorkflowInterrupt(e.interrupt),serializedContext:w,sessionState:T}:{action:`park`,...derivePendingState(S.session),serializedContext:w,sessionState:T}}return g.releaseLock(),{action:`continue`,serializedContext:w,sessionState:T}}function derivePendingState(e){let t=getPendingRuntimeActionBatch(e.state),n=getPendingAuthorization(e.state),r={authorizationNames:n?.challenges.map(e=>e.name),hasPendingAuthorization:n!==void 0,hasPendingInputBatch:hasPendingInputBatch(e.state)};return t===void 0?r:{...r,pendingRuntimeActionKeys:t.actions.map(e=>getRuntimeActionRequestKey(e))}}function resolveEffectiveOutputSchema(e){let{agentOutputSchema:t,input:n,mode:r,session:i}=e;return n?.outputSchema===void 0?r===`task`&&i.outputSchema===void 0&&t!==void 0?{...i,outputSchema:t}:i:{...i,outputSchema:n.outputSchema}}async function routeProxiedDeliverStep(e){"use step";let t=await readDurableSession(e.sessionState),n=routeDeliverPayload({payload:e.payload,state:t.state});for(let t of n.forChildren)await resumeHook(t.childContinuationToken,{auth:e.auth,kind:`deliver`,payloads:[t.payload]});return{remainder:n.forSelf}}async function dispatchTurnStep(e){"use step";return{runId:(await startWorkflowPreferLatest(turnWorkflowReference,[createTurnWorkflowInput(e)],{allowReservedAttributes:!0,attributes:normalizeEveAttributes(buildTurnAttributes({parentSessionId:e.sessionState.sessionId,requestId:e.delivery.kind===`deliver`?e.delivery.requestId:void 0,rootSessionId:readRootSessionId(e.serializedContext)??e.sessionState.sessionId}))})).runId}}export{dispatchTurnStep,resolveEffectiveOutputSchema,routeProxiedDeliverStep,turnStep};
|
|
@@ -39,6 +39,14 @@ export declare function createSessionLimitContinuationRequest(input: {
|
|
|
39
39
|
* continuation prompt.
|
|
40
40
|
*/
|
|
41
41
|
export declare function isSessionLimitContinuationRequest(request: InputRequest): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Matches request ids minted by {@link createSessionLimitContinuationRequest}.
|
|
44
|
+
*
|
|
45
|
+
* Continuation requests never enter model history (no matching tool call
|
|
46
|
+
* exists), so the id shape is the only durable marker for recognizing a
|
|
47
|
+
* stale continuation answer after its request left the pending batch.
|
|
48
|
+
*/
|
|
49
|
+
export declare function isSessionLimitContinuationRequestId(requestId: string): boolean;
|
|
42
50
|
/**
|
|
43
51
|
* Resolves the user's answer to a session-limit continuation prompt.
|
|
44
52
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const SESSION_LIMIT_CONTINUATION_TOOL_NAME=`session_limit_continuation`,SESSION_LIMIT_CONTINUE_OPTION_ID=`continue`,SESSION_LIMIT_STOP_OPTION_ID=`stop`;function createSessionLimitContinuationRequest(r){let{sessionId:i,totalUsedTokens:a,violation:o}=r,s=`${i}:limit:${o.kind}:${String(a)}
|
|
1
|
+
const SESSION_LIMIT_CONTINUATION_TOOL_NAME=`session_limit_continuation`,SESSION_LIMIT_CONTINUE_OPTION_ID=`continue`,SESSION_LIMIT_STOP_OPTION_ID=`stop`;function createSessionLimitContinuationRequest(r){let{sessionId:i,totalUsedTokens:a,violation:o}=r,s=`${i}:limit:${o.kind}:${String(a)}`;return{action:{callId:s,input:{kind:o.kind,limit:o.limit,usedTokens:o.usedTokens},kind:`tool-call`,toolName:SESSION_LIMIT_CONTINUATION_TOOL_NAME},allowFreeform:!1,display:`confirmation`,options:[{description:`Grant a fresh token budget`,id:SESSION_LIMIT_CONTINUE_OPTION_ID,label:`Approve`,style:`primary`},{description:`Stop now`,id:SESSION_LIMIT_STOP_OPTION_ID,label:`Stop`,style:`danger`}],prompt:`This session has hit the ${o.kind}-token limit (${formatCompactTokenCount(o.limit)}) per session. This is a guardrail against defective long-running sessions. If session activity looks fine, just approve to keep going.`,requestId:s}}function formatCompactTokenCount(e){return e>=1e6?`${trimTrailingZero(e/1e6)}M`:e>=1e3?`${trimTrailingZero(e/1e3)}K`:String(e)}function trimTrailingZero(e){let t=e.toFixed(1);return t.endsWith(`.0`)?t.slice(0,-2):t}function isSessionLimitContinuationRequest(t){return t.action.toolName===SESSION_LIMIT_CONTINUATION_TOOL_NAME}function isSessionLimitContinuationRequestId(e){return/:limit:(?:input|output):\d+$/u.test(e)}function resolveSessionLimitContinuation(e){let t=e.requests.find(isSessionLimitContinuationRequest);if(t===void 0)return;let n=e.responses.find(e=>e.requestId===t.requestId);if(n!==void 0){if(n.optionId===`continue`)return{granted:!0};if(n.optionId===`stop`)return{granted:!1}}}export{SESSION_LIMIT_CONTINUATION_TOOL_NAME,SESSION_LIMIT_CONTINUE_OPTION_ID,SESSION_LIMIT_STOP_OPTION_ID,createSessionLimitContinuationRequest,isSessionLimitContinuationRequest,isSessionLimitContinuationRequestId,resolveSessionLimitContinuation};
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
*
|
|
6
6
|
* 1. {@link applySessionLimitContinuation} runs after pending-input
|
|
7
7
|
* resolution and acts on the user's answer to a continuation prompt —
|
|
8
|
-
* grant a fresh budget window, or
|
|
8
|
+
* grant a fresh budget window, or cancel the in-flight turn tree.
|
|
9
9
|
* 2. {@link enforceSessionTokenLimit} runs before each model call and, when
|
|
10
10
|
* the session is over budget, parks it on the deterministic continuation
|
|
11
11
|
* prompt (sessions that can reach a human) or fails it (task-mode sessions
|
|
@@ -25,11 +25,14 @@ interface SessionLimitPolicyInput {
|
|
|
25
25
|
*
|
|
26
26
|
* Granted: resets the token budget windows via
|
|
27
27
|
* {@link extendSessionTokenBudget} and lets the step continue transparently.
|
|
28
|
-
* Declined: a user decision, not an error —
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
28
|
+
* Declined: a user decision, not an error — the decline cancels the
|
|
29
|
+
* in-flight turn tree through the standard cancellation path, settling as
|
|
30
|
+
* `turn.cancelled` → `session.waiting` with no failure surfaced anywhere.
|
|
31
|
+
* The harness only declares the intent by throwing
|
|
32
|
+
* {@link SessionLimitDeclinedError}; the execution layer detects it at the
|
|
33
|
+
* step boundary and cancels the root turn, whose cancelled arm cascades to
|
|
34
|
+
* every descendant, so the delegating parent never receives an error result
|
|
35
|
+
* it could retry against a fresh budget share.
|
|
33
36
|
*
|
|
34
37
|
* Returns `result: null` when the step should continue with `session`.
|
|
35
38
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createInputRequestedEvent
|
|
1
|
+
import{createInputRequestedEvent}from"#protocol/message.js";import{emitFailedStep,emitTurnEpilogue,setHarnessEmissionState}from"#harness/emission.js";import{SessionLimitDeclinedError}from"#harness/turn-cancellation.js";import{setPendingInputBatch}from"#harness/input-requests.js";import{extendSessionTokenBudget,getSessionTokenLimitViolation,getSessionTokenUsage}from"#harness/turn-tag-state.js";import{createSessionLimitContinuationRequest}from"#harness/session-limit-continuation.js";async function applySessionLimitContinuation(e){if(e.limitContinuation===void 0)return{result:null,session:e.session};if(e.limitContinuation.granted)return{result:null,session:extendSessionTokenBudget(e.session)};if(!(e.config.mode===`conversation`||e.session.continuationToken!==``)){let t=getSessionTokenLimitViolation(e.session);return{result:t===null?{next:{done:!0,output:``},session:e.session}:await failSessionTokenLimit({...e,violation:t}),session:e.session}}throw new SessionLimitDeclinedError}async function enforceSessionTokenLimit(e){let t=getSessionTokenLimitViolation(e.session);if(t===null)return null;let{emit:n}=e;return n!==void 0&&(e.config.mode===`conversation`||e.config.capabilities?.requestInput===!0)?parkOnSessionTokenLimit({...e,emit:n,violation:t}):failSessionTokenLimit({...e,violation:t})}async function parkOnSessionTokenLimit(t){let i=getSessionTokenUsage(t.session),a=createSessionLimitContinuationRequest({sessionId:t.session.sessionId,totalUsedTokens:t.violation.kind===`input`?i.inputTokens:i.outputTokens,violation:t.violation}),o=t.emissionState,s=setPendingInputBatch({event:{sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId},requests:[a],responseMessages:[],session:{...t.session,history:[...t.messages]}});return await t.emit(createInputRequestedEvent({requests:[a],sequence:o.sequence,stepIndex:o.stepIndex,turnId:o.turnId})),t.config.mode===`conversation`&&(o=await emitTurnEpilogue(t.emit,o,t.config.mode,s.continuationToken)),{next:null,session:setHarnessEmissionState(s,o)}}function formatSessionTokenLimitMessage(e){return`The session reached its configured ${e} token limit.`}async function failSessionTokenLimit(e){let n=getSessionTokenUsage(e.session),r=formatSessionTokenLimitMessage(e.violation.kind),i={inputTokens:n.inputTokens,kind:e.violation.kind,limit:e.violation.limit,outputTokens:n.outputTokens,usedTokens:e.violation.usedTokens};return e.emit&&await emitFailedStep(e.emit,e.emissionState,{code:`SESSION_TOKEN_LIMIT_REACHED`,details:i,message:r,sessionId:e.session.sessionId}),{next:{done:!0,isError:e.config.mode===`task`?!0:void 0,output:e.config.mode===`task`?r:``},session:e.session}}export{applySessionLimitContinuation,enforceSessionTokenLimit};
|
|
@@ -9,14 +9,32 @@ type StaleResponseConversion = {
|
|
|
9
9
|
readonly stepInput: StepInput;
|
|
10
10
|
};
|
|
11
11
|
/**
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
12
|
+
* Filter pass: removes stale answers to session-limit continuation prompts
|
|
13
|
+
* from the step input before any stale handling runs.
|
|
14
|
+
*
|
|
15
|
+
* These are dropped rather than converted: surfacing a stale "Stop" as
|
|
16
|
+
* conversational prose would read fail-open, and a stale grant must not
|
|
17
|
+
* extend any budget — a currently pending prompt (if any) stays parked and
|
|
18
|
+
* re-raises. Stripping the responses also keeps them from resolving (and
|
|
19
|
+
* clearing) a pending batch they never answered. Answers to a currently
|
|
20
|
+
* pending continuation prompt pass through untouched.
|
|
21
|
+
*/
|
|
22
|
+
export declare function dropStaleSessionLimitContinuationResponses(input: {
|
|
23
|
+
readonly pendingRequestIds: ReadonlySet<string>;
|
|
24
|
+
readonly stepInput?: StepInput;
|
|
25
|
+
}): StepInput | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* Transformation pass: a response is stale when its request ID is not in
|
|
28
|
+
* the currently pending HITL batch — the request was already answered,
|
|
29
|
+
* cleared by a follow-up message, or cancelled.
|
|
15
30
|
*
|
|
16
31
|
* Responses for pending requests stay structured; stale responses become
|
|
17
32
|
* plain user-message text. A stale response never reaches structured HITL
|
|
18
33
|
* processing, so a stale approval cannot authorize an earlier tool call.
|
|
19
34
|
* Request details recovered from history are best-effort model context.
|
|
35
|
+
*
|
|
36
|
+
* Assumes {@link dropStaleSessionLimitContinuationResponses} already ran:
|
|
37
|
+
* stale continuation answers must never reach this conversion.
|
|
20
38
|
*/
|
|
21
39
|
export declare function convertStaleResponsesToUserMessage(input: {
|
|
22
40
|
readonly history: readonly ModelMessage[];
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{appendUserContent,normalizeUserContent}from"#harness/messages.js";import{isApprovalRequest}from"#harness/input-requests.js";import{extractHistoricalInputRequests}from"#harness/input-extraction.js";function convertStaleResponsesToUserMessage(e){let t=e.stepInput?.inputResponses;if(e.stepInput===void 0||t===void 0||t.length===0)return{kind:`unchanged`,stepInput:e.stepInput};let n=[],
|
|
1
|
+
import{appendUserContent,normalizeUserContent}from"#harness/messages.js";import{isApprovalRequest}from"#harness/input-requests.js";import{isSessionLimitContinuationRequestId}from"#harness/session-limit-continuation.js";import{extractHistoricalInputRequests}from"#harness/input-extraction.js";function dropStaleSessionLimitContinuationResponses(e){let t=e.stepInput?.inputResponses;if(e.stepInput===void 0||t===void 0||t.length===0)return e.stepInput;let n=t.filter(t=>e.pendingRequestIds.has(t.requestId)||!isSessionLimitContinuationRequestId(t.requestId));if(n.length===t.length)return e.stepInput;let{inputResponses:i,...a}=e.stepInput;return n.length===0?a:{...a,inputResponses:n}}function convertStaleResponsesToUserMessage(e){let t=e.stepInput?.inputResponses;if(e.stepInput===void 0||t===void 0||t.length===0)return{kind:`unchanged`,stepInput:e.stepInput};let n=[],r=[];for(let i of t)e.pendingRequestIds.has(i.requestId)?n.push(i):r.push(i);if(r.length===0)return{kind:`unchanged`,stepInput:e.stepInput};let a=extractHistoricalInputRequests({history:e.history,requestIds:new Set(r.map(e=>e.requestId))}),o=appendOptionalUserContent(e.stepInput.message,formatModelMessage(r,a)),s=appendOptionalUserContent(e.stepInput.message,formatDisplayMessage(r,a)),{inputResponses:c,...l}=e.stepInput,u={...l,message:o};return n.length>0&&(u.inputResponses=n),{displayMessage:s,kind:`converted`,stepInput:u}}function formatModelMessage(e,t){let r=e.map(e=>{let r=t.get(e.requestId),i=r?.options?.find(t=>t.id===e.optionId),a={};if(e.optionId!==void 0&&(a.optionId=e.optionId),i!==void 0){let e={id:i.id,label:i.label};i.description!==void 0&&(e.description=i.description),a.selectedOption=e}e.text!==void 0&&(a.text=e.text);let o={requestId:e.requestId,response:a};return r!==void 0&&(o.prompt=r.prompt,o.requestType=isApprovalRequest(r)?`approval`:`question`),o});return[`The user submitted the following response to an earlier interactive prompt.`,`Treat it as new input at the current point in the conversation and decide whether it is still relevant.${e.some(e=>{let r=t.get(e.requestId);return r===void 0||isApprovalRequest(r)})?` This does not authorize an earlier action; request approval again if that action is still needed.`:``}`,JSON.stringify(r,null,2)].join(`
|
|
2
2
|
`)}function formatDisplayMessage(e,t){return e.map(e=>e.text!==void 0&&e.text.length>0?e.text:t.get(e.requestId)?.options?.find(t=>t.id===e.optionId)?.label??e.optionId??`Response to an earlier interactive prompt`).join(`
|
|
3
|
-
`)}function appendOptionalUserContent(n,r){let i=normalizeUserContent(n);return i===void 0?r:appendUserContent({appended:r,existing:i})}export{convertStaleResponsesToUserMessage};
|
|
3
|
+
`)}function appendOptionalUserContent(n,r){let i=normalizeUserContent(n);return i===void 0?r:appendUserContent({appended:r,existing:i})}export{convertStaleResponsesToUserMessage,dropStaleSessionLimitContinuationResponses};
|