@agentfield/sdk 0.1.20-rc.2 → 0.1.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 CHANGED
@@ -246,6 +246,37 @@ declare class ExecutionContext {
246
246
  static getCurrent(): ExecutionContext | undefined;
247
247
  }
248
248
 
249
+ interface DIDIdentity {
250
+ did: string;
251
+ privateKeyJwk: string;
252
+ publicKeyJwk: string;
253
+ derivationPath: string;
254
+ componentType: string;
255
+ functionName?: string;
256
+ }
257
+ interface DIDIdentityPackage {
258
+ agentDid: DIDIdentity;
259
+ reasonerDids: Record<string, DIDIdentity>;
260
+ skillDids: Record<string, DIDIdentity>;
261
+ agentfieldServerId: string;
262
+ }
263
+ interface DIDRegistrationRequest {
264
+ agentNodeId: string;
265
+ reasoners: Array<{
266
+ id: string;
267
+ [key: string]: any;
268
+ }>;
269
+ skills: Array<{
270
+ id: string;
271
+ [key: string]: any;
272
+ }>;
273
+ }
274
+ interface DIDRegistrationResponse {
275
+ success: boolean;
276
+ identityPackage?: DIDIdentityPackage;
277
+ message?: string;
278
+ error?: string;
279
+ }
249
280
  interface ExecutionCredential {
250
281
  vcId: string;
251
282
  executionId: string;
@@ -317,6 +348,12 @@ declare class DidClient {
317
348
  private readonly http;
318
349
  private readonly defaultHeaders;
319
350
  constructor(baseUrl: string, defaultHeaders?: Record<string, string | number | boolean | undefined>);
351
+ /**
352
+ * Register an agent with the DID system and obtain an identity package.
353
+ * This must be called before generating VCs to get the caller/target DIDs.
354
+ */
355
+ registerAgent(request: DIDRegistrationRequest): Promise<DIDRegistrationResponse>;
356
+ private parseIdentityPackage;
320
357
  generateCredential(params: GenerateCredentialParams): Promise<ExecutionCredential>;
321
358
  exportAuditTrail(filters?: AuditTrailFilters): Promise<AuditTrailExport>;
322
359
  private serializeDataForJson;
@@ -696,6 +733,7 @@ declare class Agent {
696
733
  private readonly memoryClient;
697
734
  private readonly memoryEventClient;
698
735
  private readonly didClient;
736
+ private readonly didManager;
699
737
  private readonly memoryWatchers;
700
738
  private readonly mcpClientRegistry?;
701
739
  private readonly mcpToolRegistrar?;
@@ -715,7 +753,7 @@ declare class Agent {
715
753
  getAIClient(): AIClient;
716
754
  getMemoryInterface(metadata?: ExecutionMetadata): MemoryInterface;
717
755
  getWorkflowReporter(metadata: ExecutionMetadata): WorkflowReporter;
718
- getDidInterface(metadata: ExecutionMetadata, defaultInput?: any): DidInterface;
756
+ getDidInterface(metadata: ExecutionMetadata, defaultInput?: any, targetName?: string): DidInterface;
719
757
  serve(): Promise<void>;
720
758
  shutdown(): Promise<void>;
721
759
  call(target: string, input: any): Promise<any>;
@@ -748,6 +786,60 @@ declare class Agent {
748
786
  private parseTarget;
749
787
  }
750
788
 
789
+ /**
790
+ * Manages DID registration and identity package storage for an agent.
791
+ *
792
+ * This class handles:
793
+ * - Registering the agent with the DID system
794
+ * - Storing the identity package (agent DID, reasoner DIDs, skill DIDs)
795
+ * - Resolving DIDs for specific functions (reasoners/skills)
796
+ */
797
+ declare class DidManager {
798
+ private readonly client;
799
+ private readonly agentNodeId;
800
+ private identityPackage?;
801
+ private _enabled;
802
+ constructor(client: DidClient, agentNodeId: string);
803
+ /**
804
+ * Register agent with the DID system and obtain identity package.
805
+ *
806
+ * @param reasoners - List of reasoner definitions
807
+ * @param skills - List of skill definitions
808
+ * @returns true if registration succeeded
809
+ */
810
+ registerAgent(reasoners: Array<{
811
+ id: string;
812
+ [key: string]: any;
813
+ }>, skills: Array<{
814
+ id: string;
815
+ [key: string]: any;
816
+ }>): Promise<boolean>;
817
+ /**
818
+ * Check if DID system is enabled and identity package is available.
819
+ */
820
+ get enabled(): boolean;
821
+ /**
822
+ * Get the agent node DID.
823
+ */
824
+ getAgentDid(): string | undefined;
825
+ /**
826
+ * Get DID for a specific function (reasoner or skill).
827
+ * Falls back to agent DID if function not found.
828
+ *
829
+ * @param functionName - Name of the reasoner or skill
830
+ * @returns DID string or undefined if not registered
831
+ */
832
+ getFunctionDid(functionName: string): string | undefined;
833
+ /**
834
+ * Get the full identity package (for debugging/inspection).
835
+ */
836
+ getIdentityPackage(): DIDIdentityPackage | undefined;
837
+ /**
838
+ * Get a summary of the identity for debugging/monitoring.
839
+ */
840
+ getIdentitySummary(): Record<string, any>;
841
+ }
842
+
751
843
  declare class MCPClient {
752
844
  readonly alias: string;
753
845
  readonly baseUrl: string;
@@ -835,4 +927,4 @@ declare class StatelessRateLimiter {
835
927
  executeWithRetry<T>(fn: () => Promise<T>): Promise<T>;
836
928
  }
837
929
 
838
- export { AIClient, type AIConfig, type AIEmbeddingOptions, type AIRequestOptions, type AIStream, Agent, type AgentCapability, type AgentConfig, type AgentHandler, AgentRouter, type AgentRouterOptions, type AgentState, type AuditTrailExport, type AuditTrailFilters, type Awaitable, type CompactCapability, type CompactDiscoveryResponse, type DeploymentType, DidClient, DidInterface, type DiscoveryFormat, type DiscoveryOptions, type DiscoveryPagination, type DiscoveryResponse, type DiscoveryResult, ExecutionContext, type ExecutionCredential, type ExecutionMetadata, type GenerateCredentialOptions, type GenerateCredentialParams, type HealthStatus, MCPClient, MCPClientRegistry, type MCPConfig, type MCPHealthSummary, type MCPServerConfig, type MCPTool, MCPToolRegistrar, type MCPToolRegistrarOptions, type MCPToolRegistration, type MemoryChangeEvent, MemoryClient, type MemoryConfig, MemoryEventClient, type MemoryEventHandler, MemoryInterface, type MemoryRequestMetadata, type MemoryRequestOptions, type MemoryScope, type MemoryWatchHandler, RateLimitError, type RateLimiterOptions, type ReasonerCapability, ReasonerContext, type ReasonerDefinition, type ReasonerHandler, type ReasonerOptions, type ServerlessEvent, type ServerlessResponse, type SkillCapability, SkillContext, type SkillDefinition, type SkillHandler, type SkillOptions, StatelessRateLimiter, type VectorSearchOptions, type VectorSearchResult, type WorkflowCredential, type WorkflowMetadata, type WorkflowProgressOptions, WorkflowReporter, type ZodSchema, getCurrentContext, getCurrentSkillContext };
930
+ export { AIClient, type AIConfig, type AIEmbeddingOptions, type AIRequestOptions, type AIStream, Agent, type AgentCapability, type AgentConfig, type AgentHandler, AgentRouter, type AgentRouterOptions, type AgentState, type AuditTrailExport, type AuditTrailFilters, type Awaitable, type CompactCapability, type CompactDiscoveryResponse, 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 ExecutionMetadata, type GenerateCredentialOptions, type GenerateCredentialParams, type HealthStatus, MCPClient, MCPClientRegistry, type MCPConfig, type MCPHealthSummary, type MCPServerConfig, type MCPTool, MCPToolRegistrar, type MCPToolRegistrarOptions, type MCPToolRegistration, type MemoryChangeEvent, MemoryClient, type MemoryConfig, MemoryEventClient, type MemoryEventHandler, MemoryInterface, type MemoryRequestMetadata, type MemoryRequestOptions, type MemoryScope, type MemoryWatchHandler, RateLimitError, type RateLimiterOptions, type ReasonerCapability, ReasonerContext, type ReasonerDefinition, type ReasonerHandler, type ReasonerOptions, type ServerlessEvent, type ServerlessResponse, type SkillCapability, SkillContext, type SkillDefinition, type SkillHandler, type SkillOptions, StatelessRateLimiter, type VectorSearchOptions, type VectorSearchResult, type WorkflowCredential, type WorkflowMetadata, type WorkflowProgressOptions, WorkflowReporter, type ZodSchema, getCurrentContext, getCurrentSkillContext };
package/dist/index.js CHANGED
@@ -1183,6 +1183,60 @@ var DidClient = class {
1183
1183
  this.http = axios.create({ baseURL: baseUrl.replace(/\/$/, "") });
1184
1184
  this.defaultHeaders = this.sanitizeHeaders(defaultHeaders ?? {});
1185
1185
  }
1186
+ /**
1187
+ * Register an agent with the DID system and obtain an identity package.
1188
+ * This must be called before generating VCs to get the caller/target DIDs.
1189
+ */
1190
+ async registerAgent(request) {
1191
+ const payload = {
1192
+ agent_node_id: request.agentNodeId,
1193
+ reasoners: request.reasoners,
1194
+ skills: request.skills
1195
+ };
1196
+ const res = await this.http.post("/api/v1/did/register", payload, {
1197
+ headers: this.mergeHeaders()
1198
+ });
1199
+ const data = res.data ?? {};
1200
+ if (!data.success) {
1201
+ return {
1202
+ success: false,
1203
+ error: data.error ?? "DID registration failed"
1204
+ };
1205
+ }
1206
+ return {
1207
+ success: true,
1208
+ identityPackage: this.parseIdentityPackage(data.identity_package),
1209
+ message: data.message
1210
+ };
1211
+ }
1212
+ parseIdentityPackage(pkg) {
1213
+ const parseIdentity = (data) => ({
1214
+ did: data?.did ?? "",
1215
+ privateKeyJwk: data?.private_key_jwk ?? "",
1216
+ publicKeyJwk: data?.public_key_jwk ?? "",
1217
+ derivationPath: data?.derivation_path ?? "",
1218
+ componentType: data?.component_type ?? "",
1219
+ functionName: data?.function_name
1220
+ });
1221
+ const reasonerDids = {};
1222
+ if (pkg?.reasoner_dids) {
1223
+ for (const [name, data] of Object.entries(pkg.reasoner_dids)) {
1224
+ reasonerDids[name] = parseIdentity(data);
1225
+ }
1226
+ }
1227
+ const skillDids = {};
1228
+ if (pkg?.skill_dids) {
1229
+ for (const [name, data] of Object.entries(pkg.skill_dids)) {
1230
+ skillDids[name] = parseIdentity(data);
1231
+ }
1232
+ }
1233
+ return {
1234
+ agentDid: parseIdentity(pkg?.agent_did),
1235
+ reasonerDids,
1236
+ skillDids,
1237
+ agentfieldServerId: pkg?.agentfield_server_id ?? ""
1238
+ };
1239
+ }
1186
1240
  async generateCredential(params) {
1187
1241
  const ctx = params.executionContext;
1188
1242
  const timestamp = ctx.timestamp instanceof Date ? ctx.timestamp.toISOString() : ctx.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
@@ -1344,6 +1398,100 @@ var DidInterface = class {
1344
1398
  }
1345
1399
  };
1346
1400
 
1401
+ // src/did/DidManager.ts
1402
+ var DidManager = class {
1403
+ client;
1404
+ agentNodeId;
1405
+ identityPackage;
1406
+ _enabled = false;
1407
+ constructor(client, agentNodeId) {
1408
+ this.client = client;
1409
+ this.agentNodeId = agentNodeId;
1410
+ }
1411
+ /**
1412
+ * Register agent with the DID system and obtain identity package.
1413
+ *
1414
+ * @param reasoners - List of reasoner definitions
1415
+ * @param skills - List of skill definitions
1416
+ * @returns true if registration succeeded
1417
+ */
1418
+ async registerAgent(reasoners, skills) {
1419
+ const request = {
1420
+ agentNodeId: this.agentNodeId,
1421
+ reasoners,
1422
+ skills
1423
+ };
1424
+ const response = await this.client.registerAgent(request);
1425
+ if (response.success && response.identityPackage) {
1426
+ this.identityPackage = response.identityPackage;
1427
+ this._enabled = true;
1428
+ return true;
1429
+ }
1430
+ console.warn(`[DID] Registration failed: ${response.error ?? "Unknown error"}`);
1431
+ return false;
1432
+ }
1433
+ /**
1434
+ * Check if DID system is enabled and identity package is available.
1435
+ */
1436
+ get enabled() {
1437
+ return this._enabled && this.identityPackage !== void 0;
1438
+ }
1439
+ /**
1440
+ * Get the agent node DID.
1441
+ */
1442
+ getAgentDid() {
1443
+ return this.identityPackage?.agentDid.did;
1444
+ }
1445
+ /**
1446
+ * Get DID for a specific function (reasoner or skill).
1447
+ * Falls back to agent DID if function not found.
1448
+ *
1449
+ * @param functionName - Name of the reasoner or skill
1450
+ * @returns DID string or undefined if not registered
1451
+ */
1452
+ getFunctionDid(functionName) {
1453
+ if (!this.identityPackage) {
1454
+ return void 0;
1455
+ }
1456
+ const reasonerDid = this.identityPackage.reasonerDids[functionName];
1457
+ if (reasonerDid) {
1458
+ return reasonerDid.did;
1459
+ }
1460
+ const skillDid = this.identityPackage.skillDids[functionName];
1461
+ if (skillDid) {
1462
+ return skillDid.did;
1463
+ }
1464
+ return this.identityPackage.agentDid.did;
1465
+ }
1466
+ /**
1467
+ * Get the full identity package (for debugging/inspection).
1468
+ */
1469
+ getIdentityPackage() {
1470
+ return this.identityPackage;
1471
+ }
1472
+ /**
1473
+ * Get a summary of the identity for debugging/monitoring.
1474
+ */
1475
+ getIdentitySummary() {
1476
+ if (!this.identityPackage) {
1477
+ return { enabled: false, message: "No identity package available" };
1478
+ }
1479
+ return {
1480
+ enabled: true,
1481
+ agentDid: this.identityPackage.agentDid.did,
1482
+ agentfieldServerId: this.identityPackage.agentfieldServerId,
1483
+ reasonerCount: Object.keys(this.identityPackage.reasonerDids).length,
1484
+ skillCount: Object.keys(this.identityPackage.skillDids).length,
1485
+ reasonerDids: Object.fromEntries(
1486
+ Object.entries(this.identityPackage.reasonerDids).map(([name, identity]) => [name, identity.did])
1487
+ ),
1488
+ skillDids: Object.fromEntries(
1489
+ Object.entries(this.identityPackage.skillDids).map(([name, identity]) => [name, identity.did])
1490
+ )
1491
+ };
1492
+ }
1493
+ };
1494
+
1347
1495
  // src/utils/pattern.ts
1348
1496
  function matchesPattern(pattern, value) {
1349
1497
  const escaped = pattern.replace(/[-/\\^$+?.()|[\]{}]/g, "\\$&").replace(/\*/g, ".*");
@@ -1614,6 +1762,7 @@ var Agent = class {
1614
1762
  memoryClient;
1615
1763
  memoryEventClient;
1616
1764
  didClient;
1765
+ didManager;
1617
1766
  memoryWatchers = [];
1618
1767
  mcpClientRegistry;
1619
1768
  mcpToolRegistrar;
@@ -1638,6 +1787,7 @@ var Agent = class {
1638
1787
  this.memoryClient = new MemoryClient(this.config.agentFieldUrl, this.config.defaultHeaders);
1639
1788
  this.memoryEventClient = new MemoryEventClient(this.config.agentFieldUrl, this.config.defaultHeaders);
1640
1789
  this.didClient = new DidClient(this.config.agentFieldUrl, this.config.defaultHeaders);
1790
+ this.didManager = new DidManager(this.didClient, this.config.nodeId);
1641
1791
  this.memoryEventClient.onEvent((event) => this.dispatchMemoryEvent(event));
1642
1792
  if (this.config.mcp?.servers?.length) {
1643
1793
  this.mcpClientRegistry = new MCPClientRegistry(this.config.devMode);
@@ -1718,12 +1868,17 @@ var Agent = class {
1718
1868
  agentNodeId: this.config.nodeId
1719
1869
  });
1720
1870
  }
1721
- getDidInterface(metadata, defaultInput) {
1871
+ getDidInterface(metadata, defaultInput, targetName) {
1872
+ const agentNodeDid = metadata.agentNodeDid ?? this.didManager.getAgentDid() ?? this.config.defaultHeaders?.["X-Agent-Node-DID"]?.toString();
1873
+ const callerDid = metadata.callerDid ?? this.didManager.getAgentDid();
1874
+ const targetDid = metadata.targetDid ?? (targetName ? this.didManager.getFunctionDid(targetName) : void 0) ?? this.didManager.getAgentDid();
1722
1875
  return new DidInterface({
1723
1876
  client: this.didClient,
1724
1877
  metadata: {
1725
1878
  ...metadata,
1726
- agentNodeDid: metadata.agentNodeDid ?? this.config.defaultHeaders?.["X-Agent-Node-DID"]?.toString()
1879
+ agentNodeDid,
1880
+ callerDid,
1881
+ targetDid
1727
1882
  },
1728
1883
  enabled: Boolean(this.config.didEnabled),
1729
1884
  defaultInput
@@ -1825,7 +1980,7 @@ var Agent = class {
1825
1980
  aiClient: this.aiClient,
1826
1981
  memory: this.getMemoryInterface(execCtx.metadata),
1827
1982
  workflow: this.getWorkflowReporter(execCtx.metadata),
1828
- did: this.getDidInterface(execCtx.metadata, input)
1983
+ did: this.getDidInterface(execCtx.metadata, input, name)
1829
1984
  })
1830
1985
  );
1831
1986
  await emitEvent("succeeded", result);
@@ -2221,7 +2376,7 @@ var Agent = class {
2221
2376
  aiClient: this.aiClient,
2222
2377
  memory: this.getMemoryInterface(params.metadata),
2223
2378
  workflow: this.getWorkflowReporter(params.metadata),
2224
- did: this.getDidInterface(params.metadata, params.input)
2379
+ did: this.getDidInterface(params.metadata, params.input, params.targetName)
2225
2380
  });
2226
2381
  const result = await reasoner.handler(ctx);
2227
2382
  if (params.respond && params.res) {
@@ -2260,7 +2415,7 @@ var Agent = class {
2260
2415
  agent: this,
2261
2416
  memory: this.getMemoryInterface(params.metadata),
2262
2417
  workflow: this.getWorkflowReporter(params.metadata),
2263
- did: this.getDidInterface(params.metadata, params.input)
2418
+ did: this.getDidInterface(params.metadata, params.input, params.targetName)
2264
2419
  });
2265
2420
  const result = await skill.handler(ctx);
2266
2421
  if (params.respond && params.res) {
@@ -2293,6 +2448,20 @@ var Agent = class {
2293
2448
  reasoners,
2294
2449
  skills
2295
2450
  });
2451
+ if (this.config.didEnabled) {
2452
+ try {
2453
+ const didRegistered = await this.didManager.registerAgent(reasoners, skills);
2454
+ if (didRegistered) {
2455
+ const summary = this.didManager.getIdentitySummary();
2456
+ console.log(`[DID] Agent registered with DID: ${summary.agentDid}`);
2457
+ console.log(`[DID] Reasoner DIDs: ${summary.reasonerCount}, Skill DIDs: ${summary.skillCount}`);
2458
+ }
2459
+ } catch (didErr) {
2460
+ if (!this.config.devMode) {
2461
+ console.warn("[DID] DID registration failed:", didErr);
2462
+ }
2463
+ }
2464
+ }
2296
2465
  } catch (err) {
2297
2466
  if (!this.config.devMode) {
2298
2467
  throw err;
@@ -2378,6 +2547,6 @@ function sanitize(value) {
2378
2547
  return value.replace(/[^0-9a-zA-Z]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "");
2379
2548
  }
2380
2549
 
2381
- export { AIClient, Agent, AgentRouter, DidClient, DidInterface, ExecutionContext, MCPClient, MCPClientRegistry, MCPToolRegistrar, MemoryClient, MemoryEventClient, MemoryInterface, RateLimitError, ReasonerContext, SkillContext, StatelessRateLimiter, WorkflowReporter, getCurrentContext, getCurrentSkillContext };
2550
+ export { AIClient, Agent, AgentRouter, DidClient, DidInterface, DidManager, ExecutionContext, MCPClient, MCPClientRegistry, MCPToolRegistrar, MemoryClient, MemoryEventClient, MemoryInterface, RateLimitError, ReasonerContext, SkillContext, StatelessRateLimiter, WorkflowReporter, getCurrentContext, getCurrentSkillContext };
2382
2551
  //# sourceMappingURL=index.js.map
2383
2552
  //# sourceMappingURL=index.js.map