@atlasent/sdk 1.5.0 → 2.5.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/index.js CHANGED
@@ -1,4 +1,25 @@
1
1
  // src/errors.ts
2
+ var StreamTimeoutError = class extends Error {
3
+ name = "StreamTimeoutError";
4
+ /** Timeout that was exceeded, in milliseconds. */
5
+ timeoutMs;
6
+ constructor(timeoutMs) {
7
+ super(`AtlaSent stream timed out after ${timeoutMs}ms with no event`);
8
+ this.timeoutMs = timeoutMs;
9
+ }
10
+ };
11
+ var StreamParseError = class extends Error {
12
+ name = "StreamParseError";
13
+ /** The raw data string that failed to parse. */
14
+ rawData;
15
+ constructor(rawData, cause) {
16
+ super(`AtlaSent stream received malformed JSON: ${rawData.slice(0, 200)}`);
17
+ this.rawData = rawData;
18
+ if (cause !== void 0) {
19
+ this.cause = cause;
20
+ }
21
+ }
22
+ };
2
23
  var AtlaSentError = class extends Error {
3
24
  // Subclasses override to their own literal (e.g. "AtlaSentDeniedError");
4
25
  // keep this assignable rather than pinned to a single literal.
@@ -22,6 +43,18 @@ var AtlaSentError = class extends Error {
22
43
  this.retryAfterMs = init.retryAfterMs;
23
44
  }
24
45
  };
46
+ var KNOWN_PERMIT_OUTCOMES = /* @__PURE__ */ new Set([
47
+ "permit_consumed",
48
+ "permit_expired",
49
+ "permit_revoked",
50
+ "permit_not_found"
51
+ ]);
52
+ function normalizePermitOutcome(raw) {
53
+ if (raw !== void 0 && KNOWN_PERMIT_OUTCOMES.has(raw)) {
54
+ return raw;
55
+ }
56
+ return void 0;
57
+ }
25
58
  var AtlaSentDeniedError = class extends AtlaSentError {
26
59
  name = "AtlaSentDeniedError";
27
60
  /** Policy decision — `"deny"` today; `"hold"` / `"escalate"` reserved. */
@@ -32,6 +65,12 @@ var AtlaSentDeniedError = class extends AtlaSentError {
32
65
  reason;
33
66
  /** Hash-chained audit-trail entry associated with the decision. */
34
67
  auditHash;
68
+ /**
69
+ * Discriminator for permit-side denial reasons. Populated only
70
+ * when the server reported `verified=false` from `/v1-verify-permit`;
71
+ * `undefined` for evaluate-time denials. See {@link PermitOutcome}.
72
+ */
73
+ outcome;
35
74
  constructor(init) {
36
75
  const msg = init.reason ? `AtlaSent ${init.decision}: ${init.reason}` : `AtlaSent ${init.decision}`;
37
76
  const errInit = { status: 200 };
@@ -41,92 +80,665 @@ var AtlaSentDeniedError = class extends AtlaSentError {
41
80
  this.evaluationId = init.evaluationId;
42
81
  this.reason = init.reason;
43
82
  this.auditHash = init.auditHash;
83
+ this.outcome = init.outcome;
84
+ }
85
+ // ── Outcome discriminators ───────────────────────────────────────
86
+ // Convenience predicates that mirror the operator runbook's matrix.
87
+ // Callers can compare `outcome` directly; these are sugar so the
88
+ // common cases are explicit at the call site.
89
+ /** `true` when the permit was explicitly revoked (D3 endpoint). */
90
+ get isRevoked() {
91
+ return this.outcome === "permit_revoked";
92
+ }
93
+ /** `true` when the permit's TTL passed before verification. */
94
+ get isExpired() {
95
+ return this.outcome === "permit_expired";
96
+ }
97
+ /**
98
+ * `true` when the permit was already consumed by a prior verify
99
+ * (v1 single-use replay protection).
100
+ */
101
+ get isConsumed() {
102
+ return this.outcome === "permit_consumed";
103
+ }
104
+ /**
105
+ * `true` when the permit id wasn't recognized server-side
106
+ * (typo, cross-tenant lookup, or pre-issuance race).
107
+ */
108
+ get isNotFound() {
109
+ return this.outcome === "permit_not_found";
110
+ }
111
+ };
112
+ var AtlaSentEscalateError = class extends AtlaSentError {
113
+ name = "AtlaSentEscalateError";
114
+ /** Always `"escalate"` — discriminates this error from other AtlaSent errors. */
115
+ decision = "escalate";
116
+ /** The user whose action triggered the escalation, if available. */
117
+ userId;
118
+ constructor(message, opts) {
119
+ super(message, {
120
+ ...opts?.requestId !== void 0 ? { requestId: opts.requestId } : {},
121
+ cause: opts?.cause
122
+ });
123
+ this.userId = opts?.userId;
124
+ }
125
+ };
126
+ var PermitRevoked = class extends AtlaSentError {
127
+ name = "PermitRevoked";
128
+ /** The id of the permit that was revoked mid-execution. */
129
+ permitId;
130
+ /** The `scope_revocations.id` that triggered the revocation, when available. */
131
+ revocationId;
132
+ constructor(permitId, revocationId) {
133
+ super(
134
+ revocationId ? `AtlaSent: permit ${permitId} revoked (revocation: ${revocationId}) \u2014 guard heartbeat halted execution` : `AtlaSent: permit ${permitId} revoked \u2014 guard heartbeat halted execution`
135
+ );
136
+ this.permitId = permitId;
137
+ this.revocationId = revocationId;
138
+ }
139
+ };
140
+
141
+ // src/types.ts
142
+ var PRODUCTION_DEPLOY_ACTION = "production.deploy";
143
+ var DEPLOYMENT_PRODUCTION_ACTION = "deployment.production";
144
+ var DEPLOY_GATE_CODES = Object.freeze({
145
+ ALLOW: "ALLOW",
146
+ DENY_POLICY: "DENY_POLICY",
147
+ DENY_AUTHORITY: "DENY_AUTHORITY",
148
+ DENY_ENVIRONMENT: "DENY_ENVIRONMENT",
149
+ PERMIT_EXPIRED: "PERMIT_EXPIRED",
150
+ VERIFY_FAILED: "VERIFY_FAILED",
151
+ ESCALATE_REQUIRED: "ESCALATE_REQUIRED",
152
+ OVERRIDE_APPROVED: "OVERRIDE_APPROVED"
153
+ });
154
+
155
+ // src/compat.ts
156
+ function normalizeEvaluateRequest(input) {
157
+ if ("action" in input && !("action_type" in input)) {
158
+ console.warn(
159
+ "[atlasent] Deprecation: action/agent request shape is deprecated. Use action_type/actor_id instead. This compatibility shim will be removed in v3.0.0."
160
+ );
161
+ const legacy = input;
162
+ const normalized = {
163
+ action_type: legacy.action,
164
+ actor_id: legacy.agent
165
+ };
166
+ if (legacy.context !== void 0) {
167
+ normalized.context = legacy.context;
168
+ }
169
+ return normalized;
170
+ }
171
+ return input;
172
+ }
173
+ function normalizeEvaluateResponse(wire) {
174
+ if (!("decision" in wire) && "permitted" in wire) {
175
+ const legacy = wire;
176
+ const normalized = {
177
+ decision: legacy.permitted ? "allow" : "deny"
178
+ };
179
+ if (legacy.decision_id !== void 0) {
180
+ normalized.permit_token = legacy.decision_id;
181
+ }
182
+ if (!legacy.permitted && legacy.reason) {
183
+ normalized.denial = { reason: legacy.reason };
184
+ }
185
+ return normalized;
44
186
  }
187
+ return wire;
188
+ }
189
+
190
+ // src/retry.ts
191
+ var DEFAULT_RETRY_POLICY = {
192
+ maxAttempts: 4,
193
+ baseDelayMs: 2e3,
194
+ maxDelayMs: 16e3
45
195
  };
196
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set([
197
+ "network",
198
+ "timeout",
199
+ "rate_limited",
200
+ "server_error",
201
+ "bad_response"
202
+ ]);
203
+ function isRetryable(err) {
204
+ if (!(err instanceof AtlaSentError)) return false;
205
+ if (err.code === void 0) return false;
206
+ return RETRYABLE_CODES.has(err.code);
207
+ }
208
+ function computeBackoffMs(attempt, policy = {}, err, random = Math.random) {
209
+ const merged = mergePolicy(policy);
210
+ const safeAttempt = Math.max(0, Math.floor(attempt));
211
+ const exp = Math.min(safeAttempt, 30);
212
+ const ceiling = Math.min(merged.maxDelayMs, merged.baseDelayMs * 2 ** exp);
213
+ const jittered = Math.floor(ceiling * clampUnit(random()));
214
+ const retryAfterMs = err instanceof AtlaSentError && typeof err.retryAfterMs === "number" ? Math.max(0, err.retryAfterMs) : 0;
215
+ return Math.max(retryAfterMs, jittered);
216
+ }
217
+ function hasAttemptsLeft(attempt, policy = {}) {
218
+ const merged = mergePolicy(policy);
219
+ return attempt + 1 < merged.maxAttempts;
220
+ }
221
+ function mergePolicy(policy) {
222
+ const maxAttempts = Math.max(
223
+ 1,
224
+ Math.floor(policy.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts)
225
+ );
226
+ const baseDelayMs = Math.max(
227
+ 0,
228
+ policy.baseDelayMs ?? DEFAULT_RETRY_POLICY.baseDelayMs
229
+ );
230
+ const maxDelayMs = Math.max(
231
+ baseDelayMs,
232
+ policy.maxDelayMs ?? DEFAULT_RETRY_POLICY.maxDelayMs
233
+ );
234
+ return { maxAttempts, baseDelayMs, maxDelayMs };
235
+ }
236
+ function clampUnit(n) {
237
+ if (!Number.isFinite(n)) return 0;
238
+ if (n < 0) return 0;
239
+ if (n >= 1) return 0.999999999;
240
+ return n;
241
+ }
46
242
 
47
243
  // src/client.ts
48
244
  var DEFAULT_BASE_URL = "https://api.atlasent.io";
49
245
  var DEFAULT_TIMEOUT_MS = 1e4;
50
- var SDK_VERSION = "0.1.0";
246
+ var SDK_VERSION = "2.2.0";
247
+ function _buildUserAgent() {
248
+ const isNode2 = typeof process !== "undefined" && typeof process?.versions?.node === "string";
249
+ return isNode2 ? `@atlasent/sdk/${SDK_VERSION} node/${process.version}` : `@atlasent/sdk/${SDK_VERSION} browser`;
250
+ }
251
+ var CONTEXT_PROPERTIES_SOFT_CAP = 64;
252
+ function _warnOversizeContext(context) {
253
+ if (context && Object.keys(context).length > CONTEXT_PROPERTIES_SOFT_CAP) {
254
+ console.warn(
255
+ `[atlasent] context has ${Object.keys(context).length} top-level keys (soft cap ${CONTEXT_PROPERTIES_SOFT_CAP}); the server may reject this. Pack richer payloads under a single top-level key.`
256
+ );
257
+ }
258
+ }
259
+ function _enforceTls(baseUrl) {
260
+ const nodeEnvValue = typeof process !== "undefined" && process.env ? process.env.ATLASENT_ALLOW_INSECURE_HTTP : void 0;
261
+ const allow = nodeEnvValue === "1" || globalThis.ATLASENT_ALLOW_INSECURE_HTTP === "1";
262
+ if (allow) return baseUrl;
263
+ let parsed;
264
+ try {
265
+ parsed = new URL(baseUrl);
266
+ } catch {
267
+ throw new AtlaSentError(`Invalid baseUrl: ${baseUrl}`, {
268
+ code: "bad_request"
269
+ });
270
+ }
271
+ if (parsed.protocol !== "https:") {
272
+ throw new AtlaSentError(
273
+ `AtlaSent baseUrl must use https:// (got ${parsed.protocol}). For local development, set ATLASENT_ALLOW_INSECURE_HTTP=1.`,
274
+ { code: "bad_request" }
275
+ );
276
+ }
277
+ return baseUrl;
278
+ }
279
+ var API_KEY_PATTERN = /^ask_(?:live|test)_[A-Za-z0-9_-]+$/;
280
+ function _validateApiKey(apiKey) {
281
+ if (typeof apiKey !== "string" || apiKey.length === 0) {
282
+ throw new AtlaSentError("apiKey is required", { code: "invalid_api_key" });
283
+ }
284
+ if (!API_KEY_PATTERN.test(apiKey)) {
285
+ const head = apiKey.slice(0, 8);
286
+ throw new AtlaSentError(
287
+ `AtlaSent apiKey does not match expected shape \`ask_(live|test)_<entropy>\` (got prefix=${JSON.stringify(head)}). Check for whitespace, quotes, or trailing characters.`,
288
+ { code: "invalid_api_key" }
289
+ );
290
+ }
291
+ return apiKey;
292
+ }
293
+ var isNode = typeof process !== "undefined" && typeof process.versions?.node === "string";
294
+ var NODE_VERSION = isNode ? process.version : null;
295
+ function deployGateEvidence(input) {
296
+ const evidence = {};
297
+ if (input.permitId) evidence.permitId = input.permitId;
298
+ if (input.permitHash) evidence.permitHash = input.permitHash;
299
+ if (input.auditHash) evidence.auditHash = input.auditHash;
300
+ if (input.verifiedAt) evidence.verifiedAt = input.verifiedAt;
301
+ return evidence;
302
+ }
51
303
  var AtlaSentClient = class {
52
304
  apiKey;
53
305
  baseUrl;
54
306
  timeoutMs;
55
307
  fetchImpl;
308
+ userAgent;
309
+ retryPolicy;
56
310
  constructor(options) {
57
311
  if (!options.apiKey || typeof options.apiKey !== "string") {
58
312
  throw new AtlaSentError("apiKey is required", {
59
313
  code: "invalid_api_key"
60
314
  });
61
315
  }
62
- this.apiKey = options.apiKey;
63
- this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
316
+ if (typeof AbortSignal.timeout !== "function") {
317
+ throw new AtlaSentError(
318
+ "@atlasent/sdk requires AbortSignal.timeout, which is not available in this runtime. Minimum supported browsers: Chrome 103+, Firefox 100+, Safari 16+. Upgrade your browser or add an AbortSignal.timeout polyfill.",
319
+ { code: "network" }
320
+ );
321
+ }
322
+ this.apiKey = _validateApiKey(options.apiKey);
323
+ this.baseUrl = _enforceTls(options.baseUrl ?? DEFAULT_BASE_URL).replace(
324
+ /\/+$/,
325
+ ""
326
+ );
64
327
  this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
65
328
  this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
329
+ this.userAgent = _buildUserAgent();
330
+ this.retryPolicy = mergePolicy(options.retryPolicy ?? {});
66
331
  }
67
332
  /**
68
333
  * Ask the policy engine whether an agent action is permitted.
69
334
  *
70
- * A "DENY" is **not** thrown it is returned in
335
+ * Accepts either the current v2.0 shape (`action_type` / `actor_id`)
336
+ * or the legacy v1.x shape (`action` / `agent`). Legacy callers
337
+ * receive a deprecation warning via `console.warn`; the shim is
338
+ * handled by {@link normalizeEvaluateRequest} and will be removed
339
+ * in v3.0.0.
340
+ *
341
+ * A "deny" is **not** thrown — it is returned in
71
342
  * `response.decision`. Network errors, invalid API key, rate
72
343
  * limits, timeouts, and malformed responses throw
73
344
  * {@link AtlaSentError}.
74
345
  */
75
346
  async evaluate(input) {
347
+ _warnOversizeContext(input.context);
348
+ const normalized = normalizeEvaluateRequest(
349
+ input
350
+ );
76
351
  const body = {
77
- action: input.action,
78
- agent: input.agent,
79
- context: input.context ?? {},
80
- api_key: this.apiKey
352
+ action_type: normalized.action_type,
353
+ actor_id: normalized.actor_id,
354
+ context: normalized.context ?? {}
81
355
  };
82
- const { body: wire, rateLimit } = await this.post("/v1-evaluate", body);
83
- if (typeof wire.permitted !== "boolean" || typeof wire.decision_id !== "string") {
356
+ const { body: wire, rateLimit } = await this.post(
357
+ "/v1-evaluate",
358
+ body
359
+ );
360
+ let decision = typeof wire.decision === "string" ? wire.decision.toLowerCase() : wire.decision;
361
+ if (decision === void 0 && typeof wire.permitted === "boolean") {
362
+ decision = wire.permitted ? "allow" : "deny";
363
+ }
364
+ const permitToken = wire.permit_token ?? wire.decision_id;
365
+ if (decision !== "allow" && decision !== "deny" && decision !== "hold" && decision !== "escalate") {
366
+ throw new AtlaSentError(
367
+ "Malformed response from /v1-evaluate: missing `decision` (or legacy `permitted`)",
368
+ { code: "bad_response" }
369
+ );
370
+ }
371
+ if (decision === "allow" && (typeof permitToken !== "string" || permitToken.length === 0)) {
84
372
  throw new AtlaSentError(
85
- "Malformed response from /v1-evaluate: missing `permitted` or `decision_id`",
373
+ "Malformed response from /v1-evaluate: decision='allow' but no `permit_token` (or legacy `decision_id`)",
86
374
  { code: "bad_response" }
87
375
  );
88
376
  }
377
+ const reason = wire.denial?.reason ?? wire.reason ?? "";
378
+ const permitId = permitToken ?? "";
89
379
  return {
90
- decision: wire.permitted ? "ALLOW" : "DENY",
91
- permitId: wire.decision_id,
92
- reason: wire.reason ?? "",
380
+ decision,
381
+ decision_canonical: decision,
382
+ evaluationId: permitId,
383
+ permitId,
384
+ // /v1-evaluate does not return a control-plane-shaped Permit body;
385
+ // callers needing the full record fetch GET /v1/permits/:id.
386
+ permit: null,
387
+ permitToken: decision === "allow" ? permitToken ?? null : null,
388
+ reasons: reason ? [reason] : [],
389
+ reason,
390
+ auditHash: wire.audit_hash ?? "",
391
+ timestamp: wire.timestamp ?? "",
392
+ rateLimit
393
+ };
394
+ }
395
+ /**
396
+ * Pre-flight evaluation that always returns the constraint trace.
397
+ *
398
+ * Wraps `POST /v1-evaluate?include=constraint_trace`. Use this from
399
+ * a workflow's submission step to surface trivial defects (missing
400
+ * fields, wrong roles, mis-set context) BEFORE pushing the request
401
+ * onto an approval queue — only requests that would actually pass
402
+ * make it through to a human reviewer.
403
+ *
404
+ * Returns an {@link EvaluatePreflightResponse} carrying the regular
405
+ * {@link EvaluateResponse} plus the {@link ConstraintTrace}. Unlike
406
+ * {@link evaluate}, this method does NOT mark a non-allow as a
407
+ * thrown condition — the whole point is to inspect both the outcome
408
+ * AND the per-policy trace, so the caller branches on
409
+ * `result.evaluation.decision` and reads `result.constraintTrace`
410
+ * to render the failing stages.
411
+ *
412
+ * The constraint-trace shape mirrors `ConstraintTraceResponse` in
413
+ * atlasent-api (`packages/types/src/index.ts`). On older
414
+ * atlasent-api deployments that omit the trace, `constraintTrace`
415
+ * is `null` rather than throwing — forward-compatible degradation.
416
+ *
417
+ * Performance: one extra round-trip on submission. Latency is
418
+ * comparable to {@link evaluate}; the response body is fuller
419
+ * (includes the per-stage trace) so the wire payload is larger.
420
+ * If the caller does not need the trace, prefer {@link evaluate}.
421
+ */
422
+ async evaluatePreflight(input) {
423
+ _warnOversizeContext(input.context);
424
+ const body = {
425
+ action_type: input.action,
426
+ actor_id: input.agent,
427
+ context: input.context ?? {}
428
+ };
429
+ const query = new URLSearchParams({ include: "constraint_trace" });
430
+ const { body: wire, rateLimit } = await this.post(
431
+ "/v1-evaluate",
432
+ body,
433
+ query
434
+ );
435
+ let decision = typeof wire.decision === "string" ? wire.decision.toLowerCase() : wire.decision;
436
+ if (decision === void 0 && typeof wire.permitted === "boolean") {
437
+ decision = wire.permitted ? "allow" : "deny";
438
+ }
439
+ if (decision !== "allow" && decision !== "deny" && decision !== "hold" && decision !== "escalate") {
440
+ throw new AtlaSentError(
441
+ "Malformed response from /v1-evaluate: missing `decision` (or legacy `permitted`)",
442
+ { code: "bad_response" }
443
+ );
444
+ }
445
+ const permitToken = wire.permit_token ?? wire.decision_id;
446
+ const reason = wire.denial?.reason ?? wire.reason ?? "";
447
+ const permitId = permitToken ?? "";
448
+ const evaluation = {
449
+ decision,
450
+ decision_canonical: decision,
451
+ evaluationId: permitId,
452
+ permitId,
453
+ // /v1-evaluate does not return a control-plane-shaped Permit body;
454
+ // callers needing the full record fetch GET /v1/permits/:id.
455
+ permit: null,
456
+ permitToken: decision === "allow" ? permitToken ?? null : null,
457
+ reasons: reason ? [reason] : [],
458
+ reason,
93
459
  auditHash: wire.audit_hash ?? "",
94
460
  timestamp: wire.timestamp ?? "",
95
461
  rateLimit
96
462
  };
463
+ let constraintTrace = null;
464
+ if (wire.constraint_trace !== void 0 && wire.constraint_trace !== null && typeof wire.constraint_trace === "object") {
465
+ constraintTrace = wire.constraint_trace;
466
+ }
467
+ return { evaluation, constraintTrace };
97
468
  }
98
469
  /**
99
470
  * Verify that a previously issued permit is still valid.
100
471
  *
472
+ * @deprecated Use {@link verifyPermitById} — the canonical REST
473
+ * surface (`POST /v1/permits/{id}/verify`) returns the unified
474
+ * verification envelope plus the full {@link PermitRecord}, instead
475
+ * of the legacy `{verified, outcome, permitHash}` shape this method
476
+ * emits. Will be removed in `@atlasent/sdk@3`.
477
+ *
101
478
  * A `verified: false` response is **not** thrown — inspect the
102
479
  * returned object. Only transport / server errors throw.
103
480
  */
104
481
  async verifyPermit(input) {
482
+ _warnOversizeContext(input.context);
105
483
  const body = {
106
- decision_id: input.permitId,
107
- action: input.action ?? "",
108
- agent: input.agent ?? "",
109
- context: input.context ?? {},
110
- api_key: this.apiKey
484
+ permit_token: input.permitId,
485
+ action_type: input.action ?? "",
486
+ actor_id: input.agent ?? ""
111
487
  };
488
+ if (input.environment !== void 0) {
489
+ body.environment = input.environment;
490
+ }
491
+ if (input.execution_hash !== void 0) {
492
+ body.execution_hash = input.execution_hash;
493
+ }
112
494
  const { body: wire, rateLimit } = await this.post(
113
495
  "/v1-verify-permit",
114
496
  body
115
497
  );
116
- if (typeof wire.verified !== "boolean") {
498
+ const valid = typeof wire.valid === "boolean" ? wire.valid : wire.verified;
499
+ if (typeof valid !== "boolean") {
117
500
  throw new AtlaSentError(
118
- "Malformed response from /v1-verify-permit: missing `verified`",
501
+ "Malformed response from /v1-verify-permit: missing `valid` (or legacy `verified`)",
119
502
  { code: "bad_response" }
120
503
  );
121
504
  }
122
505
  return {
123
- verified: wire.verified,
506
+ verified: valid,
124
507
  outcome: wire.outcome ?? "",
125
508
  permitHash: wire.permit_hash ?? "",
126
509
  timestamp: wire.timestamp ?? "",
127
510
  rateLimit
128
511
  };
129
512
  }
513
+ /**
514
+ * Run the canonical Deploy Gate V1 flow:
515
+ * evaluate `production.deploy`, verify the issued permit server-side,
516
+ * and return allow/block plus audit/evidence metadata.
517
+ *
518
+ * This helper never treats a signed/offline permit artifact as sufficient
519
+ * authorization. Execution is allowed only when `POST /v1-evaluate` returns
520
+ * `decision: "allow"` with a permit AND `POST /v1-verify-permit` returns
521
+ * `verified: true` / `valid: true`.
522
+ */
523
+ async deployGate(input = {}) {
524
+ const agent = input.agent ?? "ci-deploy-bot";
525
+ const action = input.action ?? PRODUCTION_DEPLOY_ACTION;
526
+ const context = input.context ?? {};
527
+ const evaluation = await this.evaluate({ agent, action, context });
528
+ if (evaluation.decision !== "allow") {
529
+ return {
530
+ allowed: false,
531
+ evaluation,
532
+ reason: evaluation.reason || `Deploy Gate blocked by decision=${evaluation.decision}`,
533
+ evidence: deployGateEvidence({
534
+ permitId: evaluation.permitId,
535
+ auditHash: evaluation.auditHash
536
+ })
537
+ };
538
+ }
539
+ const verification = await this.verifyPermit({
540
+ permitId: evaluation.permitId,
541
+ agent,
542
+ action,
543
+ context
544
+ });
545
+ if (!verification.verified) {
546
+ return {
547
+ allowed: false,
548
+ evaluation,
549
+ verification,
550
+ reason: verification.outcome ? `Deploy Gate blocked by permit verification outcome=${verification.outcome}` : "Deploy Gate blocked because permit verification failed",
551
+ evidence: deployGateEvidence({
552
+ permitId: evaluation.permitId,
553
+ permitHash: verification.permitHash,
554
+ auditHash: evaluation.auditHash,
555
+ verifiedAt: verification.timestamp
556
+ })
557
+ };
558
+ }
559
+ return {
560
+ allowed: true,
561
+ evaluation,
562
+ verification,
563
+ reason: evaluation.reason || "Deploy Gate permit verified",
564
+ evidence: deployGateEvidence({
565
+ permitId: evaluation.permitId,
566
+ permitHash: verification.permitHash,
567
+ auditHash: evaluation.auditHash,
568
+ verifiedAt: verification.timestamp
569
+ })
570
+ };
571
+ }
572
+ /**
573
+ * Revoke a previously-issued permit so it can no longer pass
574
+ * {@link verifyPermit}.
575
+ *
576
+ * @deprecated Use {@link revokePermitById} — the canonical REST
577
+ * surface (`POST /v1/permits/{id}/revoke`) returns the full updated
578
+ * {@link PermitRecord} with `revoked_at`/`revoked_by`/`revoke_reason`
579
+ * populated, instead of the legacy `{revoked, permitId}` envelope
580
+ * this method emits. Will be removed in `@atlasent/sdk@3`.
581
+ *
582
+ * Use this when an agent's action is cancelled, superseded, or
583
+ * determined to be unauthorized after the fact. The revocation is
584
+ * recorded in the audit log with the optional `reason`.
585
+ *
586
+ * Throws {@link AtlaSentError} on transport / auth failures.
587
+ */
588
+ async revokePermit(input) {
589
+ const body = {
590
+ decision_id: input.permitId,
591
+ reason: input.reason ?? "",
592
+ api_key: this.apiKey
593
+ };
594
+ const { body: wire, rateLimit } = await this.post("/v1-revoke-permit", body);
595
+ if (typeof wire.revoked !== "boolean" || typeof wire.decision_id !== "string") {
596
+ throw new AtlaSentError(
597
+ "Malformed response from /v1-revoke-permit: missing `revoked` or `decision_id`",
598
+ { code: "bad_response" }
599
+ );
600
+ }
601
+ return {
602
+ revoked: wire.revoked,
603
+ permitId: wire.decision_id,
604
+ revokedAt: wire.revoked_at,
605
+ auditHash: wire.audit_hash,
606
+ rateLimit
607
+ };
608
+ }
609
+ /**
610
+ * Revoke a permit through the canonical REST surface
611
+ * (`POST /v1/permits/{permitId}/revoke`).
612
+ *
613
+ * Returns the full updated {@link PermitRecord} with `status === 'revoked'`
614
+ * and `revoked_at` / `revoked_by` / `revoke_reason` populated. After
615
+ * revocation, subsequent verify calls return `410 PERMIT_REVOKED`.
616
+ *
617
+ * Idempotent on `409 permit_revoked` for already-revoked permits;
618
+ * server returns the existing revoked row in that case.
619
+ *
620
+ * Throws {@link AtlaSentError} on `404` (permit not in calling org),
621
+ * `409` (already in a terminal state), `410` (expired before revoke),
622
+ * or `429` (rate limited).
623
+ */
624
+ async revokePermitById(permitId, input = {}) {
625
+ if (!permitId) {
626
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
627
+ }
628
+ const body = {};
629
+ if (input.reason !== void 0) body.reason = input.reason;
630
+ const { body: wire, rateLimit } = await this.post(
631
+ `/v1/permits/${encodeURIComponent(permitId)}/revoke`,
632
+ body
633
+ );
634
+ return { permit: wire, rateLimit };
635
+ }
636
+ /**
637
+ * Verify a permit through the canonical REST surface
638
+ * (`POST /v1/permits/{permitId}/verify`).
639
+ *
640
+ * Returns the unified verification envelope (`valid`,
641
+ * `verification_type: 'permit'`, `reason`, `verified_at`, `evidence`)
642
+ * plus the full {@link PermitRecord} fields preserved at the top
643
+ * level. The `valid` field is the contract — pin to it.
644
+ *
645
+ * A `valid: false` is **not** thrown when the server returns 200 with
646
+ * a denial reason (matches the verify-shape unification on the wire);
647
+ * it is thrown on 4xx (`404` not found, `410` expired/consumed).
648
+ */
649
+ async verifyPermitById(permitId) {
650
+ if (!permitId) {
651
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
652
+ }
653
+ const { body: wire, rateLimit } = await this.post(`/v1/permits/${encodeURIComponent(permitId)}/verify`, {});
654
+ const { valid, verification_type, reason, verified_at, evidence, ...row } = wire;
655
+ return {
656
+ valid,
657
+ verification_type,
658
+ reason,
659
+ verified_at,
660
+ evidence,
661
+ permit: row,
662
+ rateLimit
663
+ };
664
+ }
665
+ /**
666
+ * Get a single permit's full lifecycle state.
667
+ *
668
+ * Calls `GET /v1/permits/{permitId}` (the canonical REST surface).
669
+ * Returns `status`, all timestamps, `revoked_at` / `revoked_by` /
670
+ * `revoke_reason` (when applicable), and the bound `payload_hash`
671
+ * / `decision_id`.
672
+ *
673
+ * Operator-facing introspection — answers "what state is this permit
674
+ * in, and why?" without reading audit logs.
675
+ *
676
+ * Throws {@link AtlaSentError} on `404` (permit not in calling org)
677
+ * or `410` (expired before retrieval).
678
+ */
679
+ async getPermit(permitId) {
680
+ if (!permitId) {
681
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
682
+ }
683
+ const { body: wire, rateLimit } = await this.get(
684
+ `/v1/permits/${encodeURIComponent(permitId)}`
685
+ );
686
+ return { permit: wire, rateLimit };
687
+ }
688
+ /**
689
+ * Poll whether a permit is currently valid.
690
+ *
691
+ * Calls `GET /v1/permits/{permitId}/valid` — a lightweight read
692
+ * returning only the status snapshot optimised for guard heartbeat
693
+ * polling. Guards with `permitRevalidationIntervalMs` set race this
694
+ * against `tool.execute()` and throw {@link PermitRevoked} when
695
+ * `status === "revoked"` arrives.
696
+ *
697
+ * Throws {@link AtlaSentError} on transport / auth failures.
698
+ */
699
+ async checkPermitValid(permitId) {
700
+ if (!permitId) {
701
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
702
+ }
703
+ const { body } = await this.get(
704
+ `/v1/permits/${encodeURIComponent(permitId)}/valid`
705
+ );
706
+ return body;
707
+ }
708
+ /**
709
+ * List permits issued to the calling org, most-recently-issued first.
710
+ *
711
+ * Calls `GET /v1/permits` (the canonical REST surface). Cursor-paged.
712
+ * Filters narrow on server side; pagination uses the `created_at`
713
+ * timestamp opaquely (`nextCursor`).
714
+ *
715
+ * Designed for incident review, debugging, and compliance
716
+ * reconstruction.
717
+ */
718
+ async listPermits(input = {}) {
719
+ const params = new URLSearchParams();
720
+ if (input.status) params.set("status", input.status);
721
+ if (input.actorId) params.set("actor_id", input.actorId);
722
+ if (input.actionType) params.set("action_type", input.actionType);
723
+ if (input.from) params.set("from", input.from);
724
+ if (input.to) params.set("to", input.to);
725
+ if (input.limit !== void 0) params.set("limit", String(input.limit));
726
+ if (input.cursor) params.set("cursor", input.cursor);
727
+ const { body: wire, rateLimit } = await this.get("/v1/permits", params);
728
+ if (!Array.isArray(wire.permits)) {
729
+ throw new AtlaSentError(
730
+ "Malformed response from /v1/permits: missing `permits` array",
731
+ { code: "bad_response" }
732
+ );
733
+ }
734
+ const result = {
735
+ permits: wire.permits,
736
+ total: typeof wire.total === "number" ? wire.total : wire.permits.length,
737
+ rateLimit
738
+ };
739
+ if (wire.next_cursor !== void 0) result.nextCursor = wire.next_cursor;
740
+ return result;
741
+ }
130
742
  /**
131
743
  * Self-introspection: ask the server to describe the API key this
132
744
  * client was constructed with. Returns the key's ID, organization,
@@ -141,9 +753,7 @@ var AtlaSentClient = class {
141
753
  * taxonomy as {@link AtlaSentClient.evaluate}.
142
754
  */
143
755
  async keySelf() {
144
- const { body: wire, rateLimit } = await this.get(
145
- "/v1-api-key-self"
146
- );
756
+ const { body: wire, rateLimit } = await this.get("/v1-api-key-self");
147
757
  if (typeof wire.key_id !== "string" || typeof wire.organization_id !== "string") {
148
758
  throw new AtlaSentError(
149
759
  "Malformed response from /v1-api-key-self: missing `key_id` or `organization_id`",
@@ -218,8 +828,129 @@ var AtlaSentClient = class {
218
828
  }
219
829
  return { ...wire, rateLimit };
220
830
  }
221
- async post(path, body) {
222
- return this.request(path, "POST", body, void 0);
831
+ /**
832
+ * Open a streaming evaluation session against `POST /v1-evaluate-stream`.
833
+ *
834
+ * Yields {@link StreamDecisionEvent} and {@link StreamProgressEvent} objects
835
+ * as the server emits them. The iterator ends cleanly when the server sends
836
+ * `event: done`; it throws {@link AtlaSentError} on transport errors or when
837
+ * the server sends `event: error`.
838
+ *
839
+ * The final {@link StreamDecisionEvent} (isFinal: true) carries a `permitId`
840
+ * suitable for passing to {@link verifyPermit} after the stream closes.
841
+ *
842
+ * Hardening:
843
+ * - Throws {@link StreamTimeoutError} when no event arrives within
844
+ * `opts.timeoutMs` (default 30 s). Pass `0` to disable.
845
+ * - Retries up to `opts.maxRetries` times (default 3) with 1 s / 2 s / 4 s
846
+ * delays on network drop (before a terminal event). Sends `Last-Event-ID`
847
+ * on reconnect when the server has emitted event IDs.
848
+ * - Throws {@link StreamParseError} on partial / malformed JSON rather than
849
+ * crashing with a raw `SyntaxError`.
850
+ * - Closes cleanly on `event: done` or a decision event with `done: true`.
851
+ *
852
+ * ```ts
853
+ * for await (const event of client.protectStream({ agent, action })) {
854
+ * if (event.type === "decision" && event.isFinal) {
855
+ * await client.verifyPermit({ permitId: event.permitId });
856
+ * }
857
+ * }
858
+ * ```
859
+ */
860
+ async *protectStream(input, opts = {}) {
861
+ const streamTimeoutMs = opts.timeoutMs ?? 3e4;
862
+ const maxRetries = opts.maxRetries ?? 3;
863
+ const body = {
864
+ action: input.action,
865
+ agent: input.agent,
866
+ context: input.context ?? {},
867
+ api_key: this.apiKey
868
+ };
869
+ const requestId = globalThis.crypto.randomUUID();
870
+ const url = `${this.baseUrl}/v1-evaluate-stream`;
871
+ let lastEventId;
872
+ let retryCount = 0;
873
+ while (true) {
874
+ const headers = {
875
+ Accept: "text/event-stream",
876
+ "Content-Type": "application/json",
877
+ Authorization: `Bearer ${this.apiKey}`,
878
+ "User-Agent": this.userAgent,
879
+ "X-Request-ID": requestId
880
+ };
881
+ if (lastEventId !== void 0) {
882
+ headers["Last-Event-ID"] = lastEventId;
883
+ }
884
+ const connectionTimeoutSignal = AbortSignal.timeout(this.timeoutMs);
885
+ const signal = opts.signal ? AbortSignal.any([connectionTimeoutSignal, opts.signal]) : connectionTimeoutSignal;
886
+ let response;
887
+ try {
888
+ response = await this.fetchImpl(url, {
889
+ method: "POST",
890
+ headers,
891
+ body: JSON.stringify(body),
892
+ signal
893
+ });
894
+ } catch (err) {
895
+ const mapped = mapFetchError(err, requestId);
896
+ if (mapped.code === "network" && retryCount < maxRetries) {
897
+ retryCount++;
898
+ await sleep(1e3 * Math.pow(2, retryCount - 1));
899
+ continue;
900
+ }
901
+ throw mapped;
902
+ }
903
+ if (!response.ok) {
904
+ throw await buildHttpError(response, requestId);
905
+ }
906
+ if (!response.body) {
907
+ throw new AtlaSentError("Expected streaming body from AtlaSent API", {
908
+ code: "bad_response",
909
+ status: response.status,
910
+ requestId
911
+ });
912
+ }
913
+ let streamDone = false;
914
+ let networkDrop = false;
915
+ try {
916
+ for await (const event of parseSseStream(
917
+ response.body,
918
+ requestId,
919
+ streamTimeoutMs,
920
+ (id) => {
921
+ lastEventId = id;
922
+ }
923
+ )) {
924
+ yield event;
925
+ if (event.type === "decision" && event.isFinal) {
926
+ streamDone = true;
927
+ }
928
+ }
929
+ streamDone = true;
930
+ } catch (err) {
931
+ if (err instanceof AtlaSentError && err.code === "network") {
932
+ networkDrop = true;
933
+ } else {
934
+ throw err;
935
+ }
936
+ }
937
+ if (streamDone) break;
938
+ if (networkDrop && retryCount < maxRetries) {
939
+ retryCount++;
940
+ await sleep(1e3 * Math.pow(2, retryCount - 1));
941
+ continue;
942
+ }
943
+ if (networkDrop) {
944
+ throw new AtlaSentError(
945
+ `AtlaSent stream dropped after ${retryCount} reconnection attempts`,
946
+ { code: "network", requestId }
947
+ );
948
+ }
949
+ break;
950
+ }
951
+ }
952
+ async post(path, body, query) {
953
+ return this.request(path, "POST", body, query);
223
954
  }
224
955
  async get(path, query) {
225
956
  return this.request(path, "GET", void 0, query);
@@ -231,47 +962,622 @@ var AtlaSentClient = class {
231
962
  const headers = {
232
963
  Accept: "application/json",
233
964
  Authorization: `Bearer ${this.apiKey}`,
234
- "User-Agent": `@atlasent/sdk/${SDK_VERSION} node/${process.version}`,
965
+ "User-Agent": this.userAgent,
235
966
  "X-Request-ID": requestId
236
967
  };
237
968
  if (method === "POST") headers["Content-Type"] = "application/json";
238
- const init = {
239
- method,
240
- headers,
241
- signal: AbortSignal.timeout(this.timeoutMs)
242
- };
243
- if (method === "POST") init.body = JSON.stringify(body);
244
- let response;
245
- try {
246
- response = await this.fetchImpl(url, init);
247
- } catch (err) {
248
- throw mapFetchError(err, requestId);
969
+ const bodyStr = method === "POST" ? JSON.stringify(body) : void 0;
970
+ for (let attempt = 0; ; attempt++) {
971
+ const init = {
972
+ method,
973
+ headers,
974
+ signal: AbortSignal.timeout(this.timeoutMs)
975
+ };
976
+ if (bodyStr !== void 0) init.body = bodyStr;
977
+ let response;
978
+ try {
979
+ response = await this.fetchImpl(url, init);
980
+ } catch (err) {
981
+ const mapped = mapFetchError(err, requestId);
982
+ if (isRetryable(mapped) && hasAttemptsLeft(attempt, this.retryPolicy)) {
983
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, mapped));
984
+ continue;
985
+ }
986
+ throw mapped;
987
+ }
988
+ if (!response.ok) {
989
+ const httpErr = await buildHttpError(response, requestId);
990
+ if (isRetryable(httpErr) && hasAttemptsLeft(attempt, this.retryPolicy)) {
991
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, httpErr));
992
+ continue;
993
+ }
994
+ throw httpErr;
995
+ }
996
+ let parsed;
997
+ try {
998
+ parsed = await response.json();
999
+ } catch (err) {
1000
+ const jsonErr = new AtlaSentError(
1001
+ "Invalid JSON response from AtlaSent API",
1002
+ {
1003
+ code: "bad_response",
1004
+ status: response.status,
1005
+ requestId,
1006
+ cause: err
1007
+ }
1008
+ );
1009
+ if (isRetryable(jsonErr) && hasAttemptsLeft(attempt, this.retryPolicy)) {
1010
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, jsonErr));
1011
+ continue;
1012
+ }
1013
+ throw jsonErr;
1014
+ }
1015
+ if (parsed === null || typeof parsed !== "object") {
1016
+ const shapeErr = new AtlaSentError(
1017
+ "Expected a JSON object from AtlaSent API",
1018
+ {
1019
+ code: "bad_response",
1020
+ status: response.status,
1021
+ requestId
1022
+ }
1023
+ );
1024
+ if (isRetryable(shapeErr) && hasAttemptsLeft(attempt, this.retryPolicy)) {
1025
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, shapeErr));
1026
+ continue;
1027
+ }
1028
+ throw shapeErr;
1029
+ }
1030
+ return {
1031
+ body: parsed,
1032
+ rateLimit: parseRateLimitHeaders(response.headers)
1033
+ };
249
1034
  }
250
- if (!response.ok) {
251
- throw await buildHttpError(response, requestId);
1035
+ }
1036
+ /**
1037
+ * Open a new HITL escalation. Bridges a `hold` outcome from
1038
+ * `protect()` to the approval queue: an agent that receives a
1039
+ * `hold` decision calls this to enroll the proposed action for
1040
+ * human review. The returned escalation can then be polled with
1041
+ * `getHitlEscalation()` or driven to terminal by
1042
+ * `approveHitlEscalation()` / `rejectHitlEscalation()`.
1043
+ *
1044
+ * Quorum, pool size, fallback decision and routing inherit from
1045
+ * the server-side policy when omitted from `input`.
1046
+ *
1047
+ * Calls `POST /v1/hitl`.
1048
+ */
1049
+ async createHitlEscalation(input) {
1050
+ const { body, rateLimit } = await this.post(
1051
+ "/v1/hitl",
1052
+ input
1053
+ );
1054
+ return { escalation: body, rateLimit };
1055
+ }
1056
+ /**
1057
+ * List HITL escalations for the calling org. Defaults to
1058
+ * `status=pending`; pass `status` to query other queues
1059
+ * (`escalated`, `approved`, `rejected`, `auto_approved`,
1060
+ * `timed_out`).
1061
+ *
1062
+ * Calls `GET /v1/hitl`.
1063
+ */
1064
+ async listHitlEscalations(input = {}) {
1065
+ const params = new URLSearchParams();
1066
+ if (input.status) params.set("status", input.status);
1067
+ if (input.agentId) params.set("agent_id", input.agentId);
1068
+ if (input.assignedToUserId)
1069
+ params.set("assigned_to_user_id", input.assignedToUserId);
1070
+ if (input.limit !== void 0) params.set("limit", String(input.limit));
1071
+ if (input.cursor) params.set("cursor", input.cursor);
1072
+ const { body, rateLimit } = await this.get(
1073
+ "/v1/hitl",
1074
+ params
1075
+ );
1076
+ return { data: body, rateLimit };
1077
+ }
1078
+ /**
1079
+ * Get a HITL escalation. The server payload includes a live
1080
+ * `quorum_progress` snapshot when the escalation is still open.
1081
+ *
1082
+ * Calls `GET /v1/hitl/:id`.
1083
+ */
1084
+ async getHitlEscalation(escalationId) {
1085
+ if (!escalationId) {
1086
+ throw new AtlaSentError("escalationId is required", {
1087
+ code: "bad_request"
1088
+ });
252
1089
  }
253
- let parsed;
254
- try {
255
- parsed = await response.json();
256
- } catch (err) {
257
- throw new AtlaSentError("Invalid JSON response from AtlaSent API", {
258
- code: "bad_response",
259
- status: response.status,
260
- requestId,
261
- cause: err
1090
+ const { body, rateLimit } = await this.get(
1091
+ `/v1/hitl/${encodeURIComponent(escalationId)}`
1092
+ );
1093
+ return { escalation: body, rateLimit };
1094
+ }
1095
+ /**
1096
+ * List per-approver vote rows for an escalation.
1097
+ * Calls `GET /v1/hitl/:id/approvals`.
1098
+ */
1099
+ async listHitlApprovals(escalationId) {
1100
+ const { body, rateLimit } = await this.get(`/v1/hitl/${encodeURIComponent(escalationId)}/approvals`);
1101
+ return { approvals: body.approvals ?? [], rateLimit };
1102
+ }
1103
+ /**
1104
+ * List the escalation chain hops for an escalation. Each `/escalate`
1105
+ * call appends one row.
1106
+ * Calls `GET /v1/hitl/:id/chain`.
1107
+ */
1108
+ async getHitlChain(escalationId) {
1109
+ const { body, rateLimit } = await this.get(
1110
+ `/v1/hitl/${encodeURIComponent(escalationId)}/chain`
1111
+ );
1112
+ return { chain: body.chain ?? [], rateLimit };
1113
+ }
1114
+ /**
1115
+ * Record an approve vote. Resolves the escalation only once the
1116
+ * server-side quorum count is satisfied; before that the response
1117
+ * carries a refreshed escalation row with the latest
1118
+ * `quorum_progress`.
1119
+ *
1120
+ * Calls `POST /v1/hitl/:id/approve`. The server returns 409
1121
+ * `duplicate_vote` if the same principal has already voted, and
1122
+ * 409 `already_rejected` if a concurrent reject crossed the line.
1123
+ */
1124
+ async approveHitlEscalation(escalationId, input = {}) {
1125
+ const { body, rateLimit } = await this.post(
1126
+ `/v1/hitl/${encodeURIComponent(escalationId)}/approve`,
1127
+ input
1128
+ );
1129
+ return { escalation: body, rateLimit };
1130
+ }
1131
+ /**
1132
+ * Record a reject vote. Reject is short-circuit terminal — a single
1133
+ * reject closes the escalation regardless of how many approves have
1134
+ * accumulated.
1135
+ *
1136
+ * Calls `POST /v1/hitl/:id/reject`.
1137
+ */
1138
+ async rejectHitlEscalation(escalationId, input = {}) {
1139
+ const { body, rateLimit } = await this.post(
1140
+ `/v1/hitl/${encodeURIComponent(escalationId)}/reject`,
1141
+ input
1142
+ );
1143
+ return { escalation: body, rateLimit };
1144
+ }
1145
+ /**
1146
+ * Re-route an open escalation to a higher tier. Bounded by the
1147
+ * escalation's `max_escalation_depth` — the server returns 409
1148
+ * `chain_exhausted` and applies the configured fallback decision
1149
+ * once the ceiling is hit.
1150
+ *
1151
+ * Calls `POST /v1/hitl/:id/escalate`.
1152
+ */
1153
+ async escalateHitlEscalation(escalationId, input) {
1154
+ const { body, rateLimit } = await this.post(
1155
+ `/v1/hitl/${encodeURIComponent(escalationId)}/escalate`,
1156
+ input
1157
+ );
1158
+ return { escalation: body, rateLimit };
1159
+ }
1160
+ /**
1161
+ * Manually apply the escalation's `fallback_decision`. Useful for
1162
+ * admin recovery of a hung escalation when the cron sweeper hasn't
1163
+ * run yet, or to short-circuit a stuck flow during incident
1164
+ * response.
1165
+ *
1166
+ * Calls `POST /v1/hitl/:id/timeout`.
1167
+ */
1168
+ async timeoutHitlEscalation(escalationId) {
1169
+ const { body, rateLimit } = await this.post(
1170
+ `/v1/hitl/${encodeURIComponent(escalationId)}/timeout`,
1171
+ {}
1172
+ );
1173
+ return { escalation: body, rateLimit };
1174
+ }
1175
+ /**
1176
+ * Run a named governance graph traversal query.
1177
+ *
1178
+ * Dispatches to `GET /v1/governance/graph/query?type=<queryType>`.
1179
+ * Each query type returns a different row shape — the return type
1180
+ * narrows automatically based on the literal `queryType` argument.
1181
+ *
1182
+ * `"user_approvals"` requires `params.actor_id` — the server returns
1183
+ * a 400 if it is absent.
1184
+ */
1185
+ async queryGovernanceGraph(queryType, params = {}) {
1186
+ const qs = new URLSearchParams({ type: queryType });
1187
+ if (params.actor_id) qs.set("actor_id", params.actor_id);
1188
+ const { body, rateLimit } = await this.get("/v1/governance/graph/query", qs);
1189
+ return { ...body, rateLimit };
1190
+ }
1191
+ /**
1192
+ * Reconstruct the multi-system execution timeline for a specific incident.
1193
+ *
1194
+ * Calls `GET /v1/governance/timeline/incident/{incidentId}`. Backed
1195
+ * server-side by `reconstruct_incident_chains_v2()`, which fixes the
1196
+ * `executor_id → actor_id` bug that silently produced empty timelines
1197
+ * in the original function.
1198
+ *
1199
+ * Returns full execution rows including the §13.1 columns
1200
+ * (`delegation_chain_id`, `replay_of_execution_id`, `incident_id`,
1201
+ * `policy_version_id`, `bundle_version_id`) alongside the actor
1202
+ * timeline and evidence rows.
1203
+ */
1204
+ async getIncidentTimeline(incidentId) {
1205
+ if (!incidentId) {
1206
+ throw new AtlaSentError("incidentId is required", {
1207
+ code: "bad_request"
262
1208
  });
263
1209
  }
264
- if (parsed === null || typeof parsed !== "object") {
265
- throw new AtlaSentError("Expected a JSON object from AtlaSent API", {
266
- code: "bad_response",
267
- status: response.status,
268
- requestId
1210
+ const { body, rateLimit } = await this.get(`/v1/governance/timeline/incident/${encodeURIComponent(incidentId)}`);
1211
+ return { ...body, rateLimit };
1212
+ }
1213
+ // ── Connector Management ─────────────────────────────────────────────────
1214
+ /**
1215
+ * List connectors registered for the calling org.
1216
+ * Calls `GET /v1/governance/connectors`.
1217
+ */
1218
+ async listConnectors(options = {}) {
1219
+ const params = new URLSearchParams();
1220
+ if (options.cursor) params.set("cursor", options.cursor);
1221
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1222
+ const { body, rateLimit } = await this.get("/v1/governance/connectors", params);
1223
+ const result = {
1224
+ connectors: body.connectors ?? [],
1225
+ total: body.total,
1226
+ rateLimit
1227
+ };
1228
+ if (body.next_cursor) result.nextCursor = body.next_cursor;
1229
+ return result;
1230
+ }
1231
+ /**
1232
+ * Register and install a new connector for the calling org.
1233
+ * Calls `POST /v1/governance/connectors`.
1234
+ */
1235
+ async installConnector(input) {
1236
+ const { body, rateLimit } = await this.post("/v1/governance/connectors", input);
1237
+ return { connector: body, rateLimit };
1238
+ }
1239
+ /**
1240
+ * Store encrypted credentials for a connector.
1241
+ * Calls `POST /v1/governance/connectors/{id}/authenticate`.
1242
+ */
1243
+ async authenticateConnector(connectorId, input) {
1244
+ if (!connectorId) {
1245
+ throw new AtlaSentError("connectorId is required", {
1246
+ code: "bad_request"
269
1247
  });
270
1248
  }
1249
+ const { body, rateLimit } = await this.post(
1250
+ `/v1/governance/connectors/${encodeURIComponent(connectorId)}/authenticate`,
1251
+ input
1252
+ );
271
1253
  return {
272
- body: parsed,
273
- rateLimit: parseRateLimitHeaders(response.headers)
1254
+ credential_id: body.credential_id,
1255
+ version: body.version,
1256
+ rateLimit
1257
+ };
1258
+ }
1259
+ /**
1260
+ * Trigger an incremental sync for a connector.
1261
+ * Calls `POST /v1/governance/connectors/{id}/sync`.
1262
+ */
1263
+ async syncConnector(connectorId) {
1264
+ if (!connectorId) {
1265
+ throw new AtlaSentError("connectorId is required", {
1266
+ code: "bad_request"
1267
+ });
1268
+ }
1269
+ const { body, rateLimit } = await this.post(`/v1/governance/connectors/${encodeURIComponent(connectorId)}/sync`, {});
1270
+ return { ...body, rateLimit };
1271
+ }
1272
+ /**
1273
+ * Revoke a connector and all its associated credentials.
1274
+ * Calls `POST /v1/governance/connectors/{id}/revoke`.
1275
+ */
1276
+ async revokeConnector(connectorId, reason) {
1277
+ if (!connectorId) {
1278
+ throw new AtlaSentError("connectorId is required", {
1279
+ code: "bad_request"
1280
+ });
1281
+ }
1282
+ const body = {};
1283
+ if (reason !== void 0) body.reason = reason;
1284
+ const { body: wire, rateLimit } = await this.post(
1285
+ `/v1/governance/connectors/${encodeURIComponent(connectorId)}/revoke`,
1286
+ body
1287
+ );
1288
+ return { ...wire, rateLimit };
1289
+ }
1290
+ /**
1291
+ * Rotate the credentials for a connector.
1292
+ * Calls `POST /v1/governance/connectors/{id}/rotate-credentials`.
1293
+ */
1294
+ async rotateConnectorCredentials(connectorId) {
1295
+ if (!connectorId) {
1296
+ throw new AtlaSentError("connectorId is required", {
1297
+ code: "bad_request"
1298
+ });
1299
+ }
1300
+ const { body, rateLimit } = await this.post(
1301
+ `/v1/governance/connectors/${encodeURIComponent(connectorId)}/rotate-credentials`,
1302
+ {}
1303
+ );
1304
+ return { ...body, rateLimit };
1305
+ }
1306
+ /**
1307
+ * List enforcement policies for the calling org, optionally filtered by connector type.
1308
+ * Calls `GET /v1/governance/enforcement-policies`.
1309
+ */
1310
+ async listEnforcementPolicies(connectorType) {
1311
+ const params = new URLSearchParams();
1312
+ if (connectorType) params.set("connector_type", connectorType);
1313
+ const { body, rateLimit } = await this.get("/v1/governance/enforcement-policies", params);
1314
+ return { policies: body.policies ?? [], total: body.total, rateLimit };
1315
+ }
1316
+ /**
1317
+ * Create or update a connector enforcement policy.
1318
+ * Calls `POST /v1/governance/enforcement-policies`.
1319
+ */
1320
+ async upsertEnforcementPolicy(input) {
1321
+ const { body, rateLimit } = await this.post("/v1/governance/enforcement-policies", input);
1322
+ return { policy: body, rateLimit };
1323
+ }
1324
+ // ── Organizational Risk Graph ─────────────────────────────────────────────
1325
+ /**
1326
+ * Trigger a fresh org-level risk score computation.
1327
+ * Calls `POST /v1/governance/risk/compute`.
1328
+ */
1329
+ async computeOrgRisk(options = {}) {
1330
+ const { body, rateLimit } = await this.post("/v1/governance/risk/compute", options);
1331
+ return { score: body, rateLimit };
1332
+ }
1333
+ /**
1334
+ * Retrieve the most recently computed risk score for the calling org.
1335
+ * Calls `GET /v1/governance/risk/latest`.
1336
+ */
1337
+ async getLatestOrgRisk() {
1338
+ const { body, rateLimit } = await this.get("/v1/governance/risk/latest");
1339
+ return { score: body.score ?? null, rateLimit };
1340
+ }
1341
+ /**
1342
+ * Page through historical org risk scores, most-recent first.
1343
+ * Calls `GET /v1/governance/risk/history`.
1344
+ */
1345
+ async listOrgRiskHistory(options = {}) {
1346
+ const params = new URLSearchParams();
1347
+ if (options.cursor) params.set("cursor", options.cursor);
1348
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1349
+ const { body, rateLimit } = await this.get("/v1/governance/risk/history", params);
1350
+ const result = {
1351
+ scores: body.scores ?? [],
1352
+ total: body.total,
1353
+ rateLimit
274
1354
  };
1355
+ if (body.next_cursor) result.nextCursor = body.next_cursor;
1356
+ return result;
1357
+ }
1358
+ // ── Cross-Org Permission Negotiation ──────────────────────────────────────
1359
+ async checkCrossOrgPermission(req) {
1360
+ const { body } = await this.post(
1361
+ "/v1/cross-org/permissions/check",
1362
+ req
1363
+ );
1364
+ return body;
1365
+ }
1366
+ async listCrossOrgPermissionChecks(params) {
1367
+ const qs = new URLSearchParams();
1368
+ if (params?.source_org_id) qs.set("source_org_id", params.source_org_id);
1369
+ if (params?.target_org_id) qs.set("target_org_id", params.target_org_id);
1370
+ if (params?.allowed !== void 0)
1371
+ qs.set("allowed", String(params.allowed));
1372
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
1373
+ const { body } = await this.get("/v1/cross-org/permissions/checks", qs);
1374
+ return body.checks ?? [];
1375
+ }
1376
+ // ── Anomaly Response Automation ───────────────────────────────────────────
1377
+ async listAnomalyResponseRules() {
1378
+ const { body } = await this.get(
1379
+ "/v1/anomaly-response/rules"
1380
+ );
1381
+ return body.rules ?? [];
1382
+ }
1383
+ async createAnomalyResponseRule(req) {
1384
+ const { body } = await this.post(
1385
+ "/v1/anomaly-response/rules",
1386
+ req
1387
+ );
1388
+ return body;
1389
+ }
1390
+ async updateAnomalyResponseRule(id, updates) {
1391
+ const { body } = await this.post(
1392
+ `/v1/anomaly-response/rules/${encodeURIComponent(id)}/update`,
1393
+ updates
1394
+ );
1395
+ return body;
1396
+ }
1397
+ async deleteAnomalyResponseRule(id) {
1398
+ await this.post(
1399
+ `/v1/anomaly-response/rules/${encodeURIComponent(id)}/delete`,
1400
+ {}
1401
+ );
1402
+ }
1403
+ async triggerAnomalyResponse(req) {
1404
+ const { body } = await this.post(
1405
+ "/v1/anomaly-response/trigger",
1406
+ req
1407
+ );
1408
+ return body.events ?? [];
1409
+ }
1410
+ async listAnomalyResponseEvents(params) {
1411
+ const qs = new URLSearchParams();
1412
+ if (params?.execution_id) qs.set("execution_id", params.execution_id);
1413
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
1414
+ const { body } = await this.get(
1415
+ "/v1/anomaly-response/events",
1416
+ qs
1417
+ );
1418
+ return body.events ?? [];
1419
+ }
1420
+ // ── Budget Exception Workflows ────────────────────────────────────────────
1421
+ async listBudgetExceptions(params) {
1422
+ const qs = new URLSearchParams();
1423
+ if (params?.status) qs.set("status", params.status);
1424
+ if (params?.budget_policy_id)
1425
+ qs.set("budget_policy_id", params.budget_policy_id);
1426
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
1427
+ if (params?.offset !== void 0) qs.set("offset", String(params.offset));
1428
+ const { body } = await this.get(
1429
+ "/v1/budget-exceptions",
1430
+ qs
1431
+ );
1432
+ return body.exceptions ?? [];
1433
+ }
1434
+ async getBudgetException(id) {
1435
+ const { body } = await this.get(
1436
+ `/v1/budget-exceptions/${encodeURIComponent(id)}`
1437
+ );
1438
+ return body;
1439
+ }
1440
+ async createBudgetException(req) {
1441
+ const { body } = await this.post(
1442
+ "/v1/budget-exceptions",
1443
+ req
1444
+ );
1445
+ return body;
1446
+ }
1447
+ async approveBudgetException(id, req) {
1448
+ const { body } = await this.post(
1449
+ `/v1/budget-exceptions/${encodeURIComponent(id)}/approve`,
1450
+ req
1451
+ );
1452
+ return body;
1453
+ }
1454
+ async rejectBudgetException(id, review_notes) {
1455
+ const { body } = await this.post(
1456
+ `/v1/budget-exceptions/${encodeURIComponent(id)}/reject`,
1457
+ { review_notes }
1458
+ );
1459
+ return body;
1460
+ }
1461
+ async cancelBudgetException(id) {
1462
+ const { body } = await this.post(
1463
+ `/v1/budget-exceptions/${encodeURIComponent(id)}/cancel`,
1464
+ {}
1465
+ );
1466
+ return body;
1467
+ }
1468
+ // ── Regulatory Escalation Chain ───────────────────────────────────────────
1469
+ async listRegulatoryAuthorityLevels() {
1470
+ const { body } = await this.get(
1471
+ "/v1/regulatory/authority-levels"
1472
+ );
1473
+ return body.levels ?? [];
1474
+ }
1475
+ async createRegulatoryAuthorityLevel(req) {
1476
+ const { body } = await this.post(
1477
+ "/v1/regulatory/authority-levels",
1478
+ req
1479
+ );
1480
+ return body;
1481
+ }
1482
+ async listRegulatoryEscalations(params) {
1483
+ const qs = new URLSearchParams();
1484
+ if (params?.status) qs.set("status", params.status);
1485
+ if (params?.subject_type) qs.set("subject_type", params.subject_type);
1486
+ if (params?.subject_id) qs.set("subject_id", params.subject_id);
1487
+ const { body } = await this.get(
1488
+ "/v1/regulatory/escalations",
1489
+ qs
1490
+ );
1491
+ return body.escalations ?? [];
1492
+ }
1493
+ async createRegulatoryEscalation(req) {
1494
+ const { body } = await this.post(
1495
+ "/v1/regulatory/escalations",
1496
+ req
1497
+ );
1498
+ return body;
1499
+ }
1500
+ async acknowledgeRegulatoryEscalation(id) {
1501
+ const { body } = await this.post(
1502
+ `/v1/regulatory/escalations/${encodeURIComponent(id)}/acknowledge`,
1503
+ {}
1504
+ );
1505
+ return body;
1506
+ }
1507
+ async resolveRegulatoryEscalation(id, resolution, resolution_details) {
1508
+ const { body } = await this.post(
1509
+ `/v1/regulatory/escalations/${encodeURIComponent(id)}/resolve`,
1510
+ { resolution, resolution_details }
1511
+ );
1512
+ return body;
1513
+ }
1514
+ async overrideRegulatoryEscalation(id, reason) {
1515
+ const { body } = await this.post(
1516
+ `/v1/regulatory/escalations/${encodeURIComponent(id)}/override`,
1517
+ { reason }
1518
+ );
1519
+ return body;
1520
+ }
1521
+ // ── Incentive Signal Feedback Loop ────────────────────────────────────────
1522
+ async listSignalActions(signal_id) {
1523
+ const { body } = await this.get(
1524
+ `/v1/governance/signals/${encodeURIComponent(signal_id)}/actions`
1525
+ );
1526
+ return body.actions ?? [];
1527
+ }
1528
+ async recordSignalAction(signal_id, req) {
1529
+ const { body } = await this.post(
1530
+ `/v1/governance/signals/${encodeURIComponent(signal_id)}/actions`,
1531
+ req
1532
+ );
1533
+ return body;
1534
+ }
1535
+ async recordSignalOutcome(signal_id, action_id, req) {
1536
+ const { body } = await this.post(
1537
+ `/v1/governance/signals/${encodeURIComponent(signal_id)}/actions/${encodeURIComponent(action_id)}/outcome`,
1538
+ req
1539
+ );
1540
+ return body;
1541
+ }
1542
+ async getSignalActionSummary() {
1543
+ const { body } = await this.get(
1544
+ "/v1/governance/signals/actions/summary"
1545
+ );
1546
+ return body;
1547
+ }
1548
+ // ── Cross-Org Impersonation ───────────────────────────────────────────────
1549
+ async listImpersonationGrants() {
1550
+ const { body } = await this.get(
1551
+ "/v1/cross-org/impersonation/grants"
1552
+ );
1553
+ return body.grants ?? [];
1554
+ }
1555
+ async createImpersonationGrant(req) {
1556
+ const { body } = await this.post(
1557
+ "/v1/cross-org/impersonation/grants",
1558
+ req
1559
+ );
1560
+ return body;
1561
+ }
1562
+ async revokeImpersonationGrant(id) {
1563
+ await this.post(
1564
+ `/v1/cross-org/impersonation/grants/${encodeURIComponent(id)}/revoke`,
1565
+ {}
1566
+ );
1567
+ }
1568
+ async issueImpersonationToken(grant_id, requested_duration_seconds) {
1569
+ const { body } = await this.post(
1570
+ `/v1/cross-org/impersonation/grants/${encodeURIComponent(grant_id)}/token`,
1571
+ { requested_duration_seconds }
1572
+ );
1573
+ return body;
1574
+ }
1575
+ async validateImpersonationToken(token) {
1576
+ const { body } = await this.post(
1577
+ "/v1/cross-org/impersonation/validate",
1578
+ { token }
1579
+ );
1580
+ return body;
275
1581
  }
276
1582
  };
277
1583
  function parseRateLimitHeaders(headers) {
@@ -417,6 +1723,9 @@ function buildAuditEventsQuery(query) {
417
1723
  }
418
1724
  return params;
419
1725
  }
1726
+ function sleep(ms) {
1727
+ return new Promise((resolve) => setTimeout(resolve, ms));
1728
+ }
420
1729
  function parseRetryAfter(raw) {
421
1730
  if (!raw) return void 0;
422
1731
  const seconds = Number(raw);
@@ -428,6 +1737,125 @@ function parseRetryAfter(raw) {
428
1737
  }
429
1738
  return void 0;
430
1739
  }
1740
+ async function* parseSseStream(body, requestId, timeoutMs, onEventId) {
1741
+ const reader = body.getReader();
1742
+ const decoder = new TextDecoder("utf-8");
1743
+ let buf = "";
1744
+ async function readChunk() {
1745
+ if (timeoutMs <= 0) {
1746
+ return reader.read();
1747
+ }
1748
+ return new Promise((resolve, reject) => {
1749
+ const timer = setTimeout(() => {
1750
+ reject(new StreamTimeoutError(timeoutMs));
1751
+ }, timeoutMs);
1752
+ reader.read().then(
1753
+ (result) => {
1754
+ clearTimeout(timer);
1755
+ resolve(result);
1756
+ },
1757
+ (err) => {
1758
+ clearTimeout(timer);
1759
+ reject(err);
1760
+ }
1761
+ );
1762
+ });
1763
+ }
1764
+ try {
1765
+ for (; ; ) {
1766
+ let done;
1767
+ let value;
1768
+ try {
1769
+ const result = await readChunk();
1770
+ done = result.done;
1771
+ value = result.value;
1772
+ } catch (err) {
1773
+ if (err instanceof StreamTimeoutError) throw err;
1774
+ throw new AtlaSentError(
1775
+ `AtlaSent stream read failed: ${err instanceof Error ? err.message : String(err)}`,
1776
+ { code: "network", requestId, cause: err }
1777
+ );
1778
+ }
1779
+ if (done) break;
1780
+ buf += decoder.decode(value, { stream: true });
1781
+ let boundary;
1782
+ while ((boundary = buf.indexOf("\n\n")) !== -1) {
1783
+ const block = buf.slice(0, boundary);
1784
+ buf = buf.slice(boundary + 2);
1785
+ let eventType = "message";
1786
+ let data = "";
1787
+ let eventId;
1788
+ for (const line of block.split("\n")) {
1789
+ if (line.startsWith("event: ")) eventType = line.slice(7).trim();
1790
+ else if (line.startsWith("data: ")) data = line.slice(6);
1791
+ else if (line.startsWith("id: ")) eventId = line.slice(4).trim();
1792
+ else if (line.startsWith("id:")) eventId = line.slice(3).trim();
1793
+ }
1794
+ if (eventId !== void 0) onEventId(eventId);
1795
+ if (!data) continue;
1796
+ if (eventType === "done") return;
1797
+ let parsed;
1798
+ try {
1799
+ parsed = JSON.parse(data);
1800
+ } catch (err) {
1801
+ throw new StreamParseError(data, err);
1802
+ }
1803
+ if (eventType === "error") {
1804
+ const e = parsed;
1805
+ throw new AtlaSentError(
1806
+ e.message ?? "Stream error from AtlaSent API",
1807
+ {
1808
+ code: e.code ?? "server_error",
1809
+ requestId: e.request_id ?? requestId
1810
+ }
1811
+ );
1812
+ }
1813
+ if (eventType === "decision") {
1814
+ const d = parsed;
1815
+ if (typeof d.permitted !== "boolean" || typeof d.decision_id !== "string") {
1816
+ throw new AtlaSentError(
1817
+ "Malformed decision event from AtlaSent API",
1818
+ {
1819
+ code: "bad_response",
1820
+ requestId
1821
+ }
1822
+ );
1823
+ }
1824
+ const streamDecision = d.permitted ? "allow" : "deny";
1825
+ const isFinal = d.is_final ?? false;
1826
+ yield {
1827
+ type: "decision",
1828
+ decision: streamDecision,
1829
+ decision_canonical: streamDecision,
1830
+ permitId: d.decision_id,
1831
+ reason: d.reason ?? "",
1832
+ auditHash: d.audit_hash ?? "",
1833
+ timestamp: d.timestamp ?? "",
1834
+ isFinal
1835
+ };
1836
+ if (isFinal || d.done === true) return;
1837
+ } else if (eventType === "progress") {
1838
+ const p = parsed;
1839
+ yield {
1840
+ type: "progress",
1841
+ stage: String(p["stage"] ?? ""),
1842
+ ...p
1843
+ };
1844
+ if (p.done === true) return;
1845
+ } else {
1846
+ if (parsed !== null && typeof parsed === "object" && parsed.done === true) {
1847
+ return;
1848
+ }
1849
+ }
1850
+ }
1851
+ }
1852
+ if (buf.trim().length > 0) {
1853
+ throw new StreamParseError(buf);
1854
+ }
1855
+ } finally {
1856
+ reader.releaseLock();
1857
+ }
1858
+ }
431
1859
 
432
1860
  // src/auditBundle.ts
433
1861
  import { readFile } from "fs/promises";
@@ -584,9 +2012,13 @@ function configure(options) {
584
2012
  overrides = { ...overrides, ...options };
585
2013
  sharedClient = null;
586
2014
  }
2015
+ async function deployGate(request = {}) {
2016
+ return getClient().deployGate(request);
2017
+ }
587
2018
  function getClient() {
588
2019
  if (sharedClient) return sharedClient;
589
- const apiKey = overrides.apiKey ?? process.env.ATLASENT_API_KEY;
2020
+ const envApiKey = typeof process !== "undefined" && process.env ? process.env.ATLASENT_API_KEY : void 0;
2021
+ const apiKey = overrides.apiKey ?? envApiKey;
590
2022
  if (!apiKey) {
591
2023
  throw new AtlaSentError(
592
2024
  "AtlaSent is not configured. Set ATLASENT_API_KEY in the environment, or call atlasent.configure({ apiKey }).",
@@ -595,8 +2027,11 @@ function getClient() {
595
2027
  }
596
2028
  const options = { apiKey };
597
2029
  if (overrides.baseUrl !== void 0) options.baseUrl = overrides.baseUrl;
598
- if (overrides.timeoutMs !== void 0) options.timeoutMs = overrides.timeoutMs;
2030
+ if (overrides.timeoutMs !== void 0)
2031
+ options.timeoutMs = overrides.timeoutMs;
599
2032
  if (overrides.fetch !== void 0) options.fetch = overrides.fetch;
2033
+ if (overrides.retryPolicy !== void 0)
2034
+ options.retryPolicy = overrides.retryPolicy;
600
2035
  sharedClient = new AtlaSentClient(options);
601
2036
  return sharedClient;
602
2037
  }
@@ -605,10 +2040,42 @@ function wireDecisionToDenied(serverDecision) {
605
2040
  if (lower === "hold" || lower === "escalate") return lower;
606
2041
  return "deny";
607
2042
  }
2043
+ function sortKeysDeep(val) {
2044
+ if (Array.isArray(val)) return val.map(sortKeysDeep);
2045
+ if (val !== null && typeof val === "object") {
2046
+ return Object.keys(val).sort().reduce((acc, k) => {
2047
+ acc[k] = sortKeysDeep(val[k]);
2048
+ return acc;
2049
+ }, {});
2050
+ }
2051
+ return val;
2052
+ }
2053
+ async function computeExecutionHash(payload) {
2054
+ const sorted = sortKeysDeep(payload);
2055
+ const canonical = JSON.stringify(sorted);
2056
+ if (typeof globalThis !== "undefined" && globalThis.crypto?.subtle?.digest) {
2057
+ const bytes = new TextEncoder().encode(canonical);
2058
+ const buf = await globalThis.crypto.subtle.digest("SHA-256", bytes);
2059
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
2060
+ }
2061
+ try {
2062
+ const { createHash } = await import(
2063
+ /* @vite-ignore */
2064
+ /* webpackIgnore: true */
2065
+ "crypto"
2066
+ );
2067
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
2068
+ } catch {
2069
+ console.warn(
2070
+ "[atlasent] Could not compute execution_hash: neither crypto.subtle nor node:crypto is available in this runtime."
2071
+ );
2072
+ return "";
2073
+ }
2074
+ }
608
2075
  async function protect(request) {
609
2076
  const client = getClient();
610
2077
  const evaluation = await client.evaluate(request);
611
- if (evaluation.decision !== "ALLOW") {
2078
+ if (evaluation.decision !== "allow") {
612
2079
  throw new AtlaSentDeniedError({
613
2080
  decision: wireDecisionToDenied(evaluation.decision),
614
2081
  evaluationId: evaluation.permitId,
@@ -616,19 +2083,35 @@ async function protect(request) {
616
2083
  auditHash: evaluation.auditHash
617
2084
  });
618
2085
  }
2086
+ const environment = request.context?.environment ?? (() => {
2087
+ console.warn(
2088
+ "[atlasent] environment not set on evaluate request \u2014 defaulting to 'production'. Set context.environment explicitly to suppress."
2089
+ );
2090
+ return "production";
2091
+ })();
2092
+ const evaluatePayload = {
2093
+ action_type: request.action,
2094
+ actor_id: request.agent,
2095
+ context: request.context ?? {}
2096
+ };
2097
+ const execution_hash = await computeExecutionHash(evaluatePayload);
619
2098
  const verifyRequest = {
620
2099
  permitId: evaluation.permitId,
621
2100
  agent: request.agent,
622
- action: request.action
2101
+ action: request.action,
2102
+ environment,
2103
+ ...execution_hash ? { execution_hash } : {}
623
2104
  };
624
2105
  if (request.context !== void 0) verifyRequest.context = request.context;
625
2106
  const verification = await client.verifyPermit(verifyRequest);
626
2107
  if (!verification.verified) {
2108
+ const outcome = normalizePermitOutcome(verification.outcome);
627
2109
  throw new AtlaSentDeniedError({
628
2110
  decision: "deny",
629
2111
  evaluationId: evaluation.permitId,
630
2112
  reason: `Permit failed verification (${verification.outcome})`,
631
- auditHash: evaluation.auditHash
2113
+ auditHash: evaluation.auditHash,
2114
+ ...outcome !== void 0 && { outcome }
632
2115
  });
633
2116
  }
634
2117
  return {
@@ -640,64 +2123,1318 @@ async function protect(request) {
640
2123
  };
641
2124
  }
642
2125
 
643
- // src/retry.ts
644
- var DEFAULT_RETRY_POLICY = {
645
- maxAttempts: 3,
646
- baseDelayMs: 250,
647
- maxDelayMs: 7e3
648
- };
649
- var RETRYABLE_CODES = /* @__PURE__ */ new Set([
650
- "network",
651
- "timeout",
652
- "rate_limited",
653
- "server_error",
654
- "bad_response"
655
- ]);
656
- function isRetryable(err) {
657
- if (!(err instanceof AtlaSentError)) return false;
658
- if (err.code === void 0) return false;
659
- return RETRYABLE_CODES.has(err.code);
2126
+ // src/requirePermit.ts
2127
+ async function requirePermit(action, execute) {
2128
+ await protect({
2129
+ agent: action.actor_id,
2130
+ action: action.action_type,
2131
+ context: {
2132
+ resource_id: action.resource_id,
2133
+ environment: action.environment,
2134
+ ...action.context
2135
+ }
2136
+ });
2137
+ return execute();
660
2138
  }
661
- function computeBackoffMs(attempt, policy = {}, err, random = Math.random) {
662
- const merged = mergePolicy(policy);
663
- const safeAttempt = Math.max(0, Math.floor(attempt));
664
- const exp = Math.min(safeAttempt, 30);
665
- const ceiling = Math.min(merged.maxDelayMs, merged.baseDelayMs * 2 ** exp);
666
- const jittered = Math.floor(ceiling * clampUnit(random()));
667
- const retryAfterMs = err instanceof AtlaSentError && typeof err.retryAfterMs === "number" ? Math.max(0, err.retryAfterMs) : 0;
668
- return Math.max(retryAfterMs, jittered);
2139
+ var DESTRUCTIVE_PATTERNS = [
2140
+ /rm\s+-rf/,
2141
+ /DROP\s+TABLE/i,
2142
+ /DROP\s+DATABASE/i,
2143
+ /DELETE\s+FROM/i,
2144
+ /TRUNCATE\s+TABLE/i,
2145
+ /railway\s+volume\s+delete/i,
2146
+ /kubectl\s+delete/i,
2147
+ /terraform\s+destroy/i
2148
+ ];
2149
+ function classifyCommand(command) {
2150
+ return DESTRUCTIVE_PATTERNS.some((p) => p.test(command)) ? "destructive.command" : null;
669
2151
  }
670
- function hasAttemptsLeft(attempt, policy = {}) {
671
- const merged = mergePolicy(policy);
672
- return attempt + 1 < merged.maxAttempts;
2152
+
2153
+ // src/withPermit.ts
2154
+ async function withPermit(request, fn) {
2155
+ const permit = await protect(request);
2156
+ return await fn(permit);
673
2157
  }
674
- function mergePolicy(policy) {
675
- const maxAttempts = Math.max(
676
- 1,
677
- Math.floor(policy.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts)
678
- );
679
- const baseDelayMs = Math.max(
680
- 0,
681
- policy.baseDelayMs ?? DEFAULT_RETRY_POLICY.baseDelayMs
682
- );
683
- const maxDelayMs = Math.max(
684
- baseDelayMs,
685
- policy.maxDelayMs ?? DEFAULT_RETRY_POLICY.maxDelayMs
686
- );
687
- return { maxAttempts, baseDelayMs, maxDelayMs };
2158
+
2159
+ // src/hitl.ts
2160
+ function hitlRequiredApproverCount(quorum, poolSize) {
2161
+ const n = Number.isFinite(poolSize) && poolSize >= 1 ? Math.floor(poolSize) : 1;
2162
+ switch (quorum) {
2163
+ case "single_approver":
2164
+ return 1;
2165
+ case "simple_majority":
2166
+ return Math.floor(n / 2) + 1;
2167
+ case "two_thirds":
2168
+ return Math.ceil(2 * n / 3);
2169
+ case "unanimous":
2170
+ return n;
2171
+ }
688
2172
  }
689
- function clampUnit(n) {
690
- if (!Number.isFinite(n)) return 0;
691
- if (n < 0) return 0;
692
- if (n >= 1) return 0.999999999;
693
- return n;
2173
+
2174
+ // src/sandboxDiff.ts
2175
+ function isSandboxDiffPopulated(r) {
2176
+ return r.total_writes > 0 || r.org_id !== void 0;
2177
+ }
2178
+
2179
+ // src/delegationPropagation.ts
2180
+ function delegationPropagationHadEffect(s) {
2181
+ return s.hitl_reassigned > 0 || s.financial_invalidated > 0 || s.policies_flagged > 0;
2182
+ }
2183
+
2184
+ // src/financialAction.ts
2185
+ var DEFAULT_RISK_TIER_THRESHOLDS = [
2186
+ { tier: "low", lower_bound: 0, upper_bound: 1e3, reference_currency: "USD" },
2187
+ { tier: "medium", lower_bound: 1e3, upper_bound: 5e4, reference_currency: "USD" },
2188
+ { tier: "high", lower_bound: 5e4, upper_bound: 1e6, reference_currency: "USD" },
2189
+ { tier: "critical", lower_bound: 1e6, upper_bound: null, reference_currency: "USD" }
2190
+ ];
2191
+ function classifyRiskTier(value, thresholds = DEFAULT_RISK_TIER_THRESHOLDS) {
2192
+ for (const t of thresholds) {
2193
+ if (value >= t.lower_bound && (t.upper_bound === null || value < t.upper_bound)) {
2194
+ return t.tier;
2195
+ }
2196
+ }
2197
+ return "critical";
2198
+ }
2199
+ function withinAutonomousCeiling(actionValue, ceiling) {
2200
+ if (ceiling === null) return true;
2201
+ return actionValue <= ceiling;
2202
+ }
2203
+
2204
+ // src/liabilityAttribution.ts
2205
+ var ROLE_WEIGHTS = {
2206
+ authorizer: 0.3,
2207
+ delegator: 0.15,
2208
+ delegate: 0.15,
2209
+ executor: 0.25,
2210
+ approver: 0.05,
2211
+ override_actor: 0.4,
2212
+ supervisor: 0.1,
2213
+ exception_approver: 0.05
2214
+ };
2215
+ function computeLiabilityWeights(parties, distribution = "role_weighted") {
2216
+ if (parties.length === 0) return [];
2217
+ let raw;
2218
+ if (distribution === "equal") {
2219
+ raw = parties.map(() => 1);
2220
+ } else {
2221
+ raw = parties.map((p) => ROLE_WEIGHTS[p.role] ?? 0.05);
2222
+ }
2223
+ const total = raw.reduce((s, w) => s + w, 0);
2224
+ if (total <= 0) return parties.map(() => 1 / parties.length);
2225
+ return raw.map((w) => w / total);
2226
+ }
2227
+ function buildLiabilityChain(input, distribution = "role_weighted") {
2228
+ const raw = [];
2229
+ raw.push({ ...input.authorizer, role: "authorizer" });
2230
+ for (const d of input.delegations ?? []) {
2231
+ raw.push({
2232
+ party_id: d.delegator_id,
2233
+ party_label: d.delegator_label,
2234
+ party_type: d.delegator_type,
2235
+ role: "delegator",
2236
+ acted_at: d.acted_at,
2237
+ permit_id: d.permit_id
2238
+ });
2239
+ raw.push({
2240
+ party_id: d.delegate_id,
2241
+ party_label: d.delegate_label,
2242
+ party_type: d.delegate_type,
2243
+ role: "delegate",
2244
+ acted_at: d.acted_at,
2245
+ permit_id: d.permit_id
2246
+ });
2247
+ }
2248
+ for (const a of input.approvers) {
2249
+ raw.push({ ...a, role: "approver" });
2250
+ }
2251
+ for (const s of input.supervisors ?? []) {
2252
+ raw.push({ ...s, role: "supervisor" });
2253
+ }
2254
+ raw.push({ ...input.executor, role: "executor" });
2255
+ if (input.override) {
2256
+ raw.push({
2257
+ party_id: input.override.actor_id,
2258
+ party_label: input.override.actor_label,
2259
+ party_type: input.override.actor_type,
2260
+ role: "override_actor",
2261
+ acted_at: input.override.acted_at,
2262
+ permit_id: input.override.permit_id
2263
+ });
2264
+ }
2265
+ const weights = computeLiabilityWeights(raw, distribution);
2266
+ return raw.map((p, i) => ({ ...p, liability_weight: weights[i] ?? 0 }));
2267
+ }
2268
+ function findPrimaryLiabilityParties(chain, threshold = 0.2) {
2269
+ return chain.filter((p) => p.liability_weight >= threshold);
2270
+ }
2271
+ function validateLiabilityChain(chain, hasEmergencyOverride) {
2272
+ const errors = [];
2273
+ if (chain.length === 0) {
2274
+ errors.push("liability chain must have at least one party");
2275
+ }
2276
+ const weightSum = chain.reduce((s, p) => s + p.liability_weight, 0);
2277
+ if (Math.abs(weightSum - 1) > 0.01) {
2278
+ errors.push(`liability weights sum to ${weightSum.toFixed(4)}, expected 1.0`);
2279
+ }
2280
+ const seen = /* @__PURE__ */ new Set();
2281
+ for (const p of chain) {
2282
+ const key = `${p.party_id}:${p.role}`;
2283
+ if (seen.has(key)) errors.push(`duplicate party+role: ${key}`);
2284
+ seen.add(key);
2285
+ }
2286
+ if (hasEmergencyOverride && !chain.some((p) => p.role === "override_actor")) {
2287
+ errors.push("emergency_override is true but no override_actor in chain");
2288
+ }
2289
+ return { valid: errors.length === 0, errors };
2290
+ }
2291
+
2292
+ // src/economicRisk.ts
2293
+ var SCORE_WEIGHTS = {
2294
+ exposure: 0.25,
2295
+ concentration: 0.25,
2296
+ override: 0.2,
2297
+ drift: 0.15,
2298
+ anomaly: 0.15
2299
+ };
2300
+ function computeOverallRiskScore(subScores) {
2301
+ return Math.min(
2302
+ 100,
2303
+ Math.max(
2304
+ 0,
2305
+ subScores.exposure * SCORE_WEIGHTS.exposure + subScores.concentration * SCORE_WEIGHTS.concentration + subScores.override * SCORE_WEIGHTS.override + subScores.drift * SCORE_WEIGHTS.drift + subScores.anomaly * SCORE_WEIGHTS.anomaly
2306
+ )
2307
+ );
2308
+ }
2309
+ function scoreToRiskTier(score) {
2310
+ if (score <= 25) return "low";
2311
+ if (score <= 55) return "medium";
2312
+ if (score <= 80) return "high";
2313
+ return "critical";
2314
+ }
2315
+ function computeHHI(shares) {
2316
+ return shares.reduce((acc, s) => acc + s * s, 0);
2317
+ }
2318
+ function hhiToConcentrationScore(hhi) {
2319
+ return Math.min(100, hhi / 1e4 * 100);
2320
+ }
2321
+ function computeExposureScore(records, exposureCeilingUSD = 1e7) {
2322
+ const activeStatuses = /* @__PURE__ */ new Set(
2323
+ ["pending_approval", "approved", "executing"]
2324
+ );
2325
+ const totalExposure = records.filter((r) => activeStatuses.has(r.status)).reduce((acc, r) => acc + r.action_value, 0);
2326
+ return Math.min(100, totalExposure / exposureCeilingUSD * 100);
2327
+ }
2328
+ function computeOverrideScore(totalExecutions, overriddenExecutions) {
2329
+ if (totalExecutions === 0) return 0;
2330
+ const rate = overriddenExecutions / totalExecutions;
2331
+ return Math.min(100, rate * 1e3);
2332
+ }
2333
+ function detectSelfApproval(initiatorId, approverIds) {
2334
+ return approverIds.includes(initiatorId);
2335
+ }
2336
+ function computeApprovalRiskScore(analysis) {
2337
+ return hhiToConcentrationScore(analysis.concentration_hhi);
2338
+ }
2339
+
2340
+ // src/financialQuorum.ts
2341
+ function evaluateFinancialQuorum(input) {
2342
+ const unmet = [];
2343
+ const activeFreeze = input.active_freezes.find((f) => !f.lifted);
2344
+ if (activeFreeze) {
2345
+ return {
2346
+ passed: false,
2347
+ base_quorum_passed: false,
2348
+ amount_threshold_satisfied: false,
2349
+ financial_roles_satisfied: false,
2350
+ regulator_approval_missing: false,
2351
+ blocked_by_freeze: true,
2352
+ base_quorum_proof: null,
2353
+ denial_reason: `action blocked by emergency freeze (${activeFreeze.freeze_id}): ${activeFreeze.reason}`,
2354
+ unmet_requirements: [`emergency_freeze:${activeFreeze.freeze_id}`]
2355
+ };
2356
+ }
2357
+ const baseQuorumPassed = input.base_quorum_proof !== null || input.approval_count >= input.policy.required_count;
2358
+ if (!baseQuorumPassed) {
2359
+ unmet.push(
2360
+ `base quorum requires ${input.policy.required_count} approvals, have ${input.approval_count}`
2361
+ );
2362
+ }
2363
+ let amountThresholdSatisfied = true;
2364
+ for (const threshold of input.policy.amount_thresholds) {
2365
+ if (input.action_value >= threshold.value) {
2366
+ const needed = input.policy.required_count + threshold.additional_approvals;
2367
+ if (input.approval_count < needed) {
2368
+ amountThresholdSatisfied = false;
2369
+ unmet.push(
2370
+ `amount threshold ${threshold.value} ${threshold.currency} requires ${needed} approvals`
2371
+ );
2372
+ }
2373
+ for (const req of threshold.additional_roles) {
2374
+ const present = input.present_roles[req.role] ?? 0;
2375
+ if (present < req.min) {
2376
+ amountThresholdSatisfied = false;
2377
+ unmet.push(`amount threshold requires ${req.min} ${req.role} approver(s), have ${present}`);
2378
+ }
2379
+ }
2380
+ if (threshold.senior_review_required && !(input.present_roles["senior_finance"] ?? 0)) {
2381
+ amountThresholdSatisfied = false;
2382
+ unmet.push("amount threshold requires senior_finance review");
2383
+ }
2384
+ }
2385
+ }
2386
+ let financialRolesSatisfied = true;
2387
+ for (const req of input.policy.financial_role_requirements) {
2388
+ if (req.applies_to_tiers && !req.applies_to_tiers.includes(input.risk_tier)) continue;
2389
+ if (req.applies_above !== void 0 && input.action_value < req.applies_above) continue;
2390
+ const present = input.present_roles[req.role] ?? 0;
2391
+ if (present < req.min) {
2392
+ financialRolesSatisfied = false;
2393
+ unmet.push(`financial role ${req.role} requires ${req.min} approver(s), have ${present}`);
2394
+ }
2395
+ }
2396
+ const regulatorMissing = input.policy.regulator_approval_threshold !== null && input.action_value >= input.policy.regulator_approval_threshold && !input.regulator_approval_present;
2397
+ if (regulatorMissing) {
2398
+ unmet.push("regulator approval required for this action value");
2399
+ }
2400
+ const passed = baseQuorumPassed && amountThresholdSatisfied && financialRolesSatisfied && !regulatorMissing;
2401
+ return {
2402
+ passed,
2403
+ base_quorum_passed: baseQuorumPassed,
2404
+ amount_threshold_satisfied: amountThresholdSatisfied,
2405
+ financial_roles_satisfied: financialRolesSatisfied,
2406
+ regulator_approval_missing: regulatorMissing,
2407
+ blocked_by_freeze: false,
2408
+ base_quorum_proof: input.base_quorum_proof,
2409
+ denial_reason: passed ? null : unmet[0] ?? "financial quorum not satisfied",
2410
+ unmet_requirements: unmet
2411
+ };
2412
+ }
2413
+ function computeEscalatedApprovalCount(baseCount, actionValue, thresholds) {
2414
+ let additional = 0;
2415
+ for (const t of thresholds) {
2416
+ if (actionValue >= t.value) {
2417
+ additional = Math.max(additional, t.additional_approvals);
2418
+ }
2419
+ }
2420
+ return baseCount + additional;
2421
+ }
2422
+
2423
+ // src/budgetaryGovernance.ts
2424
+ function checkBudgetConstraints(params) {
2425
+ const hardBlocks = [];
2426
+ const softWarnings = [];
2427
+ const limitsChecked = [];
2428
+ const constraintsChecked = [];
2429
+ const nowIso = (params.now ?? /* @__PURE__ */ new Date()).toISOString();
2430
+ for (const limit of params.applicableLimits) {
2431
+ limitsChecked.push(limit.limit_id);
2432
+ if (limit.period_end && nowIso > limit.period_end) {
2433
+ const v = {
2434
+ violation_type: "period_expired",
2435
+ limit_id: limit.limit_id,
2436
+ description: `Budget limit ${limit.limit_id} period expired at ${limit.period_end}`
2437
+ };
2438
+ if (limit.enforcement === "hard") hardBlocks.push(v);
2439
+ else softWarnings.push(v);
2440
+ continue;
2441
+ }
2442
+ const projected = limit.spending.spent_amount + params.actionValue;
2443
+ if (projected > limit.limit_amount) {
2444
+ const v = {
2445
+ violation_type: "limit_exceeded",
2446
+ limit_id: limit.limit_id,
2447
+ description: `Action would exceed ${limit.scope_type} limit (${limit.limit_amount} ${limit.currency})`,
2448
+ overage_amount: projected - limit.limit_amount
2449
+ };
2450
+ if (limit.enforcement === "hard") hardBlocks.push(v);
2451
+ else softWarnings.push(v);
2452
+ }
2453
+ }
2454
+ for (const constraint of params.applicableConstraints) {
2455
+ constraintsChecked.push(constraint.constraint_id);
2456
+ if (constraint.action_type !== "*" && constraint.action_type !== params.actionType) continue;
2457
+ if (!constraint.allow_anonymous_agents && params.isAnonymousAgent) {
2458
+ hardBlocks.push({
2459
+ violation_type: "anonymous_agent_blocked",
2460
+ constraint_id: constraint.constraint_id,
2461
+ description: `Anonymous agents are not permitted to execute ${params.actionType}`
2462
+ });
2463
+ }
2464
+ if (params.actionValue > constraint.max_single_transaction) {
2465
+ hardBlocks.push({
2466
+ violation_type: "single_transaction_exceeds",
2467
+ constraint_id: constraint.constraint_id,
2468
+ description: `Value ${params.actionValue} exceeds single-transaction limit ${constraint.max_single_transaction} ${constraint.currency}`,
2469
+ overage_amount: params.actionValue - constraint.max_single_transaction
2470
+ });
2471
+ }
2472
+ if (constraint.max_daily_aggregate !== null && params.currentDailySpend + params.actionValue > constraint.max_daily_aggregate) {
2473
+ hardBlocks.push({
2474
+ violation_type: "daily_aggregate_exceeds",
2475
+ constraint_id: constraint.constraint_id,
2476
+ description: `Action would exceed daily aggregate limit ${constraint.max_daily_aggregate} ${constraint.currency}`,
2477
+ overage_amount: params.currentDailySpend + params.actionValue - constraint.max_daily_aggregate
2478
+ });
2479
+ }
2480
+ if (constraint.max_monthly_aggregate !== null && params.currentMonthlySpend + params.actionValue > constraint.max_monthly_aggregate) {
2481
+ hardBlocks.push({
2482
+ violation_type: "monthly_aggregate_exceeds",
2483
+ constraint_id: constraint.constraint_id,
2484
+ description: `Action would exceed monthly aggregate limit ${constraint.max_monthly_aggregate} ${constraint.currency}`,
2485
+ overage_amount: params.currentMonthlySpend + params.actionValue - constraint.max_monthly_aggregate
2486
+ });
2487
+ }
2488
+ }
2489
+ return {
2490
+ permitted: hardBlocks.length === 0,
2491
+ hard_blocks: hardBlocks,
2492
+ soft_warnings: softWarnings,
2493
+ limits_checked: limitsChecked,
2494
+ constraints_checked: constraintsChecked
2495
+ };
2496
+ }
2497
+ function budgetUtilizationSeverity(utilizationPct) {
2498
+ if (utilizationPct >= 100) return "critical";
2499
+ if (utilizationPct >= 80) return "warn";
2500
+ return "normal";
2501
+ }
2502
+
2503
+ // src/autonomousFinancial.ts
2504
+ var RISK_TIER_ORDER = {
2505
+ low: 1,
2506
+ medium: 2,
2507
+ high: 3,
2508
+ critical: 4
2509
+ };
2510
+ function checkAutonomousBounds(params) {
2511
+ const violations = [];
2512
+ const nowIso = (params.now ?? /* @__PURE__ */ new Date()).toISOString();
2513
+ const boundsActive = params.bounds.active;
2514
+ if (!boundsActive) violations.push("agent execution bounds are inactive");
2515
+ const boundsNotExpired = params.bounds.expires_at === null || params.bounds.expires_at > nowIso;
2516
+ if (!boundsNotExpired) {
2517
+ violations.push(`agent bounds expired at ${params.bounds.expires_at}`);
2518
+ }
2519
+ const actionTypePermitted = params.bounds.permitted_action_types.includes(
2520
+ params.actionType
2521
+ );
2522
+ if (!actionTypePermitted) {
2523
+ violations.push(`action type ${params.actionType} not in agent's permitted set`);
2524
+ }
2525
+ const applicableCeiling = params.bounds.ceilings.find((c) => c.action_type === params.actionType) ?? null;
2526
+ let withinExecutionCeiling = true;
2527
+ if (applicableCeiling !== null) {
2528
+ if (params.actionValue > applicableCeiling.per_execution_max) {
2529
+ withinExecutionCeiling = false;
2530
+ violations.push(
2531
+ `value ${params.actionValue} exceeds per-execution ceiling ${applicableCeiling.per_execution_max} ${applicableCeiling.currency}`
2532
+ );
2533
+ }
2534
+ if (applicableCeiling.max_daily_count !== null) {
2535
+ const todayCount = params.currentDailyCount[params.actionType] ?? 0;
2536
+ if (todayCount >= applicableCeiling.max_daily_count) {
2537
+ withinExecutionCeiling = false;
2538
+ violations.push(
2539
+ `daily count ${todayCount} at or exceeds limit ${applicableCeiling.max_daily_count} for ${params.actionType}`
2540
+ );
2541
+ }
2542
+ }
2543
+ }
2544
+ const withinDailyAggregate = params.currentDailyAggregate + params.actionValue <= params.bounds.daily_aggregate_ceiling;
2545
+ if (!withinDailyAggregate) {
2546
+ violations.push(
2547
+ `daily aggregate ${params.currentDailyAggregate + params.actionValue} would exceed ceiling ${params.bounds.daily_aggregate_ceiling} ${params.bounds.aggregate_currency}`
2548
+ );
2549
+ }
2550
+ const withinRiskTier = RISK_TIER_ORDER[params.riskTier] <= RISK_TIER_ORDER[params.bounds.max_risk_tier];
2551
+ if (!withinRiskTier) {
2552
+ violations.push(
2553
+ `action risk tier ${params.riskTier} exceeds agent max ${params.bounds.max_risk_tier}`
2554
+ );
2555
+ }
2556
+ const permitted = boundsActive && boundsNotExpired && actionTypePermitted && withinExecutionCeiling && withinDailyAggregate && withinRiskTier;
2557
+ return {
2558
+ permitted,
2559
+ action_type_permitted: actionTypePermitted,
2560
+ within_execution_ceiling: withinExecutionCeiling,
2561
+ within_daily_aggregate: withinDailyAggregate,
2562
+ within_risk_tier: withinRiskTier,
2563
+ bounds_active: boundsActive,
2564
+ bounds_not_expired: boundsNotExpired,
2565
+ applicable_ceiling: applicableCeiling,
2566
+ denial_reason: permitted ? null : violations[0] ?? "execution out of bounds",
2567
+ violations
2568
+ };
2569
+ }
2570
+ function detectAutonomousAnomaly(params) {
2571
+ const zScore = params.historicalStdDev > 0 ? Math.abs(params.actionValue - params.historicalMeanValue) / params.historicalStdDev : 0;
2572
+ if (zScore > 3) {
2573
+ return {
2574
+ anomalyDetected: true,
2575
+ description: `action value ${params.actionValue} is ${zScore.toFixed(1)}\u03C3 from mean (${params.historicalMeanValue})`
2576
+ };
2577
+ }
2578
+ if (params.recentExecutionCount > params.burstThreshold) {
2579
+ return {
2580
+ anomalyDetected: true,
2581
+ description: `execution burst: ${params.recentExecutionCount} in window (threshold: ${params.burstThreshold})`
2582
+ };
2583
+ }
2584
+ if (params.isOffHours && params.actionValue > params.historicalMeanValue * 2) {
2585
+ return {
2586
+ anomalyDetected: true,
2587
+ description: `off-hours execution with above-average value ${params.actionValue}`
2588
+ };
2589
+ }
2590
+ return { anomalyDetected: false, description: null };
2591
+ }
2592
+
2593
+ // src/incentiveAlignment.ts
2594
+ var DEFAULT_INCENTIVE_CONFIG = {
2595
+ max_override_rate: 0.05,
2596
+ min_approval_latency_seconds: 30,
2597
+ max_emergency_bypasses_30d: 3,
2598
+ max_concentration_share: 0.4,
2599
+ max_delegation_depth: 3
2600
+ };
2601
+ function detectMisalignedIncentives(params) {
2602
+ const config = params.config ?? DEFAULT_INCENTIVE_CONFIG;
2603
+ const signals = [];
2604
+ const now = (params.now ?? /* @__PURE__ */ new Date()).toISOString();
2605
+ let signalIdx = 0;
2606
+ const makeId = () => `signal_${params.partyId}_${signalIdx++}`;
2607
+ const overrideRate = params.totalActions > 0 ? params.overrideCount / params.totalActions : 0;
2608
+ if (overrideRate > config.max_override_rate) {
2609
+ signals.push({
2610
+ signal_id: makeId(),
2611
+ signal_type: "excessive_overrides",
2612
+ party_id: params.partyId,
2613
+ party_label: params.partyLabel,
2614
+ severity: Math.min(100, overrideRate / config.max_override_rate * 50),
2615
+ description: `Override rate ${(overrideRate * 100).toFixed(1)}% exceeds threshold ${(config.max_override_rate * 100).toFixed(1)}%`,
2616
+ evidence: [`override_count:${params.overrideCount}`, `total_actions:${params.totalActions}`],
2617
+ detected_at: now,
2618
+ reviewed: false,
2619
+ reviewed_by: null
2620
+ });
2621
+ }
2622
+ if (params.emergencyBypassCount > config.max_emergency_bypasses_30d) {
2623
+ signals.push({
2624
+ signal_id: makeId(),
2625
+ signal_type: "emergency_bypass_repeat",
2626
+ party_id: params.partyId,
2627
+ party_label: params.partyLabel,
2628
+ severity: Math.min(100, params.emergencyBypassCount / config.max_emergency_bypasses_30d * 60),
2629
+ description: `${params.emergencyBypassCount} emergency bypasses in ${params.windowDays}d (threshold: ${config.max_emergency_bypasses_30d})`,
2630
+ evidence: [`bypass_count:${params.emergencyBypassCount}`],
2631
+ detected_at: now,
2632
+ reviewed: false,
2633
+ reviewed_by: null
2634
+ });
2635
+ }
2636
+ const rushCount = params.approvalLatencies.filter((l) => l < config.min_approval_latency_seconds).length;
2637
+ if (rushCount > 0 && params.approvalLatencies.length > 0) {
2638
+ const minLatency = Math.min(...params.approvalLatencies);
2639
+ const rushRate = rushCount / params.approvalLatencies.length;
2640
+ signals.push({
2641
+ signal_id: makeId(),
2642
+ signal_type: "rushed_approval",
2643
+ party_id: params.partyId,
2644
+ party_label: params.partyLabel,
2645
+ severity: Math.min(100, rushRate * 80),
2646
+ description: `${rushCount} approvals in under ${config.min_approval_latency_seconds}s (min observed: ${minLatency.toFixed(0)}s)`,
2647
+ evidence: [`rushed_count:${rushCount}`, `total_approvals:${params.approvalLatencies.length}`],
2648
+ detected_at: now,
2649
+ reviewed: false,
2650
+ reviewed_by: null
2651
+ });
2652
+ }
2653
+ if (params.approvalShare > config.max_concentration_share) {
2654
+ signals.push({
2655
+ signal_id: makeId(),
2656
+ signal_type: "authority_concentration",
2657
+ party_id: params.partyId,
2658
+ party_label: params.partyLabel,
2659
+ severity: Math.min(100, params.approvalShare / config.max_concentration_share * 50),
2660
+ description: `Party controls ${(params.approvalShare * 100).toFixed(1)}% of approvals (threshold: ${(config.max_concentration_share * 100).toFixed(1)}%)`,
2661
+ evidence: [`approval_share:${params.approvalShare.toFixed(3)}`],
2662
+ detected_at: now,
2663
+ reviewed: false,
2664
+ reviewed_by: null
2665
+ });
2666
+ }
2667
+ if (params.delegationDepthMax > config.max_delegation_depth) {
2668
+ signals.push({
2669
+ signal_id: makeId(),
2670
+ signal_type: "delegation_chain_depth",
2671
+ party_id: params.partyId,
2672
+ party_label: params.partyLabel,
2673
+ severity: Math.min(100, (params.delegationDepthMax - config.max_delegation_depth) / config.max_delegation_depth * 60),
2674
+ description: `Delegation depth ${params.delegationDepthMax} exceeds threshold ${config.max_delegation_depth}`,
2675
+ evidence: [`depth:${params.delegationDepthMax}`],
2676
+ detected_at: now,
2677
+ reviewed: false,
2678
+ reviewed_by: null
2679
+ });
2680
+ }
2681
+ return signals.sort((a, b) => b.severity - a.severity);
2682
+ }
2683
+ function computeGovernanceHealthScore(signals) {
2684
+ if (signals.length === 0) return 100;
2685
+ const totalPenalty = signals.reduce((acc, s) => acc + s.severity * 0.5, 0);
2686
+ return Math.max(0, 100 - totalPenalty);
2687
+ }
2688
+
2689
+ // src/economicEvidence.ts
2690
+ function canonicalizeForEvidence(value) {
2691
+ if (value === null || value === void 0) return "null";
2692
+ if (typeof value === "number") return Number.isFinite(value) ? String(value) : "null";
2693
+ if (typeof value === "boolean") return value ? "true" : "false";
2694
+ if (typeof value === "string") return JSON.stringify(value);
2695
+ if (Array.isArray(value)) return "[" + value.map(canonicalizeForEvidence).join(",") + "]";
2696
+ if (typeof value === "object") {
2697
+ const obj = value;
2698
+ const keys = Object.keys(obj).sort();
2699
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalizeForEvidence(obj[k])).join(",") + "}";
2700
+ }
2701
+ return "null";
2702
+ }
2703
+ function buildSignableContent(bundle) {
2704
+ return {
2705
+ bundle_id: bundle.bundle_id,
2706
+ org_id: bundle.org_id,
2707
+ purpose: bundle.purpose,
2708
+ execution_id: bundle.execution_record.execution_id,
2709
+ attribution_id: bundle.liability_attribution.attribution_id,
2710
+ liability_chain_hash: bundle.liability_attribution.chain_hash,
2711
+ approval_count: bundle.approval_provenance.length,
2712
+ permit_ids: bundle.approval_provenance.map((a) => a.permit_id),
2713
+ policy_compliant: bundle.policy_compliant,
2714
+ generated_at: bundle.generated_at
2715
+ };
2716
+ }
2717
+ function serializeSignableContent(content) {
2718
+ return new TextEncoder().encode(canonicalizeForEvidence(content));
2719
+ }
2720
+ function verifyEvidenceBundleStructure(bundle) {
2721
+ const errors = [];
2722
+ const bundlePermitIds = new Set(bundle.execution_record.permit_ids);
2723
+ const provenancePermitIds = bundle.approval_provenance.map((a) => a.permit_id);
2724
+ const permitIdsMatch = provenancePermitIds.every((id) => bundlePermitIds.has(id));
2725
+ if (!permitIdsMatch) {
2726
+ errors.push("permit IDs in approval provenance do not all appear in execution record");
2727
+ }
2728
+ const contentHashValid = typeof bundle.content_hash === "string" && bundle.content_hash.length === 64;
2729
+ if (!contentHashValid) errors.push("content_hash appears invalid (expected 64-char hex)");
2730
+ const liabilityChainHashMatches = typeof bundle.liability_attribution.chain_hash === "string" && bundle.liability_attribution.chain_hash.length > 0;
2731
+ if (!liabilityChainHashMatches) errors.push("liability_attribution.chain_hash is missing or empty");
2732
+ const signatureValid = bundle.signature !== null && bundle.signature.length > 0;
2733
+ return {
2734
+ valid: errors.length === 0 && contentHashValid,
2735
+ content_hash_valid: contentHashValid,
2736
+ signature_valid: signatureValid,
2737
+ liability_chain_hash_matches: liabilityChainHashMatches,
2738
+ permit_ids_match: permitIdsMatch,
2739
+ reason: errors.length === 0 ? null : errors[0] ?? "bundle integrity check failed"
2740
+ };
2741
+ }
2742
+
2743
+ // src/disputeReversal.ts
2744
+ var VALID_DISPUTE_TRANSITIONS = {
2745
+ open: ["under_review", "withdrawn"],
2746
+ under_review: ["escalated", "resolved_in_favor", "resolved_against", "reversed"],
2747
+ escalated: ["resolved_in_favor", "resolved_against", "reversed"],
2748
+ resolved_in_favor: [],
2749
+ resolved_against: [],
2750
+ reversed: [],
2751
+ withdrawn: []
2752
+ };
2753
+ function transitionDispute(current, next) {
2754
+ const allowed = VALID_DISPUTE_TRANSITIONS[current];
2755
+ if (!allowed.includes(next)) {
2756
+ return { success: false, new_status: null, error: `invalid dispute transition: ${current} \u2192 ${next}` };
2757
+ }
2758
+ return { success: true, new_status: next, error: null };
2759
+ }
2760
+ var VALID_REVERSAL_TRANSITIONS = {
2761
+ initiated: ["authorization_pending", "cancelled"],
2762
+ authorization_pending: ["authorized", "cancelled"],
2763
+ authorized: ["executing", "cancelled"],
2764
+ executing: ["completed", "failed"],
2765
+ completed: [],
2766
+ failed: ["initiated"],
2767
+ // Allow retry
2768
+ cancelled: []
2769
+ };
2770
+ function transitionReversal(current, next) {
2771
+ const allowed = VALID_REVERSAL_TRANSITIONS[current];
2772
+ if (!allowed.includes(next)) {
2773
+ return { success: false, error: `invalid reversal transition: ${current} \u2192 ${next}` };
2774
+ }
2775
+ return { success: true, error: null };
2776
+ }
2777
+ function isFreezeActive(freeze, now) {
2778
+ if (freeze.lifted) return false;
2779
+ if (freeze.expires_at !== null) {
2780
+ const nowIso = (now ?? /* @__PURE__ */ new Date()).toISOString();
2781
+ if (nowIso >= freeze.expires_at) return false;
2782
+ }
2783
+ return true;
2784
+ }
2785
+ function computeRemediationUrgency(_openedAt, deadline, now) {
2786
+ if (deadline === null) return "normal";
2787
+ const nowMs = (now ?? /* @__PURE__ */ new Date()).getTime();
2788
+ const deadlineMs = new Date(deadline).getTime();
2789
+ const remaining = deadlineMs - nowMs;
2790
+ if (remaining < 0) return "overdue";
2791
+ if (remaining < 24 * 60 * 60 * 1e3) return "urgent";
2792
+ return "normal";
2793
+ }
2794
+
2795
+ // src/financialDashboard.ts
2796
+ function buildLiabilityVisualization(executionId, orgId, chain) {
2797
+ const nodes = chain.map((p) => ({
2798
+ id: p.party_id,
2799
+ label: p.party_label,
2800
+ party_type: p.party_type,
2801
+ role: p.role,
2802
+ liability_weight: p.liability_weight,
2803
+ acted_at: p.acted_at
2804
+ }));
2805
+ const edges = [];
2806
+ for (let i = 0; i < chain.length - 1; i++) {
2807
+ const from = chain[i];
2808
+ const to = chain[i + 1];
2809
+ let relationship = "authorized";
2810
+ if (from.role === "delegator" && to.role === "delegate") relationship = "delegated_to";
2811
+ else if (from.role === "supervisor") relationship = "supervised";
2812
+ else if (to.role === "approver") relationship = "approved_for";
2813
+ else if (to.role === "override_actor") relationship = "overrode";
2814
+ edges.push({
2815
+ from_id: from.party_id,
2816
+ to_id: to.party_id,
2817
+ relationship,
2818
+ weight: Math.min(from.liability_weight, to.liability_weight)
2819
+ });
2820
+ }
2821
+ return {
2822
+ execution_id: executionId,
2823
+ org_id: orgId,
2824
+ nodes,
2825
+ edges,
2826
+ total_weight: chain.reduce((s, p) => s + p.liability_weight, 0)
2827
+ };
2828
+ }
2829
+ function buildRiskTimeline(snapshots) {
2830
+ return snapshots.map((s) => {
2831
+ let tier = "low";
2832
+ if (s.riskScore > 80) tier = "critical";
2833
+ else if (s.riskScore > 55) tier = "high";
2834
+ else if (s.riskScore > 25) tier = "medium";
2835
+ return {
2836
+ date: s.date,
2837
+ risk_score: s.riskScore,
2838
+ risk_tier: tier,
2839
+ action_count: s.actionCount,
2840
+ total_value: s.totalValue,
2841
+ override_count: s.overrideCount,
2842
+ anomaly_count: s.anomalyCount
2843
+ };
2844
+ });
2845
+ }
2846
+
2847
+ // src/governanceEnforcement.ts
2848
+ var GovernanceEnforcementError = class extends AtlaSentError {
2849
+ name = "GovernanceEnforcementError";
2850
+ /** Which gate fired (`financial_quorum` / `budget` / `autonomous_bounds`). */
2851
+ gate;
2852
+ /** Stable taxonomy code; maps to a row in `docs/APPROVAL_DENY_REASONS.md`. */
2853
+ denyCode;
2854
+ /** Human-readable explanation. Do NOT branch on this string — branch on `denyCode`. */
2855
+ reason;
2856
+ /** The structured advisory result that produced the denial. */
2857
+ details;
2858
+ constructor(init) {
2859
+ const errInit = { code: "forbidden" };
2860
+ if (init.requestId !== void 0) errInit.requestId = init.requestId;
2861
+ super(`[${init.gate}/${init.denyCode}] ${init.reason}`, errInit);
2862
+ this.gate = init.gate;
2863
+ this.denyCode = init.denyCode;
2864
+ this.reason = init.reason;
2865
+ this.details = init.details;
2866
+ }
2867
+ /** Combined `<gate>/<denyCode>` string used in audit records. */
2868
+ get fullyQualifiedCode() {
2869
+ return `${this.gate}/${this.denyCode}`;
2870
+ }
2871
+ };
2872
+ function financialQuorumDenyCode(result) {
2873
+ if (result.blocked_by_freeze) return "blocked_by_emergency_freeze";
2874
+ if (!result.base_quorum_passed) return "base_count_unmet";
2875
+ if (!result.amount_threshold_satisfied) return "amount_threshold_unmet";
2876
+ if (!result.financial_roles_satisfied) return "financial_role_unmet";
2877
+ if (result.regulator_approval_missing) return "regulator_approval_missing";
2878
+ return "base_count_unmet";
2879
+ }
2880
+ function enforceFinancialQuorum(result) {
2881
+ if (result.passed) return;
2882
+ const denyCode = financialQuorumDenyCode(result);
2883
+ throw new GovernanceEnforcementError({
2884
+ gate: "financial_quorum",
2885
+ denyCode,
2886
+ reason: result.denial_reason ?? `financial quorum failed: ${denyCode}`,
2887
+ details: result
2888
+ });
2889
+ }
2890
+ function enforceBudgetConstraint(result) {
2891
+ if (result.permitted) return;
2892
+ if (result.hard_blocks.length === 0) {
2893
+ throw new GovernanceEnforcementError({
2894
+ gate: "budget",
2895
+ denyCode: "limit_exceeded",
2896
+ reason: "budget enforcement failed without a structured violation",
2897
+ details: result
2898
+ });
2899
+ }
2900
+ const first = result.hard_blocks[0];
2901
+ throw new GovernanceEnforcementError({
2902
+ gate: "budget",
2903
+ denyCode: first.violation_type,
2904
+ reason: first.description,
2905
+ details: result
2906
+ });
2907
+ }
2908
+ function autonomousBoundsDenyCode(result) {
2909
+ if (!result.bounds_active) return "inactive";
2910
+ if (!result.bounds_not_expired) return "expired";
2911
+ if (!result.action_type_permitted) return "action_type_not_permitted";
2912
+ if (!result.within_execution_ceiling) return "execution_ceiling_exceeded";
2913
+ if (!result.within_daily_aggregate) return "daily_aggregate_exceeded";
2914
+ if (!result.within_risk_tier) return "risk_tier_exceeded";
2915
+ return "inactive";
2916
+ }
2917
+ function enforceAutonomousBounds(result) {
2918
+ if (result.permitted) return;
2919
+ const denyCode = autonomousBoundsDenyCode(result);
2920
+ throw new GovernanceEnforcementError({
2921
+ gate: "autonomous_bounds",
2922
+ denyCode,
2923
+ reason: result.denial_reason ?? `autonomous execution out of bounds: ${denyCode}`,
2924
+ details: result
2925
+ });
2926
+ }
2927
+ function enforceEconomicGovernance(params) {
2928
+ if (params.quorum !== void 0) enforceFinancialQuorum(params.quorum);
2929
+ if (params.budget !== void 0) enforceBudgetConstraint(params.budget);
2930
+ if (params.autonomous !== void 0) enforceAutonomousBounds(params.autonomous);
2931
+ }
2932
+
2933
+ // src/governanceWebhooks.ts
2934
+ async function verifyWebhookSignature(payload, signature, secret) {
2935
+ const prefix = "sha256=";
2936
+ if (!signature.startsWith(prefix)) return false;
2937
+ const receivedHex = signature.slice(prefix.length);
2938
+ const encoder = new TextEncoder();
2939
+ const key = await crypto.subtle.importKey(
2940
+ "raw",
2941
+ encoder.encode(secret),
2942
+ { name: "HMAC", hash: "SHA-256" },
2943
+ false,
2944
+ ["sign"]
2945
+ );
2946
+ const sigBuffer = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
2947
+ const expectedHex = Array.from(new Uint8Array(sigBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
2948
+ if (receivedHex.length !== expectedHex.length) return false;
2949
+ let diff = 0;
2950
+ for (let i = 0; i < expectedHex.length; i++) {
2951
+ diff |= receivedHex.charCodeAt(i) ^ expectedHex.charCodeAt(i);
2952
+ }
2953
+ return diff === 0;
2954
+ }
2955
+
2956
+ // src/complianceEvidence.ts
2957
+ function evidenceRunPasses(run) {
2958
+ return (run.controls ?? []).every((c) => c.status !== "finding");
2959
+ }
2960
+ function nonPassingControls(run) {
2961
+ return (run.controls ?? []).filter((c) => c.status !== "pass").sort((a, b) => {
2962
+ if (a.status === "finding" && b.status !== "finding") return -1;
2963
+ if (b.status === "finding" && a.status !== "finding") return 1;
2964
+ return 0;
2965
+ });
2966
+ }
2967
+
2968
+ // src/policySync.ts
2969
+ function formatPolicySyncDiff(run) {
2970
+ const parts = [];
2971
+ if (run.policies_added > 0) parts.push(`+${run.policies_added} added`);
2972
+ if (run.policies_updated > 0) parts.push(`~${run.policies_updated} updated`);
2973
+ if (run.policies_removed > 0) parts.push(`-${run.policies_removed} removed`);
2974
+ return parts.length > 0 ? parts.join(", ") : "no changes";
2975
+ }
2976
+ function isPolicySyncTerminal(run) {
2977
+ return run.status === "completed" || run.status === "failed" || run.status === "rejected";
2978
+ }
2979
+
2980
+ // src/webhook.ts
2981
+ var WebhookVerificationError = class extends Error {
2982
+ name = "WebhookVerificationError";
2983
+ constructor(message) {
2984
+ super(message);
2985
+ }
2986
+ };
2987
+ var _hasWebCrypto = (() => {
2988
+ try {
2989
+ return typeof crypto !== "undefined" && typeof crypto.subtle === "object" && crypto.subtle !== null;
2990
+ } catch {
2991
+ return false;
2992
+ }
2993
+ })();
2994
+ function _extractHex(signature) {
2995
+ if (typeof signature !== "string") return null;
2996
+ const hex = signature.startsWith("sha256=") ? signature.slice(7) : signature;
2997
+ if (hex.length !== 64) return null;
2998
+ if (!/^[0-9a-f]+$/i.test(hex)) return null;
2999
+ return hex.toLowerCase();
3000
+ }
3001
+ async function _timingSafeEqual(a, b) {
3002
+ if (a.length !== b.length) return false;
3003
+ if (!_hasWebCrypto) {
3004
+ const { timingSafeEqual, createHmac: _c } = await import("crypto");
3005
+ const aBuf = Buffer.from(a, "hex");
3006
+ const bBuf = Buffer.from(b, "hex");
3007
+ return timingSafeEqual(aBuf, bBuf);
3008
+ }
3009
+ let acc = 0;
3010
+ for (let i = 0; i < a.length; i++) {
3011
+ acc |= a.charCodeAt(i) ^ b.charCodeAt(i);
3012
+ }
3013
+ return acc === 0;
3014
+ }
3015
+ async function _hmacSha256Hex(payload, secret) {
3016
+ if (_hasWebCrypto) {
3017
+ const enc = new TextEncoder();
3018
+ const key = await crypto.subtle.importKey(
3019
+ "raw",
3020
+ enc.encode(secret),
3021
+ { name: "HMAC", hash: "SHA-256" },
3022
+ false,
3023
+ ["sign"]
3024
+ );
3025
+ const sig = await crypto.subtle.sign("HMAC", key, enc.encode(payload));
3026
+ return Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
3027
+ }
3028
+ const { createHmac } = await import("crypto");
3029
+ return createHmac("sha256", secret).update(payload).digest("hex");
3030
+ }
3031
+ async function verifyWebhook(payload, signature, secret) {
3032
+ try {
3033
+ const expectedHex = _extractHex(signature);
3034
+ if (expectedHex === null) return false;
3035
+ const actualHex = await _hmacSha256Hex(payload, secret);
3036
+ return await _timingSafeEqual(actualHex, expectedHex);
3037
+ } catch {
3038
+ return false;
3039
+ }
3040
+ }
3041
+ async function assertWebhook(payload, signature, secret) {
3042
+ const valid = await verifyWebhook(payload, signature, secret);
3043
+ if (!valid) {
3044
+ throw new WebhookVerificationError(
3045
+ "Webhook signature verification failed: the signature does not match the payload."
3046
+ );
3047
+ }
3048
+ }
3049
+
3050
+ // src/crossOrgPermission.ts
3051
+ function summarizeCrossOrgPermission(result) {
3052
+ if (!result.allowed) return "denied";
3053
+ if (result.conditions.length > 0) return "conditional";
3054
+ return "allowed";
3055
+ }
3056
+
3057
+ // src/anomalyResponse.ts
3058
+ function matchAnomalyRules(rules, anomalyScore) {
3059
+ return rules.filter((r) => r.is_active && anomalyScore >= r.anomaly_score_threshold).sort((a, b) => b.anomaly_score_threshold - a.anomaly_score_threshold);
3060
+ }
3061
+ function highestSeverityAction(rules) {
3062
+ const ORDER = [
3063
+ "escalate_to_regulator",
3064
+ "rollback_execution",
3065
+ "freeze_agent",
3066
+ "require_hitl",
3067
+ "create_incident",
3068
+ "notify_admin"
3069
+ ];
3070
+ for (const action of ORDER) {
3071
+ if (rules.some((r) => r.action_type === action)) return action;
3072
+ }
3073
+ return null;
3074
+ }
3075
+
3076
+ // src/budgetExceptions.ts
3077
+ function isBudgetExceptionActive(exception, now) {
3078
+ if (exception.status !== "approved") return false;
3079
+ const ts = (now ?? /* @__PURE__ */ new Date()).toISOString();
3080
+ if (exception.effective_from && ts < exception.effective_from) return false;
3081
+ if (exception.effective_until && ts > exception.effective_until) return false;
3082
+ return true;
3083
+ }
3084
+ function isBudgetExceptionTerminal(status) {
3085
+ return status === "approved" || status === "rejected" || status === "expired" || status === "cancelled";
3086
+ }
3087
+
3088
+ // src/regulatoryEscalation.ts
3089
+ function isRegulatoryEscalationTerminal(status) {
3090
+ return status === "resolved" || status === "overridden";
3091
+ }
3092
+ function isEscalationSlaBreached(escalation, targetLevel, now) {
3093
+ if (isRegulatoryEscalationTerminal(escalation.status)) return false;
3094
+ const createdMs = new Date(escalation.created_at).getTime();
3095
+ const nowMs = (now ?? /* @__PURE__ */ new Date()).getTime();
3096
+ const elapsedHours = (nowMs - createdMs) / (1e3 * 60 * 60);
3097
+ return elapsedHours > targetLevel.escalation_sla_hours;
3098
+ }
3099
+
3100
+ // src/incentiveSignalFeedback.ts
3101
+ function computeSignalEngagementRate(summary) {
3102
+ if (summary.total_signals === 0) return 0;
3103
+ return summary.acted_on / summary.total_signals;
3104
+ }
3105
+ function isSubstantiveSignalResponse(actionType) {
3106
+ return actionType === "policy_updated" || actionType === "training_initiated" || actionType === "process_changed" || actionType === "monitoring_increased" || actionType === "escalated";
3107
+ }
3108
+
3109
+ // src/crossOrgImpersonation.ts
3110
+ function isImpersonationGrantUsable(grant, now) {
3111
+ if (!grant.is_active) return false;
3112
+ if (grant.revoked_at) return false;
3113
+ const ts = (now ?? /* @__PURE__ */ new Date()).toISOString();
3114
+ if (grant.expires_at && ts > grant.expires_at) return false;
3115
+ return true;
3116
+ }
3117
+ function clampTokenDuration(grant, requestedSeconds) {
3118
+ return Math.min(requestedSeconds, grant.max_token_duration_seconds);
3119
+ }
3120
+
3121
+ // src/v2.ts
3122
+ var V2_BATCH_PATH = "/v1/evaluate/batch";
3123
+ var V2_STREAM_PATH = "/v1/evaluate/stream";
3124
+ var V2_GRAPHQL_PATH = "/v1/graphql";
3125
+ var V2_MAX_BATCH_ITEMS = 100;
3126
+ var V2_MAX_BODY_BYTES = 1e6;
3127
+ var V2_GRAPHQL_MAX_DEPTH = 8;
3128
+ var FeatureNotEnabledError = class extends AtlaSentError {
3129
+ name = "FeatureNotEnabledError";
3130
+ /** Which tenant flag is gating the endpoint. */
3131
+ feature;
3132
+ /** The wire path the SDK attempted (for diagnostics). */
3133
+ endpoint;
3134
+ constructor(init) {
3135
+ const message = `AtlaSent V2 feature '${init.feature}' is not enabled for this tenant (POST ${init.endpoint} returned 404). Enable the v2_${init.feature} flag or fall back to the v1 per-item /v1-evaluate loop.`;
3136
+ const errInit = { status: 404, code: "feature_disabled" };
3137
+ if (init.requestId !== void 0) errInit.requestId = init.requestId;
3138
+ super(message, errInit);
3139
+ this.feature = init.feature;
3140
+ this.endpoint = init.endpoint;
3141
+ }
3142
+ };
3143
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3144
+ function assertValidBatchId(batchId) {
3145
+ if (batchId === void 0) return;
3146
+ if (typeof batchId !== "string" || !UUID_RE.test(batchId)) {
3147
+ throw new TypeError(`batchId must be a valid UUID: ${String(batchId)}`);
3148
+ }
3149
+ }
3150
+ function assertItemsShape(items) {
3151
+ if (!Array.isArray(items) || items.length === 0) {
3152
+ throw new TypeError("items must be a non-empty array");
3153
+ }
3154
+ if (items.length > V2_MAX_BATCH_ITEMS) {
3155
+ throw new TypeError(
3156
+ `items length ${items.length} exceeds maximum of ${V2_MAX_BATCH_ITEMS}`
3157
+ );
3158
+ }
3159
+ }
3160
+ function assertBodyWithinCap(raw) {
3161
+ const bytes = new TextEncoder().encode(raw).length;
3162
+ if (bytes > V2_MAX_BODY_BYTES) {
3163
+ throw new TypeError(
3164
+ `request body ${bytes} bytes exceeds maximum of ${V2_MAX_BODY_BYTES}`
3165
+ );
3166
+ }
3167
+ }
3168
+ function commonHeaders(apiKey) {
3169
+ return {
3170
+ "Content-Type": "application/json",
3171
+ Accept: "application/json",
3172
+ Authorization: `Bearer ${apiKey}`
3173
+ };
3174
+ }
3175
+ function pickFetch(t) {
3176
+ if (t.fetch !== void 0) return t.fetch;
3177
+ if (typeof fetch !== "undefined") return fetch;
3178
+ throw new Error(
3179
+ "v2: no fetch implementation available (set transport.fetch or run on Node \u2265 18)"
3180
+ );
3181
+ }
3182
+ async function evaluateMany(transport, req) {
3183
+ assertItemsShape(req.items);
3184
+ assertValidBatchId(req.batchId);
3185
+ const body = { items: req.items };
3186
+ if (req.batchId !== void 0) body["batch_id"] = req.batchId;
3187
+ const raw = JSON.stringify(body);
3188
+ assertBodyWithinCap(raw);
3189
+ const url = `${transport.baseUrl}${V2_BATCH_PATH}`;
3190
+ const fetchImpl = pickFetch(transport);
3191
+ const response = await fetchImpl(url, {
3192
+ method: "POST",
3193
+ headers: commonHeaders(transport.apiKey),
3194
+ body: raw
3195
+ });
3196
+ const requestId = response.headers.get("X-Request-ID") ?? void 0;
3197
+ if (response.status === 404) {
3198
+ const init = {
3199
+ feature: "batch",
3200
+ endpoint: V2_BATCH_PATH
3201
+ };
3202
+ if (requestId !== void 0) init.requestId = requestId;
3203
+ throw new FeatureNotEnabledError(init);
3204
+ }
3205
+ if (!response.ok) {
3206
+ throwHttpError(V2_BATCH_PATH, response.status, requestId);
3207
+ }
3208
+ const parsed = await safeJson(response, V2_BATCH_PATH, requestId);
3209
+ return parseBatchResponse(parsed);
3210
+ }
3211
+ function parseBatchResponse(data) {
3212
+ const root = data ?? {};
3213
+ const rawItems = root["items"] ?? [];
3214
+ const items = rawItems.map((it) => {
3215
+ const out = {
3216
+ index: typeof it["index"] === "number" ? it["index"] : -1
3217
+ };
3218
+ const decision = it["decision"];
3219
+ if (typeof decision === "string") out.decision = decision;
3220
+ const decisionId = it["decision_id"];
3221
+ if (typeof decisionId === "string") out.decisionId = decisionId;
3222
+ const permitToken = it["permit_token"];
3223
+ if (typeof permitToken === "string") out.permitToken = permitToken;
3224
+ const reason = it["reason"];
3225
+ if (typeof reason === "string") out.reason = reason;
3226
+ const errorCode = it["error_code"];
3227
+ if (typeof errorCode === "string") out.errorCode = errorCode;
3228
+ const errorMessage = it["error_message"];
3229
+ if (typeof errorMessage === "string") out.errorMessage = errorMessage;
3230
+ return out;
3231
+ });
3232
+ const batchId = root["batch_id"];
3233
+ return {
3234
+ batchId: typeof batchId === "string" ? batchId : "",
3235
+ items,
3236
+ partial: Boolean(root["partial"])
3237
+ };
3238
+ }
3239
+ async function authorizeStream(transport, req, handlers = {}) {
3240
+ assertItemsShape(req.items);
3241
+ assertValidBatchId(req.batchId);
3242
+ const body = { items: req.items };
3243
+ if (req.batchId !== void 0) body["batch_id"] = req.batchId;
3244
+ const raw = JSON.stringify(body);
3245
+ assertBodyWithinCap(raw);
3246
+ const url = `${transport.baseUrl}${V2_STREAM_PATH}`;
3247
+ const fetchImpl = pickFetch(transport);
3248
+ const response = await fetchImpl(url, {
3249
+ method: "POST",
3250
+ headers: {
3251
+ ...commonHeaders(transport.apiKey),
3252
+ Accept: "text/event-stream"
3253
+ },
3254
+ body: raw
3255
+ });
3256
+ const requestId = response.headers.get("X-Request-ID") ?? void 0;
3257
+ if (response.status === 404) {
3258
+ const init = {
3259
+ feature: "streaming",
3260
+ endpoint: V2_STREAM_PATH
3261
+ };
3262
+ if (requestId !== void 0) init.requestId = requestId;
3263
+ throw new FeatureNotEnabledError(init);
3264
+ }
3265
+ if (!response.ok) {
3266
+ throwHttpError(V2_STREAM_PATH, response.status, requestId);
3267
+ }
3268
+ if (response.body === null) {
3269
+ throw new AtlaSentError(
3270
+ `POST ${V2_STREAM_PATH} returned no response body`,
3271
+ { code: "bad_response", status: response.status }
3272
+ );
3273
+ }
3274
+ const complete = await consumeSseStream(response.body, handlers);
3275
+ if (complete === null) {
3276
+ throw new AtlaSentError(
3277
+ "authorizeStream: stream closed without a `complete` event",
3278
+ { code: "bad_response" }
3279
+ );
3280
+ }
3281
+ return complete;
3282
+ }
3283
+ async function consumeSseStream(body, handlers) {
3284
+ const reader = body.getReader();
3285
+ const decoder = new TextDecoder("utf-8");
3286
+ let buffer = "";
3287
+ let eventName = void 0;
3288
+ let complete = null;
3289
+ while (true) {
3290
+ const { value, done } = await reader.read();
3291
+ if (value !== void 0) {
3292
+ buffer += decoder.decode(value, { stream: !done });
3293
+ }
3294
+ if (done) {
3295
+ buffer += decoder.decode();
3296
+ }
3297
+ let nl;
3298
+ while ((nl = buffer.indexOf("\n")) !== -1) {
3299
+ let line = buffer.slice(0, nl);
3300
+ buffer = buffer.slice(nl + 1);
3301
+ if (line.endsWith("\r")) line = line.slice(0, -1);
3302
+ if (line === "") {
3303
+ eventName = void 0;
3304
+ continue;
3305
+ }
3306
+ if (line.startsWith(":")) continue;
3307
+ if (line.startsWith("event:")) {
3308
+ eventName = line.slice("event:".length).trim();
3309
+ continue;
3310
+ }
3311
+ if (!line.startsWith("data:")) continue;
3312
+ const dataText = line.slice("data:".length).trim();
3313
+ let payload;
3314
+ try {
3315
+ payload = JSON.parse(dataText);
3316
+ } catch {
3317
+ continue;
3318
+ }
3319
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
3320
+ continue;
3321
+ }
3322
+ const p = payload;
3323
+ if (eventName === "decision" && handlers.onDecision !== void 0) {
3324
+ const dIndex = p["index"];
3325
+ const dDecision = p["decision"];
3326
+ const frame = {
3327
+ index: typeof dIndex === "number" ? dIndex : -1,
3328
+ decision: typeof dDecision === "string" ? dDecision : ""
3329
+ };
3330
+ const dId = p["decision_id"];
3331
+ if (typeof dId === "string") frame.decisionId = dId;
3332
+ const pt = p["permit_token"];
3333
+ if (typeof pt === "string") frame.permitToken = pt;
3334
+ const r = p["reason"];
3335
+ if (typeof r === "string") frame.reason = r;
3336
+ handlers.onDecision(frame);
3337
+ } else if (eventName === "error" && handlers.onError !== void 0) {
3338
+ const eIndex = p["index"];
3339
+ const eCode = p["error_code"];
3340
+ const eMsg = p["message"];
3341
+ handlers.onError({
3342
+ index: typeof eIndex === "number" ? eIndex : -1,
3343
+ errorCode: typeof eCode === "string" ? eCode : "",
3344
+ message: typeof eMsg === "string" ? eMsg : ""
3345
+ });
3346
+ } else if (eventName === "complete") {
3347
+ const cBatchId = p["batch_id"];
3348
+ const cCount = p["count"];
3349
+ complete = {
3350
+ batchId: typeof cBatchId === "string" ? cBatchId : "",
3351
+ count: typeof cCount === "number" ? cCount : 0,
3352
+ partial: Boolean(p["partial"])
3353
+ };
3354
+ try {
3355
+ await reader.cancel();
3356
+ } catch {
3357
+ }
3358
+ return complete;
3359
+ }
3360
+ }
3361
+ if (done) break;
3362
+ }
3363
+ return complete;
3364
+ }
3365
+ async function graphql(transport, req) {
3366
+ if (typeof req.query !== "string" || req.query.trim() === "") {
3367
+ throw new TypeError("query must be a non-empty string");
3368
+ }
3369
+ const body = { query: req.query };
3370
+ if (req.variables !== void 0) body["variables"] = req.variables;
3371
+ if (req.operationName !== void 0)
3372
+ body["operationName"] = req.operationName;
3373
+ const raw = JSON.stringify(body);
3374
+ assertBodyWithinCap(raw);
3375
+ const url = `${transport.baseUrl}${V2_GRAPHQL_PATH}`;
3376
+ const fetchImpl = pickFetch(transport);
3377
+ const response = await fetchImpl(url, {
3378
+ method: "POST",
3379
+ headers: commonHeaders(transport.apiKey),
3380
+ body: raw
3381
+ });
3382
+ const requestId = response.headers.get("X-Request-ID") ?? void 0;
3383
+ if (response.status === 404) {
3384
+ const init = {
3385
+ feature: "graphql",
3386
+ endpoint: V2_GRAPHQL_PATH
3387
+ };
3388
+ if (requestId !== void 0) init.requestId = requestId;
3389
+ throw new FeatureNotEnabledError(init);
3390
+ }
3391
+ if (!response.ok) {
3392
+ throwHttpError(V2_GRAPHQL_PATH, response.status, requestId);
3393
+ }
3394
+ const parsed = await safeJson(response, V2_GRAPHQL_PATH, requestId);
3395
+ const root = parsed ?? {};
3396
+ const out = {
3397
+ data: root["data"] ?? null
3398
+ };
3399
+ const errs = root["errors"];
3400
+ if (Array.isArray(errs) && errs.length > 0) {
3401
+ out.errors = errs;
3402
+ }
3403
+ return out;
3404
+ }
3405
+ function throwHttpError(path, status, requestId) {
3406
+ const errInit = {
3407
+ status,
3408
+ code: status >= 500 ? "server_error" : "bad_request"
3409
+ };
3410
+ if (requestId !== void 0) errInit.requestId = requestId;
3411
+ throw new AtlaSentError(`POST ${path} returned ${status}`, errInit);
3412
+ }
3413
+ async function safeJson(response, path, requestId) {
3414
+ try {
3415
+ return await response.json();
3416
+ } catch (cause) {
3417
+ const errInit = {
3418
+ status: response.status,
3419
+ code: "bad_response",
3420
+ cause
3421
+ };
3422
+ if (requestId !== void 0) errInit.requestId = requestId;
3423
+ throw new AtlaSentError(`${path}: malformed JSON response`, errInit);
3424
+ }
694
3425
  }
695
3426
 
696
3427
  // src/index.ts
697
3428
  var atlasent = {
698
3429
  protect,
3430
+ withPermit,
3431
+ deployGate,
699
3432
  configure,
3433
+ requirePermit,
3434
+ classifyCommand,
700
3435
  verifyBundle,
3436
+ PRODUCTION_DEPLOY_ACTION,
3437
+ DEPLOYMENT_PRODUCTION_ACTION,
701
3438
  AtlaSentClient,
702
3439
  AtlaSentError,
703
3440
  AtlaSentDeniedError
@@ -707,17 +3444,102 @@ export {
707
3444
  AtlaSentClient,
708
3445
  AtlaSentDeniedError,
709
3446
  AtlaSentError,
3447
+ AtlaSentEscalateError,
3448
+ DEFAULT_INCENTIVE_CONFIG,
710
3449
  DEFAULT_RETRY_POLICY,
3450
+ DEFAULT_RISK_TIER_THRESHOLDS,
3451
+ DEPLOYMENT_PRODUCTION_ACTION,
3452
+ DEPLOY_GATE_CODES,
3453
+ FeatureNotEnabledError,
3454
+ GovernanceEnforcementError,
3455
+ PRODUCTION_DEPLOY_ACTION,
3456
+ PermitRevoked,
3457
+ StreamParseError,
3458
+ StreamTimeoutError,
3459
+ V2_BATCH_PATH,
3460
+ V2_GRAPHQL_MAX_DEPTH,
3461
+ V2_GRAPHQL_PATH,
3462
+ V2_MAX_BATCH_ITEMS,
3463
+ V2_MAX_BODY_BYTES,
3464
+ V2_STREAM_PATH,
3465
+ WebhookVerificationError,
3466
+ assertWebhook,
3467
+ authorizeStream,
3468
+ budgetUtilizationSeverity,
3469
+ buildLiabilityChain,
3470
+ buildLiabilityVisualization,
3471
+ buildRiskTimeline,
3472
+ buildSignableContent,
711
3473
  canonicalJSON,
3474
+ canonicalizeForEvidence,
3475
+ checkAutonomousBounds,
3476
+ checkBudgetConstraints,
3477
+ clampTokenDuration,
3478
+ classifyCommand,
3479
+ classifyRiskTier,
3480
+ computeApprovalRiskScore,
712
3481
  computeBackoffMs,
3482
+ computeEscalatedApprovalCount,
3483
+ computeExposureScore,
3484
+ computeGovernanceHealthScore,
3485
+ computeHHI,
3486
+ computeLiabilityWeights,
3487
+ computeOverallRiskScore,
3488
+ computeOverrideScore,
3489
+ computeRemediationUrgency,
3490
+ computeSignalEngagementRate,
713
3491
  configure,
714
3492
  index_default as default,
3493
+ delegationPropagationHadEffect,
3494
+ deployGate,
3495
+ detectAutonomousAnomaly,
3496
+ detectMisalignedIncentives,
3497
+ detectSelfApproval,
3498
+ enforceAutonomousBounds,
3499
+ enforceBudgetConstraint,
3500
+ enforceEconomicGovernance,
3501
+ enforceFinancialQuorum,
3502
+ evaluateFinancialQuorum,
3503
+ evaluateMany,
3504
+ evidenceRunPasses,
3505
+ findPrimaryLiabilityParties,
3506
+ formatPolicySyncDiff,
3507
+ graphql,
715
3508
  hasAttemptsLeft,
3509
+ hhiToConcentrationScore,
3510
+ highestSeverityAction,
3511
+ hitlRequiredApproverCount,
3512
+ isBudgetExceptionActive,
3513
+ isBudgetExceptionTerminal,
3514
+ isEscalationSlaBreached,
3515
+ isFreezeActive,
3516
+ isImpersonationGrantUsable,
3517
+ isPolicySyncTerminal,
3518
+ isRegulatoryEscalationTerminal,
716
3519
  isRetryable,
3520
+ isSandboxDiffPopulated,
3521
+ isSubstantiveSignalResponse,
3522
+ matchAnomalyRules,
717
3523
  mergePolicy,
3524
+ nonPassingControls,
3525
+ normalizeEvaluateRequest,
3526
+ normalizeEvaluateResponse,
3527
+ normalizePermitOutcome,
718
3528
  protect,
3529
+ requirePermit,
3530
+ scoreToRiskTier,
3531
+ serializeSignableContent,
719
3532
  signedBytesFor,
3533
+ summarizeCrossOrgPermission,
3534
+ transitionDispute,
3535
+ transitionReversal,
3536
+ validateLiabilityChain,
720
3537
  verifyAuditBundle,
721
- verifyBundle
3538
+ verifyBundle,
3539
+ verifyEvidenceBundleStructure,
3540
+ verifyWebhook,
3541
+ verifyWebhookSignature,
3542
+ withPermit,
3543
+ withinAutonomousCeiling
722
3544
  };
723
3545
  //# sourceMappingURL=index.js.map