@silmaril-security/sdk 0.11.3 → 0.12.0

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.
@@ -119,6 +119,40 @@ function rejectConversationOptions(options) {
119
119
  }
120
120
  }
121
121
 
122
+ // src/verdicts.ts
123
+ var REMEMBERED_LIMIT = 1024;
124
+ var Remembered = class {
125
+ entries = /* @__PURE__ */ new Map();
126
+ get(key) {
127
+ if (key === void 0 || !this.entries.has(key)) return void 0;
128
+ const value = this.entries.get(key);
129
+ this.set(key, value);
130
+ return value;
131
+ }
132
+ set(key, value) {
133
+ this.entries.delete(key);
134
+ this.entries.set(key, value);
135
+ while (this.entries.size > REMEMBERED_LIMIT) this.entries.delete(this.entries.keys().next().value);
136
+ }
137
+ take(key) {
138
+ const value = this.entries.get(key);
139
+ this.entries.delete(key);
140
+ return value;
141
+ }
142
+ };
143
+ async function digest(text) {
144
+ const bytes = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
145
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
146
+ }
147
+ async function verdictKey(message, threadId, mode) {
148
+ if (!threadId || !message.id) return void 0;
149
+ try {
150
+ return JSON.stringify([threadId, message.id, await digest(JSON.stringify([message.content, message.additional_kwargs])), mode]);
151
+ } catch {
152
+ return void 0;
153
+ }
154
+ }
155
+
122
156
  // src/adapters/deepagents.ts
123
157
  var SAFE_TOOL_MESSAGE = "Silmaril Firewall blocked this tool interaction. Choose a different safe action.";
124
158
  var SAFE_FINAL_MESSAGE = "Silmaril Firewall stopped this request after repeated unsafe actions.";
@@ -313,16 +347,44 @@ function remoteNotification(message) {
313
347
  const extra = message.additional_kwargs ?? {};
314
348
  return typeof extra.lc_source === "string" && extra.lc_source.includes("async_subagent") || extra.deepagents_notification !== null && typeof extra.deepagents_notification === "object";
315
349
  }
316
- async function notificationKey(message, threadId, mode) {
317
- if (!threadId || !message.id) return void 0;
318
- try {
319
- const payload = JSON.stringify([message.content, message.additional_kwargs]);
320
- const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
321
- const hash = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
322
- return JSON.stringify([threadId, message.id, hash, mode]);
323
- } catch {
324
- return void 0;
350
+ var ASYNC_TASK_TOOLS = /* @__PURE__ */ new Set([
351
+ "start_async_task",
352
+ "check_async_task",
353
+ "update_async_task",
354
+ "cancel_async_task",
355
+ "list_async_tasks"
356
+ ]);
357
+ function lastIndexWhere(items, predicate) {
358
+ for (let index = items.length - 1; index >= 0; index--) {
359
+ if (predicate(items[index])) return index;
325
360
  }
361
+ return -1;
362
+ }
363
+ function blockedToolMessage(toolCallId, name, id) {
364
+ const message = new ToolMessage({
365
+ content: SAFE_TOOL_MESSAGE,
366
+ tool_call_id: toolCallId,
367
+ ...name === void 0 ? {} : { name },
368
+ ...id === void 0 ? {} : { id },
369
+ additional_kwargs: { silmarilBlocked: BLOCKED_TOOL_MARKER }
370
+ });
371
+ issuedBlockedMessages.add(message);
372
+ return message;
373
+ }
374
+ function isBlockedToolMessage(message) {
375
+ return ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER;
376
+ }
377
+ function rewriteInPlace(message, content) {
378
+ const { tool_calls: _toolCalls, function_call: _functionCall, ...additional_kwargs } = message.additional_kwargs ?? {};
379
+ const safe = {
380
+ content,
381
+ tool_calls: [],
382
+ invalid_tool_calls: [],
383
+ additional_kwargs,
384
+ ..."tool_call_chunks" in message ? { tool_call_chunks: [] } : {}
385
+ };
386
+ Object.assign(message, safe);
387
+ Object.assign(message.lc_kwargs, safe);
326
388
  }
327
389
  function createDeepAgentsMiddleware(firewall, options = {}) {
328
390
  rejectConversationOptions(options);
@@ -331,9 +393,10 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
331
393
  throw new Error("maxBlockedAttempts must be a positive integer");
332
394
  }
333
395
  const effectiveMode = validateMode(options.mode) ?? firewall.mode;
334
- const notificationChecks = /* @__PURE__ */ new Map();
396
+ const toolResultChecks = new Remembered();
335
397
  const parallel = options.parallel ?? false;
336
- const background = effectiveMode === "shadow" && options.failOpen !== false;
398
+ const background = (effectiveMode === "shadow" || effectiveMode === "warn") && options.failOpen !== false;
399
+ const queued = parallel && !background;
337
400
  const decide = (result, text, hook, toolName) => {
338
401
  const mode = effectiveMode ?? result.mode ?? "block";
339
402
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
@@ -372,83 +435,120 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
372
435
  };
373
436
  const classify = (text, hook, conversationId2, toolName) => {
374
437
  const check = prepare(text, hook, conversationId2, toolName);
375
- return parallel && !background ? firewall.pending.submit(check, conversationId({ conversationId: conversationId2 })) : check();
438
+ const decision = queued ? firewall.pending.submit(check, conversationId({ conversationId: conversationId2 })) : check();
439
+ decision.catch(() => void 0);
440
+ return decision;
441
+ };
442
+ const toolResultKey = async (conversationId2, toolCallId, text) => JSON.stringify([conversationId2 ?? null, toolCallId, await digest(text)]);
443
+ const unverifiedToolResults = async (messages, conversationId2) => {
444
+ const lastModelTurn = lastIndexWhere(messages, (message) => AIMessage.isInstance(message));
445
+ const results = [];
446
+ for (const [index, message] of messages.entries()) {
447
+ if (index <= lastModelTurn || !ToolMessage.isInstance(message) || isBlockedToolMessage(message)) continue;
448
+ const text = textOf(message);
449
+ const decision = toolResultChecks.take(await toolResultKey(conversationId2, message.tool_call_id, text)) ?? classify(text, HookLabel.TOOL_RESPONSE, conversationId2, message.name);
450
+ results.push({ index, message, decision });
451
+ }
452
+ return results;
376
453
  };
377
- const rememberNotification = (key, blocked) => {
378
- notificationChecks.set(key, blocked);
379
- while (notificationChecks.size > 1024) notificationChecks.delete(notificationChecks.keys().next().value);
454
+ const rememberAllowed = (key, decision) => {
455
+ if (key === void 0) return;
456
+ if (decision.cacheable && !decision.enforce) firewall.verdicts.set(key, false);
457
+ void decision.observed?.then((completed) => {
458
+ if (completed) firewall.verdicts.set(key, false);
459
+ });
380
460
  };
381
461
  return createMiddleware({
382
462
  name: "SilmarilDeepAgentsMiddleware",
383
463
  wrapModelCall: async (request, handler) => {
384
464
  const conversationId2 = nativeThreadId(request.runtime, void 0, void 0, ensureConfig());
385
- const messages = [];
386
- for (const message of request.messages) {
387
- let blocked = false;
388
- if (remoteNotification(message)) {
389
- const key = await notificationKey(message, conversationId2, effectiveMode);
390
- const cached = key === void 0 ? void 0 : notificationChecks.get(key);
391
- if (cached !== void 0) {
392
- blocked = cached;
393
- notificationChecks.delete(key);
394
- notificationChecks.set(key, cached);
395
- } else {
396
- const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId2, "async_subagent");
397
- blocked = decision.enforce;
398
- if (key !== void 0 && decision.cacheable) rememberNotification(key, blocked);
399
- if (key !== void 0) {
400
- void decision.observed?.then((completed) => {
401
- if (completed) rememberNotification(key, false);
402
- });
403
- }
404
- }
465
+ const messages = [...request.messages];
466
+ const notifications = [];
467
+ for (const [index, message] of request.messages.entries()) {
468
+ if (!remoteNotification(message)) continue;
469
+ const key = await verdictKey(message, conversationId2, effectiveMode);
470
+ const cached = firewall.verdicts.get(key);
471
+ if (cached !== void 0) {
472
+ if (cached) messages[index] = new HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } });
473
+ continue;
405
474
  }
406
- messages.push(blocked ? new HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } }) : message);
475
+ const decision = classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId2, "async_subagent");
476
+ if (!queued) await decision;
477
+ notifications.push({ index, key, decision });
407
478
  }
408
- request = { ...request, messages };
479
+ const toolResults = queued ? await unverifiedToolResults(request.messages, conversationId2) : [];
409
480
  const history = request.state.messages;
410
- let lastUserIndex = -1;
411
- for (let i = history.length - 1; i >= 0; i--) {
412
- if (HumanMessage.isInstance(history[i])) {
413
- lastUserIndex = i;
414
- break;
415
- }
416
- }
417
- const blockedCount = history.slice(lastUserIndex + 1).filter(
418
- (message) => ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER
419
- ).length;
420
- const latestUser = [...request.messages].reverse().find(HumanMessage.isInstance);
421
- const racesModel = parallel && !background && blockedCount < maxBlockedAttempts;
422
- const protectedRequest = request;
423
- const running = racesModel ? Promise.resolve().then(() => handler(protectedRequest)) : void 0;
481
+ const lastUserIndex = lastIndexWhere(history, (message) => HumanMessage.isInstance(message));
482
+ const blockedCount = history.slice(lastUserIndex + 1).filter(isBlockedToolMessage).length;
483
+ const latestUserIndex = lastIndexWhere(request.messages, (message) => HumanMessage.isInstance(message) && !remoteNotification(message));
484
+ const latestUser = latestUserIndex < 0 ? void 0 : request.messages[latestUserIndex];
485
+ const inputKey = latestUser === void 0 ? void 0 : await verdictKey(latestUser, conversationId2, effectiveMode);
486
+ const checksInput = latestUser !== void 0 && (blockedCount >= maxBlockedAttempts || firewall.verdicts.get(inputKey) !== false);
487
+ const racesModel = queued && blockedCount < maxBlockedAttempts;
488
+ const firstRequest = { ...request, messages: [...messages] };
489
+ const running = racesModel ? Promise.resolve().then(() => handler(firstRequest)) : void 0;
424
490
  running?.catch(() => void 0);
425
- const inputDecision = latestUser === void 0 ? void 0 : await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId2);
491
+ const inputDecision = checksInput ? await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId2) : void 0;
426
492
  if (inputDecision?.enforce) return new AIMessage(SAFE_OUTPUT_MESSAGE);
493
+ if (inputDecision !== void 0) rememberAllowed(inputKey, inputDecision);
494
+ let changed = false;
495
+ for (const { index, key, decision } of notifications) {
496
+ const verdict = await decision;
497
+ if (key !== void 0 && verdict.cacheable) firewall.verdicts.set(key, verdict.enforce);
498
+ rememberAllowed(key, verdict);
499
+ if (verdict.enforce) {
500
+ const message = request.messages[index];
501
+ messages[index] = new HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } });
502
+ changed = true;
503
+ }
504
+ }
505
+ const replacements = [];
506
+ let lateDenials = 0;
507
+ for (const { index, message, decision } of toolResults) {
508
+ if (!(await decision).enforce) continue;
509
+ const replacement = blockedToolMessage(message.tool_call_id, message.name, message.id);
510
+ messages[index] = replacement;
511
+ if (message.id !== void 0) replacements.push(replacement);
512
+ lateDenials += 1;
513
+ changed = true;
514
+ }
427
515
  const capMode = effectiveMode ?? inputDecision?.mode ?? "block";
428
- if (blockedCount >= maxBlockedAttempts && capMode === "block") {
429
- return new AIMessage(SAFE_FINAL_MESSAGE);
516
+ const discarded = changed && running !== void 0 ? await running.then((result) => result, () => void 0) : void 0;
517
+ const withState = (final, raw) => {
518
+ if (replacements.length === 0) return final;
519
+ if (!AIMessage.isInstance(final) || final === raw) return new Command({ update: { messages: replacements } });
520
+ if (AIMessage.isInstance(raw)) {
521
+ rewriteInPlace(raw, final.content);
522
+ return new Command({ update: { messages: replacements } });
523
+ }
524
+ return new Command({ update: { messages: [...replacements, final] } });
525
+ };
526
+ if (blockedCount + lateDenials >= maxBlockedAttempts && capMode === "block") {
527
+ return withState(new AIMessage(SAFE_FINAL_MESSAGE), discarded);
430
528
  }
431
- const response = await (running ?? handler(request));
529
+ const response = changed || running === void 0 ? await handler({ ...request, messages }) : await running;
432
530
  if (response instanceof Command && (await classify(textOfStructuredValue(response.update), HookLabel.LLM_OUTPUT, conversationId2)).enforce) {
433
- return new AIMessage(SAFE_OUTPUT_MESSAGE);
531
+ return withState(new AIMessage(SAFE_OUTPUT_MESSAGE), response);
434
532
  }
435
533
  if (AIMessage.isInstance(response) && (await classify(textOf(response), HookLabel.LLM_OUTPUT, conversationId2)).enforce) {
436
- return new AIMessage(SAFE_OUTPUT_MESSAGE);
534
+ return withState(new AIMessage(SAFE_OUTPUT_MESSAGE), response);
437
535
  }
438
- return response;
536
+ return withState(response, response);
537
+ },
538
+ afterAgent: async (state, runtime) => {
539
+ if (!queued) return void 0;
540
+ const conversationId2 = nativeThreadId(runtime, void 0, void 0, ensureConfig());
541
+ const replacements = [];
542
+ for (const { message, decision } of await unverifiedToolResults(state.messages, conversationId2)) {
543
+ if ((await decision).enforce && message.id !== void 0) {
544
+ replacements.push(blockedToolMessage(message.tool_call_id, message.name, message.id));
545
+ }
546
+ }
547
+ return replacements.length === 0 ? void 0 : { messages: replacements };
439
548
  },
440
549
  wrapToolCall: async (request, handler) => {
441
550
  const conversationId2 = nativeThreadId(request.runtime, void 0, void 0, ensureConfig());
442
- const safe = () => {
443
- const message = new ToolMessage({
444
- content: SAFE_TOOL_MESSAGE,
445
- tool_call_id: request.toolCall.id ?? "",
446
- name: request.toolCall.name,
447
- additional_kwargs: { silmarilBlocked: BLOCKED_TOOL_MARKER }
448
- });
449
- issuedBlockedMessages.add(message);
450
- return message;
451
- };
551
+ const safe = () => blockedToolMessage(request.toolCall.id ?? "", request.toolCall.name);
452
552
  if ((await classify(JSON.stringify(request.toolCall.args ?? {}), HookLabel.TOOL_CALL, conversationId2, request.toolCall.name)).enforce) {
453
553
  return safe();
454
554
  }
@@ -457,11 +557,16 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
457
557
  try {
458
558
  resultText = ToolMessage.isInstance(result) ? textOf(result) : result instanceof Command ? textOfStructuredValue(result.update) : String(result);
459
559
  } catch {
460
- const decision = await classify("[uninspectable tool result]", HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
461
- return decision.mode === "block" ? safe() : stripAllowedMarker(result);
560
+ const decision2 = await classify("[uninspectable tool result]", HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
561
+ return decision2.mode === "block" ? safe() : stripAllowedMarker(result);
562
+ }
563
+ const decision = classify(resultText, HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
564
+ if (queued && request.toolCall.id && ToolMessage.isInstance(result)) {
565
+ toolResultChecks.set(await toolResultKey(conversationId2, request.toolCall.id, resultText), decision);
566
+ return stripAllowedMarker(result);
462
567
  }
463
- if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name)).enforce) {
464
- if (["start_async_task", "check_async_task", "update_async_task", "cancel_async_task", "list_async_tasks"].includes(request.toolCall.name) && result instanceof Command && result.update && !Array.isArray(result.update) && "asyncTasks" in result.update) {
568
+ if ((await decision).enforce) {
569
+ if (ASYNC_TASK_TOOLS.has(request.toolCall.name) && result instanceof Command && result.update && !Array.isArray(result.update) && "asyncTasks" in result.update) {
465
570
  return new Command({ update: { messages: [safe()], asyncTasks: result.update.asyncTasks } });
466
571
  }
467
572
  return safe();