@private.me/xbind 3.0.0 → 3.0.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.
Files changed (217) hide show
  1. package/README.md +55 -7
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1920 -1
  3. package/dist-standalone/_deps/shared/cjs/errors.js +729 -1
  4. package/dist-standalone/_deps/shared/cjs/index.js +463 -1
  5. package/dist-standalone/_deps/shared/cjs/types.js +315 -1
  6. package/dist-standalone/_deps/shared/errors.js +244 -1
  7. package/dist-standalone/_deps/shared/index.js +72 -1
  8. package/dist-standalone/_deps/shared/types.js +86 -1
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.js +659 -1
  47. package/dist-standalone/agent-sdk.js +328 -1
  48. package/dist-standalone/agent.js +1800 -1
  49. package/dist-standalone/approval.js +193 -1
  50. package/dist-standalone/async-iterators.js +382 -1
  51. package/dist-standalone/auth.js +219 -1
  52. package/dist-standalone/auto-accept.js +229 -1
  53. package/dist-standalone/backup-config.js +201 -1
  54. package/dist-standalone/backup.js +326 -1
  55. package/dist-standalone/batch-operations.js +388 -1
  56. package/dist-standalone/cancellation.js +477 -1
  57. package/dist-standalone/checkpoint.js +186 -1
  58. package/dist-standalone/circuit-breaker.js +468 -1
  59. package/dist-standalone/cjs/agent-call.js +701 -1
  60. package/dist-standalone/cjs/agent-sdk.js +332 -1
  61. package/dist-standalone/cjs/agent.js +1837 -1
  62. package/dist-standalone/cjs/approval.js +199 -1
  63. package/dist-standalone/cjs/async-iterators.js +392 -1
  64. package/dist-standalone/cjs/auth.js +225 -1
  65. package/dist-standalone/cjs/auto-accept.js +233 -1
  66. package/dist-standalone/cjs/backup-config.js +207 -1
  67. package/dist-standalone/cjs/backup.js +330 -1
  68. package/dist-standalone/cjs/batch-operations.js +397 -1
  69. package/dist-standalone/cjs/cancellation.js +490 -1
  70. package/dist-standalone/cjs/checkpoint.js +193 -1
  71. package/dist-standalone/cjs/circuit-breaker.js +476 -1
  72. package/dist-standalone/cjs/cli/init.js +492 -1
  73. package/dist-standalone/cjs/config-validation.js +522 -1
  74. package/dist-standalone/cjs/connect.js +312 -1
  75. package/dist-standalone/cjs/connection-pool.js +506 -1
  76. package/dist-standalone/cjs/correlation-id.js +339 -1
  77. package/dist-standalone/cjs/crypto-utils.js +176 -1
  78. package/dist-standalone/cjs/debug-mode.js +534 -1
  79. package/dist-standalone/cjs/did-document.js +101 -1
  80. package/dist-standalone/cjs/did-privateme.js +130 -1
  81. package/dist-standalone/cjs/did-web.js +201 -1
  82. package/dist-standalone/cjs/discovery.js +462 -1
  83. package/dist-standalone/cjs/dual-mode.js +251 -1
  84. package/dist-standalone/cjs/email-templates.js +313 -1
  85. package/dist-standalone/cjs/email-transport.js +239 -1
  86. package/dist-standalone/cjs/envelope.js +538 -1
  87. package/dist-standalone/cjs/errors.js +913 -1
  88. package/dist-standalone/cjs/event-emitter.js +461 -1
  89. package/dist-standalone/cjs/gateway-state.js +55 -1
  90. package/dist-standalone/cjs/gateway-transport.js +120 -1
  91. package/dist-standalone/cjs/graceful-degradation.js +403 -1
  92. package/dist-standalone/cjs/guardrails.js +223 -1
  93. package/dist-standalone/cjs/health-check.js +336 -1
  94. package/dist-standalone/cjs/http-compat.js +272 -1
  95. package/dist-standalone/cjs/http-status-map.js +571 -1
  96. package/dist-standalone/cjs/identity.js +645 -1
  97. package/dist-standalone/cjs/index.js +406 -1
  98. package/dist-standalone/cjs/invitation.js +421 -1
  99. package/dist-standalone/cjs/invite.js +328 -1
  100. package/dist-standalone/cjs/key-agreement.js +335 -1
  101. package/dist-standalone/cjs/lazy-init.js +300 -1
  102. package/dist-standalone/cjs/logger.js +291 -1
  103. package/dist-standalone/cjs/mdns-discovery.js +202 -1
  104. package/dist-standalone/cjs/nonce-store.js +80 -1
  105. package/dist-standalone/cjs/pairing-manager.js +223 -1
  106. package/dist-standalone/cjs/plugin-system.js +264 -1
  107. package/dist-standalone/cjs/plugins/logging.js +168 -1
  108. package/dist-standalone/cjs/plugins/metrics.js +181 -1
  109. package/dist-standalone/cjs/plugins/validation.js +302 -1
  110. package/dist-standalone/cjs/policy.js +320 -1
  111. package/dist-standalone/cjs/progress-callbacks.js +583 -1
  112. package/dist-standalone/cjs/redis-nonce-store.js +76 -1
  113. package/dist-standalone/cjs/registry-middleware.js +50 -1
  114. package/dist-standalone/cjs/retry-strategies.js +544 -1
  115. package/dist-standalone/cjs/retry-transport.js +102 -1
  116. package/dist-standalone/cjs/runtime/browser.js +533 -1
  117. package/dist-standalone/cjs/runtime/edge.js +526 -1
  118. package/dist-standalone/cjs/runtime/react-native.js +394 -1
  119. package/dist-standalone/cjs/security-policy.js +245 -1
  120. package/dist-standalone/cjs/serialization.js +1040 -1
  121. package/dist-standalone/cjs/split-channel.js +225 -1
  122. package/dist-standalone/cjs/subscription-proof.js +230 -1
  123. package/dist-standalone/cjs/succession.js +148 -1
  124. package/dist-standalone/cjs/timeouts.js +412 -1
  125. package/dist-standalone/cjs/trace-context.js +424 -1
  126. package/dist-standalone/cjs/trace-spans.js +495 -1
  127. package/dist-standalone/cjs/transport.js +63 -1
  128. package/dist-standalone/cjs/trust-registry.js +991 -1
  129. package/dist-standalone/cjs/types/error-response.js +56 -1
  130. package/dist-standalone/cjs/vault-auth.js +178 -1
  131. package/dist-standalone/cjs/vault-store-loader.js +194 -1
  132. package/dist-standalone/cjs/verify.js +25 -1
  133. package/dist-standalone/cjs/version-info.js +543 -1
  134. package/dist-standalone/cjs/xfetch.js +340 -1
  135. package/dist-standalone/cli/init.js +455 -1
  136. package/dist-standalone/cli/setup.js +514 -1
  137. package/dist-standalone/cli/types.js +27 -1
  138. package/dist-standalone/cli/xbind.js +148 -1
  139. package/dist-standalone/config-validation.js +513 -1
  140. package/dist-standalone/connect.js +274 -1
  141. package/dist-standalone/connection-pool.js +500 -1
  142. package/dist-standalone/correlation-id.js +326 -1
  143. package/dist-standalone/crypto-utils.js +157 -1
  144. package/dist-standalone/debug-mode.js +510 -1
  145. package/dist-standalone/did-document.js +96 -1
  146. package/dist-standalone/did-privateme.js +121 -1
  147. package/dist-standalone/did-web.js +196 -1
  148. package/dist-standalone/discovery.js +458 -1
  149. package/dist-standalone/dual-mode.js +247 -1
  150. package/dist-standalone/email-templates.js +309 -1
  151. package/dist-standalone/email-transport.js +232 -1
  152. package/dist-standalone/envelope.js +525 -1
  153. package/dist-standalone/errors.js +896 -1
  154. package/dist-standalone/event-emitter.js +456 -1
  155. package/dist-standalone/gateway-state.js +51 -1
  156. package/dist-standalone/gateway-transport.js +116 -1
  157. package/dist-standalone/graceful-degradation.js +396 -1
  158. package/dist-standalone/guardrails.js +216 -1
  159. package/dist-standalone/health-check.js +332 -1
  160. package/dist-standalone/http-compat.js +267 -1
  161. package/dist-standalone/http-status-map.js +561 -1
  162. package/dist-standalone/identity.js +619 -1
  163. package/dist-standalone/index.js +78 -1
  164. package/dist-standalone/invitation.js +415 -1
  165. package/dist-standalone/invite.js +324 -1
  166. package/dist-standalone/key-agreement.js +325 -1
  167. package/dist-standalone/lazy-init.js +295 -1
  168. package/dist-standalone/logger.js +285 -1
  169. package/dist-standalone/mdns-discovery.js +195 -1
  170. package/dist-standalone/nonce-store.js +76 -1
  171. package/dist-standalone/pairing-manager.js +219 -1
  172. package/dist-standalone/plugin-system.js +257 -1
  173. package/dist-standalone/plugins/logging.d.ts +84 -0
  174. package/dist-standalone/plugins/logging.js +163 -0
  175. package/dist-standalone/plugins/metrics.d.ts +111 -0
  176. package/dist-standalone/plugins/metrics.js +176 -0
  177. package/dist-standalone/plugins/validation.d.ts +104 -0
  178. package/dist-standalone/plugins/validation.js +297 -0
  179. package/dist-standalone/policy.js +315 -1
  180. package/dist-standalone/progress-callbacks.js +576 -1
  181. package/dist-standalone/redis-nonce-store.js +72 -1
  182. package/dist-standalone/registry-middleware.js +47 -1
  183. package/dist-standalone/retry-strategies.js +534 -1
  184. package/dist-standalone/retry-transport.js +98 -1
  185. package/dist-standalone/runtime/browser.d.ts +311 -0
  186. package/dist-standalone/runtime/browser.js +516 -0
  187. package/dist-standalone/runtime/edge.d.ts +282 -0
  188. package/dist-standalone/runtime/edge.js +511 -0
  189. package/dist-standalone/runtime/react-native.d.ts +157 -0
  190. package/dist-standalone/runtime/react-native.js +383 -0
  191. package/dist-standalone/security-policy.js +239 -1
  192. package/dist-standalone/serialization.js +1031 -1
  193. package/dist-standalone/split-channel.js +219 -1
  194. package/dist-standalone/subscription-proof.js +224 -1
  195. package/dist-standalone/succession.js +142 -1
  196. package/dist-standalone/timeouts.js +398 -1
  197. package/dist-standalone/trace-context.js +414 -1
  198. package/dist-standalone/trace-spans.js +488 -1
  199. package/dist-standalone/transport.js +59 -1
  200. package/dist-standalone/trust-registry.js +950 -1
  201. package/dist-standalone/types/error-response.d.ts +209 -0
  202. package/dist-standalone/types/error-response.js +52 -0
  203. package/dist-standalone/vault-auth.js +174 -1
  204. package/dist-standalone/vault-store-loader.js +187 -1
  205. package/dist-standalone/verify.js +16 -1
  206. package/dist-standalone/version-info.js +530 -1
  207. package/dist-standalone/xfetch.js +335 -1
  208. package/package.json +4 -10
  209. package/share1.dat +0 -0
  210. package/dist-standalone/_deps/mldsa-wasm/LICENSE +0 -24
  211. package/dist-standalone/_deps/mldsa-wasm/package.json +0 -46
  212. package/dist-standalone/_deps/shared/cjs/package.json +0 -1
  213. package/dist-standalone/_deps/ux-helpers/cjs/package.json +0 -1
  214. package/dist-standalone/_deps/xchange/cjs/package.json +0 -1
  215. package/dist-standalone/_deps/xregistry/cjs/package.json +0 -1
  216. package/dist-standalone/cjs/package.json +0 -3
  217. package/dist-standalone/package.json +0 -10
@@ -1 +1,328 @@
1
- import{ok,err}from"./_deps/shared/index.js";import{generateIdentity,identityFromSeed}from"./identity.js";import{call}from"./agent-call.js";import{AgentError,AgentErrorCode}from"./agent-call.js";import{getGlobalPolicyEngine}from"./policy.js";export class AgentBuilder{_identity;_metadata;_policy;constructor(t,e,i){this._identity=t,this._metadata=e,this._policy=i}get did(){return this._identity.did}get name(){return this._metadata.name}get created(){return this._metadata.created}get identityMode(){return this._metadata.identityMode}get ttl(){return this._metadata.ttl}get timeRemaining(){if(!this._metadata.ttl)return;const t=Date.now()-this._metadata.created,e=this._metadata.ttl-t;return e>0?e:0}static async create(t){try{let e,i;if(t.identity&&"ephemeral"!==t.identity)if("persistent"===t.identity){const t=await generateIdentity();if(!t.ok)return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED,"Failed to generate persistent identity",{cause:t.error}));e=t.value,i="persistent"}else if(t.identity instanceof Uint8Array){if(32!==t.identity.length)return err(new AgentError(AgentErrorCode.INVALID_PARAMS,"Identity seed must be exactly 32 bytes",{seedLength:t.identity.length}));const a=await identityFromSeed(t.identity);if(!a.ok)return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED,"Failed to derive identity from seed",{cause:a.error}));e=a.value,i="persistent"}else e=t.identity,i="persistent";else{const t=await generateIdentity();if(!t.ok)return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED,"Failed to generate ephemeral identity",{cause:t.error}));e=t.value,i="ephemeral"}const a={name:t.name,did:e.did,created:Date.now(),identityMode:i,ttl:"ephemeral"===i?t.ttl??36e5:void 0},r=new AgentBuilder(e,a,t.policy);return"ephemeral"===i&&a.ttl&&(a.cleanupTimer=setTimeout(()=>{r.cleanup()},a.ttl)),ok(r)}catch(t){return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED,t instanceof Error?t.message:"Unknown error during agent creation",{originalError:t}))}}async call(t,e,i){const a={...i,policy:this._policy?{...this._policy,...i?.policy,allowedTools:i?.policy?.allowedTools?[...this._policy.allowedTools||[],...i.policy.allowedTools]:this._policy.allowedTools,scopes:i?.policy?.scopes?[...this._policy.scopes||[],...i.policy.scopes]:this._policy.scopes,limits:{amountPerTxn:Math.min(this._policy.limits?.amountPerTxn??1/0,i?.policy?.limits?.amountPerTxn??1/0)===1/0?void 0:Math.min(this._policy.limits?.amountPerTxn??1/0,i?.policy?.limits?.amountPerTxn??1/0),dailyAmount:Math.min(this._policy.limits?.dailyAmount??1/0,i?.policy?.limits?.dailyAmount??1/0)===1/0?void 0:Math.min(this._policy.limits?.dailyAmount??1/0,i?.policy?.limits?.dailyAmount??1/0),callsPerMinute:Math.min(this._policy.limits?.callsPerMinute??1/0,i?.policy?.limits?.callsPerMinute??1/0)===1/0?void 0:Math.min(this._policy.limits?.callsPerMinute??1/0,i?.policy?.limits?.callsPerMinute??1/0)}}:i?.policy},r=await call(t,e,a);if(r.ok){const t=getGlobalPolicyEngine();if(t.recordCall(this.did),"object"==typeof e&&null!==e){const i=e,a=i.amount??i.value??i.price??i.total;"number"==typeof a&&t.recordSpending(this.did,a)}}return r}cleanup(){this._metadata.cleanupTimer&&(clearTimeout(this._metadata.cleanupTimer),this._metadata.cleanupTimer=void 0);getGlobalPolicyEngine().reset(this.did)}extendTTL(t){if("ephemeral"!==this._metadata.identityMode||!this._metadata.ttl)return!1;this._metadata.cleanupTimer&&clearTimeout(this._metadata.cleanupTimer);const e=Date.now()-this._metadata.created,i=this._metadata.ttl-e+t;return this._metadata.ttl=this._metadata.ttl+t,this._metadata.cleanupTimer=setTimeout(()=>{this.cleanup()},i),!0}toJSON(){return{name:this.name,did:this.did,created:this.created,identityMode:this.identityMode,ttl:this.ttl,timeRemaining:this.timeRemaining}}}
1
+ /**
2
+ * @module agent-sdk
3
+ * Agent builder wrapper for AI-first interface
4
+ *
5
+ * Provides simplified agent creation with ephemeral identities,
6
+ * policy constraints, and automatic lifecycle management.
7
+ */
8
+ import { ok, err } from"./_deps/shared/index.js";
9
+ import { generateIdentity, identityFromSeed } from './identity.js';
10
+ import { call } from './agent-call.js';
11
+ import { AgentError, AgentErrorCode } from './agent-call.js';
12
+ import { getGlobalPolicyEngine } from './policy.js';
13
+ /**
14
+ * Agent builder - AI-first wrapper for xBind agent creation
15
+ *
16
+ * Provides high-level API for creating agents with automatic
17
+ * identity management, policy enforcement, and lifecycle cleanup.
18
+ *
19
+ * This is the simplified xBind agent builder for AI agents. For full
20
+ * transport-level control, use the Agent class from './agent.js'.
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * // Create ephemeral agent (auto-cleanup after 1 hour)
25
+ * const agent = await AgentBuilder.create({
26
+ * name: "invoice-agent",
27
+ * policy: {
28
+ * allowedTools: ["payments:createCharge", "payments:refund"],
29
+ * limits: {
30
+ * amountPerTxn: 1000,
31
+ * dailyAmount: 10000
32
+ * }
33
+ * }
34
+ * });
35
+ *
36
+ * // Use agent to call tools
37
+ * const result = await agent.call("payments:createCharge", {
38
+ * amount: 100,
39
+ * currency: "USD"
40
+ * });
41
+ * ```
42
+ */
43
+ export class AgentBuilder {
44
+ /** Agent identity (cryptographic keys + DID) */
45
+ _identity;
46
+ /** Agent metadata */
47
+ _metadata;
48
+ /** Policy constraints (optional) */
49
+ _policy;
50
+ /**
51
+ * Create a new AgentBuilder instance.
52
+ *
53
+ * @param identity - Agent identity
54
+ * @param metadata - Agent metadata
55
+ * @param policy - Optional policy constraints
56
+ */
57
+ constructor(identity, metadata, policy) {
58
+ this._identity = identity;
59
+ this._metadata = metadata;
60
+ this._policy = policy;
61
+ }
62
+ /**
63
+ * Agent DID (decentralized identifier).
64
+ */
65
+ get did() {
66
+ return this._identity.did;
67
+ }
68
+ /**
69
+ * Agent name.
70
+ */
71
+ get name() {
72
+ return this._metadata.name;
73
+ }
74
+ /**
75
+ * Creation timestamp (milliseconds since epoch).
76
+ */
77
+ get created() {
78
+ return this._metadata.created;
79
+ }
80
+ /**
81
+ * Identity mode ('ephemeral' or 'persistent').
82
+ */
83
+ get identityMode() {
84
+ return this._metadata.identityMode;
85
+ }
86
+ /**
87
+ * Time-to-live for ephemeral agents (milliseconds).
88
+ * Returns undefined for persistent agents.
89
+ */
90
+ get ttl() {
91
+ return this._metadata.ttl;
92
+ }
93
+ /**
94
+ * Time remaining until auto-cleanup (milliseconds).
95
+ * Returns undefined for persistent agents or if already expired.
96
+ */
97
+ get timeRemaining() {
98
+ if (!this._metadata.ttl)
99
+ return undefined;
100
+ const elapsed = Date.now() - this._metadata.created;
101
+ const remaining = this._metadata.ttl - elapsed;
102
+ return remaining > 0 ? remaining : 0;
103
+ }
104
+ /**
105
+ * Create a new agent instance.
106
+ *
107
+ * @param options - Agent creation options
108
+ * @returns AgentBuilder instance or error
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * // Ephemeral agent (default)
113
+ * const agent = await AgentBuilder.create({
114
+ * name: "task-agent",
115
+ * policy: {
116
+ * allowedTools: ["slack:sendMessage"],
117
+ * limits: { callsPerMinute: 10 }
118
+ * }
119
+ * });
120
+ * ```
121
+ *
122
+ * @example
123
+ * ```typescript
124
+ * // Persistent agent from seed
125
+ * const seed = new Uint8Array(32);
126
+ * crypto.getRandomValues(seed);
127
+ *
128
+ * const agent = await AgentBuilder.create({
129
+ * name: "persistent-agent",
130
+ * identity: seed, // Deterministic DID
131
+ * });
132
+ * ```
133
+ */
134
+ static async create(options) {
135
+ try {
136
+ // Determine identity mode
137
+ let identity;
138
+ let identityMode;
139
+ if (!options.identity || options.identity === 'ephemeral') {
140
+ // Generate ephemeral identity
141
+ const idResult = await generateIdentity();
142
+ if (!idResult.ok) {
143
+ return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED, 'Failed to generate ephemeral identity', { cause: idResult.error }));
144
+ }
145
+ identity = idResult.value;
146
+ identityMode = 'ephemeral';
147
+ }
148
+ else if (options.identity === 'persistent') {
149
+ // Generate persistent identity
150
+ const idResult = await generateIdentity();
151
+ if (!idResult.ok) {
152
+ return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED, 'Failed to generate persistent identity', { cause: idResult.error }));
153
+ }
154
+ identity = idResult.value;
155
+ identityMode = 'persistent';
156
+ }
157
+ else if (options.identity instanceof Uint8Array) {
158
+ // Deterministic identity from seed
159
+ if (options.identity.length !== 32) {
160
+ return err(new AgentError(AgentErrorCode.INVALID_PARAMS, 'Identity seed must be exactly 32 bytes', { seedLength: options.identity.length }));
161
+ }
162
+ const idResult = await identityFromSeed(options.identity);
163
+ if (!idResult.ok) {
164
+ return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED, 'Failed to derive identity from seed', { cause: idResult.error }));
165
+ }
166
+ identity = idResult.value;
167
+ identityMode = 'persistent';
168
+ }
169
+ else {
170
+ // Use provided AgentIdentity
171
+ identity = options.identity;
172
+ identityMode = 'persistent';
173
+ }
174
+ // Create metadata
175
+ const metadata = {
176
+ name: options.name,
177
+ did: identity.did,
178
+ created: Date.now(),
179
+ identityMode,
180
+ ttl: identityMode === 'ephemeral' ? (options.ttl ?? 3600000) : undefined,
181
+ };
182
+ // Create agent instance
183
+ const agent = new AgentBuilder(identity, metadata, options.policy);
184
+ // Setup auto-cleanup for ephemeral agents
185
+ if (identityMode === 'ephemeral' && metadata.ttl) {
186
+ metadata.cleanupTimer = setTimeout(() => {
187
+ agent.cleanup();
188
+ }, metadata.ttl);
189
+ }
190
+ return ok(agent);
191
+ }
192
+ catch (error) {
193
+ return err(new AgentError(AgentErrorCode.AUTHENTICATION_FAILED, error instanceof Error ? error.message : 'Unknown error during agent creation', { originalError: error }));
194
+ }
195
+ }
196
+ /**
197
+ * Call a tool/service via xBind.
198
+ *
199
+ * This method wraps agent-call.ts call() function with agent context
200
+ * and enforces policy constraints defined during agent creation.
201
+ *
202
+ * @param tool - Tool alias (e.g., "stripe:createCharge")
203
+ * @param params - Parameters to pass to the tool
204
+ * @param options - Optional call options (overrides agent policy)
205
+ * @returns Result with response data and audit receipt, or error
206
+ *
207
+ * @example
208
+ * ```typescript
209
+ * const result = await agent.call("payments:createCharge", {
210
+ * amount: 100,
211
+ * currency: "USD"
212
+ * });
213
+ *
214
+ * if (!result.ok) {
215
+ * console.error(`Payment failed: ${result.error.message}`);
216
+ * return;
217
+ * }
218
+ *
219
+ * console.log(`Charge created: ${result.value.data.id}`);
220
+ * console.log(`Audit: ${result.value.audit.timestamp}`);
221
+ * ```
222
+ */
223
+ async call(tool, params, options) {
224
+ // Merge agent policy with call-specific options
225
+ const callOptions = {
226
+ ...options,
227
+ policy: this._policy ? {
228
+ ...this._policy,
229
+ ...options?.policy,
230
+ // Merge allowed tools arrays
231
+ allowedTools: options?.policy?.allowedTools
232
+ ? [...(this._policy.allowedTools || []), ...options.policy.allowedTools]
233
+ : this._policy.allowedTools,
234
+ // Merge scopes arrays
235
+ scopes: options?.policy?.scopes
236
+ ? [...(this._policy.scopes || []), ...options.policy.scopes]
237
+ : this._policy.scopes,
238
+ // Take minimum of limits (most restrictive)
239
+ limits: {
240
+ amountPerTxn: Math.min(this._policy.limits?.amountPerTxn ?? Infinity, options?.policy?.limits?.amountPerTxn ?? Infinity) === Infinity ? undefined : Math.min(this._policy.limits?.amountPerTxn ?? Infinity, options?.policy?.limits?.amountPerTxn ?? Infinity),
241
+ dailyAmount: Math.min(this._policy.limits?.dailyAmount ?? Infinity, options?.policy?.limits?.dailyAmount ?? Infinity) === Infinity ? undefined : Math.min(this._policy.limits?.dailyAmount ?? Infinity, options?.policy?.limits?.dailyAmount ?? Infinity),
242
+ callsPerMinute: Math.min(this._policy.limits?.callsPerMinute ?? Infinity, options?.policy?.limits?.callsPerMinute ?? Infinity) === Infinity ? undefined : Math.min(this._policy.limits?.callsPerMinute ?? Infinity, options?.policy?.limits?.callsPerMinute ?? Infinity),
243
+ },
244
+ } : options?.policy,
245
+ };
246
+ // Delegate to agent-call.ts call() function
247
+ const result = await call(tool, params, callOptions);
248
+ // Record successful call for rate limiting
249
+ if (result.ok) {
250
+ const policyEngine = getGlobalPolicyEngine();
251
+ policyEngine.recordCall(this.did);
252
+ // Record spending if amount is in params
253
+ if (typeof params === 'object' && params !== null) {
254
+ const obj = params;
255
+ const amount = obj.amount ?? obj.value ?? obj.price ?? obj.total;
256
+ if (typeof amount === 'number') {
257
+ policyEngine.recordSpending(this.did, amount);
258
+ }
259
+ }
260
+ }
261
+ return result;
262
+ }
263
+ /**
264
+ * Cleanup agent resources.
265
+ *
266
+ * For ephemeral agents, this clears the cleanup timer and marks
267
+ * the agent as cleaned up. For persistent agents, this is a no-op.
268
+ *
269
+ * This method is called automatically when TTL expires for ephemeral agents.
270
+ */
271
+ cleanup() {
272
+ if (this._metadata.cleanupTimer) {
273
+ clearTimeout(this._metadata.cleanupTimer);
274
+ this._metadata.cleanupTimer = undefined;
275
+ }
276
+ // Reset policy engine state for this agent
277
+ const policyEngine = getGlobalPolicyEngine();
278
+ policyEngine.reset(this.did);
279
+ }
280
+ /**
281
+ * Extend TTL for ephemeral agents.
282
+ *
283
+ * @param additionalTime - Additional time in milliseconds
284
+ * @returns true if extended, false if not an ephemeral agent
285
+ *
286
+ * @example
287
+ * ```typescript
288
+ * // Extend by 30 minutes
289
+ * agent.extendTTL(30 * 60 * 1000);
290
+ * ```
291
+ */
292
+ extendTTL(additionalTime) {
293
+ if (this._metadata.identityMode !== 'ephemeral' || !this._metadata.ttl) {
294
+ return false;
295
+ }
296
+ // Clear existing timer
297
+ if (this._metadata.cleanupTimer) {
298
+ clearTimeout(this._metadata.cleanupTimer);
299
+ }
300
+ // Calculate new TTL (extend the total TTL, not just remaining time)
301
+ const elapsed = Date.now() - this._metadata.created;
302
+ const currentRemaining = this._metadata.ttl - elapsed;
303
+ const newRemaining = currentRemaining + additionalTime;
304
+ // Update the TTL to reflect the extension
305
+ // SAFETY: We're modifying metadata which is intentionally mutable for lifecycle management
306
+ this._metadata.ttl = this._metadata.ttl + additionalTime;
307
+ // Setup new timer
308
+ this._metadata.cleanupTimer = setTimeout(() => {
309
+ this.cleanup();
310
+ }, newRemaining);
311
+ return true;
312
+ }
313
+ /**
314
+ * Convert agent to JSON-serializable format.
315
+ *
316
+ * @returns Agent metadata (without private keys)
317
+ */
318
+ toJSON() {
319
+ return {
320
+ name: this.name,
321
+ did: this.did,
322
+ created: this.created,
323
+ identityMode: this.identityMode,
324
+ ttl: this.ttl,
325
+ timeRemaining: this.timeRemaining,
326
+ };
327
+ }
328
+ }