@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.
@@ -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
@@ -39,7 +39,7 @@ import { dirname, join } from "node:path";
39
39
  import { fileURLToPath } from "node:url";
40
40
  import { DatagustoApiClient } from "./api-client.js";
41
41
  import { buildToolDefinitions, detectEngine } from "./engine.js";
42
- import { extractBlockReason, extractPhase, hashPayload, isClaudeCodeCommand, normalizeEvaluateResponse, serializeToolResult, } from "./extractors.js";
42
+ import { clampInspectionContent, extractBlockReason, extractInspectionReason, extractPhase, hashPayload, isBareSlashCommand, isClaudeCodeCommand, normalizeEvaluateResponse, serializeToolResult, } from "./extractors.js";
43
43
  import { describeMonitoring, readMonitoringFlag, resolveMonitoring, } from "./monitoring.js";
44
44
  import { deleteState, loadState, mutateState, saveState } from "./state.js";
45
45
  /**
@@ -220,6 +220,15 @@ function normalizeHookEvent(value) {
220
220
  const key = value.trim().toLowerCase().replace(/[\s_-]/g, "");
221
221
  return HOOK_EVENT_ALIASES[key] ?? null;
222
222
  }
223
+ /** `hook_event_name` from raw stdin, or undefined when it is not JSON. */
224
+ function peekEventName(raw) {
225
+ try {
226
+ return JSON.parse(raw)?.hook_event_name;
227
+ }
228
+ catch {
229
+ return undefined;
230
+ }
231
+ }
223
232
  /**
224
233
  * True when the payload carries tool context. This is what decides how an
225
234
  * unrecognized event name is handled: an unknown TOOL event is a call we were
@@ -308,6 +317,43 @@ function resolveMonitoringForHook(cfg, sessionId, state, response, dbg) {
308
317
  dbg(`Monitoring mode active (${describeMonitoring(decision)}).`);
309
318
  return decision;
310
319
  }
320
+ /**
321
+ * Call /sessions/inspect and resolve monitoring mode from its response.
322
+ * "skipped" means nothing was inspected and nothing went wrong: no session,
323
+ * nothing to inspect, or a server that predates the endpoint (FastAPI answers
324
+ * an unknown route with 404 `{"detail":"Not Found"}`, unlike the endpoint's
325
+ * own 404 `{"detail":"Session not found"}`). "error" is for failClosed to
326
+ * judge.
327
+ */
328
+ async function inspectContent(client, cfg, sessionId, state, evaluationPoint, text, dbg) {
329
+ if (!state.sessionId) {
330
+ dbg(`No sessionId; skipping ${evaluationPoint} inspection.`);
331
+ return { kind: "skipped" };
332
+ }
333
+ const content = clampInspectionContent(text);
334
+ if (content === null) {
335
+ dbg(`Nothing to inspect at ${evaluationPoint}.`);
336
+ return { kind: "skipped" };
337
+ }
338
+ const res = await client.inspectSession({
339
+ session_id: state.sessionId,
340
+ evaluation_point: evaluationPoint,
341
+ content,
342
+ });
343
+ dbg(`Inspect ${evaluationPoint} result: ok=${res.ok}, status=${res.status}`);
344
+ if (res.status === 404 && res.data?.detail === "Not Found") {
345
+ dbg("Server has no /sessions/inspect endpoint; skipping inspection.");
346
+ return { kind: "skipped" };
347
+ }
348
+ if (!res.ok || !res.data)
349
+ return { kind: "error" };
350
+ const monitoring = resolveMonitoringForHook(cfg, sessionId, state, res.data, dbg);
351
+ return { kind: "verdict", data: res.data, monitoring };
352
+ }
353
+ /** Drop trailing periods so the reason can be followed by another sentence. */
354
+ function trimSentence(text) {
355
+ return text.replace(/[\s.。]+$/u, "");
356
+ }
311
357
  // ---------------------------------------------------------------------------
312
358
  // SessionStart — eager tool registration
313
359
  //
@@ -335,14 +381,63 @@ async function handleSessionStart(payload, client, cfg, dbg) {
335
381
  saveState(payload.session_id, state);
336
382
  }
337
383
  // ---------------------------------------------------------------------------
338
- // Stop — state cleanup (Kiro CLI's equivalent of Claude Code's SessionEnd)
384
+ // Stop — final-response inspection, then state cleanup (Kiro CLI's
385
+ // equivalent of Claude Code's SessionEnd)
386
+ //
387
+ // The response is inspected first: inspection needs the session id that the
388
+ // cleanup deletes. Only V1 and V2 send the response (`assistant_response`);
389
+ // V3 sends none (still so on Kiro CLI 2.34.0), so there is nothing to inspect
390
+ // there.
391
+ //
392
+ // Kiro CLI 2.x cannot hold a response back: its docs give `stop` no blocking
393
+ // or continue mechanism, and any non-zero exit is shown to the user as a
394
+ // warning. So a violation is recorded on the platform and reported to the
395
+ // user on stderr, with exit 2 (observed on 2.34.0 V2: the session ended with
396
+ // the response as it was). V3 can ask the agent to continue (exit 1, or a
397
+ // `decision: "block"` JSON on stdout), but sends no response to inspect, so
398
+ // the plugin never needs it; exit 2 on V3 leaves the response finished.
399
+ // An API error never blocks (the response is already shown, as in the Claude
400
+ // Code plugin); a notice says it went unchecked.
339
401
  // ---------------------------------------------------------------------------
340
402
  async function handleStop(payload, client, cfg, dbg) {
341
- dbg(`Stop: deleting state for session ${payload.session_id}`);
342
- deleteState(payload.session_id);
403
+ const state = loadState(payload.session_id);
404
+ try {
405
+ const outcome = await inspectContent(client, cfg, payload.session_id, state, "on_response", payload.assistant_response, dbg);
406
+ if (outcome.kind === "error") {
407
+ emitNotice("[datagusto] The agent's last response could not be checked (inspection API error).");
408
+ }
409
+ else if (outcome.kind === "verdict" && outcome.data.should_proceed === false) {
410
+ const reason = trimSentence(extractInspectionReason(outcome.data));
411
+ dbg(`on_response BLOCKED: ${reason}`);
412
+ if (outcome.monitoring.active) {
413
+ dbg(`[MONITOR] Response block skipped (${describeMonitoring(outcome.monitoring)}).`);
414
+ }
415
+ else {
416
+ emitBlock(`[datagusto] The agent's last response violates a policy (Kiro cannot hold it back). ${reason}.`);
417
+ }
418
+ }
419
+ else if (outcome.kind === "verdict") {
420
+ dbg("on_response ALLOWED");
421
+ }
422
+ }
423
+ finally {
424
+ dbg(`Stop: deleting state for session ${payload.session_id}`);
425
+ deleteState(payload.session_id);
426
+ }
343
427
  }
344
428
  // ---------------------------------------------------------------------------
345
- // UserPromptSubmit — tool registration + alignment
429
+ // UserPromptSubmit — tool registration + alignment + prompt inspection
430
+ //
431
+ // The prompt is inspected after alignment, because inspection needs the
432
+ // session alignment creates. Unlike alignment it is not deduplicated by
433
+ // hash: re-sending a flagged prompt must be flagged again.
434
+ //
435
+ // Kiro CLI cannot block a prompt: per its docs the prompt is sent whatever
436
+ // the exit code (observed on 2.34.0, V2 and V3). A violation exits 2 with the
437
+ // reason on stderr, which 2.x shows to the user as a warning, V3 hands to the
438
+ // agent as context, and the IDE treats as a block (per its docs; unverified
439
+ // here). The message is written for all three readers. The verdict is
440
+ // recorded on the platform either way.
346
441
  // ---------------------------------------------------------------------------
347
442
  async function handleUserPromptSubmit(payload, client, cfg, dbg) {
348
443
  const state = loadState(payload.session_id);
@@ -385,6 +480,33 @@ async function handleUserPromptSubmit(payload, client, cfg, dbg) {
385
480
  dbg("Prompt is a slash command / bash-mode shortcut, skipping alignment.");
386
481
  }
387
482
  saveState(payload.session_id, state);
483
+ if (isBareSlashCommand(payload.prompt))
484
+ return;
485
+ const outcome = await inspectContent(client, cfg, payload.session_id, state, "on_prompt_submit", payload.prompt, dbg);
486
+ if (outcome.kind === "error") {
487
+ // Only the plugin's own monitorOnly relaxes fail-closed, as on tool calls.
488
+ if (cfg.failClosed && !cfg.monitorOnly) {
489
+ emitBlock("[datagusto] This prompt could not be checked against the policies (inspection API error).");
490
+ }
491
+ else {
492
+ dbg("Prompt inspection failed; letting the prompt through (fail-open).");
493
+ }
494
+ return;
495
+ }
496
+ if (outcome.kind !== "verdict")
497
+ return;
498
+ if (outcome.data.should_proceed !== false) {
499
+ dbg("on_prompt_submit ALLOWED");
500
+ return;
501
+ }
502
+ const reason = trimSentence(extractInspectionReason(outcome.data));
503
+ dbg(`on_prompt_submit BLOCKED: ${reason}`);
504
+ if (outcome.monitoring.active) {
505
+ dbg(`[MONITOR] Prompt block skipped (${describeMonitoring(outcome.monitoring)}).`);
506
+ return;
507
+ }
508
+ emitBlock(`[datagusto] This prompt violates a policy. ${reason}. ` +
509
+ "Do not use, repeat or store that content; the prompt should be sent again without it.");
388
510
  }
389
511
  // ---------------------------------------------------------------------------
390
512
  // PreToolUse — on_start validation
@@ -655,7 +777,9 @@ async function main() {
655
777
  // DELIBERATE non-blocking fail-open on misconfiguration: exit 1 warns and
656
778
  // allows, per the Kiro CLI contract (exit 1 is not the block code — that's
657
779
  // exit 2). A broken config must never hard-block every tool call.
658
- process.exit(1);
780
+ // Except on Stop, where V3 reads exit 1 as "continue for another turn"
781
+ // (kiro.dev/docs/hooks/types.md): every turn would end in another one.
782
+ process.exit(normalizeHookEvent(peekEventName(raw)) === "Stop" ? 0 : 1);
659
783
  }
660
784
  // Empty stdin means we have zero context: we cannot tell whether this
661
785
  // invocation is gating a tool call or not. Previously this allowed (exit 0),
@@ -716,6 +840,9 @@ async function main() {
716
840
  if (event === "PreToolUse" || event === "PostToolUse" || hasToolContext(payload)) {
717
841
  emitBlock("Datagusto safety: validation failed.");
718
842
  }
843
+ else if (event === "UserPromptSubmit") {
844
+ emitBlock("[datagusto] This prompt could not be checked against the policies.");
845
+ }
719
846
  }
720
847
  }
721
848
  dbg(`=== ${rawEventName} END ===`);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "datagusto-safety-plugin-kiro",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Datagusto safety validation plugin for Kiro IDE",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,25 +1,25 @@
1
1
  {
2
2
  "version": 1,
3
- "sourceCommit": "720f760",
3
+ "sourceCommit": "000628e",
4
4
  "plugins": {
5
5
  "claude_code": {
6
- "pluginVersion": "1.0.0",
6
+ "pluginVersion": "1.1.0",
7
7
  "files": {
8
- ".claude-plugin/plugin.json": "62621afc1dfc683bcf4afdac43d6efea0ec85e55b66c7e69a85a0fe708f9f991",
9
- "README.md": "465c4c2b4aa1ba0e5a9b05573460168f67edda21977a9343f981f08ebb85999a",
10
- "dist/api-client.js": "22f46fc31fc61aa6e9c4219032b41a321ce324630fb8235cc2572797b73d29da",
8
+ ".claude-plugin/plugin.json": "01bd48ad1f8d8b000e276e4c00b60283735cd1a3390a243690d294bf28b5c65c",
9
+ "README.md": "4a52a8bb48672ae86d178340f017b2632eec1c71f8e62fbab0ef16cb64143ab9",
10
+ "dist/api-client.js": "e7eec2024f83cda93dcc390e47592ab9a9cb98a545ef230a3e51f73cc9ed5ba8",
11
11
  "dist/builtin-tools.generated.js": "870422c2a4403627486e48834fdae6ea5a1cd63dbfe707fa4db613a87028c214",
12
- "dist/extractors.js": "58c40eaad7e755b723f4f924ba56b2f37affbe42c6389bca369a62fb1c4fd1ac",
13
- "dist/index.js": "f0439bc13cc48d98037d013860b95b3ace49939c2ee2ff9f78b5d81c4bddad64",
12
+ "dist/extractors.js": "c22a4ee1d8949a9972ba69ec6154f4e55612da8334cd0247adaff57282c8ff16",
13
+ "dist/index.js": "a33220647ed78b98aa5750285ebaf4aefd8626331490c6be40d0571fc533b2b3",
14
14
  "dist/monitoring.js": "81e82124624e0deca9d11472c9ba4cd3ac7b2711b55fa10c45c22bd25f95a9d7",
15
15
  "dist/state.js": "66e724266b61fa73760a597d9ca328dd6fc31c7dfe2fb9370c764fadb20b190c",
16
16
  "dist/types.js": "a76a10af480d422f5f301cfc7d91a02db1d87695fcbf6d7475063faeb82f76a8",
17
- "hooks/hooks.json": "d50d298053754ddc6076d84fd94a35fe9c56468f5e9870a625edac6fbac65df9",
18
- "package.json": "a00fc1f5ff39648223a4fc517cda118216694074b40b8e25bbf1a11af051bce7"
17
+ "hooks/hooks.json": "0536e52460908b6595b69516c4cd4e4c1df1c2b2983dce01c62b13dfa3af94ef",
18
+ "package.json": "abeec58ee9a70c625ed259da6074046255a420168597175e8062ead069ab9a67"
19
19
  }
20
20
  },
21
21
  "kiro": {
22
- "pluginVersion": "1.0.0",
22
+ "pluginVersion": "1.1.0",
23
23
  "files": {
24
24
  ".kiro/agents/kiro_default.json": "f5cccf42d4f1a4b1a2268685ac74bae0b1068bf18dea7ff4965518a6c7b8d770",
25
25
  ".kiro/hooks/datagusto-post-tool-use.json": "58dacc6b875e733d63fd13f0f47cb2385eecea1ec29b076f71e8b9d137676258",
@@ -27,15 +27,15 @@
27
27
  ".kiro/hooks/datagusto-session-start.json": "992697cb2504e5527b26400c7aebe7e41f80d410bc0150520503897f6ff33a27",
28
28
  ".kiro/hooks/datagusto-stop.json": "f416a77d84fd74d97af8fba7b08161bc39d963fe1e4bfa86f9ed49589a16ae51",
29
29
  ".kiro/hooks/datagusto-user-prompt-submit.json": "752b562e871b19996ec0c63e90d43fdaec9930ed0871db32a95e4cd849c7237a",
30
- "dist/api-client.js": "22f46fc31fc61aa6e9c4219032b41a321ce324630fb8235cc2572797b73d29da",
30
+ "dist/api-client.js": "e7eec2024f83cda93dcc390e47592ab9a9cb98a545ef230a3e51f73cc9ed5ba8",
31
31
  "dist/builtin-tools.generated.js": "d13ae530ed33a55ec2e7d04c2f78e3b34505f68a952ecdb30a979cb9e26b3493",
32
32
  "dist/engine.js": "db0fca121485a6065c6626b4c3b114f06bd9cc8b374fad2d63f6c39565a4e891",
33
- "dist/extractors.js": "58c40eaad7e755b723f4f924ba56b2f37affbe42c6389bca369a62fb1c4fd1ac",
34
- "dist/index.js": "116d7d3e15e6fea78e830d2a6c9a101fe93207e4e6e37329c68086043f4fac64",
33
+ "dist/extractors.js": "c22a4ee1d8949a9972ba69ec6154f4e55612da8334cd0247adaff57282c8ff16",
34
+ "dist/index.js": "a39bc071062c112434678b8864df7f99e2296f61a39d76fbad3c4c9c3f39f61e",
35
35
  "dist/monitoring.js": "81e82124624e0deca9d11472c9ba4cd3ac7b2711b55fa10c45c22bd25f95a9d7",
36
36
  "dist/state.js": "66e724266b61fa73760a597d9ca328dd6fc31c7dfe2fb9370c764fadb20b190c",
37
37
  "dist/types.js": "a76a10af480d422f5f301cfc7d91a02db1d87695fcbf6d7475063faeb82f76a8",
38
- "package.json": "a0e6d2748fec919edbdb446f3e7b1184843a4e25d76230d0ff955951466e4f36"
38
+ "package.json": "121b94594a26c9e60ffb7de5c981ce2cb3c729405003600d0f12ba51818a3f8a"
39
39
  }
40
40
  }
41
41
  }