@datagusto/cli 0.2.1 → 0.2.3
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/README.md +1 -0
- package/dist/adapters/claude-code.js +2 -1
- package/dist/adapters/claude-code.js.map +1 -1
- package/dist/hooks/init/update-check.d.ts +3 -0
- package/dist/hooks/init/update-check.js +34 -0
- package/dist/hooks/init/update-check.js.map +1 -0
- package/dist/update-check.d.ts +30 -0
- package/dist/update-check.js +109 -0
- package/dist/update-check.js.map +1 -0
- package/package.json +6 -3
- package/vendor/claude_code/.claude-plugin/plugin.json +2 -2
- package/vendor/claude_code/README.md +47 -16
- package/vendor/claude_code/dist/api-client.js +9 -0
- package/vendor/claude_code/dist/extractors.js +109 -0
- package/vendor/claude_code/dist/index.js +149 -2
- package/vendor/claude_code/hooks/hooks.json +3 -0
- package/vendor/claude_code/package.json +1 -1
- package/vendor/kiro/dist/api-client.js +9 -0
- package/vendor/kiro/dist/extractors.js +109 -0
- package/vendor/kiro/dist/index.js +133 -6
- package/vendor/kiro/package.json +1 -1
- package/vendor/manifest.json +14 -14
|
@@ -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
|
],
|
|
@@ -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
|