@agentfield/sdk 0.1.92-rc.17 → 0.1.92-rc.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -5,6 +5,7 @@ import { z } from 'zod';
5
5
  import { AxiosInstance } from 'axios';
6
6
  import { WriteStream } from 'node:tty';
7
7
  import { ToolSet } from 'ai';
8
+ import { JWK } from 'jose';
8
9
 
9
10
  type ZodSchema<T> = z.Schema<T, z.ZodTypeDef, any>;
10
11
  interface AIRequestOptions {
@@ -1269,6 +1270,67 @@ declare class DidManager {
1269
1270
  getIdentitySummary(): Record<string, any>;
1270
1271
  }
1271
1272
 
1273
+ /**
1274
+ * DID-based payload encryption (JWE over X25519 keyAgreement keys).
1275
+ *
1276
+ * Encrypt a payload *to* an agent's DID so that only that agent — the holder of
1277
+ * the matching X25519 private key — can decrypt it. This underpins the
1278
+ * discuss/aggregator split: hax-sdk encrypts a scoped payload to the
1279
+ * aggregator's DID; the untrusted discuss agent forwards the ciphertext but
1280
+ * cannot read it; only the aggregator decrypts.
1281
+ *
1282
+ * Wire format is standard **JWE compact, `ECDH-ES` + `A256GCM`** over an X25519
1283
+ * key (RFC 7518 / RFC 8037), interoperable with the Python SDK's
1284
+ * `encrypt_for_did` / `decrypt` (which use `joserfc`). A ciphertext produced
1285
+ * here decrypts there and vice-versa.
1286
+ *
1287
+ * Key-ownership model: the agent owns its keypair. The X25519 private key lives
1288
+ * in the agent's environment; the public key is published in the agent's DID
1289
+ * document as a `keyAgreement` verification method of type
1290
+ * `X25519KeyAgreementKey2020`. The control plane never holds the private key.
1291
+ */
1292
+
1293
+ /** JOSE parameters. Must match the Python SDK exactly for interop. */
1294
+ declare const JWE_ALG: "ECDH-ES";
1295
+ declare const JWE_ENC: "A256GCM";
1296
+ /** W3C verification-method type published in the DID document for the X25519 key. */
1297
+ declare const KEY_AGREEMENT_TYPE: "X25519KeyAgreementKey2020";
1298
+ declare class PayloadEncryptionError extends Error {
1299
+ constructor(message: string);
1300
+ }
1301
+ /** Resolves a DID string to its document (or a control-plane resolve response). */
1302
+ type DidResolver = (did: string) => Promise<Record<string, unknown> | null>;
1303
+ type Payload = string | Uint8Array | Record<string, unknown>;
1304
+ /**
1305
+ * Generate a fresh X25519 keypair for an agent. Persist `privateJwk` into the
1306
+ * agent's environment and publish `publicJwk` as the DID `keyAgreement` key.
1307
+ */
1308
+ declare function generateX25519KeyPair(): Promise<{
1309
+ privateJwk: JWK;
1310
+ publicJwk: JWK;
1311
+ }>;
1312
+ /**
1313
+ * Pull the X25519 `keyAgreement` public JWK out of a resolved DID document.
1314
+ * Handles a bare W3C document or a control-plane response wrapping it under
1315
+ * `did_document`, and a `keyAgreement` entry that is either inline (with
1316
+ * `publicKeyJwk`) or a string reference into `verificationMethod`.
1317
+ */
1318
+ declare function extractKeyAgreementJwk(didDocument: Record<string, unknown>): JWK;
1319
+ /** Encrypt `payload` to an X25519 public JWK, returning a compact JWE string. */
1320
+ declare function encryptToJwk(publicJwk: JWK, payload: Payload): Promise<string>;
1321
+ /**
1322
+ * Resolve `did`, read its X25519 keyAgreement key, and encrypt `payload` to it.
1323
+ * Returns a compact JWE that only the DID's owner can decrypt.
1324
+ */
1325
+ declare function encryptForDid(did: string, payload: Payload, resolver: DidResolver): Promise<string>;
1326
+ /**
1327
+ * Decrypt a compact JWE produced by {@link encryptForDid} or the Python SDK.
1328
+ * Returns the raw plaintext bytes.
1329
+ */
1330
+ declare function decrypt(token: string, privateJwk: JWK): Promise<Uint8Array>;
1331
+ /** Convenience: decrypt and decode the plaintext as UTF-8 text. */
1332
+ declare function decryptToString(token: string, privateJwk: JWK): Promise<string>;
1333
+
1272
1334
  declare class RateLimitError extends Error {
1273
1335
  retryAfter?: number;
1274
1336
  status?: number;
@@ -1990,4 +2052,4 @@ declare class SessionTransportError extends Error {
1990
2052
  declare function normalizeSessionTransportValue(value: string): string;
1991
2053
  declare function validateSessionTransport(provider: string, transport: string): SessionTransportCapability;
1992
2054
 
1993
- export { ACTIVE_STATUSES, AIClient, type AIConfig, type AIEmbeddingOptions, type AIRequestOptions, type AIStream, type AIToolRequestOptions, Agent, type AgentCapability, type AgentConfig, type AgentHandler, AgentRouter, type AgentRouterOptions, type AgentState, ApprovalClient, type ApprovalRequestResponse, type ApprovalStatusResponse, Audio, type AudioOutput, type AudioRequest, type AuditTrailExport, type AuditTrailFilters, type Awaitable, CANONICAL_STATUSES, type CompactCapability, type CompactDiscoveryResponse, DIDAuthenticator, type DIDIdentity, type DIDIdentityPackage, type DIDRegistrationRequest, type DIDRegistrationResponse, type DeploymentType, DidClient, DidInterface, DidManager, type DiscoveryFormat, type DiscoveryOptions, type DiscoveryPagination, type DiscoveryResponse, type DiscoveryResult, ExecutionContext, type ExecutionCredential, type ExecutionLogAttributes, type ExecutionLogBatchPayload, type ExecutionLogContext, type ExecutionLogEmitOptions, type ExecutionLogEntry, type ExecutionLogLevel, type ExecutionLogTransport, type ExecutionLogTransportPayload, type ExecutionLogWireEntry, ExecutionLogger, type ExecutionLoggerOptions, type ExecutionMetadata, ExecutionStatus, type ExecutionStatusValue, File, type FileOutput, type GenerateCredentialOptions, type GenerateCredentialParams, HEADER_CALLER_DID, HEADER_DID_NONCE, HEADER_DID_SIGNATURE, HEADER_DID_TIMESTAMP, type HarnessConfig, type HarnessOptions, type HarnessProvider, type HarnessResult, HarnessRunner, type HealthStatus, Image, type ImageOutput, type ImageRequest, type MediaProvider, MediaProviderError, type MediaResponse, MediaRouter, type MemoryChangeEvent, MemoryClient, MemoryClientBase, type MemoryConfig, MemoryEventClient, type MemoryEventHandler, type MemoryEventHistoryOptions, MemoryInterface, type MemoryRequestMetadata, type MemoryRequestOptions, type MemoryScope, type MemoryWatchHandler, type Metrics, type MultimodalContent, MultimodalResponse, OpenRouterMediaProvider, type OpenRouterMediaProviderOptions, RateLimitError, type RateLimiterOptions, type RawExecutionContext, type RawResult, RealtimeSession, type ReasonerCapability, ReasonerContext, type ReasonerDefinition, type ReasonerHandler, type ReasonerOptions, type RequestApprovalPayload, SUPPORTED_PROVIDERS, SUPPORTED_SESSION_TRANSPORTS, type ServerlessAdapter, type ServerlessEvent, type ServerlessResponse, type SessionDefinition, type SessionOptions, type SessionProvider, type SessionTransport, type SessionTransportCapability, SessionTransportError, type SessionTurn, type SkillCapability, SkillContext, type SkillDefinition, type SkillHandler, type SkillOptions, StatelessRateLimiter, TERMINAL_STATUSES, Text, type ToolCallConfig, type ToolCallRecord, type ToolCallTrace, type ToolsOption, type VectorSearchOptions, type VectorSearchResult, Video, type VideoFrameImage, type VideoInputReference, type VideoRequest, type WaitForApprovalOptions, type WorkflowCredential, type WorkflowMetadata, type WorkflowProgressOptions, WorkflowReporter, type ZodSchema, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildSessionDefinition, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, executeToolCallLoop, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, isActive, isExecutionLogBatchPayload, isTerminal, normalizeExecutionLogEntry, normalizeSessionTransportValue, normalizeStatus, serializeExecutionLogEntry, text, validateSessionTransport, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };
2055
+ export { ACTIVE_STATUSES, AIClient, type AIConfig, type AIEmbeddingOptions, type AIRequestOptions, type AIStream, type AIToolRequestOptions, Agent, type AgentCapability, type AgentConfig, type AgentHandler, AgentRouter, type AgentRouterOptions, type AgentState, ApprovalClient, type ApprovalRequestResponse, type ApprovalStatusResponse, Audio, type AudioOutput, type AudioRequest, type AuditTrailExport, type AuditTrailFilters, type Awaitable, CANONICAL_STATUSES, type CompactCapability, type CompactDiscoveryResponse, DIDAuthenticator, type DIDIdentity, type DIDIdentityPackage, type DIDRegistrationRequest, type DIDRegistrationResponse, type DeploymentType, DidClient, DidInterface, DidManager, type DidResolver, type DiscoveryFormat, type DiscoveryOptions, type DiscoveryPagination, type DiscoveryResponse, type DiscoveryResult, ExecutionContext, type ExecutionCredential, type ExecutionLogAttributes, type ExecutionLogBatchPayload, type ExecutionLogContext, type ExecutionLogEmitOptions, type ExecutionLogEntry, type ExecutionLogLevel, type ExecutionLogTransport, type ExecutionLogTransportPayload, type ExecutionLogWireEntry, ExecutionLogger, type ExecutionLoggerOptions, type ExecutionMetadata, ExecutionStatus, type ExecutionStatusValue, File, type FileOutput, type GenerateCredentialOptions, type GenerateCredentialParams, HEADER_CALLER_DID, HEADER_DID_NONCE, HEADER_DID_SIGNATURE, HEADER_DID_TIMESTAMP, type HarnessConfig, type HarnessOptions, type HarnessProvider, type HarnessResult, HarnessRunner, type HealthStatus, Image, type ImageOutput, type ImageRequest, JWE_ALG, JWE_ENC, KEY_AGREEMENT_TYPE, type MediaProvider, MediaProviderError, type MediaResponse, MediaRouter, type MemoryChangeEvent, MemoryClient, MemoryClientBase, type MemoryConfig, MemoryEventClient, type MemoryEventHandler, type MemoryEventHistoryOptions, MemoryInterface, type MemoryRequestMetadata, type MemoryRequestOptions, type MemoryScope, type MemoryWatchHandler, type Metrics, type MultimodalContent, MultimodalResponse, OpenRouterMediaProvider, type OpenRouterMediaProviderOptions, type Payload, PayloadEncryptionError, RateLimitError, type RateLimiterOptions, type RawExecutionContext, type RawResult, RealtimeSession, type ReasonerCapability, ReasonerContext, type ReasonerDefinition, type ReasonerHandler, type ReasonerOptions, type RequestApprovalPayload, SUPPORTED_PROVIDERS, SUPPORTED_SESSION_TRANSPORTS, type ServerlessAdapter, type ServerlessEvent, type ServerlessResponse, type SessionDefinition, type SessionOptions, type SessionProvider, type SessionTransport, type SessionTransportCapability, SessionTransportError, type SessionTurn, type SkillCapability, SkillContext, type SkillDefinition, type SkillHandler, type SkillOptions, StatelessRateLimiter, TERMINAL_STATUSES, Text, type ToolCallConfig, type ToolCallRecord, type ToolCallTrace, type ToolsOption, type VectorSearchOptions, type VectorSearchResult, Video, type VideoFrameImage, type VideoInputReference, type VideoRequest, type WaitForApprovalOptions, type WorkflowCredential, type WorkflowMetadata, type WorkflowProgressOptions, WorkflowReporter, type ZodSchema, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildSessionDefinition, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, decrypt, decryptToString, encryptForDid, encryptToJwk, executeToolCallLoop, extractKeyAgreementJwk, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, generateX25519KeyPair, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, isActive, isExecutionLogBatchPayload, isTerminal, normalizeExecutionLogEntry, normalizeSessionTransportValue, normalizeStatus, serializeExecutionLogEntry, text, validateSessionTransport, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };
package/dist/index.js CHANGED
@@ -23,6 +23,7 @@ import https from 'https';
23
23
  import WebSocket from 'ws';
24
24
  import { Buffer as Buffer$1 } from 'buffer';
25
25
  import { zodToJsonSchema } from 'zod-to-json-schema';
26
+ import { generateKeyPair, exportJWK, importJWK, CompactEncrypt, compactDecrypt } from 'jose';
26
27
  import { readFile } from 'fs/promises';
27
28
 
28
29
  var __defProp = Object.defineProperty;
@@ -5197,6 +5198,105 @@ var AgentRouter = class {
5197
5198
  function sanitize(value) {
5198
5199
  return value.replace(/[^0-9a-zA-Z]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
5199
5200
  }
5201
+ var JWE_ALG = "ECDH-ES";
5202
+ var JWE_ENC = "A256GCM";
5203
+ var KEY_AGREEMENT_TYPE = "X25519KeyAgreementKey2020";
5204
+ var PayloadEncryptionError = class extends Error {
5205
+ constructor(message) {
5206
+ super(message);
5207
+ this.name = "PayloadEncryptionError";
5208
+ }
5209
+ };
5210
+ var encoder = new TextEncoder();
5211
+ function payloadToBytes(payload) {
5212
+ if (payload instanceof Uint8Array) return payload;
5213
+ if (typeof payload === "string") return encoder.encode(payload);
5214
+ return encoder.encode(JSON.stringify(payload));
5215
+ }
5216
+ async function generateX25519KeyPair() {
5217
+ const { privateKey, publicKey } = await generateKeyPair("ECDH-ES", {
5218
+ crv: "X25519",
5219
+ extractable: true
5220
+ });
5221
+ const privateJwk = await exportJWK(privateKey);
5222
+ const publicJwk = await exportJWK(publicKey);
5223
+ return { privateJwk, publicJwk };
5224
+ }
5225
+ function extractKeyAgreementJwk(didDocument) {
5226
+ if (typeof didDocument !== "object" || didDocument === null) {
5227
+ throw new PayloadEncryptionError("DID document must be an object");
5228
+ }
5229
+ const doc = didDocument["did_document"] ?? didDocument;
5230
+ const flat = doc["key_agreement"];
5231
+ if (flat && typeof flat === "object" && flat.crv === "X25519") {
5232
+ return flat;
5233
+ }
5234
+ const keyAgreement = doc["keyAgreement"];
5235
+ if (!keyAgreement || Array.isArray(keyAgreement) && keyAgreement.length === 0) {
5236
+ throw new PayloadEncryptionError(
5237
+ "DID document has no keyAgreement key; the agent has not published an X25519 encryption key"
5238
+ );
5239
+ }
5240
+ const verificationMethods = /* @__PURE__ */ new Map();
5241
+ for (const vm2 of doc["verificationMethod"] ?? []) {
5242
+ if (vm2 && typeof vm2 === "object" && typeof vm2["id"] === "string") {
5243
+ verificationMethods.set(vm2["id"], vm2);
5244
+ }
5245
+ }
5246
+ const entry = Array.isArray(keyAgreement) ? keyAgreement[0] : keyAgreement;
5247
+ let vm;
5248
+ if (typeof entry === "string") {
5249
+ vm = verificationMethods.get(entry);
5250
+ if (!vm) {
5251
+ throw new PayloadEncryptionError(
5252
+ `keyAgreement references unknown verification method ${entry}`
5253
+ );
5254
+ }
5255
+ } else if (entry && typeof entry === "object") {
5256
+ vm = entry;
5257
+ } else {
5258
+ throw new PayloadEncryptionError("unsupported keyAgreement entry shape");
5259
+ }
5260
+ const jwk = vm["publicKeyJwk"];
5261
+ if (!jwk || jwk.crv !== "X25519") {
5262
+ throw new PayloadEncryptionError(
5263
+ "keyAgreement verification method does not carry an X25519 publicKeyJwk"
5264
+ );
5265
+ }
5266
+ return jwk;
5267
+ }
5268
+ async function encryptToJwk(publicJwk, payload) {
5269
+ if (!publicJwk || publicJwk.crv !== "X25519") {
5270
+ throw new PayloadEncryptionError("publicJwk must be an X25519 OKP JWK");
5271
+ }
5272
+ try {
5273
+ const key = await importJWK(publicJwk, JWE_ALG);
5274
+ return await new CompactEncrypt(payloadToBytes(payload)).setProtectedHeader({ alg: JWE_ALG, enc: JWE_ENC }).encrypt(key);
5275
+ } catch (err) {
5276
+ if (err instanceof PayloadEncryptionError) throw err;
5277
+ throw new PayloadEncryptionError(`encryption failed: ${err.message}`);
5278
+ }
5279
+ }
5280
+ async function encryptForDid(did, payload, resolver) {
5281
+ const document = await resolver(did);
5282
+ if (!document) {
5283
+ throw new PayloadEncryptionError(`could not resolve DID ${did}`);
5284
+ }
5285
+ const publicJwk = extractKeyAgreementJwk(document);
5286
+ return encryptToJwk(publicJwk, payload);
5287
+ }
5288
+ async function decrypt(token, privateJwk) {
5289
+ try {
5290
+ const key = await importJWK(privateJwk, JWE_ALG);
5291
+ const { plaintext } = await compactDecrypt(token, key);
5292
+ return Uint8Array.from(plaintext);
5293
+ } catch (err) {
5294
+ throw new PayloadEncryptionError(`decryption failed: ${err.message}`);
5295
+ }
5296
+ }
5297
+ async function decryptToString(token, privateJwk) {
5298
+ return new TextDecoder().decode(await decrypt(token, privateJwk));
5299
+ }
5200
5300
  var IMAGE_MIME_TYPES = {
5201
5301
  ".jpg": "image/jpeg",
5202
5302
  ".jpeg": "image/jpeg",
@@ -6618,6 +6718,6 @@ function sleep2(ms) {
6618
6718
  return new Promise((resolve2) => setTimeout(resolve2, ms));
6619
6719
  }
6620
6720
 
6621
- export { ACTIVE_STATUSES, AIClient, Agent, AgentRouter, ApprovalClient, Audio, CANONICAL_STATUSES, DIDAuthenticator, DidClient, DidInterface, DidManager, ExecutionContext, ExecutionLogger, ExecutionStatus, File, HEADER_CALLER_DID, HEADER_DID_NONCE, HEADER_DID_SIGNATURE, HEADER_DID_TIMESTAMP, HarnessRunner, Image, MediaProviderError, MediaRouter, MemoryClient, MemoryClientBase, MemoryEventClient, MemoryInterface, MultimodalResponse, OpenRouterMediaProvider, RateLimitError, RealtimeSession, ReasonerContext, SUPPORTED_PROVIDERS, SUPPORTED_SESSION_TRANSPORTS, SessionTransportError, SkillContext, StatelessRateLimiter, TERMINAL_STATUSES, Text, Video, WorkflowReporter, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildSessionDefinition, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, executeToolCallLoop, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, isActive, isExecutionLogBatchPayload, isTerminal, normalizeExecutionLogEntry, normalizeSessionTransportValue, normalizeStatus, serializeExecutionLogEntry, text, validateSessionTransport, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };
6721
+ export { ACTIVE_STATUSES, AIClient, Agent, AgentRouter, ApprovalClient, Audio, CANONICAL_STATUSES, DIDAuthenticator, DidClient, DidInterface, DidManager, ExecutionContext, ExecutionLogger, ExecutionStatus, File, HEADER_CALLER_DID, HEADER_DID_NONCE, HEADER_DID_SIGNATURE, HEADER_DID_TIMESTAMP, HarnessRunner, Image, JWE_ALG, JWE_ENC, KEY_AGREEMENT_TYPE, MediaProviderError, MediaRouter, MemoryClient, MemoryClientBase, MemoryEventClient, MemoryInterface, MultimodalResponse, OpenRouterMediaProvider, PayloadEncryptionError, RateLimitError, RealtimeSession, ReasonerContext, SUPPORTED_PROVIDERS, SUPPORTED_SESSION_TRANSPORTS, SessionTransportError, SkillContext, StatelessRateLimiter, TERMINAL_STATUSES, Text, Video, WorkflowReporter, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildSessionDefinition, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, decrypt, decryptToString, encryptForDid, encryptToJwk, executeToolCallLoop, extractKeyAgreementJwk, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, generateX25519KeyPair, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, isActive, isExecutionLogBatchPayload, isTerminal, normalizeExecutionLogEntry, normalizeSessionTransportValue, normalizeStatus, serializeExecutionLogEntry, text, validateSessionTransport, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };
6622
6722
  //# sourceMappingURL=index.js.map
6623
6723
  //# sourceMappingURL=index.js.map