@execlave/sdk 1.9.0 → 1.10.0

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/client.js CHANGED
@@ -45,6 +45,7 @@ exports.formatLogMessage = formatLogMessage;
45
45
  const http_1 = require("./http");
46
46
  const agent_1 = require("./agent");
47
47
  const trace_1 = require("./trace");
48
+ const credentialProvider_1 = require("./credentialProvider");
48
49
  const errors_1 = require("./errors");
49
50
  const crypto_1 = require("crypto");
50
51
  const bypassReporter_1 = require("./bypassReporter");
@@ -145,6 +146,8 @@ const PII_PATTERNS = {
145
146
  ip_address: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g,
146
147
  api_key: /\b(?:sk|pk|ag)_[a-zA-Z0-9]{20,}\b/g,
147
148
  };
149
+ /** Deepest nesting the privacy scrubber and text extractor will walk. */
150
+ const MAX_PRIVACY_DEPTH = 32;
148
151
  // ---------------------------------------------------------------------------
149
152
  // Injection Patterns (common prompt-injection signatures)
150
153
  // ---------------------------------------------------------------------------
@@ -183,6 +186,8 @@ const INJECTION_PATTERNS = [
183
186
  */
184
187
  class Execlave {
185
188
  constructor(config = {}) {
189
+ /** Set when authenticating as one agent with workload identity federation. */
190
+ this._credentials = null;
186
191
  this._otelExporter = null;
187
192
  this._otelReady = null;
188
193
  this._state = 'INITIALIZING';
@@ -215,9 +220,27 @@ class Execlave {
215
220
  this._heartbeatIntervalMs = 600000;
216
221
  // p3 — attach a signed agent credential to each trace on ingest when enabled.
217
222
  this._stampIdentity = false;
218
- this._apiKey = config.apiKey ?? process.env.EXECLAVE_API_KEY ?? '';
219
- if (!this._apiKey) {
220
- throw new Error('apiKey must be provided or EXECLAVE_API_KEY env var must be set');
223
+ if (config.credentialProvider) {
224
+ // The platform refuses a request carrying both an API key and an agent
225
+ // credential, so refuse the configuration rather than pick one silently.
226
+ if (config.apiKey) {
227
+ throw new Error('Pass apiKey or credentialProvider, not both');
228
+ }
229
+ // The OTLP exporter authenticates with an API key only.
230
+ if (config.mode === 'otlp') {
231
+ throw new Error('mode "otlp" needs an apiKey; it is not supported with credentialProvider');
232
+ }
233
+ this._apiKey = '';
234
+ this._credentials = new credentialProvider_1.FederatedCredentialSource({
235
+ provider: config.credentialProvider,
236
+ exchange: (idpToken) => this._exchangeIdpToken(idpToken),
237
+ });
238
+ }
239
+ else {
240
+ this._apiKey = config.apiKey ?? process.env.EXECLAVE_API_KEY ?? '';
241
+ if (!this._apiKey) {
242
+ throw new Error('apiKey must be provided or EXECLAVE_API_KEY env var must be set (or pass credentialProvider)');
243
+ }
221
244
  }
222
245
  this._baseUrl = normalizeBaseUrl(config.baseUrl ?? process.env.EXECLAVE_BASE_URL ?? 'https://api.execlave.com');
223
246
  this._apiVersion = config.apiVersion !== undefined ? config.apiVersion || undefined : 'v1';
@@ -333,7 +356,8 @@ class Execlave {
333
356
  const resp = await (0, http_1.request)({
334
357
  method: 'GET',
335
358
  url: `${this._baseUrl}/health`,
336
- headers: { Authorization: `Bearer ${this._apiKey}` },
359
+ // /health needs no authentication; never exchange a credential for it.
360
+ headers: this._apiKey ? { Authorization: `Bearer ${this._apiKey}` } : {},
337
361
  timeout: 5000,
338
362
  });
339
363
  return resp.status === 200;
@@ -345,10 +369,19 @@ class Execlave {
345
369
  /**
346
370
  * Register (or re-register) an AI agent. Idempotent — call on startup.
347
371
  *
372
+ * With `credentialProvider` nothing is created: the agent already exists and
373
+ * is bound to the federated identity. The call exchanges a credential and
374
+ * names that agent `opts.agentId` in this client, so `enforcePolicy`,
375
+ * `startTrace` and the other calls can refer to it as before. Only the agent
376
+ * fields `agentId`, `name` and `environment` are used.
377
+ *
348
378
  * @returns An Agent object with prompt management methods.
349
379
  */
350
380
  async registerAgent(opts) {
351
381
  const environment = opts.environment ?? this._environment;
382
+ if (this._credentials) {
383
+ return this._nameFederatedAgent(opts.agentId, opts.name, environment);
384
+ }
352
385
  const payload = {
353
386
  agentId: opts.agentId,
354
387
  name: opts.name,
@@ -653,16 +686,23 @@ class Execlave {
653
686
  const url = `${this._baseUrl}${this.apiPath('/policies/enforce')}`;
654
687
  let resp;
655
688
  try {
689
+ const auth = await this._auth();
656
690
  resp = await (0, http_1.request)({
657
691
  method: 'POST',
658
692
  url,
659
- headers: { Authorization: `Bearer ${this._apiKey}` },
693
+ headers: auth.headers,
660
694
  body: payload,
661
695
  resolveOnClientError: true,
662
- sign: this._sign(),
696
+ sign: auth.sign,
663
697
  });
664
698
  }
665
699
  catch (err) {
700
+ // A refused federation token is the agent's identity being withdrawn
701
+ // (binding removed, provider disabled), not an outage: never fail open
702
+ // on it. An unreachable identity provider or exchange endpoint is an
703
+ // outage and follows enforcementOnOutage below, like an API outage.
704
+ if (err instanceof errors_1.ExeclaveAuthError)
705
+ throw err;
666
706
  // Network failure → circuit breaker. fail_closed must block on the FIRST
667
707
  // failure, not only once the breaker has tripped — a guarantee gated on
668
708
  // the breaker threshold silently allows the first N calls through, which
@@ -690,7 +730,7 @@ class Execlave {
690
730
  // windows are over — unless the 402 is being fail-open'd, which is itself a
691
731
  // bypass and must keep (or start) a window rather than end one.
692
732
  if (resp.status !== 402) {
693
- this._bypassReporter?.recover(opts.agentId);
733
+ this._bypassReporter?.recover(this._reportedAgentId(opts.agentId));
694
734
  }
695
735
  }
696
736
  // 5. Handle response codes
@@ -904,10 +944,11 @@ class Execlave {
904
944
  async _sendHeartbeats() {
905
945
  for (const [, agent] of this._agents) {
906
946
  try {
947
+ const { headers } = await this._auth();
907
948
  await (0, http_1.request)({
908
949
  method: 'POST',
909
950
  url: `${this._baseUrl}${this.apiPath(`/agents/${agent.id}/heartbeat`)}`,
910
- headers: { Authorization: `Bearer ${this._apiKey}` },
951
+ headers,
911
952
  body: { lastPolicyCheckAt: null },
912
953
  timeout: 10000,
913
954
  });
@@ -924,10 +965,12 @@ class Execlave {
924
965
  const pollIntervalMs = 5000;
925
966
  while (Date.now() - startedAt < timeoutMs) {
926
967
  const url = `${this._baseUrl}${this.apiPath(`/approvals/${approvalRequestId}`)}`;
968
+ // Fetched per poll: a 30-minute wait outlives a federated credential.
969
+ const { headers } = await this._auth();
927
970
  const resp = await (0, http_1.request)({
928
971
  method: 'GET',
929
972
  url,
930
- headers: { Authorization: `Bearer ${this._apiKey}` },
973
+ headers,
931
974
  resolveOnClientError: true,
932
975
  });
933
976
  if (resp.status >= 400) {
@@ -994,7 +1037,12 @@ class Execlave {
994
1037
  async authorizeAgentCall(opts) {
995
1038
  this._ensureNotShutdown();
996
1039
  const resp = await this._request('POST', this.apiPath('/agents/authorize'), {
997
- callerAgentId: opts.callerAgentId,
1040
+ // With an agent credential the caller must be the credential's agent;
1041
+ // send its UUID, since the local registerAgent name may differ from the
1042
+ // platform's external ID.
1043
+ callerAgentId: this._credentials
1044
+ ? this._resolveAgentId(opts.callerAgentId)
1045
+ : opts.callerAgentId,
998
1046
  calleeAgentId: opts.calleeAgentId,
999
1047
  action: opts.action,
1000
1048
  });
@@ -1075,6 +1123,14 @@ class Execlave {
1075
1123
  /** @internal */
1076
1124
  _bufferTrace(payload) {
1077
1125
  this._throwIfQuotaExceeded();
1126
+ // An agent credential may ingest only its own agent's traces, matched by
1127
+ // UUID: the local name given in registerAgent need not be the agent's
1128
+ // external ID on the platform.
1129
+ if (this._credentials && payload.agentId && !payload.agentUuid) {
1130
+ const agent = this._agents.get(payload.agentId);
1131
+ if (agent)
1132
+ payload.agentUuid = agent.id;
1133
+ }
1078
1134
  // Client-side PII scrubbing
1079
1135
  if (this._privacy.enabled) {
1080
1136
  this._applyPrivacy(payload);
@@ -1108,21 +1164,69 @@ class Execlave {
1108
1164
  const resp = await this._requestRaw(method, path, body);
1109
1165
  return resp.data;
1110
1166
  }
1111
- /** Signing descriptor for the HTTP layer when request signing is enabled. */
1112
- _sign() {
1113
- return this._signRequests ? { key: this._apiKey } : undefined;
1167
+ /**
1168
+ * The bearer for the next request (the API key, or a current federated
1169
+ * credential) and, when request signing is on, the HMAC key. The server
1170
+ * verifies a signature with the bearer the request presents, so the signing
1171
+ * key is always that same bearer.
1172
+ */
1173
+ async _auth() {
1174
+ const bearer = this._credentials ? (await this._credentials.get()).credential : this._apiKey;
1175
+ return {
1176
+ headers: { Authorization: `Bearer ${bearer}` },
1177
+ sign: this._signRequests ? { key: bearer } : undefined,
1178
+ };
1179
+ }
1180
+ /**
1181
+ * Exchange an identity provider token for an agent API credential. The
1182
+ * exchange endpoint is unauthenticated by design: the token is the proof.
1183
+ * A refusal (4xx other than 429) is an ExeclaveAuthError; rate limiting,
1184
+ * server errors and network failures are ExeclaveErrors, so callers can tell
1185
+ * a withdrawn identity from an outage.
1186
+ */
1187
+ async _exchangeIdpToken(idpToken) {
1188
+ const resp = await (0, http_1.request)({
1189
+ method: 'POST',
1190
+ url: `${this._baseUrl}${this.apiPath('/agent-credentials/exchange')}`,
1191
+ body: { token: idpToken },
1192
+ timeout: 10000,
1193
+ resolveOnClientError: true,
1194
+ });
1195
+ if (resp.status === 429 || resp.status >= 500) {
1196
+ throw new errors_1.ExeclaveError(`Credential exchange unavailable (${resp.status})`);
1197
+ }
1198
+ if (resp.status >= 400) {
1199
+ throw new errors_1.ExeclaveAuthError(`Credential exchange refused (${resp.status}): ${resp.data?.error?.message ?? 'unknown reason'}`);
1200
+ }
1201
+ return resp.data?.data;
1202
+ }
1203
+ /**
1204
+ * Name the federated identity's agent `agentId` in this client (see
1205
+ * registerAgent). One client authenticates as exactly one agent.
1206
+ */
1207
+ async _nameFederatedAgent(agentId, name, environment) {
1208
+ const { agentId: agentUuid } = await this._credentials.get();
1209
+ const existing = this._agents.get(agentId);
1210
+ if (existing)
1211
+ return existing;
1212
+ if (this._agents.size > 0) {
1213
+ const [named] = this._agents.keys();
1214
+ throw new errors_1.ExeclaveError(`This client authenticates as one agent, already registered as '${named}'`);
1215
+ }
1216
+ const agent = new agent_1.Agent(this, { id: agentUuid, agentId, name, environment, status: 'active' });
1217
+ this._agents.set(agentId, agent);
1218
+ return agent;
1114
1219
  }
1115
1220
  async _requestRaw(method, path, body, resolveOnClientError = false) {
1116
1221
  const url = `${this._baseUrl}${path}`;
1222
+ const auth = await this._auth();
1117
1223
  return (0, http_1.request)({
1118
1224
  method,
1119
1225
  url,
1120
- headers: {
1121
- Authorization: `Bearer ${this._apiKey}`,
1122
- },
1226
+ headers: auth.headers,
1123
1227
  body,
1124
1228
  resolveOnClientError,
1125
- sign: this._sign(),
1229
+ sign: auth.sign,
1126
1230
  });
1127
1231
  }
1128
1232
  // ========================================================================
@@ -1354,17 +1458,35 @@ class Execlave {
1354
1458
  _hashPii(value) {
1355
1459
  return (0, crypto_1.createHash)('sha256').update(value).digest('hex').slice(0, 16);
1356
1460
  }
1461
+ /**
1462
+ * Every string (and number) leaf of a value, joined: what a pattern scanner should read.
1463
+ * Recurses through arrays and objects. Coercing items with String() reduced each object in
1464
+ * a message array to "[object Object]", so nothing inside it was ever scanned.
1465
+ */
1357
1466
  _toText(data) {
1358
- if (data == null)
1359
- return '';
1360
- if (typeof data === 'string')
1361
- return data;
1362
- if (typeof data === 'object') {
1363
- if (Array.isArray(data))
1364
- return data.map(String).join(' ');
1365
- return Object.values(data).map(String).join(' ');
1366
- }
1367
- return String(data);
1467
+ const parts = [];
1468
+ const path = new Set();
1469
+ const walk = (value, depth) => {
1470
+ if (depth > MAX_PRIVACY_DEPTH || value == null)
1471
+ return;
1472
+ if (typeof value === 'string') {
1473
+ parts.push(value);
1474
+ }
1475
+ else if (typeof value === 'number' || typeof value === 'bigint') {
1476
+ parts.push(String(value));
1477
+ }
1478
+ else if (typeof value === 'object') {
1479
+ if (path.has(value))
1480
+ return;
1481
+ path.add(value);
1482
+ for (const item of Array.isArray(value) ? value : Object.values(value)) {
1483
+ walk(item, depth + 1);
1484
+ }
1485
+ path.delete(value);
1486
+ }
1487
+ };
1488
+ walk(data, 0);
1489
+ return parts.join(' ');
1368
1490
  }
1369
1491
  _scrubText(text) {
1370
1492
  if (!text)
@@ -1375,46 +1497,84 @@ class Execlave {
1375
1497
  }
1376
1498
  return result;
1377
1499
  }
1500
+ /**
1501
+ * A copy of `value` with PII replaced in every string, however deeply nested. The caller's
1502
+ * own objects are never modified. What cannot be scrubbed safely is dropped instead of
1503
+ * passed through: a cycle becomes '[CIRCULAR]', anything past the depth limit becomes
1504
+ * '[REDACTED_DEPTH_LIMIT]'. A number that holds PII becomes its redacted string.
1505
+ */
1506
+ _scrubValue(value, path, depth) {
1507
+ if (typeof value === 'string')
1508
+ return this._scrubText(value);
1509
+ if (typeof value === 'number' || typeof value === 'bigint') {
1510
+ const text = String(value);
1511
+ const scrubbed = this._scrubText(text);
1512
+ return scrubbed === text ? value : scrubbed;
1513
+ }
1514
+ if (value === null || typeof value !== 'object')
1515
+ return value;
1516
+ if (value instanceof Date)
1517
+ return value;
1518
+ if (depth > MAX_PRIVACY_DEPTH)
1519
+ return '[REDACTED_DEPTH_LIMIT]';
1520
+ if (path.has(value))
1521
+ return '[CIRCULAR]';
1522
+ path.add(value);
1523
+ let result;
1524
+ if (Array.isArray(value)) {
1525
+ result = value.map((item) => this._scrubValue(item, path, depth + 1));
1526
+ }
1527
+ else {
1528
+ const copy = {};
1529
+ for (const [key, item] of Object.entries(value)) {
1530
+ copy[key] = this._scrubValue(item, path, depth + 1);
1531
+ }
1532
+ result = copy;
1533
+ }
1534
+ path.delete(value);
1535
+ return result;
1536
+ }
1537
+ _detectPii(text) {
1538
+ const found = [];
1539
+ for (const [piiType, pattern] of Object.entries(PII_PATTERNS)) {
1540
+ const matches = text.match(new RegExp(pattern.source, pattern.flags));
1541
+ if (matches && matches.length > 0)
1542
+ found.push([piiType, matches]);
1543
+ }
1544
+ return found;
1545
+ }
1378
1546
  _applyPrivacy(payload) {
1379
1547
  const scrubFields = this._privacy.scrubFields ?? ['input', 'output'];
1380
1548
  const hashPii = this._privacy.hashPii ?? true;
1381
1549
  const piiSummary = {};
1550
+ let incomplete = false;
1382
1551
  for (const field of scrubFields) {
1383
1552
  const value = payload[field];
1384
1553
  if (!value)
1385
1554
  continue;
1386
- const text = this._toText(value);
1387
- if (!text)
1388
- continue;
1389
- // Detect PII
1390
- for (const [piiType, pattern] of Object.entries(PII_PATTERNS)) {
1391
- const matches = text.match(new RegExp(pattern.source, pattern.flags));
1392
- if (matches && matches.length > 0) {
1393
- if (!piiSummary[piiType])
1394
- piiSummary[piiType] = { count: 0, hashes: [] };
1395
- piiSummary[piiType].count += matches.length;
1396
- if (hashPii) {
1397
- piiSummary[piiType].hashes.push(...matches.map((m) => this._hashPii(m)));
1398
- }
1399
- }
1400
- }
1401
- // Replace PII with placeholders
1402
- if (typeof value === 'string') {
1403
- payload[field] = this._scrubText(value);
1404
- }
1405
- else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
1406
- const scrubbed = {};
1407
- for (const [k, v] of Object.entries(value)) {
1408
- scrubbed[k] = typeof v === 'string' ? this._scrubText(v) : v;
1555
+ const found = this._detectPii(this._toText(value));
1556
+ for (const [piiType, matches] of found) {
1557
+ if (!piiSummary[piiType])
1558
+ piiSummary[piiType] = { count: 0, hashes: [] };
1559
+ piiSummary[piiType].count += matches.length;
1560
+ if (hashPii) {
1561
+ piiSummary[piiType].hashes.push(...matches.map((m) => this._hashPii(m)));
1409
1562
  }
1410
- payload[field] = scrubbed;
1411
1563
  }
1564
+ // Always scrub, even when nothing was detected: detection stops at the depth limit, and
1565
+ // anything deeper must be dropped by the scrub rather than slip through unread.
1566
+ const scrubbed = this._scrubValue(value, new Set(), 0);
1567
+ payload[field] = scrubbed;
1568
+ // Attest only what is true: re-scan what will actually be sent. PII spanning two values,
1569
+ // for example, is detected in the joined text but cannot be removed value by value.
1570
+ if (this._detectPii(this._toText(scrubbed)).length > 0)
1571
+ incomplete = true;
1412
1572
  }
1413
1573
  if (Object.keys(piiSummary).length > 0) {
1414
1574
  if (!payload.metadata)
1415
1575
  payload.metadata = {};
1416
1576
  payload.metadata.pii_detected = piiSummary;
1417
- payload.metadata.pii_scrubbed = true;
1577
+ payload.metadata.pii_scrubbed = !incomplete;
1418
1578
  }
1419
1579
  }
1420
1580
  _scanInjection(payload) {
@@ -1444,6 +1604,14 @@ class Execlave {
1444
1604
  // ========================================================================
1445
1605
  // Helpers
1446
1606
  // ========================================================================
1607
+ /**
1608
+ * The agent ID a bypass window is reported under. With an agent credential
1609
+ * the platform accepts only the credential's own agent, by UUID or external
1610
+ * ID, and the local registerAgent name need not be the external ID.
1611
+ */
1612
+ _reportedAgentId(agentId) {
1613
+ return this._credentials ? this._resolveAgentId(agentId) : agentId;
1614
+ }
1447
1615
  _firstAgentId() {
1448
1616
  const first = this._agents.values().next();
1449
1617
  return first.done ? undefined : first.value.agentId;
@@ -1471,18 +1639,33 @@ class Execlave {
1471
1639
  const { io } = require('socket.io-client');
1472
1640
  // Use the first registered agent's agentId if available
1473
1641
  const agentId = this._firstAgentId();
1642
+ // With an agent credential the handshake runs again on every reconnect,
1643
+ // so it is a callback that fetches a current credential. The server
1644
+ // joins the socket to its own agent's room only and disconnects it when
1645
+ // the credential expires.
1646
+ const credentials = this._credentials;
1647
+ const auth = credentials
1648
+ ? (cb) => {
1649
+ credentials.get().then((c) => cb({ agentCredential: c.credential }), (err) => {
1650
+ this._log('WebSocket credential unavailable: %s', err.message);
1651
+ cb({}); // refused by the server; status polling continues
1652
+ });
1653
+ }
1654
+ : { apiKey: this._apiKey, agentId };
1474
1655
  this._socket = io(`${this._baseUrl}/sdk`, {
1475
- auth: {
1476
- apiKey: this._apiKey,
1477
- agentId,
1478
- },
1656
+ auth,
1479
1657
  transports: ['websocket'],
1480
1658
  reconnection: true,
1481
1659
  reconnectionDelay: 2000,
1482
1660
  reconnectionAttempts: 10,
1483
1661
  });
1484
1662
  this._socket.on('agent.status_updated', (data) => {
1485
- const agent = data.agentId ? this._agents.get(data.agentId) : undefined;
1663
+ // The event names the agent by internal UUID; the map is keyed by
1664
+ // the external (or local) agentId.
1665
+ const agent = data.agentId
1666
+ ? [...this._agents.values()].find((a) => a.id === data.agentId) ??
1667
+ this._agents.get(data.agentId)
1668
+ : undefined;
1486
1669
  if (data.status === 'paused' && this._state === 'ACTIVE') {
1487
1670
  this._state = 'PAUSED';
1488
1671
  if (agent)
@@ -1501,6 +1684,14 @@ class Execlave {
1501
1684
  this._socket.on('connect', () => {
1502
1685
  this._log('WebSocket control channel connected');
1503
1686
  });
1687
+ // A server-side disconnect is not retried by socket.io-client. With an
1688
+ // agent credential it is the expected one at credential expiry, so
1689
+ // reconnect; the auth callback supplies a fresh credential.
1690
+ this._socket.on('disconnect', (reason) => {
1691
+ if (credentials && reason === 'io server disconnect' && this._state !== 'SHUTDOWN') {
1692
+ this._socket?.connect();
1693
+ }
1694
+ });
1504
1695
  this._socket.on('connect_error', (err) => {
1505
1696
  // Silently fall back to HTTP polling — no user action needed
1506
1697
  this._log('WebSocket connect error: %s — falling back to HTTP polling', err.message);
@@ -1525,7 +1716,7 @@ class Execlave {
1525
1716
  this._bypassReporter?.record({
1526
1717
  reason: event.reason,
1527
1718
  source: event.source,
1528
- agentId: event.agentId,
1719
+ agentId: this._reportedAgentId(event.agentId),
1529
1720
  message: event.message,
1530
1721
  status: event.status,
1531
1722
  consecutiveFailures: event.consecutiveFailures,