@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/hono.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/hono.ts
@@ -28,6 +38,27 @@ __export(hono_exports, {
28
38
  module.exports = __toCommonJS(hono_exports);
29
39
 
30
40
  // src/errors.ts
41
+ var StreamTimeoutError = class extends Error {
42
+ name = "StreamTimeoutError";
43
+ /** Timeout that was exceeded, in milliseconds. */
44
+ timeoutMs;
45
+ constructor(timeoutMs) {
46
+ super(`AtlaSent stream timed out after ${timeoutMs}ms with no event`);
47
+ this.timeoutMs = timeoutMs;
48
+ }
49
+ };
50
+ var StreamParseError = class extends Error {
51
+ name = "StreamParseError";
52
+ /** The raw data string that failed to parse. */
53
+ rawData;
54
+ constructor(rawData, cause) {
55
+ super(`AtlaSent stream received malformed JSON: ${rawData.slice(0, 200)}`);
56
+ this.rawData = rawData;
57
+ if (cause !== void 0) {
58
+ this.cause = cause;
59
+ }
60
+ }
61
+ };
31
62
  var AtlaSentError = class extends Error {
32
63
  // Subclasses override to their own literal (e.g. "AtlaSentDeniedError");
33
64
  // keep this assignable rather than pinned to a single literal.
@@ -51,6 +82,18 @@ var AtlaSentError = class extends Error {
51
82
  this.retryAfterMs = init.retryAfterMs;
52
83
  }
53
84
  };
85
+ var KNOWN_PERMIT_OUTCOMES = /* @__PURE__ */ new Set([
86
+ "permit_consumed",
87
+ "permit_expired",
88
+ "permit_revoked",
89
+ "permit_not_found"
90
+ ]);
91
+ function normalizePermitOutcome(raw) {
92
+ if (raw !== void 0 && KNOWN_PERMIT_OUTCOMES.has(raw)) {
93
+ return raw;
94
+ }
95
+ return void 0;
96
+ }
54
97
  var AtlaSentDeniedError = class extends AtlaSentError {
55
98
  name = "AtlaSentDeniedError";
56
99
  /** Policy decision — `"deny"` today; `"hold"` / `"escalate"` reserved. */
@@ -61,6 +104,12 @@ var AtlaSentDeniedError = class extends AtlaSentError {
61
104
  reason;
62
105
  /** Hash-chained audit-trail entry associated with the decision. */
63
106
  auditHash;
107
+ /**
108
+ * Discriminator for permit-side denial reasons. Populated only
109
+ * when the server reported `verified=false` from `/v1-verify-permit`;
110
+ * `undefined` for evaluate-time denials. See {@link PermitOutcome}.
111
+ */
112
+ outcome;
64
113
  constructor(init) {
65
114
  const msg = init.reason ? `AtlaSent ${init.decision}: ${init.reason}` : `AtlaSent ${init.decision}`;
66
115
  const errInit = { status: 200 };
@@ -70,92 +119,620 @@ var AtlaSentDeniedError = class extends AtlaSentError {
70
119
  this.evaluationId = init.evaluationId;
71
120
  this.reason = init.reason;
72
121
  this.auditHash = init.auditHash;
122
+ this.outcome = init.outcome;
123
+ }
124
+ // ── Outcome discriminators ───────────────────────────────────────
125
+ // Convenience predicates that mirror the operator runbook's matrix.
126
+ // Callers can compare `outcome` directly; these are sugar so the
127
+ // common cases are explicit at the call site.
128
+ /** `true` when the permit was explicitly revoked (D3 endpoint). */
129
+ get isRevoked() {
130
+ return this.outcome === "permit_revoked";
131
+ }
132
+ /** `true` when the permit's TTL passed before verification. */
133
+ get isExpired() {
134
+ return this.outcome === "permit_expired";
135
+ }
136
+ /**
137
+ * `true` when the permit was already consumed by a prior verify
138
+ * (v1 single-use replay protection).
139
+ */
140
+ get isConsumed() {
141
+ return this.outcome === "permit_consumed";
142
+ }
143
+ /**
144
+ * `true` when the permit id wasn't recognized server-side
145
+ * (typo, cross-tenant lookup, or pre-issuance race).
146
+ */
147
+ get isNotFound() {
148
+ return this.outcome === "permit_not_found";
73
149
  }
74
150
  };
75
151
 
152
+ // src/types.ts
153
+ var PRODUCTION_DEPLOY_ACTION = "production.deploy";
154
+ var DEPLOY_GATE_CODES = Object.freeze({
155
+ ALLOW: "ALLOW",
156
+ DENY_POLICY: "DENY_POLICY",
157
+ DENY_AUTHORITY: "DENY_AUTHORITY",
158
+ DENY_ENVIRONMENT: "DENY_ENVIRONMENT",
159
+ PERMIT_EXPIRED: "PERMIT_EXPIRED",
160
+ VERIFY_FAILED: "VERIFY_FAILED",
161
+ ESCALATE_REQUIRED: "ESCALATE_REQUIRED",
162
+ OVERRIDE_APPROVED: "OVERRIDE_APPROVED"
163
+ });
164
+
165
+ // src/compat.ts
166
+ function normalizeEvaluateRequest(input) {
167
+ if ("action" in input && !("action_type" in input)) {
168
+ console.warn(
169
+ "[atlasent] Deprecation: action/agent request shape is deprecated. Use action_type/actor_id instead. This compatibility shim will be removed in v3.0.0."
170
+ );
171
+ const legacy = input;
172
+ const normalized = {
173
+ action_type: legacy.action,
174
+ actor_id: legacy.agent
175
+ };
176
+ if (legacy.context !== void 0) {
177
+ normalized.context = legacy.context;
178
+ }
179
+ return normalized;
180
+ }
181
+ return input;
182
+ }
183
+
184
+ // src/retry.ts
185
+ var DEFAULT_RETRY_POLICY = {
186
+ maxAttempts: 4,
187
+ baseDelayMs: 2e3,
188
+ maxDelayMs: 16e3
189
+ };
190
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set([
191
+ "network",
192
+ "timeout",
193
+ "rate_limited",
194
+ "server_error",
195
+ "bad_response"
196
+ ]);
197
+ function isRetryable(err) {
198
+ if (!(err instanceof AtlaSentError)) return false;
199
+ if (err.code === void 0) return false;
200
+ return RETRYABLE_CODES.has(err.code);
201
+ }
202
+ function computeBackoffMs(attempt, policy = {}, err, random = Math.random) {
203
+ const merged = mergePolicy(policy);
204
+ const safeAttempt = Math.max(0, Math.floor(attempt));
205
+ const exp = Math.min(safeAttempt, 30);
206
+ const ceiling = Math.min(merged.maxDelayMs, merged.baseDelayMs * 2 ** exp);
207
+ const jittered = Math.floor(ceiling * clampUnit(random()));
208
+ const retryAfterMs = err instanceof AtlaSentError && typeof err.retryAfterMs === "number" ? Math.max(0, err.retryAfterMs) : 0;
209
+ return Math.max(retryAfterMs, jittered);
210
+ }
211
+ function hasAttemptsLeft(attempt, policy = {}) {
212
+ const merged = mergePolicy(policy);
213
+ return attempt + 1 < merged.maxAttempts;
214
+ }
215
+ function mergePolicy(policy) {
216
+ const maxAttempts = Math.max(
217
+ 1,
218
+ Math.floor(policy.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts)
219
+ );
220
+ const baseDelayMs = Math.max(
221
+ 0,
222
+ policy.baseDelayMs ?? DEFAULT_RETRY_POLICY.baseDelayMs
223
+ );
224
+ const maxDelayMs = Math.max(
225
+ baseDelayMs,
226
+ policy.maxDelayMs ?? DEFAULT_RETRY_POLICY.maxDelayMs
227
+ );
228
+ return { maxAttempts, baseDelayMs, maxDelayMs };
229
+ }
230
+ function clampUnit(n) {
231
+ if (!Number.isFinite(n)) return 0;
232
+ if (n < 0) return 0;
233
+ if (n >= 1) return 0.999999999;
234
+ return n;
235
+ }
236
+
76
237
  // src/client.ts
77
238
  var DEFAULT_BASE_URL = "https://api.atlasent.io";
78
239
  var DEFAULT_TIMEOUT_MS = 1e4;
79
- var SDK_VERSION = "0.1.0";
240
+ var SDK_VERSION = "2.2.0";
241
+ function _buildUserAgent() {
242
+ const isNode2 = typeof process !== "undefined" && typeof process?.versions?.node === "string";
243
+ return isNode2 ? `@atlasent/sdk/${SDK_VERSION} node/${process.version}` : `@atlasent/sdk/${SDK_VERSION} browser`;
244
+ }
245
+ var CONTEXT_PROPERTIES_SOFT_CAP = 64;
246
+ function _warnOversizeContext(context) {
247
+ if (context && Object.keys(context).length > CONTEXT_PROPERTIES_SOFT_CAP) {
248
+ console.warn(
249
+ `[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.`
250
+ );
251
+ }
252
+ }
253
+ function _enforceTls(baseUrl) {
254
+ const nodeEnvValue = typeof process !== "undefined" && process.env ? process.env.ATLASENT_ALLOW_INSECURE_HTTP : void 0;
255
+ const allow = nodeEnvValue === "1" || globalThis.ATLASENT_ALLOW_INSECURE_HTTP === "1";
256
+ if (allow) return baseUrl;
257
+ let parsed;
258
+ try {
259
+ parsed = new URL(baseUrl);
260
+ } catch {
261
+ throw new AtlaSentError(`Invalid baseUrl: ${baseUrl}`, {
262
+ code: "bad_request"
263
+ });
264
+ }
265
+ if (parsed.protocol !== "https:") {
266
+ throw new AtlaSentError(
267
+ `AtlaSent baseUrl must use https:// (got ${parsed.protocol}). For local development, set ATLASENT_ALLOW_INSECURE_HTTP=1.`,
268
+ { code: "bad_request" }
269
+ );
270
+ }
271
+ return baseUrl;
272
+ }
273
+ var API_KEY_PATTERN = /^ask_(?:live|test)_[A-Za-z0-9_-]+$/;
274
+ function _validateApiKey(apiKey) {
275
+ if (typeof apiKey !== "string" || apiKey.length === 0) {
276
+ throw new AtlaSentError("apiKey is required", { code: "invalid_api_key" });
277
+ }
278
+ if (!API_KEY_PATTERN.test(apiKey)) {
279
+ const head = apiKey.slice(0, 8);
280
+ throw new AtlaSentError(
281
+ `AtlaSent apiKey does not match expected shape \`ask_(live|test)_<entropy>\` (got prefix=${JSON.stringify(head)}). Check for whitespace, quotes, or trailing characters.`,
282
+ { code: "invalid_api_key" }
283
+ );
284
+ }
285
+ return apiKey;
286
+ }
287
+ var isNode = typeof process !== "undefined" && typeof process.versions?.node === "string";
288
+ var NODE_VERSION = isNode ? process.version : null;
289
+ function deployGateEvidence(input) {
290
+ const evidence = {};
291
+ if (input.permitId) evidence.permitId = input.permitId;
292
+ if (input.permitHash) evidence.permitHash = input.permitHash;
293
+ if (input.auditHash) evidence.auditHash = input.auditHash;
294
+ if (input.verifiedAt) evidence.verifiedAt = input.verifiedAt;
295
+ return evidence;
296
+ }
80
297
  var AtlaSentClient = class {
81
298
  apiKey;
82
299
  baseUrl;
83
300
  timeoutMs;
84
301
  fetchImpl;
302
+ userAgent;
303
+ retryPolicy;
85
304
  constructor(options) {
86
305
  if (!options.apiKey || typeof options.apiKey !== "string") {
87
306
  throw new AtlaSentError("apiKey is required", {
88
307
  code: "invalid_api_key"
89
308
  });
90
309
  }
91
- this.apiKey = options.apiKey;
92
- this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
310
+ if (typeof AbortSignal.timeout !== "function") {
311
+ throw new AtlaSentError(
312
+ "@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.",
313
+ { code: "network" }
314
+ );
315
+ }
316
+ this.apiKey = _validateApiKey(options.apiKey);
317
+ this.baseUrl = _enforceTls(options.baseUrl ?? DEFAULT_BASE_URL).replace(
318
+ /\/+$/,
319
+ ""
320
+ );
93
321
  this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
94
322
  this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
323
+ this.userAgent = _buildUserAgent();
324
+ this.retryPolicy = mergePolicy(options.retryPolicy ?? {});
95
325
  }
96
326
  /**
97
327
  * Ask the policy engine whether an agent action is permitted.
98
328
  *
99
- * A "DENY" is **not** thrown it is returned in
329
+ * Accepts either the current v2.0 shape (`action_type` / `actor_id`)
330
+ * or the legacy v1.x shape (`action` / `agent`). Legacy callers
331
+ * receive a deprecation warning via `console.warn`; the shim is
332
+ * handled by {@link normalizeEvaluateRequest} and will be removed
333
+ * in v3.0.0.
334
+ *
335
+ * A "deny" is **not** thrown — it is returned in
100
336
  * `response.decision`. Network errors, invalid API key, rate
101
337
  * limits, timeouts, and malformed responses throw
102
338
  * {@link AtlaSentError}.
103
339
  */
104
340
  async evaluate(input) {
341
+ _warnOversizeContext(input.context);
342
+ const normalized = normalizeEvaluateRequest(
343
+ input
344
+ );
105
345
  const body = {
106
- action: input.action,
107
- agent: input.agent,
108
- context: input.context ?? {},
109
- api_key: this.apiKey
346
+ action_type: normalized.action_type,
347
+ actor_id: normalized.actor_id,
348
+ context: normalized.context ?? {}
110
349
  };
111
- const { body: wire, rateLimit } = await this.post("/v1-evaluate", body);
112
- if (typeof wire.permitted !== "boolean" || typeof wire.decision_id !== "string") {
350
+ const { body: wire, rateLimit } = await this.post(
351
+ "/v1-evaluate",
352
+ body
353
+ );
354
+ let decision = typeof wire.decision === "string" ? wire.decision.toLowerCase() : wire.decision;
355
+ if (decision === void 0 && typeof wire.permitted === "boolean") {
356
+ decision = wire.permitted ? "allow" : "deny";
357
+ }
358
+ const permitToken = wire.permit_token ?? wire.decision_id;
359
+ if (decision !== "allow" && decision !== "deny" && decision !== "hold" && decision !== "escalate") {
360
+ throw new AtlaSentError(
361
+ "Malformed response from /v1-evaluate: missing `decision` (or legacy `permitted`)",
362
+ { code: "bad_response" }
363
+ );
364
+ }
365
+ if (decision === "allow" && (typeof permitToken !== "string" || permitToken.length === 0)) {
113
366
  throw new AtlaSentError(
114
- "Malformed response from /v1-evaluate: missing `permitted` or `decision_id`",
367
+ "Malformed response from /v1-evaluate: decision='allow' but no `permit_token` (or legacy `decision_id`)",
115
368
  { code: "bad_response" }
116
369
  );
117
370
  }
371
+ const reason = wire.denial?.reason ?? wire.reason ?? "";
372
+ const permitId = permitToken ?? "";
118
373
  return {
119
- decision: wire.permitted ? "ALLOW" : "DENY",
120
- permitId: wire.decision_id,
121
- reason: wire.reason ?? "",
374
+ decision,
375
+ decision_canonical: decision,
376
+ evaluationId: permitId,
377
+ permitId,
378
+ // /v1-evaluate does not return a control-plane-shaped Permit body;
379
+ // callers needing the full record fetch GET /v1/permits/:id.
380
+ permit: null,
381
+ permitToken: decision === "allow" ? permitToken ?? null : null,
382
+ reasons: reason ? [reason] : [],
383
+ reason,
122
384
  auditHash: wire.audit_hash ?? "",
123
385
  timestamp: wire.timestamp ?? "",
124
386
  rateLimit
125
387
  };
126
388
  }
389
+ /**
390
+ * Pre-flight evaluation that always returns the constraint trace.
391
+ *
392
+ * Wraps `POST /v1-evaluate?include=constraint_trace`. Use this from
393
+ * a workflow's submission step to surface trivial defects (missing
394
+ * fields, wrong roles, mis-set context) BEFORE pushing the request
395
+ * onto an approval queue — only requests that would actually pass
396
+ * make it through to a human reviewer.
397
+ *
398
+ * Returns an {@link EvaluatePreflightResponse} carrying the regular
399
+ * {@link EvaluateResponse} plus the {@link ConstraintTrace}. Unlike
400
+ * {@link evaluate}, this method does NOT mark a non-allow as a
401
+ * thrown condition — the whole point is to inspect both the outcome
402
+ * AND the per-policy trace, so the caller branches on
403
+ * `result.evaluation.decision` and reads `result.constraintTrace`
404
+ * to render the failing stages.
405
+ *
406
+ * The constraint-trace shape mirrors `ConstraintTraceResponse` in
407
+ * atlasent-api (`packages/types/src/index.ts`). On older
408
+ * atlasent-api deployments that omit the trace, `constraintTrace`
409
+ * is `null` rather than throwing — forward-compatible degradation.
410
+ *
411
+ * Performance: one extra round-trip on submission. Latency is
412
+ * comparable to {@link evaluate}; the response body is fuller
413
+ * (includes the per-stage trace) so the wire payload is larger.
414
+ * If the caller does not need the trace, prefer {@link evaluate}.
415
+ */
416
+ async evaluatePreflight(input) {
417
+ _warnOversizeContext(input.context);
418
+ const body = {
419
+ action_type: input.action,
420
+ actor_id: input.agent,
421
+ context: input.context ?? {}
422
+ };
423
+ const query = new URLSearchParams({ include: "constraint_trace" });
424
+ const { body: wire, rateLimit } = await this.post(
425
+ "/v1-evaluate",
426
+ body,
427
+ query
428
+ );
429
+ let decision = typeof wire.decision === "string" ? wire.decision.toLowerCase() : wire.decision;
430
+ if (decision === void 0 && typeof wire.permitted === "boolean") {
431
+ decision = wire.permitted ? "allow" : "deny";
432
+ }
433
+ if (decision !== "allow" && decision !== "deny" && decision !== "hold" && decision !== "escalate") {
434
+ throw new AtlaSentError(
435
+ "Malformed response from /v1-evaluate: missing `decision` (or legacy `permitted`)",
436
+ { code: "bad_response" }
437
+ );
438
+ }
439
+ const permitToken = wire.permit_token ?? wire.decision_id;
440
+ const reason = wire.denial?.reason ?? wire.reason ?? "";
441
+ const permitId = permitToken ?? "";
442
+ const evaluation = {
443
+ decision,
444
+ decision_canonical: decision,
445
+ evaluationId: permitId,
446
+ permitId,
447
+ // /v1-evaluate does not return a control-plane-shaped Permit body;
448
+ // callers needing the full record fetch GET /v1/permits/:id.
449
+ permit: null,
450
+ permitToken: decision === "allow" ? permitToken ?? null : null,
451
+ reasons: reason ? [reason] : [],
452
+ reason,
453
+ auditHash: wire.audit_hash ?? "",
454
+ timestamp: wire.timestamp ?? "",
455
+ rateLimit
456
+ };
457
+ let constraintTrace = null;
458
+ if (wire.constraint_trace !== void 0 && wire.constraint_trace !== null && typeof wire.constraint_trace === "object") {
459
+ constraintTrace = wire.constraint_trace;
460
+ }
461
+ return { evaluation, constraintTrace };
462
+ }
127
463
  /**
128
464
  * Verify that a previously issued permit is still valid.
129
465
  *
466
+ * @deprecated Use {@link verifyPermitById} — the canonical REST
467
+ * surface (`POST /v1/permits/{id}/verify`) returns the unified
468
+ * verification envelope plus the full {@link PermitRecord}, instead
469
+ * of the legacy `{verified, outcome, permitHash}` shape this method
470
+ * emits. Will be removed in `@atlasent/sdk@3`.
471
+ *
130
472
  * A `verified: false` response is **not** thrown — inspect the
131
473
  * returned object. Only transport / server errors throw.
132
474
  */
133
475
  async verifyPermit(input) {
476
+ _warnOversizeContext(input.context);
134
477
  const body = {
135
- decision_id: input.permitId,
136
- action: input.action ?? "",
137
- agent: input.agent ?? "",
138
- context: input.context ?? {},
139
- api_key: this.apiKey
478
+ permit_token: input.permitId,
479
+ action_type: input.action ?? "",
480
+ actor_id: input.agent ?? ""
140
481
  };
482
+ if (input.environment !== void 0) {
483
+ body.environment = input.environment;
484
+ }
485
+ if (input.execution_hash !== void 0) {
486
+ body.execution_hash = input.execution_hash;
487
+ }
141
488
  const { body: wire, rateLimit } = await this.post(
142
489
  "/v1-verify-permit",
143
490
  body
144
491
  );
145
- if (typeof wire.verified !== "boolean") {
492
+ const valid = typeof wire.valid === "boolean" ? wire.valid : wire.verified;
493
+ if (typeof valid !== "boolean") {
146
494
  throw new AtlaSentError(
147
- "Malformed response from /v1-verify-permit: missing `verified`",
495
+ "Malformed response from /v1-verify-permit: missing `valid` (or legacy `verified`)",
148
496
  { code: "bad_response" }
149
497
  );
150
498
  }
151
499
  return {
152
- verified: wire.verified,
500
+ verified: valid,
153
501
  outcome: wire.outcome ?? "",
154
502
  permitHash: wire.permit_hash ?? "",
155
503
  timestamp: wire.timestamp ?? "",
156
504
  rateLimit
157
505
  };
158
506
  }
507
+ /**
508
+ * Run the canonical Deploy Gate V1 flow:
509
+ * evaluate `production.deploy`, verify the issued permit server-side,
510
+ * and return allow/block plus audit/evidence metadata.
511
+ *
512
+ * This helper never treats a signed/offline permit artifact as sufficient
513
+ * authorization. Execution is allowed only when `POST /v1-evaluate` returns
514
+ * `decision: "allow"` with a permit AND `POST /v1-verify-permit` returns
515
+ * `verified: true` / `valid: true`.
516
+ */
517
+ async deployGate(input = {}) {
518
+ const agent = input.agent ?? "ci-deploy-bot";
519
+ const action = input.action ?? PRODUCTION_DEPLOY_ACTION;
520
+ const context = input.context ?? {};
521
+ const evaluation = await this.evaluate({ agent, action, context });
522
+ if (evaluation.decision !== "allow") {
523
+ return {
524
+ allowed: false,
525
+ evaluation,
526
+ reason: evaluation.reason || `Deploy Gate blocked by decision=${evaluation.decision}`,
527
+ evidence: deployGateEvidence({
528
+ permitId: evaluation.permitId,
529
+ auditHash: evaluation.auditHash
530
+ })
531
+ };
532
+ }
533
+ const verification = await this.verifyPermit({
534
+ permitId: evaluation.permitId,
535
+ agent,
536
+ action,
537
+ context
538
+ });
539
+ if (!verification.verified) {
540
+ return {
541
+ allowed: false,
542
+ evaluation,
543
+ verification,
544
+ reason: verification.outcome ? `Deploy Gate blocked by permit verification outcome=${verification.outcome}` : "Deploy Gate blocked because permit verification failed",
545
+ evidence: deployGateEvidence({
546
+ permitId: evaluation.permitId,
547
+ permitHash: verification.permitHash,
548
+ auditHash: evaluation.auditHash,
549
+ verifiedAt: verification.timestamp
550
+ })
551
+ };
552
+ }
553
+ return {
554
+ allowed: true,
555
+ evaluation,
556
+ verification,
557
+ reason: evaluation.reason || "Deploy Gate permit verified",
558
+ evidence: deployGateEvidence({
559
+ permitId: evaluation.permitId,
560
+ permitHash: verification.permitHash,
561
+ auditHash: evaluation.auditHash,
562
+ verifiedAt: verification.timestamp
563
+ })
564
+ };
565
+ }
566
+ /**
567
+ * Revoke a previously-issued permit so it can no longer pass
568
+ * {@link verifyPermit}.
569
+ *
570
+ * @deprecated Use {@link revokePermitById} — the canonical REST
571
+ * surface (`POST /v1/permits/{id}/revoke`) returns the full updated
572
+ * {@link PermitRecord} with `revoked_at`/`revoked_by`/`revoke_reason`
573
+ * populated, instead of the legacy `{revoked, permitId}` envelope
574
+ * this method emits. Will be removed in `@atlasent/sdk@3`.
575
+ *
576
+ * Use this when an agent's action is cancelled, superseded, or
577
+ * determined to be unauthorized after the fact. The revocation is
578
+ * recorded in the audit log with the optional `reason`.
579
+ *
580
+ * Throws {@link AtlaSentError} on transport / auth failures.
581
+ */
582
+ async revokePermit(input) {
583
+ const body = {
584
+ decision_id: input.permitId,
585
+ reason: input.reason ?? "",
586
+ api_key: this.apiKey
587
+ };
588
+ const { body: wire, rateLimit } = await this.post("/v1-revoke-permit", body);
589
+ if (typeof wire.revoked !== "boolean" || typeof wire.decision_id !== "string") {
590
+ throw new AtlaSentError(
591
+ "Malformed response from /v1-revoke-permit: missing `revoked` or `decision_id`",
592
+ { code: "bad_response" }
593
+ );
594
+ }
595
+ return {
596
+ revoked: wire.revoked,
597
+ permitId: wire.decision_id,
598
+ revokedAt: wire.revoked_at,
599
+ auditHash: wire.audit_hash,
600
+ rateLimit
601
+ };
602
+ }
603
+ /**
604
+ * Revoke a permit through the canonical REST surface
605
+ * (`POST /v1/permits/{permitId}/revoke`).
606
+ *
607
+ * Returns the full updated {@link PermitRecord} with `status === 'revoked'`
608
+ * and `revoked_at` / `revoked_by` / `revoke_reason` populated. After
609
+ * revocation, subsequent verify calls return `410 PERMIT_REVOKED`.
610
+ *
611
+ * Idempotent on `409 permit_revoked` for already-revoked permits;
612
+ * server returns the existing revoked row in that case.
613
+ *
614
+ * Throws {@link AtlaSentError} on `404` (permit not in calling org),
615
+ * `409` (already in a terminal state), `410` (expired before revoke),
616
+ * or `429` (rate limited).
617
+ */
618
+ async revokePermitById(permitId, input = {}) {
619
+ if (!permitId) {
620
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
621
+ }
622
+ const body = {};
623
+ if (input.reason !== void 0) body.reason = input.reason;
624
+ const { body: wire, rateLimit } = await this.post(
625
+ `/v1/permits/${encodeURIComponent(permitId)}/revoke`,
626
+ body
627
+ );
628
+ return { permit: wire, rateLimit };
629
+ }
630
+ /**
631
+ * Verify a permit through the canonical REST surface
632
+ * (`POST /v1/permits/{permitId}/verify`).
633
+ *
634
+ * Returns the unified verification envelope (`valid`,
635
+ * `verification_type: 'permit'`, `reason`, `verified_at`, `evidence`)
636
+ * plus the full {@link PermitRecord} fields preserved at the top
637
+ * level. The `valid` field is the contract — pin to it.
638
+ *
639
+ * A `valid: false` is **not** thrown when the server returns 200 with
640
+ * a denial reason (matches the verify-shape unification on the wire);
641
+ * it is thrown on 4xx (`404` not found, `410` expired/consumed).
642
+ */
643
+ async verifyPermitById(permitId) {
644
+ if (!permitId) {
645
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
646
+ }
647
+ const { body: wire, rateLimit } = await this.post(`/v1/permits/${encodeURIComponent(permitId)}/verify`, {});
648
+ const { valid, verification_type, reason, verified_at, evidence, ...row } = wire;
649
+ return {
650
+ valid,
651
+ verification_type,
652
+ reason,
653
+ verified_at,
654
+ evidence,
655
+ permit: row,
656
+ rateLimit
657
+ };
658
+ }
659
+ /**
660
+ * Get a single permit's full lifecycle state.
661
+ *
662
+ * Calls `GET /v1/permits/{permitId}` (the canonical REST surface).
663
+ * Returns `status`, all timestamps, `revoked_at` / `revoked_by` /
664
+ * `revoke_reason` (when applicable), and the bound `payload_hash`
665
+ * / `decision_id`.
666
+ *
667
+ * Operator-facing introspection — answers "what state is this permit
668
+ * in, and why?" without reading audit logs.
669
+ *
670
+ * Throws {@link AtlaSentError} on `404` (permit not in calling org)
671
+ * or `410` (expired before retrieval).
672
+ */
673
+ async getPermit(permitId) {
674
+ if (!permitId) {
675
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
676
+ }
677
+ const { body: wire, rateLimit } = await this.get(
678
+ `/v1/permits/${encodeURIComponent(permitId)}`
679
+ );
680
+ return { permit: wire, rateLimit };
681
+ }
682
+ /**
683
+ * Poll whether a permit is currently valid.
684
+ *
685
+ * Calls `GET /v1/permits/{permitId}/valid` — a lightweight read
686
+ * returning only the status snapshot optimised for guard heartbeat
687
+ * polling. Guards with `permitRevalidationIntervalMs` set race this
688
+ * against `tool.execute()` and throw {@link PermitRevoked} when
689
+ * `status === "revoked"` arrives.
690
+ *
691
+ * Throws {@link AtlaSentError} on transport / auth failures.
692
+ */
693
+ async checkPermitValid(permitId) {
694
+ if (!permitId) {
695
+ throw new AtlaSentError("permitId is required", { code: "bad_request" });
696
+ }
697
+ const { body } = await this.get(
698
+ `/v1/permits/${encodeURIComponent(permitId)}/valid`
699
+ );
700
+ return body;
701
+ }
702
+ /**
703
+ * List permits issued to the calling org, most-recently-issued first.
704
+ *
705
+ * Calls `GET /v1/permits` (the canonical REST surface). Cursor-paged.
706
+ * Filters narrow on server side; pagination uses the `created_at`
707
+ * timestamp opaquely (`nextCursor`).
708
+ *
709
+ * Designed for incident review, debugging, and compliance
710
+ * reconstruction.
711
+ */
712
+ async listPermits(input = {}) {
713
+ const params = new URLSearchParams();
714
+ if (input.status) params.set("status", input.status);
715
+ if (input.actorId) params.set("actor_id", input.actorId);
716
+ if (input.actionType) params.set("action_type", input.actionType);
717
+ if (input.from) params.set("from", input.from);
718
+ if (input.to) params.set("to", input.to);
719
+ if (input.limit !== void 0) params.set("limit", String(input.limit));
720
+ if (input.cursor) params.set("cursor", input.cursor);
721
+ const { body: wire, rateLimit } = await this.get("/v1/permits", params);
722
+ if (!Array.isArray(wire.permits)) {
723
+ throw new AtlaSentError(
724
+ "Malformed response from /v1/permits: missing `permits` array",
725
+ { code: "bad_response" }
726
+ );
727
+ }
728
+ const result = {
729
+ permits: wire.permits,
730
+ total: typeof wire.total === "number" ? wire.total : wire.permits.length,
731
+ rateLimit
732
+ };
733
+ if (wire.next_cursor !== void 0) result.nextCursor = wire.next_cursor;
734
+ return result;
735
+ }
159
736
  /**
160
737
  * Self-introspection: ask the server to describe the API key this
161
738
  * client was constructed with. Returns the key's ID, organization,
@@ -170,9 +747,7 @@ var AtlaSentClient = class {
170
747
  * taxonomy as {@link AtlaSentClient.evaluate}.
171
748
  */
172
749
  async keySelf() {
173
- const { body: wire, rateLimit } = await this.get(
174
- "/v1-api-key-self"
175
- );
750
+ const { body: wire, rateLimit } = await this.get("/v1-api-key-self");
176
751
  if (typeof wire.key_id !== "string" || typeof wire.organization_id !== "string") {
177
752
  throw new AtlaSentError(
178
753
  "Malformed response from /v1-api-key-self: missing `key_id` or `organization_id`",
@@ -247,8 +822,129 @@ var AtlaSentClient = class {
247
822
  }
248
823
  return { ...wire, rateLimit };
249
824
  }
250
- async post(path, body) {
251
- return this.request(path, "POST", body, void 0);
825
+ /**
826
+ * Open a streaming evaluation session against `POST /v1-evaluate-stream`.
827
+ *
828
+ * Yields {@link StreamDecisionEvent} and {@link StreamProgressEvent} objects
829
+ * as the server emits them. The iterator ends cleanly when the server sends
830
+ * `event: done`; it throws {@link AtlaSentError} on transport errors or when
831
+ * the server sends `event: error`.
832
+ *
833
+ * The final {@link StreamDecisionEvent} (isFinal: true) carries a `permitId`
834
+ * suitable for passing to {@link verifyPermit} after the stream closes.
835
+ *
836
+ * Hardening:
837
+ * - Throws {@link StreamTimeoutError} when no event arrives within
838
+ * `opts.timeoutMs` (default 30 s). Pass `0` to disable.
839
+ * - Retries up to `opts.maxRetries` times (default 3) with 1 s / 2 s / 4 s
840
+ * delays on network drop (before a terminal event). Sends `Last-Event-ID`
841
+ * on reconnect when the server has emitted event IDs.
842
+ * - Throws {@link StreamParseError} on partial / malformed JSON rather than
843
+ * crashing with a raw `SyntaxError`.
844
+ * - Closes cleanly on `event: done` or a decision event with `done: true`.
845
+ *
846
+ * ```ts
847
+ * for await (const event of client.protectStream({ agent, action })) {
848
+ * if (event.type === "decision" && event.isFinal) {
849
+ * await client.verifyPermit({ permitId: event.permitId });
850
+ * }
851
+ * }
852
+ * ```
853
+ */
854
+ async *protectStream(input, opts = {}) {
855
+ const streamTimeoutMs = opts.timeoutMs ?? 3e4;
856
+ const maxRetries = opts.maxRetries ?? 3;
857
+ const body = {
858
+ action: input.action,
859
+ agent: input.agent,
860
+ context: input.context ?? {},
861
+ api_key: this.apiKey
862
+ };
863
+ const requestId = globalThis.crypto.randomUUID();
864
+ const url = `${this.baseUrl}/v1-evaluate-stream`;
865
+ let lastEventId;
866
+ let retryCount = 0;
867
+ while (true) {
868
+ const headers = {
869
+ Accept: "text/event-stream",
870
+ "Content-Type": "application/json",
871
+ Authorization: `Bearer ${this.apiKey}`,
872
+ "User-Agent": this.userAgent,
873
+ "X-Request-ID": requestId
874
+ };
875
+ if (lastEventId !== void 0) {
876
+ headers["Last-Event-ID"] = lastEventId;
877
+ }
878
+ const connectionTimeoutSignal = AbortSignal.timeout(this.timeoutMs);
879
+ const signal = opts.signal ? AbortSignal.any([connectionTimeoutSignal, opts.signal]) : connectionTimeoutSignal;
880
+ let response;
881
+ try {
882
+ response = await this.fetchImpl(url, {
883
+ method: "POST",
884
+ headers,
885
+ body: JSON.stringify(body),
886
+ signal
887
+ });
888
+ } catch (err) {
889
+ const mapped = mapFetchError(err, requestId);
890
+ if (mapped.code === "network" && retryCount < maxRetries) {
891
+ retryCount++;
892
+ await sleep(1e3 * Math.pow(2, retryCount - 1));
893
+ continue;
894
+ }
895
+ throw mapped;
896
+ }
897
+ if (!response.ok) {
898
+ throw await buildHttpError(response, requestId);
899
+ }
900
+ if (!response.body) {
901
+ throw new AtlaSentError("Expected streaming body from AtlaSent API", {
902
+ code: "bad_response",
903
+ status: response.status,
904
+ requestId
905
+ });
906
+ }
907
+ let streamDone = false;
908
+ let networkDrop = false;
909
+ try {
910
+ for await (const event of parseSseStream(
911
+ response.body,
912
+ requestId,
913
+ streamTimeoutMs,
914
+ (id) => {
915
+ lastEventId = id;
916
+ }
917
+ )) {
918
+ yield event;
919
+ if (event.type === "decision" && event.isFinal) {
920
+ streamDone = true;
921
+ }
922
+ }
923
+ streamDone = true;
924
+ } catch (err) {
925
+ if (err instanceof AtlaSentError && err.code === "network") {
926
+ networkDrop = true;
927
+ } else {
928
+ throw err;
929
+ }
930
+ }
931
+ if (streamDone) break;
932
+ if (networkDrop && retryCount < maxRetries) {
933
+ retryCount++;
934
+ await sleep(1e3 * Math.pow(2, retryCount - 1));
935
+ continue;
936
+ }
937
+ if (networkDrop) {
938
+ throw new AtlaSentError(
939
+ `AtlaSent stream dropped after ${retryCount} reconnection attempts`,
940
+ { code: "network", requestId }
941
+ );
942
+ }
943
+ break;
944
+ }
945
+ }
946
+ async post(path, body, query) {
947
+ return this.request(path, "POST", body, query);
252
948
  }
253
949
  async get(path, query) {
254
950
  return this.request(path, "GET", void 0, query);
@@ -260,48 +956,623 @@ var AtlaSentClient = class {
260
956
  const headers = {
261
957
  Accept: "application/json",
262
958
  Authorization: `Bearer ${this.apiKey}`,
263
- "User-Agent": `@atlasent/sdk/${SDK_VERSION} node/${process.version}`,
959
+ "User-Agent": this.userAgent,
264
960
  "X-Request-ID": requestId
265
961
  };
266
962
  if (method === "POST") headers["Content-Type"] = "application/json";
267
- const init = {
268
- method,
269
- headers,
270
- signal: AbortSignal.timeout(this.timeoutMs)
271
- };
272
- if (method === "POST") init.body = JSON.stringify(body);
273
- let response;
274
- try {
275
- response = await this.fetchImpl(url, init);
276
- } catch (err) {
277
- throw mapFetchError(err, requestId);
963
+ const bodyStr = method === "POST" ? JSON.stringify(body) : void 0;
964
+ for (let attempt = 0; ; attempt++) {
965
+ const init = {
966
+ method,
967
+ headers,
968
+ signal: AbortSignal.timeout(this.timeoutMs)
969
+ };
970
+ if (bodyStr !== void 0) init.body = bodyStr;
971
+ let response;
972
+ try {
973
+ response = await this.fetchImpl(url, init);
974
+ } catch (err) {
975
+ const mapped = mapFetchError(err, requestId);
976
+ if (isRetryable(mapped) && hasAttemptsLeft(attempt, this.retryPolicy)) {
977
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, mapped));
978
+ continue;
979
+ }
980
+ throw mapped;
981
+ }
982
+ if (!response.ok) {
983
+ const httpErr = await buildHttpError(response, requestId);
984
+ if (isRetryable(httpErr) && hasAttemptsLeft(attempt, this.retryPolicy)) {
985
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, httpErr));
986
+ continue;
987
+ }
988
+ throw httpErr;
989
+ }
990
+ let parsed;
991
+ try {
992
+ parsed = await response.json();
993
+ } catch (err) {
994
+ const jsonErr = new AtlaSentError(
995
+ "Invalid JSON response from AtlaSent API",
996
+ {
997
+ code: "bad_response",
998
+ status: response.status,
999
+ requestId,
1000
+ cause: err
1001
+ }
1002
+ );
1003
+ if (isRetryable(jsonErr) && hasAttemptsLeft(attempt, this.retryPolicy)) {
1004
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, jsonErr));
1005
+ continue;
1006
+ }
1007
+ throw jsonErr;
1008
+ }
1009
+ if (parsed === null || typeof parsed !== "object") {
1010
+ const shapeErr = new AtlaSentError(
1011
+ "Expected a JSON object from AtlaSent API",
1012
+ {
1013
+ code: "bad_response",
1014
+ status: response.status,
1015
+ requestId
1016
+ }
1017
+ );
1018
+ if (isRetryable(shapeErr) && hasAttemptsLeft(attempt, this.retryPolicy)) {
1019
+ await sleep(computeBackoffMs(attempt, this.retryPolicy, shapeErr));
1020
+ continue;
1021
+ }
1022
+ throw shapeErr;
1023
+ }
1024
+ return {
1025
+ body: parsed,
1026
+ rateLimit: parseRateLimitHeaders(response.headers)
1027
+ };
278
1028
  }
279
- if (!response.ok) {
280
- throw await buildHttpError(response, requestId);
1029
+ }
1030
+ /**
1031
+ * Open a new HITL escalation. Bridges a `hold` outcome from
1032
+ * `protect()` to the approval queue: an agent that receives a
1033
+ * `hold` decision calls this to enroll the proposed action for
1034
+ * human review. The returned escalation can then be polled with
1035
+ * `getHitlEscalation()` or driven to terminal by
1036
+ * `approveHitlEscalation()` / `rejectHitlEscalation()`.
1037
+ *
1038
+ * Quorum, pool size, fallback decision and routing inherit from
1039
+ * the server-side policy when omitted from `input`.
1040
+ *
1041
+ * Calls `POST /v1/hitl`.
1042
+ */
1043
+ async createHitlEscalation(input) {
1044
+ const { body, rateLimit } = await this.post(
1045
+ "/v1/hitl",
1046
+ input
1047
+ );
1048
+ return { escalation: body, rateLimit };
1049
+ }
1050
+ /**
1051
+ * List HITL escalations for the calling org. Defaults to
1052
+ * `status=pending`; pass `status` to query other queues
1053
+ * (`escalated`, `approved`, `rejected`, `auto_approved`,
1054
+ * `timed_out`).
1055
+ *
1056
+ * Calls `GET /v1/hitl`.
1057
+ */
1058
+ async listHitlEscalations(input = {}) {
1059
+ const params = new URLSearchParams();
1060
+ if (input.status) params.set("status", input.status);
1061
+ if (input.agentId) params.set("agent_id", input.agentId);
1062
+ if (input.assignedToUserId)
1063
+ params.set("assigned_to_user_id", input.assignedToUserId);
1064
+ if (input.limit !== void 0) params.set("limit", String(input.limit));
1065
+ if (input.cursor) params.set("cursor", input.cursor);
1066
+ const { body, rateLimit } = await this.get(
1067
+ "/v1/hitl",
1068
+ params
1069
+ );
1070
+ return { data: body, rateLimit };
1071
+ }
1072
+ /**
1073
+ * Get a HITL escalation. The server payload includes a live
1074
+ * `quorum_progress` snapshot when the escalation is still open.
1075
+ *
1076
+ * Calls `GET /v1/hitl/:id`.
1077
+ */
1078
+ async getHitlEscalation(escalationId) {
1079
+ if (!escalationId) {
1080
+ throw new AtlaSentError("escalationId is required", {
1081
+ code: "bad_request"
1082
+ });
281
1083
  }
282
- let parsed;
283
- try {
284
- parsed = await response.json();
285
- } catch (err) {
286
- throw new AtlaSentError("Invalid JSON response from AtlaSent API", {
287
- code: "bad_response",
288
- status: response.status,
289
- requestId,
290
- cause: err
1084
+ const { body, rateLimit } = await this.get(
1085
+ `/v1/hitl/${encodeURIComponent(escalationId)}`
1086
+ );
1087
+ return { escalation: body, rateLimit };
1088
+ }
1089
+ /**
1090
+ * List per-approver vote rows for an escalation.
1091
+ * Calls `GET /v1/hitl/:id/approvals`.
1092
+ */
1093
+ async listHitlApprovals(escalationId) {
1094
+ const { body, rateLimit } = await this.get(`/v1/hitl/${encodeURIComponent(escalationId)}/approvals`);
1095
+ return { approvals: body.approvals ?? [], rateLimit };
1096
+ }
1097
+ /**
1098
+ * List the escalation chain hops for an escalation. Each `/escalate`
1099
+ * call appends one row.
1100
+ * Calls `GET /v1/hitl/:id/chain`.
1101
+ */
1102
+ async getHitlChain(escalationId) {
1103
+ const { body, rateLimit } = await this.get(
1104
+ `/v1/hitl/${encodeURIComponent(escalationId)}/chain`
1105
+ );
1106
+ return { chain: body.chain ?? [], rateLimit };
1107
+ }
1108
+ /**
1109
+ * Record an approve vote. Resolves the escalation only once the
1110
+ * server-side quorum count is satisfied; before that the response
1111
+ * carries a refreshed escalation row with the latest
1112
+ * `quorum_progress`.
1113
+ *
1114
+ * Calls `POST /v1/hitl/:id/approve`. The server returns 409
1115
+ * `duplicate_vote` if the same principal has already voted, and
1116
+ * 409 `already_rejected` if a concurrent reject crossed the line.
1117
+ */
1118
+ async approveHitlEscalation(escalationId, input = {}) {
1119
+ const { body, rateLimit } = await this.post(
1120
+ `/v1/hitl/${encodeURIComponent(escalationId)}/approve`,
1121
+ input
1122
+ );
1123
+ return { escalation: body, rateLimit };
1124
+ }
1125
+ /**
1126
+ * Record a reject vote. Reject is short-circuit terminal — a single
1127
+ * reject closes the escalation regardless of how many approves have
1128
+ * accumulated.
1129
+ *
1130
+ * Calls `POST /v1/hitl/:id/reject`.
1131
+ */
1132
+ async rejectHitlEscalation(escalationId, input = {}) {
1133
+ const { body, rateLimit } = await this.post(
1134
+ `/v1/hitl/${encodeURIComponent(escalationId)}/reject`,
1135
+ input
1136
+ );
1137
+ return { escalation: body, rateLimit };
1138
+ }
1139
+ /**
1140
+ * Re-route an open escalation to a higher tier. Bounded by the
1141
+ * escalation's `max_escalation_depth` — the server returns 409
1142
+ * `chain_exhausted` and applies the configured fallback decision
1143
+ * once the ceiling is hit.
1144
+ *
1145
+ * Calls `POST /v1/hitl/:id/escalate`.
1146
+ */
1147
+ async escalateHitlEscalation(escalationId, input) {
1148
+ const { body, rateLimit } = await this.post(
1149
+ `/v1/hitl/${encodeURIComponent(escalationId)}/escalate`,
1150
+ input
1151
+ );
1152
+ return { escalation: body, rateLimit };
1153
+ }
1154
+ /**
1155
+ * Manually apply the escalation's `fallback_decision`. Useful for
1156
+ * admin recovery of a hung escalation when the cron sweeper hasn't
1157
+ * run yet, or to short-circuit a stuck flow during incident
1158
+ * response.
1159
+ *
1160
+ * Calls `POST /v1/hitl/:id/timeout`.
1161
+ */
1162
+ async timeoutHitlEscalation(escalationId) {
1163
+ const { body, rateLimit } = await this.post(
1164
+ `/v1/hitl/${encodeURIComponent(escalationId)}/timeout`,
1165
+ {}
1166
+ );
1167
+ return { escalation: body, rateLimit };
1168
+ }
1169
+ /**
1170
+ * Run a named governance graph traversal query.
1171
+ *
1172
+ * Dispatches to `GET /v1/governance/graph/query?type=<queryType>`.
1173
+ * Each query type returns a different row shape — the return type
1174
+ * narrows automatically based on the literal `queryType` argument.
1175
+ *
1176
+ * `"user_approvals"` requires `params.actor_id` — the server returns
1177
+ * a 400 if it is absent.
1178
+ */
1179
+ async queryGovernanceGraph(queryType, params = {}) {
1180
+ const qs = new URLSearchParams({ type: queryType });
1181
+ if (params.actor_id) qs.set("actor_id", params.actor_id);
1182
+ const { body, rateLimit } = await this.get("/v1/governance/graph/query", qs);
1183
+ return { ...body, rateLimit };
1184
+ }
1185
+ /**
1186
+ * Reconstruct the multi-system execution timeline for a specific incident.
1187
+ *
1188
+ * Calls `GET /v1/governance/timeline/incident/{incidentId}`. Backed
1189
+ * server-side by `reconstruct_incident_chains_v2()`, which fixes the
1190
+ * `executor_id → actor_id` bug that silently produced empty timelines
1191
+ * in the original function.
1192
+ *
1193
+ * Returns full execution rows including the §13.1 columns
1194
+ * (`delegation_chain_id`, `replay_of_execution_id`, `incident_id`,
1195
+ * `policy_version_id`, `bundle_version_id`) alongside the actor
1196
+ * timeline and evidence rows.
1197
+ */
1198
+ async getIncidentTimeline(incidentId) {
1199
+ if (!incidentId) {
1200
+ throw new AtlaSentError("incidentId is required", {
1201
+ code: "bad_request"
291
1202
  });
292
1203
  }
293
- if (parsed === null || typeof parsed !== "object") {
294
- throw new AtlaSentError("Expected a JSON object from AtlaSent API", {
295
- code: "bad_response",
296
- status: response.status,
297
- requestId
1204
+ const { body, rateLimit } = await this.get(`/v1/governance/timeline/incident/${encodeURIComponent(incidentId)}`);
1205
+ return { ...body, rateLimit };
1206
+ }
1207
+ // ── Connector Management ─────────────────────────────────────────────────
1208
+ /**
1209
+ * List connectors registered for the calling org.
1210
+ * Calls `GET /v1/governance/connectors`.
1211
+ */
1212
+ async listConnectors(options = {}) {
1213
+ const params = new URLSearchParams();
1214
+ if (options.cursor) params.set("cursor", options.cursor);
1215
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1216
+ const { body, rateLimit } = await this.get("/v1/governance/connectors", params);
1217
+ const result = {
1218
+ connectors: body.connectors ?? [],
1219
+ total: body.total,
1220
+ rateLimit
1221
+ };
1222
+ if (body.next_cursor) result.nextCursor = body.next_cursor;
1223
+ return result;
1224
+ }
1225
+ /**
1226
+ * Register and install a new connector for the calling org.
1227
+ * Calls `POST /v1/governance/connectors`.
1228
+ */
1229
+ async installConnector(input) {
1230
+ const { body, rateLimit } = await this.post("/v1/governance/connectors", input);
1231
+ return { connector: body, rateLimit };
1232
+ }
1233
+ /**
1234
+ * Store encrypted credentials for a connector.
1235
+ * Calls `POST /v1/governance/connectors/{id}/authenticate`.
1236
+ */
1237
+ async authenticateConnector(connectorId, input) {
1238
+ if (!connectorId) {
1239
+ throw new AtlaSentError("connectorId is required", {
1240
+ code: "bad_request"
298
1241
  });
299
1242
  }
1243
+ const { body, rateLimit } = await this.post(
1244
+ `/v1/governance/connectors/${encodeURIComponent(connectorId)}/authenticate`,
1245
+ input
1246
+ );
300
1247
  return {
301
- body: parsed,
302
- rateLimit: parseRateLimitHeaders(response.headers)
1248
+ credential_id: body.credential_id,
1249
+ version: body.version,
1250
+ rateLimit
303
1251
  };
304
1252
  }
1253
+ /**
1254
+ * Trigger an incremental sync for a connector.
1255
+ * Calls `POST /v1/governance/connectors/{id}/sync`.
1256
+ */
1257
+ async syncConnector(connectorId) {
1258
+ if (!connectorId) {
1259
+ throw new AtlaSentError("connectorId is required", {
1260
+ code: "bad_request"
1261
+ });
1262
+ }
1263
+ const { body, rateLimit } = await this.post(`/v1/governance/connectors/${encodeURIComponent(connectorId)}/sync`, {});
1264
+ return { ...body, rateLimit };
1265
+ }
1266
+ /**
1267
+ * Revoke a connector and all its associated credentials.
1268
+ * Calls `POST /v1/governance/connectors/{id}/revoke`.
1269
+ */
1270
+ async revokeConnector(connectorId, reason) {
1271
+ if (!connectorId) {
1272
+ throw new AtlaSentError("connectorId is required", {
1273
+ code: "bad_request"
1274
+ });
1275
+ }
1276
+ const body = {};
1277
+ if (reason !== void 0) body.reason = reason;
1278
+ const { body: wire, rateLimit } = await this.post(
1279
+ `/v1/governance/connectors/${encodeURIComponent(connectorId)}/revoke`,
1280
+ body
1281
+ );
1282
+ return { ...wire, rateLimit };
1283
+ }
1284
+ /**
1285
+ * Rotate the credentials for a connector.
1286
+ * Calls `POST /v1/governance/connectors/{id}/rotate-credentials`.
1287
+ */
1288
+ async rotateConnectorCredentials(connectorId) {
1289
+ if (!connectorId) {
1290
+ throw new AtlaSentError("connectorId is required", {
1291
+ code: "bad_request"
1292
+ });
1293
+ }
1294
+ const { body, rateLimit } = await this.post(
1295
+ `/v1/governance/connectors/${encodeURIComponent(connectorId)}/rotate-credentials`,
1296
+ {}
1297
+ );
1298
+ return { ...body, rateLimit };
1299
+ }
1300
+ /**
1301
+ * List enforcement policies for the calling org, optionally filtered by connector type.
1302
+ * Calls `GET /v1/governance/enforcement-policies`.
1303
+ */
1304
+ async listEnforcementPolicies(connectorType) {
1305
+ const params = new URLSearchParams();
1306
+ if (connectorType) params.set("connector_type", connectorType);
1307
+ const { body, rateLimit } = await this.get("/v1/governance/enforcement-policies", params);
1308
+ return { policies: body.policies ?? [], total: body.total, rateLimit };
1309
+ }
1310
+ /**
1311
+ * Create or update a connector enforcement policy.
1312
+ * Calls `POST /v1/governance/enforcement-policies`.
1313
+ */
1314
+ async upsertEnforcementPolicy(input) {
1315
+ const { body, rateLimit } = await this.post("/v1/governance/enforcement-policies", input);
1316
+ return { policy: body, rateLimit };
1317
+ }
1318
+ // ── Organizational Risk Graph ─────────────────────────────────────────────
1319
+ /**
1320
+ * Trigger a fresh org-level risk score computation.
1321
+ * Calls `POST /v1/governance/risk/compute`.
1322
+ */
1323
+ async computeOrgRisk(options = {}) {
1324
+ const { body, rateLimit } = await this.post("/v1/governance/risk/compute", options);
1325
+ return { score: body, rateLimit };
1326
+ }
1327
+ /**
1328
+ * Retrieve the most recently computed risk score for the calling org.
1329
+ * Calls `GET /v1/governance/risk/latest`.
1330
+ */
1331
+ async getLatestOrgRisk() {
1332
+ const { body, rateLimit } = await this.get("/v1/governance/risk/latest");
1333
+ return { score: body.score ?? null, rateLimit };
1334
+ }
1335
+ /**
1336
+ * Page through historical org risk scores, most-recent first.
1337
+ * Calls `GET /v1/governance/risk/history`.
1338
+ */
1339
+ async listOrgRiskHistory(options = {}) {
1340
+ const params = new URLSearchParams();
1341
+ if (options.cursor) params.set("cursor", options.cursor);
1342
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1343
+ const { body, rateLimit } = await this.get("/v1/governance/risk/history", params);
1344
+ const result = {
1345
+ scores: body.scores ?? [],
1346
+ total: body.total,
1347
+ rateLimit
1348
+ };
1349
+ if (body.next_cursor) result.nextCursor = body.next_cursor;
1350
+ return result;
1351
+ }
1352
+ // ── Cross-Org Permission Negotiation ──────────────────────────────────────
1353
+ async checkCrossOrgPermission(req) {
1354
+ const { body } = await this.post(
1355
+ "/v1/cross-org/permissions/check",
1356
+ req
1357
+ );
1358
+ return body;
1359
+ }
1360
+ async listCrossOrgPermissionChecks(params) {
1361
+ const qs = new URLSearchParams();
1362
+ if (params?.source_org_id) qs.set("source_org_id", params.source_org_id);
1363
+ if (params?.target_org_id) qs.set("target_org_id", params.target_org_id);
1364
+ if (params?.allowed !== void 0)
1365
+ qs.set("allowed", String(params.allowed));
1366
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
1367
+ const { body } = await this.get("/v1/cross-org/permissions/checks", qs);
1368
+ return body.checks ?? [];
1369
+ }
1370
+ // ── Anomaly Response Automation ───────────────────────────────────────────
1371
+ async listAnomalyResponseRules() {
1372
+ const { body } = await this.get(
1373
+ "/v1/anomaly-response/rules"
1374
+ );
1375
+ return body.rules ?? [];
1376
+ }
1377
+ async createAnomalyResponseRule(req) {
1378
+ const { body } = await this.post(
1379
+ "/v1/anomaly-response/rules",
1380
+ req
1381
+ );
1382
+ return body;
1383
+ }
1384
+ async updateAnomalyResponseRule(id, updates) {
1385
+ const { body } = await this.post(
1386
+ `/v1/anomaly-response/rules/${encodeURIComponent(id)}/update`,
1387
+ updates
1388
+ );
1389
+ return body;
1390
+ }
1391
+ async deleteAnomalyResponseRule(id) {
1392
+ await this.post(
1393
+ `/v1/anomaly-response/rules/${encodeURIComponent(id)}/delete`,
1394
+ {}
1395
+ );
1396
+ }
1397
+ async triggerAnomalyResponse(req) {
1398
+ const { body } = await this.post(
1399
+ "/v1/anomaly-response/trigger",
1400
+ req
1401
+ );
1402
+ return body.events ?? [];
1403
+ }
1404
+ async listAnomalyResponseEvents(params) {
1405
+ const qs = new URLSearchParams();
1406
+ if (params?.execution_id) qs.set("execution_id", params.execution_id);
1407
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
1408
+ const { body } = await this.get(
1409
+ "/v1/anomaly-response/events",
1410
+ qs
1411
+ );
1412
+ return body.events ?? [];
1413
+ }
1414
+ // ── Budget Exception Workflows ────────────────────────────────────────────
1415
+ async listBudgetExceptions(params) {
1416
+ const qs = new URLSearchParams();
1417
+ if (params?.status) qs.set("status", params.status);
1418
+ if (params?.budget_policy_id)
1419
+ qs.set("budget_policy_id", params.budget_policy_id);
1420
+ if (params?.limit !== void 0) qs.set("limit", String(params.limit));
1421
+ if (params?.offset !== void 0) qs.set("offset", String(params.offset));
1422
+ const { body } = await this.get(
1423
+ "/v1/budget-exceptions",
1424
+ qs
1425
+ );
1426
+ return body.exceptions ?? [];
1427
+ }
1428
+ async getBudgetException(id) {
1429
+ const { body } = await this.get(
1430
+ `/v1/budget-exceptions/${encodeURIComponent(id)}`
1431
+ );
1432
+ return body;
1433
+ }
1434
+ async createBudgetException(req) {
1435
+ const { body } = await this.post(
1436
+ "/v1/budget-exceptions",
1437
+ req
1438
+ );
1439
+ return body;
1440
+ }
1441
+ async approveBudgetException(id, req) {
1442
+ const { body } = await this.post(
1443
+ `/v1/budget-exceptions/${encodeURIComponent(id)}/approve`,
1444
+ req
1445
+ );
1446
+ return body;
1447
+ }
1448
+ async rejectBudgetException(id, review_notes) {
1449
+ const { body } = await this.post(
1450
+ `/v1/budget-exceptions/${encodeURIComponent(id)}/reject`,
1451
+ { review_notes }
1452
+ );
1453
+ return body;
1454
+ }
1455
+ async cancelBudgetException(id) {
1456
+ const { body } = await this.post(
1457
+ `/v1/budget-exceptions/${encodeURIComponent(id)}/cancel`,
1458
+ {}
1459
+ );
1460
+ return body;
1461
+ }
1462
+ // ── Regulatory Escalation Chain ───────────────────────────────────────────
1463
+ async listRegulatoryAuthorityLevels() {
1464
+ const { body } = await this.get(
1465
+ "/v1/regulatory/authority-levels"
1466
+ );
1467
+ return body.levels ?? [];
1468
+ }
1469
+ async createRegulatoryAuthorityLevel(req) {
1470
+ const { body } = await this.post(
1471
+ "/v1/regulatory/authority-levels",
1472
+ req
1473
+ );
1474
+ return body;
1475
+ }
1476
+ async listRegulatoryEscalations(params) {
1477
+ const qs = new URLSearchParams();
1478
+ if (params?.status) qs.set("status", params.status);
1479
+ if (params?.subject_type) qs.set("subject_type", params.subject_type);
1480
+ if (params?.subject_id) qs.set("subject_id", params.subject_id);
1481
+ const { body } = await this.get(
1482
+ "/v1/regulatory/escalations",
1483
+ qs
1484
+ );
1485
+ return body.escalations ?? [];
1486
+ }
1487
+ async createRegulatoryEscalation(req) {
1488
+ const { body } = await this.post(
1489
+ "/v1/regulatory/escalations",
1490
+ req
1491
+ );
1492
+ return body;
1493
+ }
1494
+ async acknowledgeRegulatoryEscalation(id) {
1495
+ const { body } = await this.post(
1496
+ `/v1/regulatory/escalations/${encodeURIComponent(id)}/acknowledge`,
1497
+ {}
1498
+ );
1499
+ return body;
1500
+ }
1501
+ async resolveRegulatoryEscalation(id, resolution, resolution_details) {
1502
+ const { body } = await this.post(
1503
+ `/v1/regulatory/escalations/${encodeURIComponent(id)}/resolve`,
1504
+ { resolution, resolution_details }
1505
+ );
1506
+ return body;
1507
+ }
1508
+ async overrideRegulatoryEscalation(id, reason) {
1509
+ const { body } = await this.post(
1510
+ `/v1/regulatory/escalations/${encodeURIComponent(id)}/override`,
1511
+ { reason }
1512
+ );
1513
+ return body;
1514
+ }
1515
+ // ── Incentive Signal Feedback Loop ────────────────────────────────────────
1516
+ async listSignalActions(signal_id) {
1517
+ const { body } = await this.get(
1518
+ `/v1/governance/signals/${encodeURIComponent(signal_id)}/actions`
1519
+ );
1520
+ return body.actions ?? [];
1521
+ }
1522
+ async recordSignalAction(signal_id, req) {
1523
+ const { body } = await this.post(
1524
+ `/v1/governance/signals/${encodeURIComponent(signal_id)}/actions`,
1525
+ req
1526
+ );
1527
+ return body;
1528
+ }
1529
+ async recordSignalOutcome(signal_id, action_id, req) {
1530
+ const { body } = await this.post(
1531
+ `/v1/governance/signals/${encodeURIComponent(signal_id)}/actions/${encodeURIComponent(action_id)}/outcome`,
1532
+ req
1533
+ );
1534
+ return body;
1535
+ }
1536
+ async getSignalActionSummary() {
1537
+ const { body } = await this.get(
1538
+ "/v1/governance/signals/actions/summary"
1539
+ );
1540
+ return body;
1541
+ }
1542
+ // ── Cross-Org Impersonation ───────────────────────────────────────────────
1543
+ async listImpersonationGrants() {
1544
+ const { body } = await this.get(
1545
+ "/v1/cross-org/impersonation/grants"
1546
+ );
1547
+ return body.grants ?? [];
1548
+ }
1549
+ async createImpersonationGrant(req) {
1550
+ const { body } = await this.post(
1551
+ "/v1/cross-org/impersonation/grants",
1552
+ req
1553
+ );
1554
+ return body;
1555
+ }
1556
+ async revokeImpersonationGrant(id) {
1557
+ await this.post(
1558
+ `/v1/cross-org/impersonation/grants/${encodeURIComponent(id)}/revoke`,
1559
+ {}
1560
+ );
1561
+ }
1562
+ async issueImpersonationToken(grant_id, requested_duration_seconds) {
1563
+ const { body } = await this.post(
1564
+ `/v1/cross-org/impersonation/grants/${encodeURIComponent(grant_id)}/token`,
1565
+ { requested_duration_seconds }
1566
+ );
1567
+ return body;
1568
+ }
1569
+ async validateImpersonationToken(token) {
1570
+ const { body } = await this.post(
1571
+ "/v1/cross-org/impersonation/validate",
1572
+ { token }
1573
+ );
1574
+ return body;
1575
+ }
305
1576
  };
306
1577
  function parseRateLimitHeaders(headers) {
307
1578
  const rawLimit = headers.get("x-ratelimit-limit");
@@ -446,6 +1717,9 @@ function buildAuditEventsQuery(query) {
446
1717
  }
447
1718
  return params;
448
1719
  }
1720
+ function sleep(ms) {
1721
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1722
+ }
449
1723
  function parseRetryAfter(raw) {
450
1724
  if (!raw) return void 0;
451
1725
  const seconds = Number(raw);
@@ -457,13 +1731,133 @@ function parseRetryAfter(raw) {
457
1731
  }
458
1732
  return void 0;
459
1733
  }
1734
+ async function* parseSseStream(body, requestId, timeoutMs, onEventId) {
1735
+ const reader = body.getReader();
1736
+ const decoder = new TextDecoder("utf-8");
1737
+ let buf = "";
1738
+ async function readChunk() {
1739
+ if (timeoutMs <= 0) {
1740
+ return reader.read();
1741
+ }
1742
+ return new Promise((resolve2, reject) => {
1743
+ const timer = setTimeout(() => {
1744
+ reject(new StreamTimeoutError(timeoutMs));
1745
+ }, timeoutMs);
1746
+ reader.read().then(
1747
+ (result) => {
1748
+ clearTimeout(timer);
1749
+ resolve2(result);
1750
+ },
1751
+ (err) => {
1752
+ clearTimeout(timer);
1753
+ reject(err);
1754
+ }
1755
+ );
1756
+ });
1757
+ }
1758
+ try {
1759
+ for (; ; ) {
1760
+ let done;
1761
+ let value;
1762
+ try {
1763
+ const result = await readChunk();
1764
+ done = result.done;
1765
+ value = result.value;
1766
+ } catch (err) {
1767
+ if (err instanceof StreamTimeoutError) throw err;
1768
+ throw new AtlaSentError(
1769
+ `AtlaSent stream read failed: ${err instanceof Error ? err.message : String(err)}`,
1770
+ { code: "network", requestId, cause: err }
1771
+ );
1772
+ }
1773
+ if (done) break;
1774
+ buf += decoder.decode(value, { stream: true });
1775
+ let boundary;
1776
+ while ((boundary = buf.indexOf("\n\n")) !== -1) {
1777
+ const block = buf.slice(0, boundary);
1778
+ buf = buf.slice(boundary + 2);
1779
+ let eventType = "message";
1780
+ let data = "";
1781
+ let eventId;
1782
+ for (const line of block.split("\n")) {
1783
+ if (line.startsWith("event: ")) eventType = line.slice(7).trim();
1784
+ else if (line.startsWith("data: ")) data = line.slice(6);
1785
+ else if (line.startsWith("id: ")) eventId = line.slice(4).trim();
1786
+ else if (line.startsWith("id:")) eventId = line.slice(3).trim();
1787
+ }
1788
+ if (eventId !== void 0) onEventId(eventId);
1789
+ if (!data) continue;
1790
+ if (eventType === "done") return;
1791
+ let parsed;
1792
+ try {
1793
+ parsed = JSON.parse(data);
1794
+ } catch (err) {
1795
+ throw new StreamParseError(data, err);
1796
+ }
1797
+ if (eventType === "error") {
1798
+ const e = parsed;
1799
+ throw new AtlaSentError(
1800
+ e.message ?? "Stream error from AtlaSent API",
1801
+ {
1802
+ code: e.code ?? "server_error",
1803
+ requestId: e.request_id ?? requestId
1804
+ }
1805
+ );
1806
+ }
1807
+ if (eventType === "decision") {
1808
+ const d = parsed;
1809
+ if (typeof d.permitted !== "boolean" || typeof d.decision_id !== "string") {
1810
+ throw new AtlaSentError(
1811
+ "Malformed decision event from AtlaSent API",
1812
+ {
1813
+ code: "bad_response",
1814
+ requestId
1815
+ }
1816
+ );
1817
+ }
1818
+ const streamDecision = d.permitted ? "allow" : "deny";
1819
+ const isFinal = d.is_final ?? false;
1820
+ yield {
1821
+ type: "decision",
1822
+ decision: streamDecision,
1823
+ decision_canonical: streamDecision,
1824
+ permitId: d.decision_id,
1825
+ reason: d.reason ?? "",
1826
+ auditHash: d.audit_hash ?? "",
1827
+ timestamp: d.timestamp ?? "",
1828
+ isFinal
1829
+ };
1830
+ if (isFinal || d.done === true) return;
1831
+ } else if (eventType === "progress") {
1832
+ const p = parsed;
1833
+ yield {
1834
+ type: "progress",
1835
+ stage: String(p["stage"] ?? ""),
1836
+ ...p
1837
+ };
1838
+ if (p.done === true) return;
1839
+ } else {
1840
+ if (parsed !== null && typeof parsed === "object" && parsed.done === true) {
1841
+ return;
1842
+ }
1843
+ }
1844
+ }
1845
+ }
1846
+ if (buf.trim().length > 0) {
1847
+ throw new StreamParseError(buf);
1848
+ }
1849
+ } finally {
1850
+ reader.releaseLock();
1851
+ }
1852
+ }
460
1853
 
461
1854
  // src/protect.ts
462
1855
  var sharedClient = null;
463
1856
  var overrides = {};
464
1857
  function getClient() {
465
1858
  if (sharedClient) return sharedClient;
466
- const apiKey = overrides.apiKey ?? process.env.ATLASENT_API_KEY;
1859
+ const envApiKey = typeof process !== "undefined" && process.env ? process.env.ATLASENT_API_KEY : void 0;
1860
+ const apiKey = overrides.apiKey ?? envApiKey;
467
1861
  if (!apiKey) {
468
1862
  throw new AtlaSentError(
469
1863
  "AtlaSent is not configured. Set ATLASENT_API_KEY in the environment, or call atlasent.configure({ apiKey }).",
@@ -472,8 +1866,11 @@ function getClient() {
472
1866
  }
473
1867
  const options = { apiKey };
474
1868
  if (overrides.baseUrl !== void 0) options.baseUrl = overrides.baseUrl;
475
- if (overrides.timeoutMs !== void 0) options.timeoutMs = overrides.timeoutMs;
1869
+ if (overrides.timeoutMs !== void 0)
1870
+ options.timeoutMs = overrides.timeoutMs;
476
1871
  if (overrides.fetch !== void 0) options.fetch = overrides.fetch;
1872
+ if (overrides.retryPolicy !== void 0)
1873
+ options.retryPolicy = overrides.retryPolicy;
477
1874
  sharedClient = new AtlaSentClient(options);
478
1875
  return sharedClient;
479
1876
  }
@@ -482,10 +1879,42 @@ function wireDecisionToDenied(serverDecision) {
482
1879
  if (lower === "hold" || lower === "escalate") return lower;
483
1880
  return "deny";
484
1881
  }
1882
+ function sortKeysDeep(val) {
1883
+ if (Array.isArray(val)) return val.map(sortKeysDeep);
1884
+ if (val !== null && typeof val === "object") {
1885
+ return Object.keys(val).sort().reduce((acc, k) => {
1886
+ acc[k] = sortKeysDeep(val[k]);
1887
+ return acc;
1888
+ }, {});
1889
+ }
1890
+ return val;
1891
+ }
1892
+ async function computeExecutionHash(payload) {
1893
+ const sorted = sortKeysDeep(payload);
1894
+ const canonical = JSON.stringify(sorted);
1895
+ if (typeof globalThis !== "undefined" && globalThis.crypto?.subtle?.digest) {
1896
+ const bytes = new TextEncoder().encode(canonical);
1897
+ const buf = await globalThis.crypto.subtle.digest("SHA-256", bytes);
1898
+ return Array.from(new Uint8Array(buf)).map((b) => b.toString(16).padStart(2, "0")).join("");
1899
+ }
1900
+ try {
1901
+ const { createHash } = await import(
1902
+ /* @vite-ignore */
1903
+ /* webpackIgnore: true */
1904
+ "crypto"
1905
+ );
1906
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
1907
+ } catch {
1908
+ console.warn(
1909
+ "[atlasent] Could not compute execution_hash: neither crypto.subtle nor node:crypto is available in this runtime."
1910
+ );
1911
+ return "";
1912
+ }
1913
+ }
485
1914
  async function protect(request) {
486
1915
  const client = getClient();
487
1916
  const evaluation = await client.evaluate(request);
488
- if (evaluation.decision !== "ALLOW") {
1917
+ if (evaluation.decision !== "allow") {
489
1918
  throw new AtlaSentDeniedError({
490
1919
  decision: wireDecisionToDenied(evaluation.decision),
491
1920
  evaluationId: evaluation.permitId,
@@ -493,19 +1922,35 @@ async function protect(request) {
493
1922
  auditHash: evaluation.auditHash
494
1923
  });
495
1924
  }
1925
+ const environment = request.context?.environment ?? (() => {
1926
+ console.warn(
1927
+ "[atlasent] environment not set on evaluate request \u2014 defaulting to 'production'. Set context.environment explicitly to suppress."
1928
+ );
1929
+ return "production";
1930
+ })();
1931
+ const evaluatePayload = {
1932
+ action_type: request.action,
1933
+ actor_id: request.agent,
1934
+ context: request.context ?? {}
1935
+ };
1936
+ const execution_hash = await computeExecutionHash(evaluatePayload);
496
1937
  const verifyRequest = {
497
1938
  permitId: evaluation.permitId,
498
1939
  agent: request.agent,
499
- action: request.action
1940
+ action: request.action,
1941
+ environment,
1942
+ ...execution_hash ? { execution_hash } : {}
500
1943
  };
501
1944
  if (request.context !== void 0) verifyRequest.context = request.context;
502
1945
  const verification = await client.verifyPermit(verifyRequest);
503
1946
  if (!verification.verified) {
1947
+ const outcome = normalizePermitOutcome(verification.outcome);
504
1948
  throw new AtlaSentDeniedError({
505
1949
  decision: "deny",
506
1950
  evaluationId: evaluation.permitId,
507
1951
  reason: `Permit failed verification (${verification.outcome})`,
508
- auditHash: evaluation.auditHash
1952
+ auditHash: evaluation.auditHash,
1953
+ ...outcome !== void 0 && { outcome }
509
1954
  });
510
1955
  }
511
1956
  return {