@agentfield/sdk 0.1.92-rc.2 → 0.1.92-rc.20
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 +139 -1
- package/dist/index.js +250 -7
- package/dist/index.js.map +1 -1
- package/package.json +8 -4
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 {
|
|
@@ -273,6 +274,14 @@ interface ExecutionStatusUpdate {
|
|
|
273
274
|
progress?: number;
|
|
274
275
|
statusReason?: string;
|
|
275
276
|
}
|
|
277
|
+
interface RestartExecutionOptions {
|
|
278
|
+
scope?: 'workflow' | 'execution';
|
|
279
|
+
reuse?: 'succeeded-before' | 'all-succeeded' | 'none';
|
|
280
|
+
fork?: boolean;
|
|
281
|
+
reason?: string;
|
|
282
|
+
input?: Record<string, unknown>;
|
|
283
|
+
context?: Record<string, unknown>;
|
|
284
|
+
}
|
|
276
285
|
declare class AgentFieldClient {
|
|
277
286
|
private readonly http;
|
|
278
287
|
private readonly config;
|
|
@@ -294,7 +303,11 @@ declare class AgentFieldClient {
|
|
|
294
303
|
targetDid?: string;
|
|
295
304
|
agentNodeDid?: string;
|
|
296
305
|
agentNodeId?: string;
|
|
306
|
+
replaySourceRunId?: string;
|
|
307
|
+
replayBeforeExecutionId?: string;
|
|
308
|
+
replayMode?: string;
|
|
297
309
|
}): Promise<T>;
|
|
310
|
+
restartExecution(executionId: string, options?: RestartExecutionOptions): Promise<any>;
|
|
298
311
|
publishWorkflowEvent(event: {
|
|
299
312
|
executionId: string;
|
|
300
313
|
runId: string;
|
|
@@ -369,6 +382,9 @@ interface ExecutionMetadata {
|
|
|
369
382
|
callerDid?: string;
|
|
370
383
|
targetDid?: string;
|
|
371
384
|
agentNodeDid?: string;
|
|
385
|
+
replaySourceRunId?: string;
|
|
386
|
+
replayBeforeExecutionId?: string;
|
|
387
|
+
replayMode?: string;
|
|
372
388
|
}
|
|
373
389
|
declare class ExecutionContext {
|
|
374
390
|
readonly input: any;
|
|
@@ -1085,6 +1101,45 @@ declare class HarnessRunner {
|
|
|
1085
1101
|
private sleep;
|
|
1086
1102
|
}
|
|
1087
1103
|
|
|
1104
|
+
interface SessionDefinition {
|
|
1105
|
+
name: string;
|
|
1106
|
+
provider: string;
|
|
1107
|
+
transport: string;
|
|
1108
|
+
model?: string;
|
|
1109
|
+
modalities: string[];
|
|
1110
|
+
voice?: string;
|
|
1111
|
+
tools: string[];
|
|
1112
|
+
tags: string[];
|
|
1113
|
+
proposed_tags: string[];
|
|
1114
|
+
approved_tags: string[];
|
|
1115
|
+
metadata: Record<string, unknown>;
|
|
1116
|
+
}
|
|
1117
|
+
interface SessionOptions {
|
|
1118
|
+
provider: string;
|
|
1119
|
+
transport: string;
|
|
1120
|
+
model?: string;
|
|
1121
|
+
modalities?: string[];
|
|
1122
|
+
voice?: string;
|
|
1123
|
+
tools?: string[];
|
|
1124
|
+
tags?: string[];
|
|
1125
|
+
metadata?: Record<string, unknown>;
|
|
1126
|
+
}
|
|
1127
|
+
interface SessionTurn {
|
|
1128
|
+
text?: string;
|
|
1129
|
+
transcript?: string;
|
|
1130
|
+
audio?: unknown;
|
|
1131
|
+
audioFormat?: string;
|
|
1132
|
+
channel?: string;
|
|
1133
|
+
metadata?: Record<string, unknown>;
|
|
1134
|
+
}
|
|
1135
|
+
declare class RealtimeSession {
|
|
1136
|
+
readonly sessionId: string;
|
|
1137
|
+
readonly definition: SessionDefinition;
|
|
1138
|
+
constructor(sessionId: string, definition: SessionDefinition);
|
|
1139
|
+
input(): Promise<SessionTurn>;
|
|
1140
|
+
}
|
|
1141
|
+
declare function buildSessionDefinition(name: string, options: SessionOptions): SessionDefinition;
|
|
1142
|
+
|
|
1088
1143
|
declare class Agent {
|
|
1089
1144
|
readonly config: AgentConfig;
|
|
1090
1145
|
readonly app: express.Express;
|
|
@@ -1101,6 +1156,7 @@ declare class Agent {
|
|
|
1101
1156
|
private readonly memoryWatchers;
|
|
1102
1157
|
private readonly localVerifier?;
|
|
1103
1158
|
private readonly realtimeValidationFunctions;
|
|
1159
|
+
private readonly sessions;
|
|
1104
1160
|
private readonly processLogRing;
|
|
1105
1161
|
private readonly executionLogger;
|
|
1106
1162
|
/** Tracks an AbortController per in-flight execution_id so the
|
|
@@ -1112,6 +1168,8 @@ declare class Agent {
|
|
|
1112
1168
|
reasoner<TInput = any, TOutput = any>(name: string, handler: ReasonerHandler<TInput, TOutput>, options?: ReasonerOptions): this;
|
|
1113
1169
|
skill<TInput = any, TOutput = any>(name: string, handler: SkillHandler<TInput, TOutput>, options?: SkillOptions): this;
|
|
1114
1170
|
includeRouter(router: AgentRouter): void;
|
|
1171
|
+
session(name: string, options: SessionOptions, handler: (session: RealtimeSession) => Promise<unknown> | unknown): this;
|
|
1172
|
+
sessionDefinitions(): SessionDefinition[];
|
|
1115
1173
|
handler(adapter?: (event: any, context?: any) => ServerlessEvent): AgentHandler;
|
|
1116
1174
|
watchMemory(pattern: string | string[], handler: MemoryWatchHandler, options?: {
|
|
1117
1175
|
scope?: string;
|
|
@@ -1227,6 +1285,67 @@ declare class DidManager {
|
|
|
1227
1285
|
getIdentitySummary(): Record<string, any>;
|
|
1228
1286
|
}
|
|
1229
1287
|
|
|
1288
|
+
/**
|
|
1289
|
+
* DID-based payload encryption (JWE over X25519 keyAgreement keys).
|
|
1290
|
+
*
|
|
1291
|
+
* Encrypt a payload *to* an agent's DID so that only that agent — the holder of
|
|
1292
|
+
* the matching X25519 private key — can decrypt it. This underpins the
|
|
1293
|
+
* discuss/aggregator split: hax-sdk encrypts a scoped payload to the
|
|
1294
|
+
* aggregator's DID; the untrusted discuss agent forwards the ciphertext but
|
|
1295
|
+
* cannot read it; only the aggregator decrypts.
|
|
1296
|
+
*
|
|
1297
|
+
* Wire format is standard **JWE compact, `ECDH-ES` + `A256GCM`** over an X25519
|
|
1298
|
+
* key (RFC 7518 / RFC 8037), interoperable with the Python SDK's
|
|
1299
|
+
* `encrypt_for_did` / `decrypt` (which use `joserfc`). A ciphertext produced
|
|
1300
|
+
* here decrypts there and vice-versa.
|
|
1301
|
+
*
|
|
1302
|
+
* Key-ownership model: the agent owns its keypair. The X25519 private key lives
|
|
1303
|
+
* in the agent's environment; the public key is published in the agent's DID
|
|
1304
|
+
* document as a `keyAgreement` verification method of type
|
|
1305
|
+
* `X25519KeyAgreementKey2020`. The control plane never holds the private key.
|
|
1306
|
+
*/
|
|
1307
|
+
|
|
1308
|
+
/** JOSE parameters. Must match the Python SDK exactly for interop. */
|
|
1309
|
+
declare const JWE_ALG: "ECDH-ES";
|
|
1310
|
+
declare const JWE_ENC: "A256GCM";
|
|
1311
|
+
/** W3C verification-method type published in the DID document for the X25519 key. */
|
|
1312
|
+
declare const KEY_AGREEMENT_TYPE: "X25519KeyAgreementKey2020";
|
|
1313
|
+
declare class PayloadEncryptionError extends Error {
|
|
1314
|
+
constructor(message: string);
|
|
1315
|
+
}
|
|
1316
|
+
/** Resolves a DID string to its document (or a control-plane resolve response). */
|
|
1317
|
+
type DidResolver = (did: string) => Promise<Record<string, unknown> | null>;
|
|
1318
|
+
type Payload = string | Uint8Array | Record<string, unknown>;
|
|
1319
|
+
/**
|
|
1320
|
+
* Generate a fresh X25519 keypair for an agent. Persist `privateJwk` into the
|
|
1321
|
+
* agent's environment and publish `publicJwk` as the DID `keyAgreement` key.
|
|
1322
|
+
*/
|
|
1323
|
+
declare function generateX25519KeyPair(): Promise<{
|
|
1324
|
+
privateJwk: JWK;
|
|
1325
|
+
publicJwk: JWK;
|
|
1326
|
+
}>;
|
|
1327
|
+
/**
|
|
1328
|
+
* Pull the X25519 `keyAgreement` public JWK out of a resolved DID document.
|
|
1329
|
+
* Handles a bare W3C document or a control-plane response wrapping it under
|
|
1330
|
+
* `did_document`, and a `keyAgreement` entry that is either inline (with
|
|
1331
|
+
* `publicKeyJwk`) or a string reference into `verificationMethod`.
|
|
1332
|
+
*/
|
|
1333
|
+
declare function extractKeyAgreementJwk(didDocument: Record<string, unknown>): JWK;
|
|
1334
|
+
/** Encrypt `payload` to an X25519 public JWK, returning a compact JWE string. */
|
|
1335
|
+
declare function encryptToJwk(publicJwk: JWK, payload: Payload): Promise<string>;
|
|
1336
|
+
/**
|
|
1337
|
+
* Resolve `did`, read its X25519 keyAgreement key, and encrypt `payload` to it.
|
|
1338
|
+
* Returns a compact JWE that only the DID's owner can decrypt.
|
|
1339
|
+
*/
|
|
1340
|
+
declare function encryptForDid(did: string, payload: Payload, resolver: DidResolver): Promise<string>;
|
|
1341
|
+
/**
|
|
1342
|
+
* Decrypt a compact JWE produced by {@link encryptForDid} or the Python SDK.
|
|
1343
|
+
* Returns the raw plaintext bytes.
|
|
1344
|
+
*/
|
|
1345
|
+
declare function decrypt(token: string, privateJwk: JWK): Promise<Uint8Array>;
|
|
1346
|
+
/** Convenience: decrypt and decode the plaintext as UTF-8 text. */
|
|
1347
|
+
declare function decryptToString(token: string, privateJwk: JWK): Promise<string>;
|
|
1348
|
+
|
|
1230
1349
|
declare class RateLimitError extends Error {
|
|
1231
1350
|
retryAfter?: number;
|
|
1232
1351
|
status?: number;
|
|
@@ -1929,4 +2048,23 @@ declare class ApprovalClient {
|
|
|
1929
2048
|
waitForApproval(executionId: string, opts?: WaitForApprovalOptions): Promise<ApprovalStatusResponse>;
|
|
1930
2049
|
}
|
|
1931
2050
|
|
|
1932
|
-
|
|
2051
|
+
declare const SUPPORTED_SESSION_TRANSPORTS: {
|
|
2052
|
+
readonly openai: readonly ["webrtc", "websocket"];
|
|
2053
|
+
readonly openrouter: readonly ["audio_turns"];
|
|
2054
|
+
};
|
|
2055
|
+
type SessionProvider = keyof typeof SUPPORTED_SESSION_TRANSPORTS;
|
|
2056
|
+
type SessionTransport = (typeof SUPPORTED_SESSION_TRANSPORTS)[SessionProvider][number];
|
|
2057
|
+
interface SessionTransportCapability {
|
|
2058
|
+
provider: SessionProvider;
|
|
2059
|
+
transport: SessionTransport;
|
|
2060
|
+
}
|
|
2061
|
+
declare class SessionTransportError extends Error {
|
|
2062
|
+
readonly provider: string;
|
|
2063
|
+
readonly transport: string;
|
|
2064
|
+
readonly supported: readonly string[];
|
|
2065
|
+
constructor(provider: string, transport: string, supported: readonly string[]);
|
|
2066
|
+
}
|
|
2067
|
+
declare function normalizeSessionTransportValue(value: string): string;
|
|
2068
|
+
declare function validateSessionTransport(provider: string, transport: string): SessionTransportCapability;
|
|
2069
|
+
|
|
2070
|
+
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,12 +23,18 @@ 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;
|
|
29
30
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
30
|
-
var __esm = (fn, res) => function __init() {
|
|
31
|
-
|
|
31
|
+
var __esm = (fn, res, err) => function __init() {
|
|
32
|
+
if (err) throw err[0];
|
|
33
|
+
try {
|
|
34
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
35
|
+
} catch (e) {
|
|
36
|
+
throw err = [e], e;
|
|
37
|
+
}
|
|
32
38
|
};
|
|
33
39
|
var __export = (target, all) => {
|
|
34
40
|
for (var name in all)
|
|
@@ -813,6 +819,7 @@ var init_runner = __esm({
|
|
|
813
819
|
constructor(config) {
|
|
814
820
|
this.config = config;
|
|
815
821
|
}
|
|
822
|
+
config;
|
|
816
823
|
async run(prompt, options = {}) {
|
|
817
824
|
const { schema, ...rest } = options;
|
|
818
825
|
const resolved = this.resolveOptions(this.config, rest);
|
|
@@ -2323,6 +2330,9 @@ var AgentFieldClient = class {
|
|
|
2323
2330
|
if (metadata?.targetDid) headers["X-Target-DID"] = metadata.targetDid;
|
|
2324
2331
|
if (metadata?.agentNodeDid) headers["X-Agent-Node-DID"] = metadata.agentNodeDid;
|
|
2325
2332
|
if (metadata?.agentNodeId) headers["X-Agent-Node-ID"] = metadata.agentNodeId;
|
|
2333
|
+
if (metadata?.replaySourceRunId) headers["X-AgentField-Replay-Source-Run-ID"] = metadata.replaySourceRunId;
|
|
2334
|
+
if (metadata?.replayBeforeExecutionId) headers["X-AgentField-Replay-Before-Execution-ID"] = metadata.replayBeforeExecutionId;
|
|
2335
|
+
if (metadata?.replayMode) headers["X-AgentField-Replay-Mode"] = metadata.replayMode;
|
|
2326
2336
|
const bodyStr = JSON.stringify({ input });
|
|
2327
2337
|
const authHeaders = this.didAuthenticator.signRequest(Buffer.from(bodyStr));
|
|
2328
2338
|
try {
|
|
@@ -2349,6 +2359,44 @@ var AgentFieldClient = class {
|
|
|
2349
2359
|
throw err;
|
|
2350
2360
|
}
|
|
2351
2361
|
}
|
|
2362
|
+
async restartExecution(executionId, options = {}) {
|
|
2363
|
+
if (!executionId) {
|
|
2364
|
+
throw new Error("executionId is required");
|
|
2365
|
+
}
|
|
2366
|
+
const body = {
|
|
2367
|
+
scope: options.scope ?? "workflow",
|
|
2368
|
+
reuse: options.reuse ?? "succeeded-before",
|
|
2369
|
+
fork: options.fork,
|
|
2370
|
+
reason: options.reason,
|
|
2371
|
+
input: options.input,
|
|
2372
|
+
context: options.context
|
|
2373
|
+
};
|
|
2374
|
+
const bodyStr = JSON.stringify(body);
|
|
2375
|
+
const authHeaders = this.didAuthenticator.signRequest(Buffer.from(bodyStr));
|
|
2376
|
+
try {
|
|
2377
|
+
const res = await this.http.post(
|
|
2378
|
+
`/api/v1/executions/${encodeURIComponent(executionId)}/restart`,
|
|
2379
|
+
bodyStr,
|
|
2380
|
+
{ headers: this.mergeHeaders({ "Content-Type": "application/json", ...authHeaders }) }
|
|
2381
|
+
);
|
|
2382
|
+
return res.data;
|
|
2383
|
+
} catch (err) {
|
|
2384
|
+
const respData = err?.response?.data;
|
|
2385
|
+
if (respData) {
|
|
2386
|
+
const status = err.response.status;
|
|
2387
|
+
const msg = respData.message || respData.error || JSON.stringify(respData);
|
|
2388
|
+
const enriched = Object.assign(
|
|
2389
|
+
new Error(`restart execution ${executionId} failed (${status}): ${msg}`),
|
|
2390
|
+
{
|
|
2391
|
+
status,
|
|
2392
|
+
responseData: respData
|
|
2393
|
+
}
|
|
2394
|
+
);
|
|
2395
|
+
throw enriched;
|
|
2396
|
+
}
|
|
2397
|
+
throw err;
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2352
2400
|
async publishWorkflowEvent(event) {
|
|
2353
2401
|
const payload = {
|
|
2354
2402
|
execution_id: event.executionId,
|
|
@@ -2545,6 +2593,9 @@ var AgentFieldClient = class {
|
|
|
2545
2593
|
if (metadata.targetDid) headers["x-target-did"] = metadata.targetDid;
|
|
2546
2594
|
if (metadata.agentNodeDid) headers["x-agent-node-did"] = metadata.agentNodeDid;
|
|
2547
2595
|
if (metadata.agentNodeId) headers["x-agent-node-id"] = metadata.agentNodeId;
|
|
2596
|
+
if (metadata.replaySourceRunId) headers["x-agentfield-replay-source-run-id"] = metadata.replaySourceRunId;
|
|
2597
|
+
if (metadata.replayBeforeExecutionId) headers["x-agentfield-replay-before-execution-id"] = metadata.replayBeforeExecutionId;
|
|
2598
|
+
if (metadata.replayMode) headers["x-agentfield-replay-mode"] = metadata.replayMode;
|
|
2548
2599
|
return headers;
|
|
2549
2600
|
}
|
|
2550
2601
|
setDIDCredentials(did, privateKeyJwk) {
|
|
@@ -3805,6 +3856,83 @@ function registerAgentfieldLogsRoute(app, ring) {
|
|
|
3805
3856
|
});
|
|
3806
3857
|
}
|
|
3807
3858
|
|
|
3859
|
+
// src/sessionTransport.ts
|
|
3860
|
+
var SUPPORTED_SESSION_TRANSPORTS = {
|
|
3861
|
+
openai: ["webrtc", "websocket"],
|
|
3862
|
+
openrouter: ["audio_turns"]
|
|
3863
|
+
};
|
|
3864
|
+
var SessionTransportError = class extends Error {
|
|
3865
|
+
provider;
|
|
3866
|
+
transport;
|
|
3867
|
+
supported;
|
|
3868
|
+
constructor(provider, transport, supported) {
|
|
3869
|
+
const supportedDisplay = supported.length > 0 ? supported.join(", ") : "none";
|
|
3870
|
+
super(
|
|
3871
|
+
`Unsupported session transport '${transport}' for provider '${provider}'. Supported transports: ${supportedDisplay}. AgentField does not infer or switch providers; set provider and transport explicitly.`
|
|
3872
|
+
);
|
|
3873
|
+
this.name = "SessionTransportError";
|
|
3874
|
+
this.provider = provider;
|
|
3875
|
+
this.transport = transport;
|
|
3876
|
+
this.supported = supported;
|
|
3877
|
+
}
|
|
3878
|
+
};
|
|
3879
|
+
function normalizeSessionTransportValue(value) {
|
|
3880
|
+
return value.trim().toLowerCase().replace(/-/g, "_");
|
|
3881
|
+
}
|
|
3882
|
+
function validateSessionTransport(provider, transport) {
|
|
3883
|
+
const normalizedProvider = normalizeSessionTransportValue(provider);
|
|
3884
|
+
const normalizedTransport = normalizeSessionTransportValue(transport);
|
|
3885
|
+
if (!normalizedProvider) {
|
|
3886
|
+
throw new Error("Session provider is required; AgentField does not infer providers.");
|
|
3887
|
+
}
|
|
3888
|
+
if (!normalizedTransport) {
|
|
3889
|
+
throw new Error("Session transport is required; AgentField does not infer transports.");
|
|
3890
|
+
}
|
|
3891
|
+
const supported = SUPPORTED_SESSION_TRANSPORTS[normalizedProvider];
|
|
3892
|
+
if (!supported) {
|
|
3893
|
+
const known = Object.keys(SUPPORTED_SESSION_TRANSPORTS).sort().join(", ");
|
|
3894
|
+
throw new Error(
|
|
3895
|
+
`Unknown session provider '${provider}'. Known providers: ${known}. Register provider capabilities before using a custom session provider.`
|
|
3896
|
+
);
|
|
3897
|
+
}
|
|
3898
|
+
if (!supported.includes(normalizedTransport)) {
|
|
3899
|
+
throw new SessionTransportError(normalizedProvider, normalizedTransport, supported);
|
|
3900
|
+
}
|
|
3901
|
+
return {
|
|
3902
|
+
provider: normalizedProvider,
|
|
3903
|
+
transport: normalizedTransport
|
|
3904
|
+
};
|
|
3905
|
+
}
|
|
3906
|
+
|
|
3907
|
+
// src/session.ts
|
|
3908
|
+
var RealtimeSession = class {
|
|
3909
|
+
sessionId;
|
|
3910
|
+
definition;
|
|
3911
|
+
constructor(sessionId, definition) {
|
|
3912
|
+
this.sessionId = sessionId;
|
|
3913
|
+
this.definition = definition;
|
|
3914
|
+
}
|
|
3915
|
+
async input() {
|
|
3916
|
+
throw new Error("session.input() is populated by the AgentField control plane transport adapter");
|
|
3917
|
+
}
|
|
3918
|
+
};
|
|
3919
|
+
function buildSessionDefinition(name, options) {
|
|
3920
|
+
const capability = validateSessionTransport(options.provider, options.transport);
|
|
3921
|
+
return {
|
|
3922
|
+
name,
|
|
3923
|
+
provider: capability.provider,
|
|
3924
|
+
transport: capability.transport,
|
|
3925
|
+
model: options.model,
|
|
3926
|
+
modalities: options.modalities ?? ["audio", "text"],
|
|
3927
|
+
voice: options.voice,
|
|
3928
|
+
tools: options.tools ?? [],
|
|
3929
|
+
tags: options.tags ?? [],
|
|
3930
|
+
proposed_tags: options.tags ?? [],
|
|
3931
|
+
approved_tags: [],
|
|
3932
|
+
metadata: options.metadata ?? {}
|
|
3933
|
+
};
|
|
3934
|
+
}
|
|
3935
|
+
|
|
3808
3936
|
// src/agent/Agent.ts
|
|
3809
3937
|
var TargetNotFoundError = class extends Error {
|
|
3810
3938
|
};
|
|
@@ -3841,6 +3969,7 @@ var Agent = class {
|
|
|
3841
3969
|
memoryWatchers = [];
|
|
3842
3970
|
localVerifier;
|
|
3843
3971
|
realtimeValidationFunctions = /* @__PURE__ */ new Set();
|
|
3972
|
+
sessions = /* @__PURE__ */ new Map();
|
|
3844
3973
|
processLogRing = new ProcessLogRing();
|
|
3845
3974
|
executionLogger;
|
|
3846
3975
|
/** Tracks an AbortController per in-flight execution_id so the
|
|
@@ -3905,6 +4034,13 @@ var Agent = class {
|
|
|
3905
4034
|
this.reasoners.includeRouter(router);
|
|
3906
4035
|
this.skills.includeRouter(router);
|
|
3907
4036
|
}
|
|
4037
|
+
session(name, options, handler) {
|
|
4038
|
+
this.sessions.set(name, { definition: buildSessionDefinition(name, options), handler });
|
|
4039
|
+
return this;
|
|
4040
|
+
}
|
|
4041
|
+
sessionDefinitions() {
|
|
4042
|
+
return Array.from(this.sessions.values()).map((entry) => entry.definition);
|
|
4043
|
+
}
|
|
3908
4044
|
handler(adapter) {
|
|
3909
4045
|
return async (event, res) => {
|
|
3910
4046
|
if (res && typeof res === "object" && typeof res.setHeader === "function") {
|
|
@@ -4252,7 +4388,10 @@ var Agent = class {
|
|
|
4252
4388
|
callerDid: parentMetadata?.callerDid,
|
|
4253
4389
|
targetDid: parentMetadata?.targetDid,
|
|
4254
4390
|
agentNodeDid: parentMetadata?.agentNodeDid,
|
|
4255
|
-
agentNodeId: this.config.nodeId
|
|
4391
|
+
agentNodeId: this.config.nodeId,
|
|
4392
|
+
replaySourceRunId: parentMetadata?.replaySourceRunId,
|
|
4393
|
+
replayBeforeExecutionId: parentMetadata?.replayBeforeExecutionId,
|
|
4394
|
+
replayMode: parentMetadata?.replayMode
|
|
4256
4395
|
});
|
|
4257
4396
|
this.executionLogger.system("agent.call.completed", "Remote agent call completed", {
|
|
4258
4397
|
target,
|
|
@@ -4518,7 +4657,10 @@ var Agent = class {
|
|
|
4518
4657
|
reasonerId: overrides?.reasonerId ?? normalized["x-reasoner-id"],
|
|
4519
4658
|
callerDid: overrides?.callerDid ?? normalized["x-caller-did"],
|
|
4520
4659
|
targetDid: overrides?.targetDid ?? normalized["x-target-did"],
|
|
4521
|
-
agentNodeDid: overrides?.agentNodeDid ?? normalized["x-agent-node-did"] ?? normalized["x-agent-did"]
|
|
4660
|
+
agentNodeDid: overrides?.agentNodeDid ?? normalized["x-agent-node-did"] ?? normalized["x-agent-did"],
|
|
4661
|
+
replaySourceRunId: overrides?.replaySourceRunId ?? normalized["x-agentfield-replay-source-run-id"],
|
|
4662
|
+
replayBeforeExecutionId: overrides?.replayBeforeExecutionId ?? normalized["x-agentfield-replay-before-execution-id"],
|
|
4663
|
+
replayMode: overrides?.replayMode ?? normalized["x-agentfield-replay-mode"]
|
|
4522
4664
|
};
|
|
4523
4665
|
}
|
|
4524
4666
|
handleHttpRequest(req, res) {
|
|
@@ -4701,7 +4843,8 @@ var Agent = class {
|
|
|
4701
4843
|
version: this.config.version,
|
|
4702
4844
|
deployment_type: deploymentType,
|
|
4703
4845
|
reasoners: this.reasonerDefinitions(),
|
|
4704
|
-
skills: this.skillDefinitions()
|
|
4846
|
+
skills: this.skillDefinitions(),
|
|
4847
|
+
sessions: this.sessionDefinitions()
|
|
4705
4848
|
};
|
|
4706
4849
|
}
|
|
4707
4850
|
async executeInvocation(params) {
|
|
@@ -4986,7 +5129,8 @@ var Agent = class {
|
|
|
4986
5129
|
sdk: {
|
|
4987
5130
|
language: "typescript",
|
|
4988
5131
|
version: AGENTFIELD_TS_SDK_VERSION
|
|
4989
|
-
}
|
|
5132
|
+
},
|
|
5133
|
+
sessions: this.sessionDefinitions()
|
|
4990
5134
|
}
|
|
4991
5135
|
}
|
|
4992
5136
|
});
|
|
@@ -5104,6 +5248,105 @@ var AgentRouter = class {
|
|
|
5104
5248
|
function sanitize(value) {
|
|
5105
5249
|
return value.replace(/[^0-9a-zA-Z]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
|
|
5106
5250
|
}
|
|
5251
|
+
var JWE_ALG = "ECDH-ES";
|
|
5252
|
+
var JWE_ENC = "A256GCM";
|
|
5253
|
+
var KEY_AGREEMENT_TYPE = "X25519KeyAgreementKey2020";
|
|
5254
|
+
var PayloadEncryptionError = class extends Error {
|
|
5255
|
+
constructor(message) {
|
|
5256
|
+
super(message);
|
|
5257
|
+
this.name = "PayloadEncryptionError";
|
|
5258
|
+
}
|
|
5259
|
+
};
|
|
5260
|
+
var encoder = new TextEncoder();
|
|
5261
|
+
function payloadToBytes(payload) {
|
|
5262
|
+
if (payload instanceof Uint8Array) return payload;
|
|
5263
|
+
if (typeof payload === "string") return encoder.encode(payload);
|
|
5264
|
+
return encoder.encode(JSON.stringify(payload));
|
|
5265
|
+
}
|
|
5266
|
+
async function generateX25519KeyPair() {
|
|
5267
|
+
const { privateKey, publicKey } = await generateKeyPair("ECDH-ES", {
|
|
5268
|
+
crv: "X25519",
|
|
5269
|
+
extractable: true
|
|
5270
|
+
});
|
|
5271
|
+
const privateJwk = await exportJWK(privateKey);
|
|
5272
|
+
const publicJwk = await exportJWK(publicKey);
|
|
5273
|
+
return { privateJwk, publicJwk };
|
|
5274
|
+
}
|
|
5275
|
+
function extractKeyAgreementJwk(didDocument) {
|
|
5276
|
+
if (typeof didDocument !== "object" || didDocument === null) {
|
|
5277
|
+
throw new PayloadEncryptionError("DID document must be an object");
|
|
5278
|
+
}
|
|
5279
|
+
const doc = didDocument["did_document"] ?? didDocument;
|
|
5280
|
+
const flat = doc["key_agreement"];
|
|
5281
|
+
if (flat && typeof flat === "object" && flat.crv === "X25519") {
|
|
5282
|
+
return flat;
|
|
5283
|
+
}
|
|
5284
|
+
const keyAgreement = doc["keyAgreement"];
|
|
5285
|
+
if (!keyAgreement || Array.isArray(keyAgreement) && keyAgreement.length === 0) {
|
|
5286
|
+
throw new PayloadEncryptionError(
|
|
5287
|
+
"DID document has no keyAgreement key; the agent has not published an X25519 encryption key"
|
|
5288
|
+
);
|
|
5289
|
+
}
|
|
5290
|
+
const verificationMethods = /* @__PURE__ */ new Map();
|
|
5291
|
+
for (const vm2 of doc["verificationMethod"] ?? []) {
|
|
5292
|
+
if (vm2 && typeof vm2 === "object" && typeof vm2["id"] === "string") {
|
|
5293
|
+
verificationMethods.set(vm2["id"], vm2);
|
|
5294
|
+
}
|
|
5295
|
+
}
|
|
5296
|
+
const entry = Array.isArray(keyAgreement) ? keyAgreement[0] : keyAgreement;
|
|
5297
|
+
let vm;
|
|
5298
|
+
if (typeof entry === "string") {
|
|
5299
|
+
vm = verificationMethods.get(entry);
|
|
5300
|
+
if (!vm) {
|
|
5301
|
+
throw new PayloadEncryptionError(
|
|
5302
|
+
`keyAgreement references unknown verification method ${entry}`
|
|
5303
|
+
);
|
|
5304
|
+
}
|
|
5305
|
+
} else if (entry && typeof entry === "object") {
|
|
5306
|
+
vm = entry;
|
|
5307
|
+
} else {
|
|
5308
|
+
throw new PayloadEncryptionError("unsupported keyAgreement entry shape");
|
|
5309
|
+
}
|
|
5310
|
+
const jwk = vm["publicKeyJwk"];
|
|
5311
|
+
if (!jwk || jwk.crv !== "X25519") {
|
|
5312
|
+
throw new PayloadEncryptionError(
|
|
5313
|
+
"keyAgreement verification method does not carry an X25519 publicKeyJwk"
|
|
5314
|
+
);
|
|
5315
|
+
}
|
|
5316
|
+
return jwk;
|
|
5317
|
+
}
|
|
5318
|
+
async function encryptToJwk(publicJwk, payload) {
|
|
5319
|
+
if (!publicJwk || publicJwk.crv !== "X25519") {
|
|
5320
|
+
throw new PayloadEncryptionError("publicJwk must be an X25519 OKP JWK");
|
|
5321
|
+
}
|
|
5322
|
+
try {
|
|
5323
|
+
const key = await importJWK(publicJwk, JWE_ALG);
|
|
5324
|
+
return await new CompactEncrypt(payloadToBytes(payload)).setProtectedHeader({ alg: JWE_ALG, enc: JWE_ENC }).encrypt(key);
|
|
5325
|
+
} catch (err) {
|
|
5326
|
+
if (err instanceof PayloadEncryptionError) throw err;
|
|
5327
|
+
throw new PayloadEncryptionError(`encryption failed: ${err.message}`);
|
|
5328
|
+
}
|
|
5329
|
+
}
|
|
5330
|
+
async function encryptForDid(did, payload, resolver) {
|
|
5331
|
+
const document = await resolver(did);
|
|
5332
|
+
if (!document) {
|
|
5333
|
+
throw new PayloadEncryptionError(`could not resolve DID ${did}`);
|
|
5334
|
+
}
|
|
5335
|
+
const publicJwk = extractKeyAgreementJwk(document);
|
|
5336
|
+
return encryptToJwk(publicJwk, payload);
|
|
5337
|
+
}
|
|
5338
|
+
async function decrypt(token, privateJwk) {
|
|
5339
|
+
try {
|
|
5340
|
+
const key = await importJWK(privateJwk, JWE_ALG);
|
|
5341
|
+
const { plaintext } = await compactDecrypt(token, key);
|
|
5342
|
+
return Uint8Array.from(plaintext);
|
|
5343
|
+
} catch (err) {
|
|
5344
|
+
throw new PayloadEncryptionError(`decryption failed: ${err.message}`);
|
|
5345
|
+
}
|
|
5346
|
+
}
|
|
5347
|
+
async function decryptToString(token, privateJwk) {
|
|
5348
|
+
return new TextDecoder().decode(await decrypt(token, privateJwk));
|
|
5349
|
+
}
|
|
5107
5350
|
var IMAGE_MIME_TYPES = {
|
|
5108
5351
|
".jpg": "image/jpeg",
|
|
5109
5352
|
".jpeg": "image/jpeg",
|
|
@@ -6525,6 +6768,6 @@ function sleep2(ms) {
|
|
|
6525
6768
|
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
6526
6769
|
}
|
|
6527
6770
|
|
|
6528
|
-
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, ReasonerContext, SUPPORTED_PROVIDERS, SkillContext, StatelessRateLimiter, TERMINAL_STATUSES, Text, Video, WorkflowReporter, audioFromBase64, audioFromBuffer, audioFromFile, audioFromUrl, buildProvider, buildToolConfig, capabilitiesToTools, capabilityToMetadataTool, capabilityToTool, createExecutionLogger, createHarnessResult, createMetrics, createMultimodalResponse, createRawResult, executeToolCallLoop, fileFromBase64, fileFromBuffer, fileFromPath, fileFromUrl, getCurrentContext, getCurrentSkillContext, imageFromBase64, imageFromBuffer, imageFromFile, imageFromUrl, isActive, isExecutionLogBatchPayload, isTerminal, normalizeExecutionLogEntry, normalizeStatus, serializeExecutionLogEntry, text, videoFromBase64, videoFromBuffer, videoFromFile, videoFromUrl };
|
|
6771
|
+
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 };
|
|
6529
6772
|
//# sourceMappingURL=index.js.map
|
|
6530
6773
|
//# sourceMappingURL=index.js.map
|