@datagusto/cli 0.2.0 → 0.2.2

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.
@@ -1,6 +1,6 @@
1
1
  # Datagusto Safety Plugin for Claude Code
2
2
 
3
- A Claude Code plugin that calls [Datagusto](https://datagusto.com) safety validation APIs to enforce guardrails on agent tool execution.
3
+ A Claude Code plugin that calls [Datagusto](https://datagusto.com) safety validation APIs to enforce guardrails on agent tool execution, and to check the user's prompts and Claude's final responses against the organization's policies (personal data, credentials, ...).
4
4
 
5
5
  This is the Claude Code port of the [OpenClaw plugin](../openclaw). Both plugins talk to the same Datagusto backend (the meta harness) and implement the same business semantics — proceed/block/ask/inject driven by the `/sessions/validate` response — but each maps that contract onto its own host framework's native hook vocabulary independently. See [Architecture](#architecture) and [Differences from the OpenClaw plugin](#differences-from-the-openclaw-plugin) for where the two diverge structurally.
6
6
 
@@ -43,7 +43,7 @@ for await (const message of query({
43
43
  })) { /* ... */ }
44
44
  ```
45
45
 
46
- Either path auto-discovers `.claude-plugin/plugin.json` and wires all seven hooks declared in `hooks/hooks.json` — there's nothing else to configure for loading. (Marketplace/npm distribution isn't set up here; both loading paths above work directly off a locally built directory.)
46
+ Either path auto-discovers `.claude-plugin/plugin.json` and wires all eight hooks declared in `hooks/hooks.json` — there's nothing else to configure for loading. (Marketplace/npm distribution isn't set up here; both loading paths above work directly off a locally built directory.)
47
47
 
48
48
  ## Testing (quickstart)
49
49
 
@@ -98,7 +98,7 @@ None of them is `required`, so Claude Code never blocks on a prompt for them. `d
98
98
  | `fail_closed` | `boolean` | `true` | Block tool execution when API calls fail |
99
99
  | `verbose` | `boolean` | `false` | Enable hook-by-hook logging to stderr |
100
100
  | `monitor_only` | `boolean` | `false` | Log deny/ask/block/inject/auto-approve decisions without enforcing them. OR-ed with the platform's per-agent monitoring mode — see [Platform monitoring mode](#platform-monitoring-mode) |
101
- | `auto_approve_vetted_permissions` | `boolean` | `false` | Auto-resolve Claude Code's native `PermissionRequest` dialog when `PreToolUse` already vetted the same call — see [`PermissionRequest`](#4-permissionrequest--auto-resolving-the-native-dialog) below |
101
+ | `auto_approve_vetted_permissions` | `boolean` | `false` | Auto-resolve Claude Code's native `PermissionRequest` dialog when `PreToolUse` already vetted the same call — see [`PermissionRequest`](#5-permissionrequest--auto-resolving-the-native-dialog) below |
102
102
 
103
103
  ### Dev fallback: running without a plugin host
104
104
 
@@ -134,20 +134,42 @@ If you'd rather not load this as a plugin, the compiled script can still be wire
134
134
 
135
135
  ## How It Works
136
136
 
137
- The plugin handles seven Claude Code hook events. Each invocation is a separate process: it reads one JSON payload from stdin, does its work, writes a decision to stdout, and exits.
137
+ The plugin handles eight Claude Code hook events. Each invocation is a separate process: it reads one JSON payload from stdin, does its work, writes a decision to stdout, and exits.
138
138
 
139
139
  ### 1. `SessionStart` — Eager Tool Registration
140
140
 
141
141
  Fires once per session (new, resumed, or post-compact). Sends the bundled built-in tool catalog (see [Built-in tool catalog](#built-in-tool-catalog)) to `POST /api/v1/public/safety/tools/register`, hash-gated so it's a no-op once already registered. Decouples registration from the first user prompt — a session that only ever runs slash commands still gets its tools registered.
142
142
 
143
- ### 2. `UserPromptSubmit` — Alignment (+ Registration Fallback)
143
+ ### 2. `UserPromptSubmit` — Alignment + Prompt Inspection (+ Registration Fallback)
144
144
 
145
145
  Fires once per user turn, before the prompt reaches the model:
146
146
 
147
147
  - **Alignment**: Sends `payload.prompt` — the raw user instruction, no parsing needed — to `POST /api/v1/public/safety/sessions/alignment`. The returned `session_id` is persisted for subsequent validation calls. Prompts that are slash commands (`/compact`) or bash-mode shortcuts (`!ls`) are skipped.
148
+ - **Prompt inspection**: Then sends the prompt to `POST /api/v1/public/safety/sessions/inspect` with `evaluation_point: "on_prompt_submit"`, which runs the organization's policies for that point (deterministic detectors such as personal data or credentials; no LLM). It runs after alignment because it needs the session alignment created, and unlike alignment it is not deduplicated: re-sending a blocked prompt is blocked again. Only a bare slash command (`/compact`, no arguments) skips inspection: command arguments, a prompt that starts with a path, and bash-mode input (`!...`) are all inspected, since any of them can carry a secret.
148
149
  - **Tool registration**: Repeats the same hash-gated registration `SessionStart` already does, as a cheap defense-in-depth fallback.
149
150
 
150
- ### 3. `PreToolUse` — Pre-execution Validation
151
+ | Inspection result | Claude Code response |
152
+ |---------|-----------------------|
153
+ | `should_proceed: false` | `{ "decision": "block", "reason": ... }`. The prompt never reaches Claude. The reason, shown to the user, names the policy, its statement and the detected type (e.g. `Detected secrets: aws_access_key`); detected values are never in the response. Claude Code's block message still quotes the prompt, and keeps it in the local transcript and prompt history. The newer `suppressOriginalPrompt` field would hide it from the message, but is not sent: a Claude Code version that rejected the unknown field would drop the whole block. |
154
+ | `should_proceed: true` | _(no output)_ |
155
+ | API error, or an exception anywhere in this hook (registration and alignment included) | Blocked with `fail_closed: true`, let through with `fail_closed: false`. |
156
+ | No session (alignment failed) | Not inspected. On the very first prompt of a session, a server outage therefore skips inspection rather than blocking: inspection cannot run before alignment. |
157
+ | Server without `/sessions/inspect` (404 `Not Found`) | Not inspected, so the plugin keeps working against older servers. |
158
+
159
+ Monitor-mode policies never block: their violations come back with `blocked: false` and are only recorded.
160
+
161
+ ### 3. `Stop` — Final-Response Inspection
162
+
163
+ Fires when Claude finishes its turn (per turn, not at session end). Sends Claude's final response to `/sessions/inspect` with `evaluation_point: "on_response"`. The text comes from the payload's `last_assistant_message` (Claude Code 2.1.47+), or else from the last assistant message in the transcript at `transcript_path` (text blocks only, subagent entries skipped).
164
+
165
+ | Inspection result | Claude Code response |
166
+ |---------|-----------------------|
167
+ | `should_proceed: false` | `{ "decision": "block", "reason": ... }`: Claude does not stop, and is told to write the response again without the detected content. The response it already showed is not taken back. |
168
+ | `should_proceed: false` while `stop_hook_active` is `true` | _(no output)_. Claude is already continuing because of a Stop hook, and blocking again could loop. The rewritten response is still inspected, so the platform records its verdict. |
169
+ | `should_proceed: true` | _(no output)_ |
170
+ | API error | Never blocks, regardless of `fail_closed`: blocking can't hide a response already on screen and would only make Claude repeat itself. A `systemMessage` tells the user the response went unchecked. |
171
+
172
+ ### 4. `PreToolUse` — Pre-execution Validation
151
173
 
152
174
  Before each tool call, calls `POST /api/v1/public/safety/sessions/validate` with `timing: "on_start"`. The response is routed by `should_proceed` and `severity`, and the verdict is cached for `PermissionRequest` (below) to consult:
153
175
 
@@ -157,11 +179,11 @@ Before each tool call, calls `POST /api/v1/public/safety/sessions/validate` with
157
179
  | `severity: "medium"` + `injected_instruction` | `hookSpecificOutput.permissionDecision: "ask"` | Claude Code's normal permission prompt is shown with the injected instruction as the reason. |
158
180
  | `should_proceed: true` (severity low) | _(no output)_ | Execution proceeds; Claude Code's own permission system (if any) still applies — see `PermissionRequest`. |
159
181
 
160
- ### 4. `PermissionRequest` — Auto-Resolving the Native Dialog
182
+ ### 5. `PermissionRequest` — Auto-Resolving the Native Dialog
161
183
 
162
184
  Fires after `PreToolUse`, only when Claude Code's own permission settings would still show a dialog (i.e. `PreToolUse` passed the call through with no explicit decision). When `auto_approve_vetted_permissions` is enabled, this reuses the cached `PreToolUse` verdict to answer the dialog automatically — without a second Datagusto round-trip — instead of prompting the user again for a call Datagusto already vetted. It never touches a cached `ask` verdict (severity medium): that case exists specifically so the user sees the dialog with Datagusto's injected context. Off by default; a no-op when disabled.
163
185
 
164
- ### 5. `PostToolUse` / `PostToolUseFailure` — Post-execution Validation
186
+ ### 6. `PostToolUse` / `PostToolUseFailure` — Post-execution Validation
165
187
 
166
188
  After each tool call succeeds (`PostToolUse`) or fails (`PostToolUseFailure` — same payload shape, same handling), calls the validate API with `timing: "on_end"` and the tool's output:
167
189
 
@@ -171,7 +193,7 @@ After each tool call succeeds (`PostToolUse`) or fails (`PostToolUseFailure` —
171
193
  | `injected_instruction` (without block) | `hookSpecificOutput.additionalContext` — appended as extra context for Claude. |
172
194
  | Otherwise | _(no output)_ |
173
195
 
174
- ### 6. `SessionEnd` — State Cleanup
196
+ ### 7. `SessionEnd` — State Cleanup
175
197
 
176
198
  Fires once per session, on exit. Deletes the per-session state file so `os.tmpdir()/datagusto-safety-plugin/` doesn't accumulate stale entries indefinitely.
177
199
 
@@ -181,20 +203,22 @@ Set `monitor_only: true` (or `DATAGUSTO_SAFETY_MONITOR_ONLY=true`) to log all de
181
203
 
182
204
  ### Platform monitoring mode
183
205
 
184
- Independently of `monitor_only`, the Datagusto platform has a per-agent **monitoring mode** (dashboard: agent settings → monitoring). When it is on, the server still evaluates guardrails, records every verdict and detects incidents, but returns `monitoring_mode_enabled: true` on `/sessions/alignment` and `/sessions/validate` responses and expects the client not to enforce them.
206
+ Independently of `monitor_only`, the Datagusto platform has a per-agent **monitoring mode** (dashboard: agent settings → monitoring). When it is on, the server still evaluates guardrails, records every verdict and detects incidents, but returns `monitoring_mode_enabled: true` on `/sessions/alignment`, `/sessions/validate` and `/sessions/inspect` responses and expects the client not to enforce them.
185
207
 
186
208
  The plugin honours that flag: effective monitoring = `monitor_only` **OR** `monitoring_mode_enabled`. Either switch disables enforcement; there is no way for one to override the other. The platform value is resolved per request:
187
209
 
188
- 1. `monitoring_mode_enabled` on the current validate response (follows a settings change mid-session), then
189
- 2. the value most recently reported by any alignment or validate response for this session (kept in the per-session state file, and the only source for `PermissionRequest` and for calls where only `/guardrails/evaluate` ran, since that endpoint carries no flag), then
210
+ 1. `monitoring_mode_enabled` on the current validate or inspect response (follows a settings change mid-session), then
211
+ 2. the value most recently reported by any alignment, validate or inspect response for this session (kept in the per-session state file, and the only source for `PermissionRequest` and for calls where only `/guardrails/evaluate` ran, since that endpoint carries no flag), then
190
212
  3. `false` — servers that omit the field behave exactly as before.
191
213
 
192
214
  The first time a session sees the platform flag as `true`, one user-facing notice is emitted via the hook output's `systemMessage` field regardless of `verbose` (merged into the deny / ask / block JSON when there is one, or written as a bare `{ "systemMessage": ... }` on allow paths); every skipped verdict is then logged as `[MONITOR] ... skipped (platform monitoring mode)` (vs. `(plugin monitorOnly)`) when `verbose` is on. Fail-closed handling of API errors is governed by `monitor_only` alone; the platform flag never relaxes it, because an errored request carries no verdict.
193
215
 
194
216
  ## Fail-Closed vs Fail-Open
195
217
 
196
- - **`fail_closed: true`** (default): Tool execution is denied when the Datagusto API is unreachable or errors. Safe default for production.
197
- - **`fail_closed: false`**: Tool execution is allowed to proceed on API errors. Use for development/testing.
218
+ - **`fail_closed: true`** (default): Tool execution is denied, and a prompt is blocked, when the Datagusto API is unreachable or errors. Safe default for production.
219
+ - **`fail_closed: false`**: Tool execution and prompts are allowed to proceed on API errors. Use for development/testing.
220
+
221
+ The `Stop` hook is the exception: an inspection error there never blocks (see [`Stop`](#3-stop--final-response-inspection)).
198
222
 
199
223
  Misconfiguration (missing `server_url`/`api_key`) is always fail-**open** regardless of `fail_closed`. Blocking every tool call would leave the user unable to use the agent to troubleshoot. Instead, `SessionStart` shows a warning (via `systemMessage`) that tool calls aren't being checked and suggests `dg setup claude-code`, and every other hook writes the same warning to stderr and exits non-blocking. `fail_closed` still governs API errors once the plugin is configured.
200
224
 
@@ -209,7 +233,7 @@ Set `verbose: true` (via `userConfig` or `claude-code.json`) to see per-hook log
209
233
  | Error | Cause | Solution |
210
234
  |-------|-------|----------|
211
235
  | `Datagusto safety plugin isn't configured` (tool calls not checked) | Missing `serverUrl` / `apiKey` | Run `dg setup claude-code`, or check the plugin's `userConfig` values, or `claude-code.json` / `DATAGUSTO_SAFETY_*` in dev-fallback mode |
212
- | `no session_id available` (on every tool call) | `UserPromptSubmit` hook isn't firing, or alignment failed | Confirm the plugin loaded (all 7 hooks should appear in the SDK's `init` message); check `verbose` logs for the alignment API error |
236
+ | `no session_id available` (on every tool call) | `UserPromptSubmit` hook isn't firing, or alignment failed | Confirm the plugin loaded (all 8 hooks should appear in the SDK's `init` message); check `verbose` logs for the alignment API error |
213
237
  | `validation API error` | Datagusto server returned non-2xx | Check server health and API key validity |
214
238
  | Tool denied unexpectedly | API error with `fail_closed: true` | Set `fail_closed: false` to allow tools during API outages |
215
239
 
@@ -230,6 +254,8 @@ Claude Code plugin (.claude-plugin/plugin.json + hooks/hooks.json), per hook eve
230
254
  |
231
255
  |-- UserPromptSubmit ---> payload.prompt --------------> POST /sessions/alignment
232
256
  | -> persist session_id to state file
257
+ | -> payload.prompt --------------> POST /sessions/inspect (on_prompt_submit)
258
+ | should_proceed=false --> decision: block (prompt never reaches Claude)
233
259
  | -> registration fallback (hash-gated, same as SessionStart)
234
260
  |
235
261
  |-- PreToolUse --------> POST /sessions/validate (on_start)
@@ -247,6 +273,11 @@ Claude Code plugin (.claude-plugin/plugin.json + hooks/hooks.json), per hook eve
247
273
  | injected_instruction --> additionalContext (feedback only)
248
274
  | otherwise --> (no output)
249
275
  |
276
+ |-- Stop --------------> last_assistant_message ----> POST /sessions/inspect (on_response)
277
+ | (or the transcript's last assistant text)
278
+ | should_proceed=false --> decision: block (Claude rewrites)
279
+ | stop_hook_active=true --> (never blocks)
280
+ |
250
281
  |-- SessionEnd ---------> delete per-session state file
251
282
  ```
252
283
 
@@ -256,7 +287,7 @@ State (`sessionId`, `registeredToolsHash`, `lastUserInstructionHash`, `lastPreTo
256
287
 
257
288
  Both plugins implement the same business semantics against the same Datagusto contract (`/sessions/validate`'s `should_proceed`/`severity`/`injected_instruction` fields), mapped independently onto each host's native hook vocabulary:
258
289
 
259
- - **7 Claude Code hooks vs. OpenClaw's 5.** No Claude Code analogue of `before_agent_start` (state is namespaced by Claude Code's stable `session_id`, so there's nothing to reset) or `tool_result_persist` (folded into `PostToolUse`'s own `updatedToolOutput`, see below). Conversely, Claude Code's `SessionStart`/`SessionEnd`/`PostToolUseFailure`/`PermissionRequest` have no OpenClaw equivalent — they map onto lifecycle concepts (explicit session boundaries, a host-native permission dialog) that don't exist in OpenClaw's single-long-running-process architecture.
290
+ - **8 Claude Code hooks vs. OpenClaw's 5.** No Claude Code analogue of `before_agent_start` (state is namespaced by Claude Code's stable `session_id`, so there's nothing to reset) or `tool_result_persist` (folded into `PostToolUse`'s own `updatedToolOutput`, see below). Conversely, Claude Code's `SessionStart`/`SessionEnd`/`PostToolUseFailure`/`PermissionRequest` have no OpenClaw equivalent, and the prompt / response inspection on `UserPromptSubmit` / `Stop` is not implemented in the OpenClaw plugin — they map onto lifecycle concepts (explicit session boundaries, a host-native permission dialog) that don't exist in OpenClaw's single-long-running-process architecture.
260
291
  - **No race conditions.** OpenClaw's `before_tool_call` awaits a pending alignment promise because hooks share one process; Claude Code hooks run as separate, sequential processes, so `UserPromptSubmit`/`SessionStart` always finish before the next `PreToolUse`.
261
292
  - **`PostToolUse` can rewrite output.** `hookSpecificOutput.updatedToolOutput` replaces the tool's recorded result, the same underlying capability as OpenClaw's `tool_result_persist` rewrite, expressed through Claude Code's own hook field instead.
262
293
  - **Simpler instruction extraction.** `payload.prompt` is the raw current instruction; no scanning `historyMessages` and no channel-metadata stripping (only slash-command / bash-mode filtering).
@@ -4,6 +4,7 @@
4
4
  const TOOLS_REGISTER_PATH = "/api/v1/public/safety/tools/register";
5
5
  const SESSIONS_ALIGNMENT_PATH = "/api/v1/public/safety/sessions/alignment";
6
6
  const SESSIONS_VALIDATE_PATH = "/api/v1/public/safety/sessions/validate";
7
+ const SESSIONS_INSPECT_PATH = "/api/v1/public/safety/sessions/inspect";
7
8
  const GUARDRAILS_EVALUATE_PATH = "/api/v1/public/guardrails/evaluate";
8
9
  export class DatagustoApiClient {
9
10
  baseUrl;
@@ -41,6 +42,14 @@ export class DatagustoApiClient {
41
42
  async evaluateGuardrails(payload) {
42
43
  return this._post(GUARDRAILS_EVALUATE_PATH, payload);
43
44
  }
45
+ /**
46
+ * Inspect a submitted prompt or a final response against the policies
47
+ * evaluated at that point (deterministic detectors, no LLM). Session-scoped:
48
+ * needs the session_id from postAlignment.
49
+ */
50
+ async inspectSession(payload) {
51
+ return this._post(SESSIONS_INSPECT_PATH, payload);
52
+ }
44
53
  // -- Internal helper ------------------------------------------------------
45
54
  async _post(endpoint, body) {
46
55
  const url = this.baseUrl + endpoint;
@@ -37,6 +37,15 @@ export function isClaudeCodeCommand(prompt) {
37
37
  const trimmed = prompt.trim();
38
38
  return /^\/\w+/.test(trimmed) || trimmed.startsWith("!");
39
39
  }
40
+ /**
41
+ * True only for a slash command with no arguments (e.g. "/compact"), the one
42
+ * kind of input prompt inspection may skip. Narrower than isClaudeCodeCommand
43
+ * on purpose: a command's arguments reach the model, and a prompt that starts
44
+ * with a path ("/Users/me/.aws/credentials has ...") is ordinary text.
45
+ */
46
+ export function isBareSlashCommand(prompt) {
47
+ return /^\/[\w:.-]+$/.test(prompt.trim());
48
+ }
40
49
  // -- Stable hashing ---------------------------------------------------------
41
50
  /**
42
51
  * Recursively sort object keys so that `JSON.stringify` produces
@@ -198,4 +207,104 @@ export function normalizeEvaluateResponse(data) {
198
207
  injected_instruction: injectedInstruction,
199
208
  };
200
209
  }
210
+ // -- Prompt / response inspection --------------------------------------------
211
+ /** Largest `content` /sessions/inspect accepts (it 422s above this). */
212
+ export const MAX_INSPECTION_CONTENT_LENGTH = 1_000_000;
213
+ /**
214
+ * Trim `text` to what /sessions/inspect accepts. Returns null for text that
215
+ * is empty or whitespace-only, which the endpoint rejects and which has
216
+ * nothing to inspect anyway.
217
+ */
218
+ export function clampInspectionContent(text) {
219
+ if (typeof text !== "string" || text.trim().length === 0)
220
+ return null;
221
+ return text.length > MAX_INSPECTION_CONTENT_LENGTH
222
+ ? text.slice(0, MAX_INSPECTION_CONTENT_LENGTH)
223
+ : text;
224
+ }
225
+ /**
226
+ * Human-readable reason for a blocking /sessions/inspect verdict: each
227
+ * blocking policy's statement (`result.message`) followed by the detected
228
+ * type (`result.reason`, e.g. "Detected secrets: aws_access_key"). Detected
229
+ * values are never part of the response, so none can leak into the reason.
230
+ * Falls back to the blocked `policy_evaluations[]`, then to
231
+ * extractBlockReason.
232
+ */
233
+ export function extractInspectionReason(data) {
234
+ const parts = [];
235
+ for (const g of data.triggered_guardrails ?? []) {
236
+ if (g.triggered === false)
237
+ continue;
238
+ for (const action of g.actions ?? []) {
239
+ if (action.action_type !== "block")
240
+ continue;
241
+ const message = action.result?.message;
242
+ const reason = action.result?.reason;
243
+ const text = [message, reason].filter((t) => typeof t === "string" && t.length > 0).join(" — ");
244
+ if (text)
245
+ parts.push(g.guardrail_name ? `${g.guardrail_name}: ${text}` : text);
246
+ }
247
+ }
248
+ if (parts.length > 0)
249
+ return parts.join("; ");
250
+ const blocked = (data.policy_evaluations ?? []).filter((p) => p.blocked);
251
+ if (blocked.length > 0)
252
+ return blocked.map((p) => `${p.policy_name}: ${p.reason}`).join("; ");
253
+ return extractBlockReason(data);
254
+ }
255
+ /**
256
+ * Text of the agent's final message, read from a Claude Code transcript
257
+ * (JSONL, one entry per line). Fallback for Claude Code versions whose Stop
258
+ * payload has no `last_assistant_message`.
259
+ *
260
+ * Walks back from the end and joins the `text` blocks of the assistant
261
+ * entries after the last user entry (Claude Code writes one API message as
262
+ * several entries, one per content block). Tool calls, thinking and
263
+ * sidechain (subagent) entries are skipped. If the trailing assistant
264
+ * entries have no text — the turn ended on a tool call — it keeps walking
265
+ * back to the most recent assistant entry that has some.
266
+ */
267
+ export function extractLastAssistantText(transcriptJsonl) {
268
+ const lines = transcriptJsonl.split("\n");
269
+ const texts = [];
270
+ for (let i = lines.length - 1; i >= 0; i--) {
271
+ const line = lines[i].trim();
272
+ if (!line)
273
+ continue;
274
+ let entry;
275
+ try {
276
+ entry = JSON.parse(line);
277
+ }
278
+ catch {
279
+ continue; // a partially written last line
280
+ }
281
+ if (entry.isSidechain === true)
282
+ continue;
283
+ if (entry.type === "user") {
284
+ // A tool result is a user entry too; walk past it while no text has
285
+ // been found. A real prompt is the turn boundary: stop there rather
286
+ // than return the previous turn's response (the transcript can lag).
287
+ if (texts.length > 0 || !isToolResultEntry(entry))
288
+ break;
289
+ continue;
290
+ }
291
+ if (entry.type !== "assistant")
292
+ continue;
293
+ const content = entry.message?.content;
294
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content : [];
295
+ const entryTexts = blocks
296
+ .filter((b) => !!b && b.type === "text" && typeof b.text === "string")
297
+ .map((b) => b.text);
298
+ texts.unshift(...entryTexts);
299
+ }
300
+ const joined = texts.join("\n").trim();
301
+ return joined.length > 0 ? joined : null;
302
+ }
303
+ /** True for a transcript user entry that only carries tool results. */
304
+ function isToolResultEntry(entry) {
305
+ const content = entry.message?.content;
306
+ return (Array.isArray(content) &&
307
+ content.length > 0 &&
308
+ content.every((b) => !!b && b.type === "tool_result"));
309
+ }
201
310
  //# sourceMappingURL=extractors.js.map
@@ -13,7 +13,7 @@ import { readFileSync } from "node:fs";
13
13
  import { dirname, join } from "node:path";
14
14
  import { fileURLToPath } from "node:url";
15
15
  import { DatagustoApiClient } from "./api-client.js";
16
- import { buildBuiltinToolDefinitions, extractBlockReason, extractPhase, hashPayload, isClaudeCodeCommand, normalizeEvaluateResponse, serializeToolResult, } from "./extractors.js";
16
+ import { buildBuiltinToolDefinitions, clampInspectionContent, extractBlockReason, extractInspectionReason, extractLastAssistantText, extractPhase, hashPayload, isBareSlashCommand, isClaudeCodeCommand, normalizeEvaluateResponse, serializeToolResult, } from "./extractors.js";
17
17
  import { describeMonitoring, readMonitoringFlag, resolveMonitoring, } from "./monitoring.js";
18
18
  import { deleteState, loadState, mutateState } from "./state.js";
19
19
  /**
@@ -191,6 +191,20 @@ function injectPostToolUseContext(note, hookEventName) {
191
191
  },
192
192
  });
193
193
  }
194
+ /**
195
+ * Blocks a submitted prompt. `reason` is shown to the user and never reaches
196
+ * Claude. Deliberately no `hookSpecificOutput.suppressOriginalPrompt`: it is
197
+ * recent, and a Claude Code that rejects the unknown key would discard the
198
+ * whole decision and let the prompt through. The prompt text therefore
199
+ * appears in the block message (it is in the local transcript either way).
200
+ */
201
+ function blockUserPrompt(reason) {
202
+ writeDecision({ decision: "block", reason });
203
+ }
204
+ /** Keeps Claude from stopping; `reason` tells it what to fix first. */
205
+ function blockStop(reason) {
206
+ writeDecision({ decision: "block", reason });
207
+ }
194
208
  const PLATFORM_MONITORING_NOTICE = "[datagusto] Platform monitoring mode is enabled for this agent: " +
195
209
  "guardrail verdicts are recorded but not enforced.";
196
210
  /**
@@ -232,6 +246,39 @@ function resolveMonitoringForHook(cfg, claudeSessionId, state, response, dbg) {
232
246
  dbg(`Monitoring mode active (${describeMonitoring(decision)}).`);
233
247
  return decision;
234
248
  }
249
+ /**
250
+ * Call /sessions/inspect and resolve monitoring mode from its response.
251
+ * "skipped" means nothing was inspected and nothing went wrong: no session,
252
+ * nothing to inspect, or a server that predates the endpoint (FastAPI answers
253
+ * an unknown route with 404 `{"detail":"Not Found"}`, unlike the endpoint's
254
+ * own 404 `{"detail":"Session not found"}`). "error" is for failClosed to
255
+ * judge.
256
+ */
257
+ async function inspectContent(client, cfg, claudeSessionId, state, evaluationPoint, text, dbg) {
258
+ if (!state.sessionId) {
259
+ dbg(`No sessionId; skipping ${evaluationPoint} inspection.`);
260
+ return { kind: "skipped" };
261
+ }
262
+ const content = clampInspectionContent(text);
263
+ if (content === null) {
264
+ dbg(`Nothing to inspect at ${evaluationPoint}.`);
265
+ return { kind: "skipped" };
266
+ }
267
+ const res = await client.inspectSession({
268
+ session_id: state.sessionId,
269
+ evaluation_point: evaluationPoint,
270
+ content,
271
+ });
272
+ dbg(`Inspect ${evaluationPoint} result: ok=${res.ok}, status=${res.status}`);
273
+ if (res.status === 404 && res.data?.detail === "Not Found") {
274
+ dbg("Server has no /sessions/inspect endpoint; skipping inspection.");
275
+ return { kind: "skipped" };
276
+ }
277
+ if (!res.ok || !res.data)
278
+ return { kind: "error" };
279
+ const monitoring = resolveMonitoringForHook(cfg, claudeSessionId, state, res.data, dbg);
280
+ return { kind: "verdict", data: res.data, monitoring };
281
+ }
235
282
  // ---------------------------------------------------------------------------
236
283
  // SessionStart — eager tool registration
237
284
  //
@@ -268,7 +315,7 @@ async function handleSessionEnd(payload, client, cfg, dbg) {
268
315
  deleteState(payload.session_id);
269
316
  }
270
317
  // ---------------------------------------------------------------------------
271
- // UserPromptSubmit — tool registration + alignment
318
+ // UserPromptSubmit — tool registration + alignment + prompt inspection
272
319
  //
273
320
  // Folds OpenClaw's two hooks (`before_agent_start` reset + `llm_input`
274
321
  // register/align) into one: Claude Code fires this once per user turn and
@@ -276,6 +323,10 @@ async function handleSessionEnd(payload, client, cfg, dbg) {
276
323
  // and no separate reset step (state is already namespaced by session_id).
277
324
  // Tool registration is also covered by SessionStart now; this hash-gated
278
325
  // check stays as a cheap defense-in-depth fallback.
326
+ //
327
+ // The prompt is inspected after alignment, because inspection needs the
328
+ // session alignment creates. Unlike alignment it is not deduplicated by
329
+ // hash: re-sending a blocked prompt must be blocked again.
279
330
  // ---------------------------------------------------------------------------
280
331
  async function handleUserPromptSubmit(payload, client, cfg, dbg) {
281
332
  const state = loadState(payload.session_id);
@@ -322,6 +373,96 @@ async function handleUserPromptSubmit(payload, client, cfg, dbg) {
322
373
  s.sessionId = state.sessionId;
323
374
  s.lastUserInstructionHash = state.lastUserInstructionHash;
324
375
  });
376
+ if (isBareSlashCommand(payload.prompt))
377
+ return;
378
+ const outcome = await inspectContent(client, cfg, payload.session_id, state, "on_prompt_submit", payload.prompt, dbg);
379
+ if (outcome.kind === "error") {
380
+ // Only the plugin's own monitorOnly relaxes fail-closed, as on tool calls.
381
+ if (cfg.failClosed && !cfg.monitorOnly) {
382
+ blockUserPrompt("Datagusto safety: the prompt could not be checked (inspection API error). Try again.");
383
+ }
384
+ else {
385
+ dbg("Prompt inspection failed; letting the prompt through (fail-open).");
386
+ }
387
+ return;
388
+ }
389
+ if (outcome.kind !== "verdict")
390
+ return;
391
+ if (outcome.data.should_proceed !== false) {
392
+ dbg("on_prompt_submit ALLOWED");
393
+ return;
394
+ }
395
+ const reason = trimSentence(extractInspectionReason(outcome.data));
396
+ dbg(`on_prompt_submit BLOCKED: ${reason}`);
397
+ if (outcome.monitoring.active) {
398
+ dbg(`[MONITOR] Prompt block skipped (${describeMonitoring(outcome.monitoring)}).`);
399
+ return;
400
+ }
401
+ blockUserPrompt(`Datagusto blocked this prompt. ${reason}. Remove that content and send the prompt again.`);
402
+ }
403
+ // ---------------------------------------------------------------------------
404
+ // Stop — final-response inspection
405
+ //
406
+ // Fires when Claude finishes its turn (SessionEnd, not this, cleans up state).
407
+ // A block keeps Claude from stopping and hands it the reason, so it rewrites
408
+ // the response; the text it already showed is not taken back.
409
+ //
410
+ // Two things never block here:
411
+ // - stop_hook_active: Claude is already continuing because of a Stop hook,
412
+ // and blocking again on the same detector could loop. The rewritten
413
+ // response is still inspected, so the platform records its verdict.
414
+ // - API errors: blocking cannot hide a response that is already on screen,
415
+ // and would only make Claude repeat itself, so failClosed does not apply.
416
+ // The user is told the response went unchecked instead.
417
+ // ---------------------------------------------------------------------------
418
+ async function handleStop(payload, client, cfg, dbg) {
419
+ const state = loadState(payload.session_id);
420
+ if (!state.sessionId) {
421
+ dbg("No sessionId; skipping on_response inspection.");
422
+ return;
423
+ }
424
+ const text = typeof payload.last_assistant_message === "string"
425
+ ? payload.last_assistant_message
426
+ : readLastAssistantText(payload.transcript_path, dbg);
427
+ const outcome = await inspectContent(client, cfg, payload.session_id, state, "on_response", text, dbg);
428
+ if (outcome.kind === "error") {
429
+ pendingSystemMessage = "[datagusto] Claude's last response could not be checked (inspection API error).";
430
+ return;
431
+ }
432
+ if (outcome.kind !== "verdict")
433
+ return;
434
+ if (outcome.data.should_proceed !== false) {
435
+ dbg("on_response ALLOWED");
436
+ return;
437
+ }
438
+ const reason = trimSentence(extractInspectionReason(outcome.data));
439
+ dbg(`on_response BLOCKED: ${reason}`);
440
+ if (outcome.monitoring.active) {
441
+ dbg(`[MONITOR] Response block skipped (${describeMonitoring(outcome.monitoring)}).`);
442
+ return;
443
+ }
444
+ if (payload.stop_hook_active === true) {
445
+ dbg("Response block skipped: already continuing because of a Stop hook (loop guard).");
446
+ return;
447
+ }
448
+ blockStop(`Datagusto blocked your last response. ${reason}. ` +
449
+ "Write the response again without that content, and do not repeat or quote it.");
450
+ }
451
+ /** Drop trailing periods so the reason can be followed by another sentence. */
452
+ function trimSentence(text) {
453
+ return text.replace(/[\s.。]+$/u, "");
454
+ }
455
+ /** Claude Code before 2.1.47 sends no `last_assistant_message`; read the transcript. */
456
+ function readLastAssistantText(transcriptPath, dbg) {
457
+ if (typeof transcriptPath !== "string" || !transcriptPath)
458
+ return null;
459
+ try {
460
+ return extractLastAssistantText(readFileSync(transcriptPath, "utf8"));
461
+ }
462
+ catch (err) {
463
+ dbg(`Could not read transcript: ${err instanceof Error ? err.message : err}`);
464
+ return null;
465
+ }
325
466
  }
326
467
  // ---------------------------------------------------------------------------
327
468
  // PreToolUse — on_start validation
@@ -662,6 +803,9 @@ async function main() {
662
803
  case "PostToolUseFailure":
663
804
  await handlePostToolUse(payload, client, cfg, dbg);
664
805
  break;
806
+ case "Stop":
807
+ await handleStop(payload, client, cfg, dbg);
808
+ break;
665
809
  case "SessionEnd":
666
810
  await handleSessionEnd(payload, client, cfg, dbg);
667
811
  break;
@@ -676,6 +820,9 @@ async function main() {
676
820
  if (payload.hook_event_name === "PreToolUse") {
677
821
  denyPreToolUse("Datagusto safety: validation failed.");
678
822
  }
823
+ else if (payload.hook_event_name === "UserPromptSubmit") {
824
+ blockUserPrompt("Datagusto safety: the prompt could not be checked. Try again.");
825
+ }
679
826
  else if (payload.hook_event_name === "PostToolUse" || payload.hook_event_name === "PostToolUseFailure") {
680
827
  const p = payload;
681
828
  blockPostToolUseWithRewrite(p.tool_name, "Datagusto safety: validation failed.", "exception", p.hook_event_name);
@@ -9,6 +9,9 @@
9
9
  "UserPromptSubmit": [
10
10
  { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/index.js\"" }] }
11
11
  ],
12
+ "Stop": [
13
+ { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/index.js\"" }] }
14
+ ],
12
15
  "PreToolUse": [
13
16
  { "matcher": "*", "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/dist/index.js\"" }] }
14
17
  ],
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "datagusto-safety-plugin",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Datagusto safety validation plugin for Claude Code",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -4,6 +4,7 @@
4
4
  const TOOLS_REGISTER_PATH = "/api/v1/public/safety/tools/register";
5
5
  const SESSIONS_ALIGNMENT_PATH = "/api/v1/public/safety/sessions/alignment";
6
6
  const SESSIONS_VALIDATE_PATH = "/api/v1/public/safety/sessions/validate";
7
+ const SESSIONS_INSPECT_PATH = "/api/v1/public/safety/sessions/inspect";
7
8
  const GUARDRAILS_EVALUATE_PATH = "/api/v1/public/guardrails/evaluate";
8
9
  export class DatagustoApiClient {
9
10
  baseUrl;
@@ -41,6 +42,14 @@ export class DatagustoApiClient {
41
42
  async evaluateGuardrails(payload) {
42
43
  return this._post(GUARDRAILS_EVALUATE_PATH, payload);
43
44
  }
45
+ /**
46
+ * Inspect a submitted prompt or a final response against the policies
47
+ * evaluated at that point (deterministic detectors, no LLM). Session-scoped:
48
+ * needs the session_id from postAlignment.
49
+ */
50
+ async inspectSession(payload) {
51
+ return this._post(SESSIONS_INSPECT_PATH, payload);
52
+ }
44
53
  // -- Internal helper ------------------------------------------------------
45
54
  async _post(endpoint, body) {
46
55
  const url = this.baseUrl + endpoint;