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