@sentisec/sdk 1.0.0 → 1.1.1

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
@@ -59,7 +59,9 @@ function isOpenAILike(client) {
59
59
  if (client === null || typeof client !== "object") return false;
60
60
  const c = client;
61
61
  if (typeof c.baseURL !== "string") return false;
62
- if (typeof c.defaultHeaders !== "object" || c.defaultHeaders === null) return false;
62
+ if (c.defaultHeaders !== void 0 && (typeof c.defaultHeaders !== "object" || c.defaultHeaders === null)) {
63
+ return false;
64
+ }
63
65
  const chat = c.chat;
64
66
  if (chat === void 0 || chat.completions === void 0) return false;
65
67
  if (typeof chat.completions.create !== "function") return false;
@@ -79,14 +81,14 @@ function wrapOpenAI(client, ctx, opts) {
79
81
  const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
80
82
  warnIfDiscardingExplicitBaseUrl(client.baseURL, proxyBaseUrl);
81
83
  client.baseURL = proxyBaseUrl;
82
- client.defaultHeaders = {
83
- ...client.defaultHeaders,
84
- "x-sentisec-session-id": ctx.sessionId
85
- };
84
+ const viaDefaults = typeof client.defaultHeaders === "object" && client.defaultHeaders !== null;
85
+ if (viaDefaults) {
86
+ client.defaultHeaders = { ...client.defaultHeaders, "x-sentisec-session-id": ctx.sessionId };
87
+ }
86
88
  const originalCreate = client.chat.completions.create.bind(client.chat.completions);
87
- client.chat.completions.create = async (params) => {
89
+ client.chat.completions.create = async (params, options) => {
88
90
  try {
89
- return await originalCreate(params);
91
+ return await originalCreate(params, viaDefaults ? options : withSessionHeader(options, ctx.sessionId));
90
92
  } catch (err) {
91
93
  const halt = await tryReadHaltBody(err);
92
94
  if (halt !== null) {
@@ -97,6 +99,13 @@ function wrapOpenAI(client, ctx, opts) {
97
99
  };
98
100
  return client;
99
101
  }
102
+ function withSessionHeader(options, sessionId) {
103
+ const headers = options?.["headers"];
104
+ if (headers !== void 0 && (typeof headers !== "object" || headers === null || Array.isArray(headers) || typeof Headers !== "undefined" && headers instanceof Headers)) {
105
+ return options ?? {};
106
+ }
107
+ return { ...options, headers: { "x-sentisec-session-id": sessionId, ...headers } };
108
+ }
100
109
  async function tryReadHaltBody(err) {
101
110
  if (err === null || typeof err !== "object") return null;
102
111
  const e = err;
@@ -145,7 +154,9 @@ function isAnthropicLike(client) {
145
154
  if (client === null || typeof client !== "object") return false;
146
155
  const c = client;
147
156
  if (typeof c.baseURL !== "string") return false;
148
- if (typeof c.defaultHeaders !== "object" || c.defaultHeaders === null) return false;
157
+ if (c.defaultHeaders !== void 0 && (typeof c.defaultHeaders !== "object" || c.defaultHeaders === null)) {
158
+ return false;
159
+ }
149
160
  const messages = c.messages;
150
161
  if (messages === void 0 || typeof messages.create !== "function") return false;
151
162
  if (c.chat !== void 0 && c.chat.completions !== void 0 && typeof c.chat.completions.create === "function") {
@@ -222,19 +233,20 @@ function wrapAnthropic(client, ctx, opts) {
222
233
  "wrap-anthropic: client failed isAnthropicLike() but the Anthropic adapter was selected \u2014 vendor-registry mismatch."
223
234
  );
224
235
  }
225
- const proxyBaseUrl = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
236
+ const resolved = resolveProxyBaseUrl(ctx.workspace, opts, ctx.endpoint);
237
+ const proxyBaseUrl = opts?.baseUrl !== void 0 ? resolved : resolved.replace(/\/v1\/?$/, "");
226
238
  warnIfDiscardingExplicitBaseUrl(client.baseURL, proxyBaseUrl);
227
239
  client.baseURL = proxyBaseUrl;
228
- client.defaultHeaders = {
229
- ...client.defaultHeaders,
230
- "x-sentisec-session-id": ctx.sessionId
231
- };
240
+ const viaDefaults = typeof client.defaultHeaders === "object" && client.defaultHeaders !== null;
241
+ if (viaDefaults) {
242
+ client.defaultHeaders = { ...client.defaultHeaders, "x-sentisec-session-id": ctx.sessionId };
243
+ }
232
244
  const onBlock = opts?.onBlock ?? "gated_return";
233
245
  const originalCreate = client.messages.create.bind(client.messages);
234
- client.messages.create = async (params) => {
246
+ client.messages.create = async (params, options) => {
235
247
  let response;
236
248
  try {
237
- response = await originalCreate(params);
249
+ response = await originalCreate(params, viaDefaults ? options : withSessionHeader(options, ctx.sessionId));
238
250
  } catch (err) {
239
251
  const rescued = tryRescueHaltEnvelopeFromError(err);
240
252
  if (rescued !== null) {
@@ -295,11 +307,232 @@ function installWrap(MonitorCtor) {
295
307
  }
296
308
  }
297
309
  throw new Error(
298
- `Monitor.wrap: no registered vendor adapter matched the client. Registered vendors: [${registry.map((e) => e.name).join(", ")}]. OpenAI shape requires {baseURL, defaultHeaders, chat.completions.create}; Anthropic shape requires {baseURL, defaultHeaders, messages.create}.`
310
+ `Monitor.wrap: no registered vendor adapter matched the client. Registered vendors: [${registry.map((e) => e.name).join(", ")}]. OpenAI shape requires {baseURL, chat.completions.create}; Anthropic shape requires {baseURL, messages.create}.`
299
311
  );
300
312
  };
301
313
  }
302
314
 
315
+ // src/offer.ts
316
+ var CONTINUATION_HEADER = "X-Sentisec-Continuation";
317
+ var REFUSED_HEADER = "X-Sentisec-Continuation-Refused";
318
+ var SESSION_HEADER = "x-session-id";
319
+ var APPLICATION_HEADER = "X-Sentisec-Application";
320
+ var IN_BAND_HEADER = "X-Sentisec-In-Band-Wait";
321
+ var str = (v) => typeof v === "string" && v ? v : void 0;
322
+ function fromCalls(calls, headerHandle) {
323
+ if (!Array.isArray(calls)) return [];
324
+ const out = [];
325
+ for (const entry of calls) {
326
+ const actionId = str(entry?.["action_id"]);
327
+ const statusUrl = str(entry?.["status_url"]);
328
+ if (!actionId || !statusUrl) continue;
329
+ const p = { actionId, statusUrl };
330
+ const reviewId = str(entry["review_id"]);
331
+ const callId = str(entry["call_id"]);
332
+ const continuation = str(entry["continuation"]);
333
+ if (reviewId) p.reviewId = reviewId;
334
+ if (callId) p.callId = callId;
335
+ if (continuation) p.continuation = continuation;
336
+ const exact = entry["exact_call"];
337
+ if (exact && typeof exact === "object") p.exactCall = exact;
338
+ out.push(p);
339
+ }
340
+ const only = out[0];
341
+ if (out.length === 1 && only && !only.continuation && headerHandle) only.continuation = headerHandle;
342
+ return out;
343
+ }
344
+ function approvalOf(body) {
345
+ return body?.sentisec?.approval;
346
+ }
347
+ function approvalCalls(body) {
348
+ const approval = approvalOf(body);
349
+ return approval?.status === "pending" ? approval.calls : void 0;
350
+ }
351
+ function bodyOf(response) {
352
+ const pair = response;
353
+ return pair && typeof pair === "object" && "data" in pair && pair.response ? pair.data : response;
354
+ }
355
+ function completedCalls(response) {
356
+ return completedFrom(approvalOf(bodyOf(response))?.completed);
357
+ }
358
+ function completedFrom(entries) {
359
+ if (!Array.isArray(entries)) return [];
360
+ const out = [];
361
+ for (const entry of entries) {
362
+ const callId = str(entry?.["call_id"]);
363
+ const outcome = str(entry?.["outcome"]);
364
+ if (!callId || !outcome) continue;
365
+ const c = { callId, outcome };
366
+ const rung = str(entry["rung"]);
367
+ const releasedAs = str(entry["released_as"]);
368
+ if (rung) c.rung = rung;
369
+ if (releasedAs) c.releasedAs = releasedAs;
370
+ out.push(c);
371
+ }
372
+ return out;
373
+ }
374
+ function pendingApprovals(response) {
375
+ const pair = response;
376
+ if (pair && typeof pair === "object" && "data" in pair && pair.response) {
377
+ const handle = pair.response.headers?.get?.(CONTINUATION_HEADER) ?? void 0;
378
+ return fromCalls(approvalCalls(pair.data), handle ?? void 0);
379
+ }
380
+ return fromCalls(approvalCalls(response));
381
+ }
382
+
383
+ // src/sse-verdicts.ts
384
+ var VERDICT_COMMENT = ": sentisec-verdict ";
385
+ var IN_BAND_COMMENT = ": sentisec-in-band-wait";
386
+ var SseVerdicts = class {
387
+ partial = "";
388
+ decoder = new TextDecoder();
389
+ announced = /* @__PURE__ */ new Map();
390
+ settled = [];
391
+ /** How many keep-alives arrived (`> 0`: the reply waited for a person). */
392
+ waits = 0;
393
+ /** The trailing verdict label, when the plane sent one. */
394
+ verdict;
395
+ /** Read one chunk; a line split across chunks is joined first. */
396
+ feed(chunk) {
397
+ const text = typeof chunk === "string" ? chunk : this.decoder.decode(chunk, { stream: true });
398
+ const lines = (this.partial + text).split("\n");
399
+ this.partial = lines.pop() ?? "";
400
+ for (const line of lines) this.line(line.replace(/\r$/, ""));
401
+ }
402
+ /** Read a last line that had no newline. */
403
+ close() {
404
+ const last = this.partial + this.decoder.decode();
405
+ this.partial = "";
406
+ if (last) this.line(last.replace(/\r$/, ""));
407
+ }
408
+ line(line) {
409
+ if (line === IN_BAND_COMMENT) {
410
+ this.waits += 1;
411
+ return;
412
+ }
413
+ if (!line.startsWith(VERDICT_COMMENT)) return;
414
+ let payload;
415
+ try {
416
+ payload = JSON.parse(line.slice(VERDICT_COMMENT.length));
417
+ } catch {
418
+ return;
419
+ }
420
+ if (!payload || typeof payload !== "object") return;
421
+ const approval = payload.approval;
422
+ if (approval && typeof approval === "object") {
423
+ if (approval.status === "pending") {
424
+ for (const p of fromCalls(approval.calls)) this.announced.set(p.actionId, p);
425
+ }
426
+ this.settled.push(...completedFrom(approval.completed));
427
+ } else if (typeof payload.verdict === "string") {
428
+ this.verdict = payload.verdict;
429
+ }
430
+ }
431
+ /** The calls still held at the point read so far (announced, not completed). */
432
+ get pending() {
433
+ const done = new Set(this.settled.map((c) => c.callId));
434
+ return [...this.announced.values()].filter((p) => !p.callId || !done.has(p.callId));
435
+ }
436
+ /** The calls a person settled while the stream waited. */
437
+ get completed() {
438
+ return [...this.settled];
439
+ }
440
+ };
441
+ function verdictsOf(stream) {
442
+ const verdicts = new SseVerdicts();
443
+ verdicts.feed(stream);
444
+ verdicts.close();
445
+ return verdicts;
446
+ }
447
+ function pendingFromSse(stream) {
448
+ return verdictsOf(stream).pending;
449
+ }
450
+ function completedFromSse(stream) {
451
+ return verdictsOf(stream).completed;
452
+ }
453
+ function tapSse(response, verdicts, onEnd) {
454
+ if (response.body === null) return response;
455
+ const tap = new TransformStream({
456
+ transform(chunk, controller) {
457
+ verdicts.feed(chunk);
458
+ controller.enqueue(chunk);
459
+ },
460
+ flush() {
461
+ verdicts.close();
462
+ onEnd?.();
463
+ }
464
+ });
465
+ return new Response(response.body.pipeThrough(tap), {
466
+ status: response.status,
467
+ statusText: response.statusText,
468
+ headers: response.headers
469
+ });
470
+ }
471
+
472
+ // src/stream-request.ts
473
+ var SentisecStreamError = class extends Error {
474
+ status;
475
+ body;
476
+ constructor(status, body) {
477
+ super(`Sentisec stream request failed with HTTP ${status}: ${body.slice(0, 200)}`);
478
+ this.name = "SentisecStreamError";
479
+ this.status = status;
480
+ this.body = body;
481
+ Object.setPrototypeOf(this, new.target.prototype);
482
+ }
483
+ };
484
+ async function readTail(reader, decoder, verdicts, ms = 1e3) {
485
+ const deadline = Date.now() + ms;
486
+ for (; ; ) {
487
+ const left = deadline - Date.now();
488
+ if (left <= 0) break;
489
+ let timer;
490
+ const late = new Promise((resolve) => {
491
+ timer = setTimeout(() => resolve("late"), left);
492
+ });
493
+ const next = await Promise.race([reader.read(), late]).catch(() => "late");
494
+ clearTimeout(timer);
495
+ if (next === "late") {
496
+ reader.cancel().catch(() => void 0);
497
+ break;
498
+ }
499
+ if (next.done) break;
500
+ verdicts.feed(decoder.decode(next.value, { stream: true }));
501
+ }
502
+ verdicts.close();
503
+ }
504
+ function requestHeaders(base, auth, client, options) {
505
+ const headers = { ...base, ...auth };
506
+ const add = (source) => {
507
+ if (typeof Headers !== "undefined" && source instanceof Headers) {
508
+ source.forEach((value, key) => {
509
+ headers[key] = value;
510
+ });
511
+ } else if (source && typeof source === "object" && !Array.isArray(source)) {
512
+ for (const [key, value] of Object.entries(source)) {
513
+ if (typeof value === "string") headers[key] = value;
514
+ }
515
+ }
516
+ };
517
+ add(client.defaultHeaders);
518
+ add(options?.["headers"]);
519
+ return headers;
520
+ }
521
+ function streamVerdict(verdicts, sessionId) {
522
+ const out = { verdict: verdicts.verdict ?? "UNKNOWN", session_id: sessionId };
523
+ const pending = verdicts.pending;
524
+ const completed = verdicts.completed;
525
+ if (pending.length > 0 || completed.length > 0) out.approval = { pending, completed };
526
+ return out;
527
+ }
528
+ function linkSignal(controller, ...signals) {
529
+ for (const signal of signals) {
530
+ if (signal instanceof AbortSignal) {
531
+ signal.addEventListener("abort", () => controller.abort(), { once: true });
532
+ }
533
+ }
534
+ }
535
+
303
536
  // src/streaming.ts
304
537
  function parseSSEChunk(raw) {
305
538
  const events = [];
@@ -357,7 +590,7 @@ function abortPromise(signal) {
357
590
  p.catch(() => void 0);
358
591
  return p;
359
592
  }
360
- async function* readSSEStream(response, signal) {
593
+ async function* readSSEStream(response, signal, verdicts) {
361
594
  const body = response.body;
362
595
  if (body === null) {
363
596
  yield { type: "done" };
@@ -408,7 +641,9 @@ async function* readSSEStream(response, signal) {
408
641
  return;
409
642
  }
410
643
  if (value !== void 0) {
411
- buffer += decoder.decode(value, { stream: true });
644
+ const text = decoder.decode(value, { stream: true });
645
+ verdicts?.feed(text);
646
+ buffer += text;
412
647
  }
413
648
  const splitIdx = buffer.lastIndexOf("\n\n");
414
649
  if (splitIdx === -1) continue;
@@ -417,6 +652,7 @@ async function* readSSEStream(response, signal) {
417
652
  const events = parseSSEChunk(complete);
418
653
  for (const ev of events) {
419
654
  if (ev.data === "[DONE]") {
655
+ if (verdicts !== void 0) await readTail(reader, decoder, verdicts);
420
656
  yield { type: "done" };
421
657
  return;
422
658
  }
@@ -430,9 +666,12 @@ async function* readSSEStream(response, signal) {
430
666
  reader.releaseLock();
431
667
  }
432
668
  }
433
- async function collectSSEEvents(response, signal) {
669
+ async function collectSSEEvents(response, signal, verdicts) {
670
+ if (!response.ok) {
671
+ throw new SentisecStreamError(response.status, await response.text().catch(() => ""));
672
+ }
434
673
  const events = [];
435
- const gen = readSSEStream(response, signal);
674
+ const gen = readSSEStream(response, signal, verdicts);
436
675
  for await (const ev of gen) {
437
676
  events.push(ev);
438
677
  if (ev.type === "done" || ev.type === "aborted") break;
@@ -450,27 +689,27 @@ function isOpenAIHaltChunk(chunk) {
450
689
  }
451
690
  function wrapOpenAIStream(client, sessionId, opts) {
452
691
  const originalCreate = client.chat.completions.create.bind(client.chat.completions);
453
- client.chat.completions.create = async function(params) {
692
+ client.chat.completions.create = async function(params, options) {
454
693
  if (params.stream !== true) {
455
- return originalCreate(params);
694
+ return originalCreate(params, options);
456
695
  }
457
- const url = `${client.baseURL}/chat/completions`;
458
- const headers = {
459
- "content-type": "application/json",
460
- accept: "text/event-stream",
461
- ...client.defaultHeaders
462
- };
696
+ const url = `${client.baseURL.replace(/\/+$/, "")}/chat/completions`;
697
+ const headers = requestHeaders(
698
+ { "content-type": "application/json", accept: "text/event-stream" },
699
+ typeof client.apiKey === "string" && client.apiKey ? { authorization: `Bearer ${client.apiKey}` } : {},
700
+ client,
701
+ options
702
+ );
463
703
  const abortController = new AbortController();
464
- if (opts?.signal !== void 0) {
465
- opts.signal.addEventListener("abort", () => abortController.abort(), { once: true });
466
- }
704
+ linkSignal(abortController, opts?.signal, options?.["signal"]);
467
705
  const response = await globalThis.fetch(url, {
468
706
  method: "POST",
469
707
  headers,
470
708
  body: JSON.stringify(params),
471
709
  signal: abortController.signal
472
710
  });
473
- const rawEvents = await collectSSEEvents(response, opts?.signal);
711
+ const verdicts = new SseVerdicts();
712
+ const rawEvents = await collectSSEEvents(response, opts?.signal, verdicts);
474
713
  const chunks = [];
475
714
  let aborted = false;
476
715
  for (const ev of rawEvents) {
@@ -507,7 +746,7 @@ function wrapOpenAIStream(client, sessionId, opts) {
507
746
  if (chunk === void 0) continue;
508
747
  if (i === lastIdx && !isOpenAIHaltChunk(chunk)) {
509
748
  const withVerdict = Object.assign({}, chunk, {
510
- sentisec: { verdict: "PASS", session_id: sessionId }
749
+ sentisec: streamVerdict(verdicts, sessionId)
511
750
  });
512
751
  output.push(withVerdict);
513
752
  } else if (isOpenAIHaltChunk(chunk)) {
@@ -562,28 +801,33 @@ function isAnthropicHaltEvent(event) {
562
801
  }
563
802
  function wrapAnthropicStream(client, sessionId, opts) {
564
803
  const originalCreate = client.messages.create.bind(client.messages);
565
- client.messages.create = async function(params) {
804
+ client.messages.create = async function(params, options) {
566
805
  if (params.stream !== true) {
567
- return originalCreate(params);
568
- }
569
- const url = `${client.baseURL}/messages`;
570
- const headers = {
571
- "content-type": "application/json",
572
- accept: "text/event-stream",
573
- "anthropic-version": "2023-06-01",
574
- ...client.defaultHeaders
575
- };
576
- const abortController = new AbortController();
577
- if (opts?.signal !== void 0) {
578
- opts.signal.addEventListener("abort", () => abortController.abort(), { once: true });
806
+ return originalCreate(params, options);
579
807
  }
808
+ const base = client.baseURL.replace(/\/+$/, "");
809
+ const url = base.endsWith("/v1") ? `${base}/messages` : `${base}/v1/messages`;
810
+ const auth = typeof client.apiKey === "string" && client.apiKey ? { "x-api-key": client.apiKey } : typeof client.authToken === "string" && client.authToken ? { authorization: `Bearer ${client.authToken}` } : {};
811
+ const headers = requestHeaders(
812
+ {
813
+ "content-type": "application/json",
814
+ accept: "text/event-stream",
815
+ "anthropic-version": "2023-06-01"
816
+ },
817
+ auth,
818
+ client,
819
+ options
820
+ );
821
+ const abortController = new AbortController();
822
+ linkSignal(abortController, opts?.signal, options?.["signal"]);
580
823
  const response = await globalThis.fetch(url, {
581
824
  method: "POST",
582
825
  headers,
583
826
  body: JSON.stringify(params),
584
827
  signal: abortController.signal
585
828
  });
586
- const rawEvents = await collectSSEEvents(response, opts?.signal);
829
+ const verdicts = new SseVerdicts();
830
+ const rawEvents = await collectSSEEvents(response, opts?.signal, verdicts);
587
831
  const output = [];
588
832
  let aborted = false;
589
833
  for (const ev of rawEvents) {
@@ -601,7 +845,7 @@ function wrapAnthropicStream(client, sessionId, opts) {
601
845
  if (anthropicEvent.type === "message_stop") {
602
846
  output.push({
603
847
  ...anthropicEvent,
604
- sentisec: { verdict: "PASS", session_id: sessionId }
848
+ sentisec: streamVerdict(verdicts, sessionId)
605
849
  });
606
850
  } else {
607
851
  output.push(anthropicEvent);
@@ -651,6 +895,282 @@ function wrapAnthropicStream(client, sessionId, opts) {
651
895
  return client;
652
896
  }
653
897
 
898
+ // src/approvals.ts
899
+ var HOLD_TIMEOUT_MS = 6e4;
900
+ var APPROVED = "approved_not_run";
901
+ var OPEN = /* @__PURE__ */ new Set(["waiting", "unknown"]);
902
+ var LEGACY = {
903
+ pending: "waiting",
904
+ armed: APPROVED,
905
+ consumed: "released",
906
+ declined: "declined",
907
+ revoked: "revoked",
908
+ expired: "expired"
909
+ };
910
+ function firstAnswer(first) {
911
+ const completed = completedCalls(first);
912
+ if (completed.length === 0) return { response: first, pending: [], resent: false, states: {}, completed };
913
+ const outcome = completed.some((c) => c.outcome === "released") ? "released" : completed[0]?.outcome ?? "released";
914
+ return { response: first, outcome, pending: [], resent: false, states: {}, rung: "in_band", completed };
915
+ }
916
+ function planeOrigin(baseUrl) {
917
+ const url = new URL(baseUrl);
918
+ let path = url.pathname;
919
+ for (const marker of ["/ws/", "/v1/"]) {
920
+ const cut = path.indexOf(marker);
921
+ if (cut >= 0) {
922
+ path = path.slice(0, cut);
923
+ break;
924
+ }
925
+ }
926
+ if (path.endsWith("/v1")) path = path.slice(0, -3);
927
+ return `${url.protocol}//${url.host}${path.replace(/\/+$/, "")}`;
928
+ }
929
+ function stateOf(status, body) {
930
+ if (status === 401 || status === 403 || status === 404) return "unavailable";
931
+ if (status !== 200 || !body || typeof body !== "object") return "unknown";
932
+ const b = body;
933
+ if (typeof b.outcome?.outcome === "string") return b.outcome.outcome;
934
+ return LEGACY[String(b.status)] ?? "unknown";
935
+ }
936
+ function summary(states) {
937
+ const values = Object.values(states);
938
+ if (values.includes(APPROVED)) return APPROVED;
939
+ if (values.some((v) => OPEN.has(v)) || values.length === 0) return "waiting";
940
+ return values[0] ?? "waiting";
941
+ }
942
+ function refusalOf(err) {
943
+ const e = err;
944
+ if ((e?.status ?? e?.response?.status) !== 409) return void 0;
945
+ const headers = e.headers ?? e.response?.headers;
946
+ if (!headers) return void 0;
947
+ if (typeof headers.get === "function") {
948
+ return headers.get(REFUSED_HEADER) ?? void 0;
949
+ }
950
+ const record = headers;
951
+ return record[REFUSED_HEADER.toLowerCase()] ?? record[REFUSED_HEADER];
952
+ }
953
+ var sleep = (ms, signal) => new Promise((resolve) => {
954
+ if (signal?.aborted) {
955
+ resolve();
956
+ return;
957
+ }
958
+ const done = () => {
959
+ clearTimeout(timer);
960
+ signal?.removeEventListener("abort", done);
961
+ resolve();
962
+ };
963
+ const timer = setTimeout(done, ms);
964
+ signal?.addEventListener("abort", done, { once: true });
965
+ });
966
+ var Approvals = class _Approvals {
967
+ origin;
968
+ apiKey;
969
+ application;
970
+ pollMs;
971
+ /** `apiKey` must be the key that sent the call; `endpoint` the plane root. */
972
+ constructor(opts) {
973
+ this.apiKey = opts.apiKey;
974
+ this.origin = planeOrigin(opts.endpoint);
975
+ this.application = opts.application;
976
+ this.pollMs = Math.max(1e3, opts.pollMs ?? 5e3);
977
+ }
978
+ /** From an OpenAI / Anthropic client already pointed at Sentisec. */
979
+ static fromClient(client, opts = {}) {
980
+ return new _Approvals({ apiKey: client.apiKey, endpoint: client.baseURL, ...opts });
981
+ }
982
+ labels(sessionId, handle) {
983
+ const headers = {};
984
+ if (this.application) headers[APPLICATION_HEADER] = this.application;
985
+ if (sessionId) headers[SESSION_HEADER] = sessionId;
986
+ if (handle) headers[CONTINUATION_HEADER] = handle;
987
+ return headers;
988
+ }
989
+ async read(p) {
990
+ try {
991
+ const resp = await fetch(
992
+ this.origin + p.statusUrl,
993
+ { headers: { Authorization: `Bearer ${this.apiKey}` } }
994
+ );
995
+ const after = Number(resp.headers.get("retry-after") ?? "") * 1e3;
996
+ const body = await resp.json().catch(() => void 0);
997
+ return [stateOf(resp.status, body), Math.max(this.pollMs, Number.isFinite(after) ? after : 0)];
998
+ } catch {
999
+ return ["unknown", this.pollMs];
1000
+ }
1001
+ }
1002
+ /** The held call's stored outcome now (one read). */
1003
+ async status(p) {
1004
+ return (await this.read(p))[0];
1005
+ }
1006
+ /** Read every held call until none is still deciding, `waitMs` passes, or `signal` aborts. */
1007
+ async wait(pending, waitMs = 9e5, signal) {
1008
+ const deadline = Date.now() + waitMs;
1009
+ const states = Object.fromEntries(pending.map((p) => [p.actionId, "waiting"]));
1010
+ for (; ; ) {
1011
+ let pause = this.pollMs;
1012
+ for (const p of pending) {
1013
+ if (OPEN.has(states[p.actionId] ?? "waiting")) {
1014
+ const [state, after] = await this.read(p);
1015
+ states[p.actionId] = state;
1016
+ pause = Math.max(pause, after);
1017
+ }
1018
+ }
1019
+ const left = deadline - Date.now();
1020
+ if (!Object.values(states).some((s) => OPEN.has(s)) || left <= 0 || signal?.aborted) return states;
1021
+ await sleep(Math.min(pause, left), signal);
1022
+ }
1023
+ }
1024
+ async resend(create, first, pending, states, body, sessionId) {
1025
+ const outcome = summary(states);
1026
+ const completed = first === void 0 ? [] : completedCalls(first);
1027
+ const approved = pending.find((p) => states[p.actionId] === APPROVED);
1028
+ if (!approved) return { response: first, outcome, pending, resent: false, states, completed };
1029
+ try {
1030
+ const again = await create(body, { headers: this.labels(sessionId, approved.continuation) });
1031
+ return { response: again, outcome, pending, resent: true, states, rung: "handle", completed };
1032
+ } catch (err) {
1033
+ const refused = refusalOf(err);
1034
+ if (refused === void 0) throw err;
1035
+ return { response: first, outcome, pending, resent: false, refused, states, completed };
1036
+ }
1037
+ }
1038
+ /** Send `body`; if a call is held, wait for its decision and re-send once (JSON, not streams). */
1039
+ async complete(create, body, opts = {}) {
1040
+ if (body?.stream === true) {
1041
+ throw new TypeError("complete() reads a JSON answer; for a stream give the client approvals.fetch({ onPending }) and resume() the offer it hands you");
1042
+ }
1043
+ const first = await create(body, { headers: this.labels(opts.sessionId) });
1044
+ const pending = pendingApprovals(first);
1045
+ if (pending.length === 0) return firstAnswer(first);
1046
+ const states = await this.wait(pending, opts.waitMs ?? 9e5);
1047
+ return this.resend(create, first, pending, states, body, opts.sessionId);
1048
+ }
1049
+ /** For stored calls: read their outcome (`waitMs` > 0 waits) and re-send `body` once if approved. */
1050
+ async resume(create, pending, body, opts = {}) {
1051
+ const states = await this.wait(pending, opts.waitMs ?? 0);
1052
+ return this.resend(create, void 0, pending, states, body, opts.sessionId);
1053
+ }
1054
+ /**
1055
+ * A `fetch` that completes held calls in place: a JSON answer holding a
1056
+ * call waits for the decision and, once approved, the identical request
1057
+ * is re-sent once with the handle; the caller receives the final answer.
1058
+ * A reply held open by the plane (rung i) is read to its end first.
1059
+ * `onPending` sees each held call (store it to resume after a restart).
1060
+ *
1061
+ * The whole wait runs inside one `fetch`, so the caller's deadline bounds
1062
+ * it: openai-node's `timeout` (default 10 min) or an `AbortSignal`. When it
1063
+ * aborts, the wait stops and the caller gets the held answer (the call
1064
+ * still waits; `onPending` has its offer). Give the client at least
1065
+ * `HOLD_TIMEOUT_MS` (60 s) so a held reply is read to its end.
1066
+ *
1067
+ * A stream answer passes through unchanged and live: the plane holds it
1068
+ * open itself while a person decides inside the window (rung i), and the
1069
+ * released call arrives in it under `<call_id>_ib`. Its comments are read
1070
+ * on the way; a call still waiting when the stream ends goes to
1071
+ * `onPending` (nothing is re-sent inside a stream the client already read).
1072
+ */
1073
+ fetch(opts = {}, inner = globalThis.fetch) {
1074
+ return async (input, init) => {
1075
+ const headers = new Headers(init?.headers);
1076
+ for (const [k, v] of Object.entries(this.labels(opts.sessionId))) {
1077
+ if (!headers.has(k)) headers.set(k, v);
1078
+ }
1079
+ const first = await inner(input, { ...init, headers });
1080
+ const type = first.headers.get("content-type") ?? "";
1081
+ if (type.includes("text/event-stream")) {
1082
+ const verdicts = new SseVerdicts();
1083
+ return tapSse(first, verdicts, () => {
1084
+ const pending2 = verdicts.pending;
1085
+ if (pending2.length > 0) opts.onPending?.(pending2);
1086
+ });
1087
+ }
1088
+ if (!type.includes("application/json")) return first;
1089
+ const text = await first.text();
1090
+ const copy = () => new Response(text, {
1091
+ status: first.status,
1092
+ statusText: first.statusText,
1093
+ headers: first.headers
1094
+ });
1095
+ let data;
1096
+ try {
1097
+ data = JSON.parse(text);
1098
+ } catch {
1099
+ return copy();
1100
+ }
1101
+ const pending = pendingApprovals({ data, response: first });
1102
+ if (pending.length === 0 || typeof init?.body !== "string") return copy();
1103
+ opts.onPending?.(pending);
1104
+ const signal = init?.signal ?? null;
1105
+ const states = await this.wait(pending, opts.waitMs ?? 9e5, signal);
1106
+ const approved = pending.find((p) => states[p.actionId] === APPROVED);
1107
+ if (!approved || signal?.aborted) return copy();
1108
+ if (approved.continuation) headers.set(CONTINUATION_HEADER, approved.continuation);
1109
+ const again = await inner(input, { ...init, headers });
1110
+ return again.status === 409 && again.headers.get(REFUSED_HEADER) ? copy() : again;
1111
+ };
1112
+ }
1113
+ };
1114
+
1115
+ // src/blocked.ts
1116
+ var BLOCKED_TOOL_NAME = "sentisec_tool_call_blocked";
1117
+ var NOT_RUN_RESULT = "This action has not run.";
1118
+ var nameOf = (v) => v?.name;
1119
+ function isBlocked(call) {
1120
+ const fn = call?.function;
1121
+ return (fn !== void 0 ? nameOf(fn) : nameOf(call)) === BLOCKED_TOOL_NAME;
1122
+ }
1123
+ function reasonOf(args) {
1124
+ let parsed = args;
1125
+ if (typeof args === "string") {
1126
+ try {
1127
+ parsed = JSON.parse(args);
1128
+ } catch {
1129
+ return void 0;
1130
+ }
1131
+ }
1132
+ return str(parsed?.reason);
1133
+ }
1134
+ var list = (v) => Array.isArray(v) ? v : [];
1135
+ function blockedCalls(response) {
1136
+ const body = bodyOf(response);
1137
+ if (!body || typeof body !== "object") return [];
1138
+ const out = [];
1139
+ for (const choice of list(body["choices"])) {
1140
+ for (const call of list(choice?.["message"]?.["tool_calls"])) {
1141
+ const fn = call?.["function"];
1142
+ const id = str(call?.["id"]);
1143
+ if (id && fn?.["name"] === BLOCKED_TOOL_NAME) out.push(withReason({ callId: id, wire: "chat" }, fn["arguments"]));
1144
+ }
1145
+ }
1146
+ for (const block of list(body["content"])) {
1147
+ const id = str(block?.["id"]);
1148
+ if (id && block["type"] === "tool_use" && block["name"] === BLOCKED_TOOL_NAME) {
1149
+ out.push(withReason({ callId: id, wire: "messages" }, block["input"]));
1150
+ }
1151
+ }
1152
+ for (const item of list(body["output"])) {
1153
+ const id = str(item?.["call_id"]);
1154
+ if (id && item["type"] === "function_call" && item["name"] === BLOCKED_TOOL_NAME) {
1155
+ out.push(withReason({ callId: id, wire: "responses" }, item["arguments"]));
1156
+ }
1157
+ }
1158
+ return out;
1159
+ }
1160
+ function withReason(call, args) {
1161
+ const reason = reasonOf(args);
1162
+ if (reason) call.reason = reason;
1163
+ return call;
1164
+ }
1165
+ function blockedResult(call) {
1166
+ if (call.wire === "messages") return { type: "tool_result", tool_use_id: call.callId, content: NOT_RUN_RESULT };
1167
+ if (call.wire === "responses") return { type: "function_call_output", call_id: call.callId, output: NOT_RUN_RESULT };
1168
+ return { role: "tool", tool_call_id: call.callId, content: NOT_RUN_RESULT };
1169
+ }
1170
+ function blockedResults(response) {
1171
+ return blockedCalls(response).map(blockedResult);
1172
+ }
1173
+
654
1174
  // src/index.ts
655
1175
  var SentisecError = class extends Error {
656
1176
  constructor(message) {
@@ -768,4 +1288,4 @@ Object.setPrototypeOf(SentisecHijackError.prototype, SentisecError.prototype);
768
1288
  Object.setPrototypeOf(SentisecAnthropicBlockError.prototype, SentisecError.prototype);
769
1289
  installWrap(Monitor);
770
1290
 
771
- export { BUILTIN_POLICIES, DEFAULT_ENDPOINT, DEFAULT_INGRESS_TEMPLATE, ENV_ENDPOINT, Monitor, SentisecAnthropicBlockError, SentisecError, SentisecHijackError, Session, TaskTamperError, UnknownPolicyError, VerifierBackendNotConfigured, WORKSPACE_PROXY_PATH, src_default as default, resolveProxyBaseUrl, wrapAnthropicStream, wrapOpenAIStream };
1291
+ export { APPLICATION_HEADER, Approvals, BLOCKED_TOOL_NAME, BUILTIN_POLICIES, CONTINUATION_HEADER, DEFAULT_ENDPOINT, DEFAULT_INGRESS_TEMPLATE, ENV_ENDPOINT, HOLD_TIMEOUT_MS, IN_BAND_HEADER, Monitor, NOT_RUN_RESULT, REFUSED_HEADER, SESSION_HEADER, SentisecAnthropicBlockError, SentisecError, SentisecHijackError, SentisecStreamError, Session, SseVerdicts, TaskTamperError, UnknownPolicyError, VerifierBackendNotConfigured, WORKSPACE_PROXY_PATH, blockedCalls, blockedResult, blockedResults, completedCalls, completedFromSse, src_default as default, isBlocked, pendingApprovals, pendingFromSse, planeOrigin, refusalOf, resolveProxyBaseUrl, wrapAnthropicStream, wrapOpenAIStream };