@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/CHANGELOG.md CHANGED
@@ -14,6 +14,101 @@ Versions that were prepared but never reached npm are listed under
14
14
 
15
15
  ## [Unreleased]
16
16
 
17
+ ## [1.1.1] — 2026-12-04
18
+
19
+ ### Fixed
20
+
21
+ - **`npm install @sentisec/sdk` gets the `sentisec` CLI when `python3` is
22
+ too new.** The install step chooses a Python the CLI is built for, in the
23
+ same order as the one-line install: `SENTISEC_PYTHON` when set; `python3`
24
+ when its version is supported; else the newest of `python3.14`,
25
+ `python3.13`, `python3.12`, `python3.11` on `PATH`. It says which one it
26
+ chose and, when that is not `python3`, why. With none of them, it says
27
+ what it found and what is supported, and the library still installs.
28
+ - **`sentisec` keeps running on the Python chosen at install.** The
29
+ launcher runs the CLI with that interpreter, recorded in
30
+ `native/<platform>/<arch>/interpreter.json`, instead of whatever
31
+ `python3` names at run time; if that Python is removed, it says so and
32
+ names `npm rebuild -g @sentisec/sdk`. The `PYMINOR` file is gone.
33
+
34
+ ## [1.1.0] — 2026-11-22
35
+
36
+ ### Added
37
+
38
+ - **`Approvals` — finish a tool call that waits for a person's approval.**
39
+ `approvals.complete(create, body, { sessionId, waitMs })` sends the
40
+ request and, when the answer holds a call, reads its status until a
41
+ person decides, then re-sends the same request once with the
42
+ continuation header so the approved call runs exactly once;
43
+ `resume(create, pending, body)` does the same later from a stored
44
+ `PendingApproval`. `approvals.fetch()` does it inside `fetch`, so
45
+ openai-node, the AI SDK or Mastra keep their tool loop unchanged.
46
+ `pendingApprovals`, `pendingFromSse`, `planeOrigin` and `refusalOf` are
47
+ exported. Nothing is added to a message; the continuation travels only
48
+ in the header. The same flow as the Python SDK's `Approvals`.
49
+ - **A reply held for a decision (the in-band wait).** `complete` and
50
+ `approvals.fetch()` read a held reply to its end and report a call a
51
+ person settled while it waited: `outcome` `released` (under
52
+ `<call_id>_ib`) or `declined`, `rung: "in_band"`, `result.completed`
53
+ (`completedCalls(response)`); a re-send reports `rung: "handle"`. The
54
+ offer is read from the body (a held reply has no approval headers).
55
+ `IN_BAND_HEADER` and `HOLD_TIMEOUT_MS` are exported.
56
+ - **Answering a renamed call without running it.** `isBlocked(call)`,
57
+ `blockedCalls(response)`, `blockedResult(call)` and
58
+ `blockedResults(response)` for Chat, Messages and Responses.
59
+ - **Streams in `approvals.fetch()`.** A stream answer passes through
60
+ unchanged and live while its `: sentisec-verdict` comments are read; a
61
+ call still waiting when the stream ends goes to `onPending` (finish it
62
+ with `resume`). `completedFromSse` and `SseVerdicts` (incremental) are
63
+ exported; `complete` given a stream body throws a `TypeError` before
64
+ sending, instead of returning a stream it cannot read.
65
+
66
+ ### Changed
67
+
68
+ - **`approvals.fetch()` ends its wait at the caller's deadline.** The wait
69
+ inside `fetch` stops when the request's `AbortSignal` fires (openai-node's
70
+ `timeout`), and the loop gets the held answer instead of an abort that
71
+ openai-node would retry as a new request. The answer handed back is a
72
+ copy read to its end, so an abort after that point cannot break it.
73
+
74
+ ### Fixed
75
+
76
+ - **`wrapOpenAIStream` / `wrapAnthropicStream` send the client's key.**
77
+ They built their own request from `client.defaultHeaders`, which
78
+ openai-node 5–6 and current @anthropic-ai/sdk do not have, so every
79
+ stream went out with no key, got a 401, and came back as an empty
80
+ stream with no error. They now send the client's `apiKey` (Anthropic:
81
+ `x-api-key`, or `authToken` as a Bearer), its `defaultHeaders` when it
82
+ keeps a plain object of them and the call's own `options.headers` and
83
+ `signal`; a non-2xx answer throws `SentisecStreamError`.
84
+ - **The stream adapters no longer invent a verdict.** The last event's
85
+ `sentisec.verdict` was always `"PASS"`, whatever Sentisec decided. It is
86
+ now Sentisec's own label from its trailing comment (`NOMINAL`,
87
+ `ELEVATED`, `SUSPICIOUS`, `HIJACK`; `UNKNOWN` when none came), and
88
+ `sentisec.approval` carries the held calls (`pending`, `completed`).
89
+ `VerdictValue` gains those labels; `PASS`, `SANITIZE` and `PENDING` stay
90
+ in the type and are no longer produced.
91
+ - **`pendingFromSse` no longer reports a call released while the stream
92
+ waited as still pending.** It ignored the completion comment that
93
+ follows the offer.
94
+ - **`Monitor.wrap()` accepts current openai-node and @anthropic-ai/sdk
95
+ clients.** The detectors required a `defaultHeaders` object, which
96
+ openai-node 5–6 and current @anthropic-ai/sdk do not expose, so
97
+ `monitor.wrap(new OpenAI(...))` — the README's own example — threw "no
98
+ registered vendor adapter matched". `defaultHeaders` is now optional;
99
+ without it the session header rides each call's options.
100
+ - **A wrapped Anthropic client reaches the Messages route.** Its base URL
101
+ was `…/ws/<workspace>/v1`, and the Anthropic SDK appends `/v1/messages`
102
+ itself, so every call went to `…/v1/v1/messages` (404; hidden until now
103
+ because the detector rejected the real client first). The wrap now sets
104
+ `…/ws/<workspace>`; a literal `baseUrl` is still used as given, and the
105
+ Anthropic stream adapter accepts either form.
106
+ - **Wrapped clients pass per-call options through.** The wrapped
107
+ `chat.completions.create` / `messages.create` (and the stream adapters'
108
+ non-stream path) dropped the second argument, so headers such as
109
+ `X-Sentisec-Continuation` from `Approvals`, and a per-call `timeout` or
110
+ `signal`, never reached the request.
111
+
17
112
  ## [1.0.0] — 2026-10-17
18
113
 
19
114
  ### Changed (in the source, not yet in any published version)
package/README.md CHANGED
@@ -35,7 +35,8 @@ Resolution order, highest first:
35
35
  1. `wrap(client, { baseUrl })` — a literal, fully-formed URL for one
36
36
  wrap call. Nothing is appended to it.
37
37
  2. `new Monitor({ endpoint })` — a control-plane **host**; the SDK
38
- appends `/ws/<workspace>/v1`.
38
+ appends `/ws/<workspace>/v1` (OpenAI) or `/ws/<workspace>` (Anthropic,
39
+ whose client adds `/v1/messages` itself).
39
40
  3. `SENTISEC_ENDPOINT` — same host semantics, from the environment.
40
41
  4. the hosted default, `https://api.sentisec.ch`.
41
42
 
@@ -175,12 +176,23 @@ for await (const chunk of stream) {
175
176
  process.stdout.write(content);
176
177
 
177
178
  if (chunk.sentisec) {
178
- // Final chunk: verdict is attached.
179
+ // Final chunk: what Sentisec said about the turn.
179
180
  console.log("\nVerdict:", chunk.sentisec.verdict, chunk.sentisec.session_id);
180
181
  }
181
182
  }
182
183
  ```
183
184
 
185
+ The request carries what the client itself would send: its `apiKey`
186
+ (`Authorization: Bearer`; for Anthropic `x-api-key`, or `authToken` as a
187
+ Bearer), its `defaultHeaders` when it keeps a plain object of them, and the
188
+ call's own `options.headers`. A non-2xx answer throws `SentisecStreamError`
189
+ (`status`, `body`). `sentisec.verdict` on the last event is Sentisec's own
190
+ label for the turn (`NOMINAL`, `ELEVATED`, `SUSPICIOUS`, `HIJACK`), read
191
+ from its trailing SSE comment — `UNKNOWN` when it sent none, `ABORT` when
192
+ you aborted. `sentisec.approval`, when a call was held, lists the calls
193
+ still waiting (`pending`, with the handle `Approvals.resume` needs) and
194
+ those settled while the stream waited (`completed`).
195
+
184
196
  AbortSignal support:
185
197
 
186
198
  ```ts
@@ -232,6 +244,91 @@ for await (const event of stream) {
232
244
 
233
245
  ---
234
246
 
247
+ ## When a tool call waits for approval
248
+
249
+ A workspace can hold a consequential tool call until a person approves it.
250
+ Three things can happen to the reply, and the first two need no code:
251
+
252
+ - **The reply waits for the decision.** The reply is held open for the
253
+ workspace's window (45 seconds by default): a JSON reply sends `200` and
254
+ its headers at once, a space about every 10 seconds, then the JSON; a
255
+ stream sends its earlier frames, then an SSE comment about every 10
256
+ seconds (every SSE client skips it). Approved inside the window, the
257
+ call comes back in that same reply under the id `<call_id>_ib`; run it
258
+ and answer it under that id. openai-node's own
259
+ `timeout` stops counting once the headers arrive, so a plain client
260
+ waits through it; a total deadline of your own (`AbortSignal.timeout`,
261
+ a framework timeout) must be at least `HOLD_TIMEOUT_MS` (60 s).
262
+ - **The model is told the step is waiting.** Nobody decided in time (or a
263
+ person declined): the call comes back renamed `sentisec_tool_call_blocked`
264
+ with a plain-words `reason`. Nothing runs it: answer it with
265
+ `blockedResults(response)` (a short fixed result Sentisec replaces with
266
+ its ruling before the model reads it). The AI SDK and Mastra answer an
267
+ unknown tool with their own tool error, which Sentisec replaces the same way.
268
+ - **The app finishes it later**, around one call:
269
+
270
+ ```ts
271
+ import OpenAI from "openai";
272
+ import { Approvals, blockedResults, isBlocked } from "@sentisec/sdk";
273
+
274
+ const client = new OpenAI({ apiKey: KEY, baseURL: `https://api.sentisec.ch/ws/${WS}/v1` });
275
+ const approvals = Approvals.fromClient(client, { application: "refund-desk" }); // label optional
276
+
277
+ const result = await approvals.complete(
278
+ (body, options) => client.chat.completions.create(body, options),
279
+ { model, messages, tools },
280
+ { sessionId: ticketId }, // optional
281
+ );
282
+ const message = result.response.choices[0].message; // once approved, the call comes back released
283
+ messages.push(message);
284
+ for (const call of message.tool_calls ?? []) {
285
+ if (!isBlocked(call)) messages.push(await runMyTool(call)); // your own tools
286
+ }
287
+ messages.push(...blockedResults(result.response)); // renamed calls, answered, never run
288
+ ```
289
+
290
+ or inside `fetch`, for any fetch-based stack (openai-node, the AI SDK,
291
+ Mastra, LangChain.js) — the tool loop itself does not change:
292
+
293
+ ```ts
294
+ const approvals = new Approvals({ apiKey: KEY, endpoint: "https://api.sentisec.ch" });
295
+ const client = new OpenAI({ apiKey: KEY, baseURL: `https://api.sentisec.ch/ws/${WS}/v1`,
296
+ fetch: approvals.fetch({ sessionId: ticketId, onPending: store }) });
297
+ ```
298
+
299
+ `complete` reads a held reply to its end; when the answer still holds a
300
+ call, the helper reads its status with your key until a person decides
301
+ (15 minutes by default, `waitMs`), and once approved re-sends the same
302
+ request once with the `X-Sentisec-Continuation` header, so the call runs
303
+ exactly once. `result.outcome` says how it ended: `released` / `declined`
304
+ with `rung: "in_band"` (decided while the reply waited; `result.completed`
305
+ lists the calls), `approved_not_run` with `rung: "handle"` (re-sent),
306
+ `declined`, `lapsed`, `expired`, `revoked`, `released` (decided later,
307
+ nothing re-sent), or `waiting` (`waitMs` passed first). A re-send refused
308
+ with `409 continuation_refused` sets `refused` and returns the first answer.
309
+ Inside `fetch` the whole wait runs within one request, so the client's
310
+ deadline bounds it (openai-node's `timeout`, 10 minutes by default): when it
311
+ fires, the wait stops and the loop receives the held answer, nothing is
312
+ retried, and `onPending` has the offer. A ticket that ends first stores
313
+ `result.pending` (plain JSON) and later calls `approvals.resume(create,
314
+ pending, body)`. A held reply carries no `X-Sentisec-Approval` or
315
+ `X-Sentisec-Continuation` header; the helper reads `sentisec.approval` from
316
+ the body. The continuation travels only in a request header — never in a
317
+ message the model or your user sees; store a `PendingApproval` like a
318
+ credential for that one call.
319
+
320
+ Streams: the offer and the in-band completion ride SSE comments
321
+ (`: sentisec-verdict {...}`), which openai-node and @anthropic-ai/sdk skip.
322
+ Through `approvals.fetch()` a stream passes through unchanged and live; its
323
+ comments are read on the way, and a call still waiting when the stream ends
324
+ goes to `onPending` (finish it later with `approvals.resume(create, pending,
325
+ body)`). A call settled while the stream waited needs nothing: it is in the
326
+ stream under `<call_id>_ib`. `complete` reads JSON answers only (a stream
327
+ body throws a `TypeError` before anything is sent); `pendingFromSse`,
328
+ `completedFromSse` and `SseVerdicts` read the comments from raw text.
329
+
330
+ ---
331
+
235
332
  ## Policies
236
333
 
237
334
  Three built-in policy bundles ship with Phase 1:
@@ -262,10 +359,11 @@ replacements for each other.
262
359
  | Feature | TypeScript (`@sentisec/sdk`) | Python (`sentisec-sdk`) |
263
360
  |---|---|---|
264
361
  | Provider wrappers | `monitor.wrap(client)` dispatches to OpenAI or Anthropic and returns the same client. | `monitor.wrap_openai(client)` and `monitor.wrap_anthropic(client)` return the same client. |
265
- | Proxy destination | Appends `/ws/<customerId>/v1` to the endpoint host; `wrap(client, { baseUrl })` overrides the complete URL. | Appends `/v1/proxy/openai` or `/v1/proxy/anthropic` to the endpoint host. |
362
+ | Proxy destination | Appends `/ws/<customerId>/v1` (OpenAI) or `/ws/<customerId>` (Anthropic) to the endpoint host; `wrap(client, { baseUrl })` overrides the complete URL. | Appends `/v1/proxy/openai` or `/v1/proxy/anthropic` to the endpoint host. |
266
363
  | Configuration | `apiKey`, `model` and `task` are required constructor fields; `customerId` defaults to `cust_local`. Endpoint precedence is wrap override, constructor, environment, hosted default. | Resolves credentials from explicit arguments, environment and saved profiles; the endpoint falls back to the hosted default. |
267
364
  | Response handling | OpenAI HALT responses raise `SentisecHijackError`. Anthropic returns a synthetic block tool-use response by default, or raises `SentisecAnthropicBlockError` with `onBlock: "throw"`. | Thin wrappers rewrite the destination and API key; response handling remains with the provider client. |
268
- | Streaming | Separate `wrapOpenAIStream` and `wrapAnthropicStream` helpers expose verdict metadata and AbortSignal support. | Thin wrappers leave the provider client's streaming interface in place; no matching Sentisec streaming helpers are exported. |
365
+ | Streaming | Separate `wrapOpenAIStream` and `wrapAnthropicStream` helpers expose Sentisec's verdict label and held calls on the last event, and AbortSignal support. | Thin wrappers leave the provider client's streaming interface in place; no matching Sentisec streaming helpers are exported. |
366
+ | Calls held for approval | `Approvals`: `complete` / `resume` around a call, or `approvals.fetch()` for fetch-based stacks. | `Approvals`: `complete` / `resume`, sync and async. |
269
367
  | Session lifecycle and forensic export | `Monitor.session()`, `Session.wrap()` and `Session.exportForensicBundle()` are reserved methods that currently throw. Use `Monitor.wrap()` for provider calls. | Exports a frozen `Session` record; `Monitor` has no session lifecycle or forensic export methods. |
270
368
 
271
369
  Matching type names do not imply feature parity between the distributions.
@@ -277,7 +375,6 @@ Matching type names do not imply feature parity between the distributions.
277
375
  ```bash
278
376
  pnpm install # from repo root
279
377
  pnpm --filter @sentisec/sdk build # tsup → dist/
280
- pnpm --filter @sentisec/sdk test # vitest (36 tests)
281
378
  pnpm --filter @sentisec/sdk typecheck
282
379
  ```
283
380
 
package/bin/sentisec.js CHANGED
@@ -1,17 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
  // @sentisec/sdk → bin/sentisec
3
- // Delegates to the native Sentisec CLI binary installed by
4
- // scripts/install-binary.js (npm postinstall) into
5
- // node_modules/@sentisec/sdk/native/<platform>/<arch>/<pyminor>/sentisec.
3
+ // Runs the native Sentisec CLI that scripts/install-binary.js (npm
4
+ // postinstall) placed in
5
+ // node_modules/@sentisec/sdk/native/<platform>/<arch>/<pyminor>/sentisec,
6
+ // with the interpreter that script chose and recorded in
7
+ // native/<platform>/<arch>/interpreter.json — never with whatever python3
8
+ // names at run time.
6
9
  //
7
- // Soft-fail surface: if the binary is missing (e.g., the postinstall
8
- // soft-failed because python3 was unavailable, the platform/python tuple
9
- // wasn't published, or the user set SENTISEC_SKIP_POSTINSTALL), print a
10
- // clear recovery message and exit 1. The library import path
11
- // (`import { SentisecClient } from '@sentisec/sdk'`) is unaffected.
10
+ // Soft-fail surface: if the CLI or its interpreter is missing (e.g., the
11
+ // postinstall found no supported Python, the platform/python tuple wasn't
12
+ // published, the user set SENTISEC_SKIP_POSTINSTALL, or the chosen Python
13
+ // was uninstalled since), print a clear recovery message and exit 1. The
14
+ // library import path (`import { SentisecClient } from '@sentisec/sdk'`) is
15
+ // unaffected.
12
16
 
13
17
  import { spawn } from "node:child_process";
14
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
18
+ import { existsSync, readFileSync } from "node:fs";
15
19
  import { dirname, join } from "node:path";
16
20
  import { fileURLToPath } from "node:url";
17
21
 
@@ -26,6 +30,7 @@ const SUPPORTED_ARCHES = new Set(["arm64", "x64"]);
26
30
  const platform = process.platform;
27
31
  const arch = process.arch;
28
32
 
33
+ /** @param {string} reason @returns {never} */
29
34
  function printRecoveryAndExit(reason) {
30
35
  const lines = [
31
36
  `[sentisec] ${reason}`,
@@ -38,7 +43,7 @@ function printRecoveryAndExit(reason) {
38
43
  `[sentisec] pipx install sentisec-sdk`,
39
44
  `[sentisec]`,
40
45
  `[sentisec] Or re-run the npm postinstall after fixing the root cause:`,
41
- `[sentisec] npm rebuild @sentisec/sdk`,
46
+ `[sentisec] npm rebuild -g @sentisec/sdk (without -g for a project install)`,
42
47
  ];
43
48
  process.stderr.write(lines.join("\n") + "\n");
44
49
  process.exit(1);
@@ -60,65 +65,46 @@ if (!existsSync(nativeRoot)) {
60
65
  );
61
66
  }
62
67
 
63
- // Resolve which python-minor was installed. Prefer the PYMINOR marker file
64
- // written by install-binary.js; fall back to the highest py-minor directory
65
- // present (so the shim still works if a maintainer hand-dropped a binary).
66
- function resolvePyMinor() {
67
- const markerPath = join(nativeRoot, "PYMINOR");
68
- if (existsSync(markerPath)) {
69
- try {
70
- const value = readFileSync(markerPath, "utf8").trim();
71
- if (/^\d+\.\d+$/.test(value)) return value;
72
- } catch {
73
- // fall through to scan
74
- }
75
- }
76
- // Scan native/<platform>/<arch>/ for `3.11` / `3.12` / `3.13` subdirs.
77
- let candidates;
68
+ // Written by scripts/install-binary.js: { "python": <path>, "minor": "3.13" }.
69
+ const INTERPRETER_MARKER = "interpreter.json";
70
+
71
+ function readInterpreter() {
78
72
  try {
79
- candidates = readdirSync(nativeRoot).filter(
80
- (name) =>
81
- /^3\.\d+$/.test(name) &&
82
- (() => {
83
- try {
84
- return statSync(join(nativeRoot, name)).isDirectory();
85
- } catch {
86
- return false;
87
- }
88
- })()
89
- );
73
+ const data = JSON.parse(readFileSync(join(nativeRoot, INTERPRETER_MARKER), "utf8"));
74
+ if (typeof data?.python === "string" && /^\d+\.\d+$/.test(data?.minor ?? "")) {
75
+ return data;
76
+ }
90
77
  } catch {
91
- return null;
78
+ // missing or unreadable: reported below
92
79
  }
93
- if (candidates.length === 0) return null;
94
- // Highest minor wins (e.g., 3.13 > 3.12 > 3.11).
95
- candidates.sort((a, b) => {
96
- const am = parseInt(a.split(".")[1], 10);
97
- const bm = parseInt(b.split(".")[1], 10);
98
- return bm - am;
99
- });
100
- return candidates[0];
80
+ return null;
101
81
  }
102
82
 
103
- const pyMinor = resolvePyMinor();
104
- if (!pyMinor) {
83
+ const interpreter = readInterpreter();
84
+ if (!interpreter) {
105
85
  printRecoveryAndExit(
106
- `No installed CLI binary found under ${nativeRoot}. ` +
107
- `The npm postinstall fetcher did not place a binary here.`
86
+ `No installed CLI found under ${nativeRoot}: ${INTERPRETER_MARKER} is missing. ` +
87
+ `The npm postinstall did not place the CLI here.`
108
88
  );
109
89
  }
110
90
 
111
- const binaryPath = join(nativeRoot, pyMinor, "sentisec");
91
+ const binaryPath = join(nativeRoot, interpreter.minor, "sentisec");
112
92
  if (!existsSync(binaryPath)) {
93
+ printRecoveryAndExit(`Native CLI binary missing at ${binaryPath}.`);
94
+ }
95
+ if (!existsSync(interpreter.python)) {
113
96
  printRecoveryAndExit(
114
- `Native CLI binary missing at ${binaryPath}. ` +
115
- `The PYMINOR marker (${pyMinor}) points at a non-existent install.`
97
+ `The Python chosen at install, ${interpreter.python}, is no longer there.`
116
98
  );
117
99
  }
118
100
 
119
- const child = spawn(binaryPath, process.argv.slice(2), { stdio: "inherit" });
101
+ const child = spawn(interpreter.python, [binaryPath, ...process.argv.slice(2)], {
102
+ stdio: "inherit",
103
+ });
120
104
  child.on("error", (err) => {
121
- process.stderr.write(`[sentisec] Failed to launch ${binaryPath}: ${err.message}\n`);
105
+ process.stderr.write(
106
+ `[sentisec] Failed to launch ${interpreter.python} ${binaryPath}: ${err.message}\n`
107
+ );
122
108
  process.exit(1);
123
109
  });
124
110
  child.on("exit", (code, signal) => {