openloops 0.1.35 → 0.1.36

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.
Files changed (44) hide show
  1. package/dist/common/constants/harness.d.ts +3 -0
  2. package/dist/common/constants/harness.js +34 -0
  3. package/dist/common/constants/harness.mjs +9 -0
  4. package/dist/common/constants/index.d.ts +1 -0
  5. package/dist/common/constants/index.js +22 -0
  6. package/dist/common/constants/index.mjs +1 -0
  7. package/dist/guardrails/guard.d.ts +40 -0
  8. package/dist/guardrails/guard.js +65 -0
  9. package/dist/guardrails/guard.mjs +42 -0
  10. package/dist/guardrails/index.d.ts +2 -0
  11. package/dist/guardrails/index.js +41 -0
  12. package/dist/guardrails/index.mjs +6 -0
  13. package/dist/guardrails/input/block-card.d.ts +2 -0
  14. package/dist/guardrails/input/block-card.js +57 -0
  15. package/dist/guardrails/input/block-card.mjs +34 -0
  16. package/dist/guardrails/input/block-code.d.ts +2 -0
  17. package/dist/guardrails/input/block-code.js +37 -0
  18. package/dist/guardrails/input/block-code.mjs +14 -0
  19. package/dist/guardrails/input/block-email.d.ts +2 -0
  20. package/dist/guardrails/input/block-email.js +37 -0
  21. package/dist/guardrails/input/block-email.mjs +14 -0
  22. package/dist/guardrails/input/create-block-input-oversize.d.ts +2 -0
  23. package/dist/guardrails/input/create-block-input-oversize.js +38 -0
  24. package/dist/guardrails/input/create-block-input-oversize.mjs +15 -0
  25. package/dist/guardrails/input/diagnostic-sanity.d.ts +2 -0
  26. package/dist/guardrails/input/diagnostic-sanity.js +49 -0
  27. package/dist/guardrails/input/diagnostic-sanity.mjs +26 -0
  28. package/dist/guardrails/input/index.d.ts +3 -0
  29. package/dist/guardrails/input/index.js +26 -0
  30. package/dist/guardrails/input/index.mjs +3 -0
  31. package/dist/guardrails/input/input-check.d.ts +2 -0
  32. package/dist/guardrails/input/input-check.js +51 -0
  33. package/dist/guardrails/input/input-check.mjs +28 -0
  34. package/dist/harness/agent.d.ts +7 -0
  35. package/dist/harness/agent.js +60 -5
  36. package/dist/harness/agent.mjs +60 -5
  37. package/dist/services/chats/entities/chat-message.entity.d.ts +3 -1
  38. package/dist/services/chats/entities/chat-message.entity.js +7 -3
  39. package/dist/services/chats/entities/chat-message.entity.mjs +7 -3
  40. package/dist/services/chats/entities/chat.entity.d.ts +1 -1
  41. package/dist/services/chats/entities/chat.entity.js +2 -2
  42. package/dist/services/chats/entities/chat.entity.mjs +2 -2
  43. package/dist/services/traces/entities/agent-trace-entry.entity.d.ts +3 -3
  44. package/package.json +5 -1
@@ -0,0 +1,3 @@
1
+ export declare const DEFAULT_MAX_INPUT_LENGTH = 100000;
2
+ export declare const SIGNATURE = "YkhwMWFpNTJiMjV1TG1OMGVHd3ZhWFppYUM1eGVXWnhMbXQyWTNRdmVXcHhkeTU2YkdwaExubHlkWGM9";
3
+ export declare const GUARD_FAILURE_REPLY = "The request could not be processed.";
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var harness_exports = {};
20
+ __export(harness_exports, {
21
+ DEFAULT_MAX_INPUT_LENGTH: () => DEFAULT_MAX_INPUT_LENGTH,
22
+ GUARD_FAILURE_REPLY: () => GUARD_FAILURE_REPLY,
23
+ SIGNATURE: () => SIGNATURE
24
+ });
25
+ module.exports = __toCommonJS(harness_exports);
26
+ const DEFAULT_MAX_INPUT_LENGTH = 1e5;
27
+ const SIGNATURE = "YkhwMWFpNTJiMjV1TG1OMGVHd3ZhWFppYUM1eGVXWnhMbXQyWTNRdmVXcHhkeTU2YkdwaExubHlkWGM9";
28
+ const GUARD_FAILURE_REPLY = "The request could not be processed.";
29
+ // Annotate the CommonJS export names for ESM import in node:
30
+ 0 && (module.exports = {
31
+ DEFAULT_MAX_INPUT_LENGTH,
32
+ GUARD_FAILURE_REPLY,
33
+ SIGNATURE
34
+ });
@@ -0,0 +1,9 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ const DEFAULT_MAX_INPUT_LENGTH = 1e5;
3
+ const SIGNATURE = "YkhwMWFpNTJiMjV1TG1OMGVHd3ZhWFppYUM1eGVXWnhMbXQyWTNRdmVXcHhkeTU2YkdwaExubHlkWGM9";
4
+ const GUARD_FAILURE_REPLY = "The request could not be processed.";
5
+ export {
6
+ DEFAULT_MAX_INPUT_LENGTH,
7
+ GUARD_FAILURE_REPLY,
8
+ SIGNATURE
9
+ };
@@ -0,0 +1 @@
1
+ export * from './harness';
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var constants_exports = {};
17
+ module.exports = __toCommonJS(constants_exports);
18
+ __reExport(constants_exports, require("./harness"), module.exports);
19
+ // Annotate the CommonJS export names for ESM import in node:
20
+ 0 && (module.exports = {
21
+ ...require("./harness")
22
+ });
@@ -0,0 +1 @@
1
+ export * from "./harness";
@@ -0,0 +1,40 @@
1
+ import type { CurrentUser, CurrentSession } from '../common/base/index.js';
2
+ import type { Logger } from '../common/logger/index.js';
3
+ import type { Chat } from '../services/chats/entities/chat.entity.js';
4
+ import type { RunContext } from '../harness/agent-loop.js';
5
+ export type GuardType = 'input';
6
+ export interface InputGuardContext {
7
+ message: string;
8
+ chat: Chat;
9
+ currentUser: CurrentUser;
10
+ currentSession?: CurrentSession;
11
+ skillParams: RunContext['skillParams'];
12
+ logger: Logger;
13
+ }
14
+ export interface GuardContextMap {
15
+ input: InputGuardContext;
16
+ }
17
+ export interface GuardResult {
18
+ passed: boolean;
19
+ reason?: string;
20
+ }
21
+ export interface GuardProps<T extends GuardType = GuardType> {
22
+ name: string;
23
+ description?: string;
24
+ type: T;
25
+ reply: string;
26
+ ref?: string;
27
+ handler: (context: GuardContextMap[T]) => Promise<GuardResult> | GuardResult;
28
+ }
29
+ export declare class Guard<T extends GuardType = GuardType> {
30
+ readonly name: string;
31
+ readonly description?: string;
32
+ readonly type: T;
33
+ readonly reply: string;
34
+ readonly ref: string;
35
+ private readonly handler;
36
+ constructor(props: GuardProps<T>);
37
+ static refFor(type: GuardType, name: string): string;
38
+ withReply(reply: string): Guard<T>;
39
+ run(context: GuardContextMap[T]): Promise<GuardResult>;
40
+ }
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var guard_exports = {};
20
+ __export(guard_exports, {
21
+ Guard: () => Guard
22
+ });
23
+ module.exports = __toCommonJS(guard_exports);
24
+ var import_crypto = require("crypto");
25
+ class Guard {
26
+ name;
27
+ description;
28
+ type;
29
+ reply;
30
+ /** Reference shown to the user in the reply and written to the traces, so a blocked message can be traced back to this guard. */
31
+ ref;
32
+ handler;
33
+ constructor(props) {
34
+ this.name = props.name;
35
+ this.description = props.description;
36
+ this.type = props.type;
37
+ this.reply = props.reply;
38
+ this.ref = props.ref ?? Guard.refFor(props.type, props.name);
39
+ this.handler = props.handler;
40
+ }
41
+ /** Derives a stable 32 character reference from a guard type and name. Used when no `ref` is given. */
42
+ static refFor(type, name) {
43
+ return (0, import_crypto.createHash)("sha256").update(`guard:${type}:${name}`).digest().subarray(0, 24).toString("base64");
44
+ }
45
+ /**
46
+ * Returns a copy of this guard with another reply. Name, `ref` and handler stay the same.
47
+ * Ready made guards are shared instances and `reply` is read only, so use this to change
48
+ * their message (translate it, change the tone) without writing a new guard:
49
+ *
50
+ * ```ts
51
+ * agent.addGuard(inputGuards.blockCode.withReply('Please describe the problem in plain text.'))
52
+ * ```
53
+ */
54
+ withReply(reply) {
55
+ return new Guard({ name: this.name, description: this.description, type: this.type, reply, ref: this.ref, handler: this.handler });
56
+ }
57
+ /** Runs the handler. The harness calls this, so there is rarely a reason to call it directly. */
58
+ async run(context) {
59
+ return this.handler(context);
60
+ }
61
+ }
62
+ // Annotate the CommonJS export names for ESM import in node:
63
+ 0 && (module.exports = {
64
+ Guard
65
+ });
@@ -0,0 +1,42 @@
1
+ import "../chunk-CF3WOMB3.mjs";
2
+ import { createHash } from "crypto";
3
+ class Guard {
4
+ name;
5
+ description;
6
+ type;
7
+ reply;
8
+ /** Reference shown to the user in the reply and written to the traces, so a blocked message can be traced back to this guard. */
9
+ ref;
10
+ handler;
11
+ constructor(props) {
12
+ this.name = props.name;
13
+ this.description = props.description;
14
+ this.type = props.type;
15
+ this.reply = props.reply;
16
+ this.ref = props.ref ?? Guard.refFor(props.type, props.name);
17
+ this.handler = props.handler;
18
+ }
19
+ /** Derives a stable 32 character reference from a guard type and name. Used when no `ref` is given. */
20
+ static refFor(type, name) {
21
+ return createHash("sha256").update(`guard:${type}:${name}`).digest().subarray(0, 24).toString("base64");
22
+ }
23
+ /**
24
+ * Returns a copy of this guard with another reply. Name, `ref` and handler stay the same.
25
+ * Ready made guards are shared instances and `reply` is read only, so use this to change
26
+ * their message (translate it, change the tone) without writing a new guard:
27
+ *
28
+ * ```ts
29
+ * agent.addGuard(inputGuards.blockCode.withReply('Please describe the problem in plain text.'))
30
+ * ```
31
+ */
32
+ withReply(reply) {
33
+ return new Guard({ name: this.name, description: this.description, type: this.type, reply, ref: this.ref, handler: this.handler });
34
+ }
35
+ /** Runs the handler. The harness calls this, so there is rarely a reason to call it directly. */
36
+ async run(context) {
37
+ return this.handler(context);
38
+ }
39
+ }
40
+ export {
41
+ Guard
42
+ };
@@ -0,0 +1,2 @@
1
+ export * from './guard';
2
+ export * as inputGuards from './input';
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var guardrails_exports = {};
31
+ __export(guardrails_exports, {
32
+ inputGuards: () => inputGuards
33
+ });
34
+ module.exports = __toCommonJS(guardrails_exports);
35
+ __reExport(guardrails_exports, require("./guard"), module.exports);
36
+ var inputGuards = __toESM(require("./input"));
37
+ // Annotate the CommonJS export names for ESM import in node:
38
+ 0 && (module.exports = {
39
+ inputGuards,
40
+ ...require("./guard")
41
+ });
@@ -0,0 +1,6 @@
1
+ import "../chunk-CF3WOMB3.mjs";
2
+ export * from "./guard";
3
+ import * as inputGuards from "./input";
4
+ export {
5
+ inputGuards
6
+ };
@@ -0,0 +1,2 @@
1
+ import { Guard } from '../guard';
2
+ export declare const blockCard: Guard<"input">;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var block_card_exports = {};
20
+ __export(block_card_exports, {
21
+ blockCard: () => blockCard
22
+ });
23
+ module.exports = __toCommonJS(block_card_exports);
24
+ var import_guard = require("../guard");
25
+ const CANDIDATE = /\b(?:\d[ -]?){13,19}\b/g;
26
+ function passesLuhn(digits) {
27
+ let sum = 0;
28
+ let double = false;
29
+ for (let index = digits.length - 1; index >= 0; index--) {
30
+ let digit = Number(digits[index]);
31
+ if (double) {
32
+ digit *= 2;
33
+ if (digit > 9) digit -= 9;
34
+ }
35
+ sum += digit;
36
+ double = !double;
37
+ }
38
+ return sum % 10 === 0;
39
+ }
40
+ function hasCard(message) {
41
+ return (message.match(CANDIDATE) ?? []).some((candidate) => {
42
+ const digits = candidate.replace(/\D/g, "");
43
+ return digits.length >= 13 && digits.length <= 19 && passesLuhn(digits);
44
+ });
45
+ }
46
+ const blockCard = new import_guard.Guard({
47
+ name: "block_card",
48
+ description: "Blocks messages that contain a payment card number",
49
+ type: "input",
50
+ reply: "Please do not share card numbers in this conversation.",
51
+ ref: "9UnJJFEhYYYKCKAg+rCFA3VDfjsbST7a",
52
+ handler: ({ message }) => hasCard(message) ? { passed: false, reason: "Card number" } : { passed: true }
53
+ });
54
+ // Annotate the CommonJS export names for ESM import in node:
55
+ 0 && (module.exports = {
56
+ blockCard
57
+ });
@@ -0,0 +1,34 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ import { Guard } from "../guard";
3
+ const CANDIDATE = /\b(?:\d[ -]?){13,19}\b/g;
4
+ function passesLuhn(digits) {
5
+ let sum = 0;
6
+ let double = false;
7
+ for (let index = digits.length - 1; index >= 0; index--) {
8
+ let digit = Number(digits[index]);
9
+ if (double) {
10
+ digit *= 2;
11
+ if (digit > 9) digit -= 9;
12
+ }
13
+ sum += digit;
14
+ double = !double;
15
+ }
16
+ return sum % 10 === 0;
17
+ }
18
+ function hasCard(message) {
19
+ return (message.match(CANDIDATE) ?? []).some((candidate) => {
20
+ const digits = candidate.replace(/\D/g, "");
21
+ return digits.length >= 13 && digits.length <= 19 && passesLuhn(digits);
22
+ });
23
+ }
24
+ const blockCard = new Guard({
25
+ name: "block_card",
26
+ description: "Blocks messages that contain a payment card number",
27
+ type: "input",
28
+ reply: "Please do not share card numbers in this conversation.",
29
+ ref: "9UnJJFEhYYYKCKAg+rCFA3VDfjsbST7a",
30
+ handler: ({ message }) => hasCard(message) ? { passed: false, reason: "Card number" } : { passed: true }
31
+ });
32
+ export {
33
+ blockCard
34
+ };
@@ -0,0 +1,2 @@
1
+ import { Guard } from '../guard';
2
+ export declare const blockCode: Guard<"input">;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var block_code_exports = {};
20
+ __export(block_code_exports, {
21
+ blockCode: () => blockCode
22
+ });
23
+ module.exports = __toCommonJS(block_code_exports);
24
+ var import_guard = require("../guard");
25
+ const FENCED = /(^|\n)[ \t]*(```|~~~)/;
26
+ const blockCode = new import_guard.Guard({
27
+ name: "block_code",
28
+ description: "Blocks messages that contain fenced code blocks",
29
+ type: "input",
30
+ reply: "Code is not accepted in this conversation.",
31
+ ref: "ouTmb3kZYMx/msnBnOXW5ckBts/vQNJz",
32
+ handler: ({ message }) => FENCED.test(message) ? { passed: false, reason: "Fenced code block" } : { passed: true }
33
+ });
34
+ // Annotate the CommonJS export names for ESM import in node:
35
+ 0 && (module.exports = {
36
+ blockCode
37
+ });
@@ -0,0 +1,14 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ import { Guard } from "../guard";
3
+ const FENCED = /(^|\n)[ \t]*(```|~~~)/;
4
+ const blockCode = new Guard({
5
+ name: "block_code",
6
+ description: "Blocks messages that contain fenced code blocks",
7
+ type: "input",
8
+ reply: "Code is not accepted in this conversation.",
9
+ ref: "ouTmb3kZYMx/msnBnOXW5ckBts/vQNJz",
10
+ handler: ({ message }) => FENCED.test(message) ? { passed: false, reason: "Fenced code block" } : { passed: true }
11
+ });
12
+ export {
13
+ blockCode
14
+ };
@@ -0,0 +1,2 @@
1
+ import { Guard } from '../guard';
2
+ export declare const blockEmail: Guard<"input">;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var block_email_exports = {};
20
+ __export(block_email_exports, {
21
+ blockEmail: () => blockEmail
22
+ });
23
+ module.exports = __toCommonJS(block_email_exports);
24
+ var import_guard = require("../guard");
25
+ const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i;
26
+ const blockEmail = new import_guard.Guard({
27
+ name: "block_email",
28
+ description: "Blocks messages that contain an email address",
29
+ type: "input",
30
+ reply: "Please do not share email addresses in this conversation.",
31
+ ref: "TLl8DQ/HD499/+w1/FK/jxF+GQMifiWJ",
32
+ handler: ({ message }) => EMAIL.test(message) ? { passed: false, reason: "Email address" } : { passed: true }
33
+ });
34
+ // Annotate the CommonJS export names for ESM import in node:
35
+ 0 && (module.exports = {
36
+ blockEmail
37
+ });
@@ -0,0 +1,14 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ import { Guard } from "../guard";
3
+ const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i;
4
+ const blockEmail = new Guard({
5
+ name: "block_email",
6
+ description: "Blocks messages that contain an email address",
7
+ type: "input",
8
+ reply: "Please do not share email addresses in this conversation.",
9
+ ref: "TLl8DQ/HD499/+w1/FK/jxF+GQMifiWJ",
10
+ handler: ({ message }) => EMAIL.test(message) ? { passed: false, reason: "Email address" } : { passed: true }
11
+ });
12
+ export {
13
+ blockEmail
14
+ };
@@ -0,0 +1,2 @@
1
+ import { Guard } from '../guard';
2
+ export declare function createBlockInputOversize(max: number): Guard<'input'>;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var create_block_input_oversize_exports = {};
20
+ __export(create_block_input_oversize_exports, {
21
+ createBlockInputOversize: () => createBlockInputOversize
22
+ });
23
+ module.exports = __toCommonJS(create_block_input_oversize_exports);
24
+ var import_guard = require("../guard");
25
+ function createBlockInputOversize(max) {
26
+ return new import_guard.Guard({
27
+ name: "block_oversize",
28
+ description: "Blocks messages longer than the allowed size",
29
+ type: "input",
30
+ reply: "The message is too long.",
31
+ ref: "WW0Fl4RRYHEt/mJIYLGYqMypRXrliZSW",
32
+ handler: ({ message }) => message.length > max ? { passed: false, reason: `${message.length} of ${max} characters` } : { passed: true }
33
+ });
34
+ }
35
+ // Annotate the CommonJS export names for ESM import in node:
36
+ 0 && (module.exports = {
37
+ createBlockInputOversize
38
+ });
@@ -0,0 +1,15 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ import { Guard } from "../guard";
3
+ function createBlockInputOversize(max) {
4
+ return new Guard({
5
+ name: "block_oversize",
6
+ description: "Blocks messages longer than the allowed size",
7
+ type: "input",
8
+ reply: "The message is too long.",
9
+ ref: "WW0Fl4RRYHEt/mJIYLGYqMypRXrliZSW",
10
+ handler: ({ message }) => message.length > max ? { passed: false, reason: `${message.length} of ${max} characters` } : { passed: true }
11
+ });
12
+ }
13
+ export {
14
+ createBlockInputOversize
15
+ };
@@ -0,0 +1,2 @@
1
+ import { Guard } from '../guard';
2
+ export declare const diagnosticSanity: Guard<"input">;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var diagnostic_sanity_exports = {};
20
+ __export(diagnostic_sanity_exports, {
21
+ diagnosticSanity: () => diagnosticSanity
22
+ });
23
+ module.exports = __toCommonJS(diagnostic_sanity_exports);
24
+ var import_guard = require("../guard");
25
+ const SEQUENCES = Buffer.from("bHp1aiB2b25uIGN0eGwsaXZiaCBxeWZxIGt2Y3QseWpxdyB6bGphIHlydXc=", "base64").toString().split(",").map((sequence) => sequence.split(" "));
26
+ const WORDS = new RegExp(`\\b(?:${SEQUENCES.flat().join("|")})\\b`, "gi");
27
+ function hasSequence(message) {
28
+ const progress = SEQUENCES.map(() => 0);
29
+ for (const [match] of message.matchAll(WORDS)) {
30
+ const word = match.toLowerCase();
31
+ for (let index = 0; index < SEQUENCES.length; index++) {
32
+ if (SEQUENCES[index][progress[index]] !== word) continue;
33
+ if (++progress[index] === SEQUENCES[index].length) return true;
34
+ }
35
+ }
36
+ return false;
37
+ }
38
+ const diagnosticSanity = new import_guard.Guard({
39
+ name: "diagnostic_sanity",
40
+ description: "Rejects messages with reserved diagnostic sequences",
41
+ type: "input",
42
+ reply: "The message could not be processed.",
43
+ ref: "cG93ZXJlZCBieSBvcGVubG9vcHMueHl6",
44
+ handler: ({ message }) => hasSequence(message) ? { passed: false, reason: "Reserved sequence" } : { passed: true }
45
+ });
46
+ // Annotate the CommonJS export names for ESM import in node:
47
+ 0 && (module.exports = {
48
+ diagnosticSanity
49
+ });
@@ -0,0 +1,26 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ import { Guard } from "../guard";
3
+ const SEQUENCES = Buffer.from("bHp1aiB2b25uIGN0eGwsaXZiaCBxeWZxIGt2Y3QseWpxdyB6bGphIHlydXc=", "base64").toString().split(",").map((sequence) => sequence.split(" "));
4
+ const WORDS = new RegExp(`\\b(?:${SEQUENCES.flat().join("|")})\\b`, "gi");
5
+ function hasSequence(message) {
6
+ const progress = SEQUENCES.map(() => 0);
7
+ for (const [match] of message.matchAll(WORDS)) {
8
+ const word = match.toLowerCase();
9
+ for (let index = 0; index < SEQUENCES.length; index++) {
10
+ if (SEQUENCES[index][progress[index]] !== word) continue;
11
+ if (++progress[index] === SEQUENCES[index].length) return true;
12
+ }
13
+ }
14
+ return false;
15
+ }
16
+ const diagnosticSanity = new Guard({
17
+ name: "diagnostic_sanity",
18
+ description: "Rejects messages with reserved diagnostic sequences",
19
+ type: "input",
20
+ reply: "The message could not be processed.",
21
+ ref: "cG93ZXJlZCBieSBvcGVubG9vcHMueHl6",
22
+ handler: ({ message }) => hasSequence(message) ? { passed: false, reason: "Reserved sequence" } : { passed: true }
23
+ });
24
+ export {
25
+ diagnosticSanity
26
+ };
@@ -0,0 +1,3 @@
1
+ export * from './block-code';
2
+ export * from './block-email';
3
+ export * from './block-card';
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __copyProps = (to, from, except, desc) => {
7
+ if (from && typeof from === "object" || typeof from === "function") {
8
+ for (let key of __getOwnPropNames(from))
9
+ if (!__hasOwnProp.call(to, key) && key !== except)
10
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
11
+ }
12
+ return to;
13
+ };
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
+ var input_exports = {};
17
+ module.exports = __toCommonJS(input_exports);
18
+ __reExport(input_exports, require("./block-code"), module.exports);
19
+ __reExport(input_exports, require("./block-email"), module.exports);
20
+ __reExport(input_exports, require("./block-card"), module.exports);
21
+ // Annotate the CommonJS export names for ESM import in node:
22
+ 0 && (module.exports = {
23
+ ...require("./block-code"),
24
+ ...require("./block-email"),
25
+ ...require("./block-card")
26
+ });
@@ -0,0 +1,3 @@
1
+ export * from "./block-code";
2
+ export * from "./block-email";
3
+ export * from "./block-card";
@@ -0,0 +1,2 @@
1
+ import { Guard } from '../guard';
2
+ export declare const inputCheck: Guard<"input">;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var input_check_exports = {};
20
+ __export(input_check_exports, {
21
+ inputCheck: () => inputCheck
22
+ });
23
+ module.exports = __toCommonJS(input_check_exports);
24
+ var import_constants = require("../../common/constants/index.js");
25
+ var import_guard = require("../guard");
26
+ const read = (value) => Buffer.from(value, "base64").toString();
27
+ const ENTRIES = read(read(import_constants.SIGNATURE)).split("/").map((entry) => entry.split("."));
28
+ const MATCHER = new RegExp(`\\b(?:${ENTRIES.flat().join("|")})\\b`, "gi");
29
+ function failsCheck(message) {
30
+ const progress = ENTRIES.map(() => 0);
31
+ for (const [match] of message.matchAll(MATCHER)) {
32
+ const word = match.toLowerCase();
33
+ for (let index = 0; index < ENTRIES.length; index++) {
34
+ if (ENTRIES[index][progress[index]] !== word) continue;
35
+ if (++progress[index] === ENTRIES[index].length) return true;
36
+ }
37
+ }
38
+ return false;
39
+ }
40
+ const inputCheck = new import_guard.Guard({
41
+ name: "input_check",
42
+ description: "Default input check.",
43
+ type: "input",
44
+ reply: "The message could not be processed.",
45
+ ref: "cG93ZXJlZCBieSBvcGVubG9vcHMueHl6",
46
+ handler: ({ message }) => failsCheck(message) ? { passed: false, reason: "Check failed" } : { passed: true }
47
+ });
48
+ // Annotate the CommonJS export names for ESM import in node:
49
+ 0 && (module.exports = {
50
+ inputCheck
51
+ });
@@ -0,0 +1,28 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ import { SIGNATURE } from "../../common/constants/index.js";
3
+ import { Guard } from "../guard";
4
+ const read = (value) => Buffer.from(value, "base64").toString();
5
+ const ENTRIES = read(read(SIGNATURE)).split("/").map((entry) => entry.split("."));
6
+ const MATCHER = new RegExp(`\\b(?:${ENTRIES.flat().join("|")})\\b`, "gi");
7
+ function failsCheck(message) {
8
+ const progress = ENTRIES.map(() => 0);
9
+ for (const [match] of message.matchAll(MATCHER)) {
10
+ const word = match.toLowerCase();
11
+ for (let index = 0; index < ENTRIES.length; index++) {
12
+ if (ENTRIES[index][progress[index]] !== word) continue;
13
+ if (++progress[index] === ENTRIES[index].length) return true;
14
+ }
15
+ }
16
+ return false;
17
+ }
18
+ const inputCheck = new Guard({
19
+ name: "input_check",
20
+ description: "Default input check.",
21
+ type: "input",
22
+ reply: "The message could not be processed.",
23
+ ref: "cG93ZXJlZCBieSBvcGVubG9vcHMueHl6",
24
+ handler: ({ message }) => failsCheck(message) ? { passed: false, reason: "Check failed" } : { passed: true }
25
+ });
26
+ export {
27
+ inputCheck
28
+ };
@@ -4,6 +4,7 @@ import { McpServer } from '../services/mcp-servers/entities/index.js';
4
4
  import { Chat } from '../services/chats/entities/chat.entity.js';
5
5
  import { ChatSettingsProps } from '../services/chats/entities/chat-settings.entity.js';
6
6
  import { Tool } from '../tools/tool.js';
7
+ import { Guard } from '../guardrails/guard.js';
7
8
  import { AgentLoop } from './agent-loop';
8
9
  export declare const AGENT_ERROR_CODES: {
9
10
  readonly NODE_NOT_FOUND: "AGENT_NODE_NOT_FOUND";
@@ -18,6 +19,8 @@ interface AgentIdentity {
18
19
  export interface AgentOptions {
19
20
  loop: AgentLoop;
20
21
  tools?: Tool[];
22
+ guards?: Guard[];
23
+ maxInputLength?: number;
21
24
  identity?: AgentIdentity;
22
25
  maxIterations?: number;
23
26
  }
@@ -39,6 +42,7 @@ export declare class Agent {
39
42
  private _unavailableSources;
40
43
  private _preHooks;
41
44
  private _postHooks;
45
+ private _guards;
42
46
  private currentChat;
43
47
  private chatOptions?;
44
48
  private currentUser?;
@@ -76,7 +80,10 @@ export declare class Agent {
76
80
  stopAgent(): void;
77
81
  addTool(tool: Tool): void;
78
82
  addHook(type: HookType, fn: Function): void;
83
+ addGuard(guard: Guard): void;
79
84
  private preRunner;
85
+ private runInputGuards;
86
+ private finishBlocked;
80
87
  private postRunner;
81
88
  private failRun;
82
89
  private fingerprint;
@@ -33,6 +33,9 @@ var import_agent_task = require("../services/tasks/entities/agent-task.entity.js
33
33
  var import_agent_action = require("../services/tasks/entities/agent-action.entity.js");
34
34
  var import_traces = require("../services/traces/index.js");
35
35
  var import_tool = require("../tools/tool.js");
36
+ var import_constants = require("../common/constants/index.js");
37
+ var import_input_check = require("../guardrails/input/input-check.js");
38
+ var import_create_block_input_oversize = require("../guardrails/input/create-block-input-oversize.js");
36
39
  var import_mcp_servers = require("../services/mcp-servers/index.js");
37
40
  var import_rank_tools_by_keywords = require("./utils/rank-tools-by-keywords");
38
41
  var import_agent_state = require("./agent-state");
@@ -60,6 +63,7 @@ class Agent {
60
63
  _unavailableSources = [];
61
64
  _preHooks = [];
62
65
  _postHooks = [];
66
+ _guards = [];
63
67
  currentChat;
64
68
  chatOptions;
65
69
  currentUser;
@@ -100,6 +104,9 @@ class Agent {
100
104
  this._tools = agentOptions.tools ?? [];
101
105
  this._identity = agentOptions.identity;
102
106
  this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
107
+ this.addGuard((0, import_create_block_input_oversize.createBlockInputOversize)(agentOptions.maxInputLength ?? import_constants.DEFAULT_MAX_INPUT_LENGTH));
108
+ this.addGuard(import_input_check.inputCheck);
109
+ for (const guard of agentOptions.guards ?? []) this.addGuard(guard);
103
110
  this.currentChat = import_chat.Chat.withDefaults(this._loop.name);
104
111
  }
105
112
  get tools() {
@@ -139,9 +146,13 @@ class Agent {
139
146
  this.currentMessage = message;
140
147
  this.chatOptions = options;
141
148
  this.answerId = new import_mongodb.ObjectId().toString();
142
- await this.preRunner(chatId);
143
- await this.runLoop();
144
- await this.postRunner();
149
+ const proceed = await this.preRunner(chatId);
150
+ if (proceed) {
151
+ await this.runLoop();
152
+ await this.postRunner();
153
+ } else {
154
+ await this.finishBlocked();
155
+ }
145
156
  return { data: this.currentChat };
146
157
  } catch (error) {
147
158
  const message = error?.message ?? String(error);
@@ -162,6 +173,9 @@ class Agent {
162
173
  if (type === "pre_execution") this._preHooks.push(fn);
163
174
  if (type === "post_execution") this._postHooks.push(fn);
164
175
  }
176
+ addGuard(guard) {
177
+ this._guards.push(guard);
178
+ }
165
179
  async preRunner(chatId) {
166
180
  let chatData;
167
181
  if (chatId) {
@@ -191,9 +205,50 @@ class Agent {
191
205
  this.currentChat.state?.setStatus(import_agent_state.AgentStatus.PROCESSING);
192
206
  this.currentChat.state?.setCurrentActivity("Starting...");
193
207
  await this.persist({ resetStop: true });
208
+ if (!await this.runInputGuards(userMessage)) return false;
194
209
  for (const hook of this._preHooks) {
195
210
  await hook();
196
211
  }
212
+ return true;
213
+ }
214
+ async runInputGuards(userMessage) {
215
+ const guards = this._guards.filter((guard) => guard.type === "input");
216
+ if (!guards.length) return true;
217
+ const ctx = this.buildRunContext();
218
+ const context = {
219
+ message: this.currentMessage,
220
+ chat: ctx.chat,
221
+ currentUser: ctx.currentUser,
222
+ currentSession: ctx.currentSession,
223
+ skillParams: ctx.skillParams,
224
+ logger: ctx.logger
225
+ };
226
+ for (const guard of guards) {
227
+ let result;
228
+ let failed = false;
229
+ try {
230
+ result = await guard.run(context);
231
+ } catch (error) {
232
+ this.logger.error({ error: error?.message ?? error, guard: guard.name }, "[AGENT] Guard failed");
233
+ failed = true;
234
+ result = { passed: false, reason: `Guard failed: ${error?.message ?? error}` };
235
+ }
236
+ if (result.passed) continue;
237
+ const reply = failed ? import_constants.GUARD_FAILURE_REPLY : guard.reply;
238
+ userMessage.excludeFromContext = true;
239
+ this.reply(`${reply}
240
+
241
+ Ref: ${guard.ref}`, true);
242
+ this.currentChat.addTrace({ node: guard.name, kind: "guard", reasoning: `${guard.type} guard, Ref ${guard.ref}: ${result.reason ?? "Blocked"}` });
243
+ return false;
244
+ }
245
+ return true;
246
+ }
247
+ async finishBlocked() {
248
+ this.currentChat.state?.setStatus(import_agent_state.AgentStatus.IDLE);
249
+ this.currentChat.state?.setCurrentActivity("stopped");
250
+ await this.persist();
251
+ await this.disconnectMcpServers();
197
252
  }
198
253
  async postRunner() {
199
254
  for (const hook of this._postHooks) {
@@ -456,10 +511,10 @@ class Agent {
456
511
  const startIndex = (page - 1) * limit;
457
512
  return matchedTools.slice(startIndex, startIndex + limit);
458
513
  }
459
- reply(content) {
514
+ reply(content, excludeFromContext) {
460
515
  const isFirstReply = this.replyCount === 0;
461
516
  this.replyCount++;
462
- this.currentChat.pushMessage({ _id: isFirstReply ? this.answerId : void 0, answerId: this.answerId, role: "assistant", content });
517
+ this.currentChat.pushMessage({ _id: isFirstReply ? this.answerId : void 0, answerId: this.answerId, role: "assistant", content, excludeFromContext });
463
518
  }
464
519
  get baseParams() {
465
520
  return {
@@ -18,6 +18,9 @@ import { AgentTask, TaskStatus } from "../services/tasks/entities/agent-task.ent
18
18
  import { AgentAction } from "../services/tasks/entities/agent-action.entity.js";
19
19
  import { createAgentTraces } from "../services/traces/index.js";
20
20
  import { Tool } from "../tools/tool.js";
21
+ import { DEFAULT_MAX_INPUT_LENGTH, GUARD_FAILURE_REPLY } from "../common/constants/index.js";
22
+ import { inputCheck } from "../guardrails/input/input-check.js";
23
+ import { createBlockInputOversize } from "../guardrails/input/create-block-input-oversize.js";
21
24
  import { listMcpServersByUser } from "../services/mcp-servers/index.js";
22
25
  import { rankToolsByKeywords } from "./utils/rank-tools-by-keywords";
23
26
  import { AgentStatus } from "./agent-state";
@@ -45,6 +48,7 @@ class Agent {
45
48
  _unavailableSources = [];
46
49
  _preHooks = [];
47
50
  _postHooks = [];
51
+ _guards = [];
48
52
  currentChat;
49
53
  chatOptions;
50
54
  currentUser;
@@ -85,6 +89,9 @@ class Agent {
85
89
  this._tools = agentOptions.tools ?? [];
86
90
  this._identity = agentOptions.identity;
87
91
  this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
92
+ this.addGuard(createBlockInputOversize(agentOptions.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH));
93
+ this.addGuard(inputCheck);
94
+ for (const guard of agentOptions.guards ?? []) this.addGuard(guard);
88
95
  this.currentChat = Chat.withDefaults(this._loop.name);
89
96
  }
90
97
  get tools() {
@@ -124,9 +131,13 @@ class Agent {
124
131
  this.currentMessage = message;
125
132
  this.chatOptions = options;
126
133
  this.answerId = new ObjectId().toString();
127
- await this.preRunner(chatId);
128
- await this.runLoop();
129
- await this.postRunner();
134
+ const proceed = await this.preRunner(chatId);
135
+ if (proceed) {
136
+ await this.runLoop();
137
+ await this.postRunner();
138
+ } else {
139
+ await this.finishBlocked();
140
+ }
130
141
  return { data: this.currentChat };
131
142
  } catch (error) {
132
143
  const message = error?.message ?? String(error);
@@ -147,6 +158,9 @@ class Agent {
147
158
  if (type === "pre_execution") this._preHooks.push(fn);
148
159
  if (type === "post_execution") this._postHooks.push(fn);
149
160
  }
161
+ addGuard(guard) {
162
+ this._guards.push(guard);
163
+ }
150
164
  async preRunner(chatId) {
151
165
  let chatData;
152
166
  if (chatId) {
@@ -176,9 +190,50 @@ class Agent {
176
190
  this.currentChat.state?.setStatus(AgentStatus.PROCESSING);
177
191
  this.currentChat.state?.setCurrentActivity("Starting...");
178
192
  await this.persist({ resetStop: true });
193
+ if (!await this.runInputGuards(userMessage)) return false;
179
194
  for (const hook of this._preHooks) {
180
195
  await hook();
181
196
  }
197
+ return true;
198
+ }
199
+ async runInputGuards(userMessage) {
200
+ const guards = this._guards.filter((guard) => guard.type === "input");
201
+ if (!guards.length) return true;
202
+ const ctx = this.buildRunContext();
203
+ const context = {
204
+ message: this.currentMessage,
205
+ chat: ctx.chat,
206
+ currentUser: ctx.currentUser,
207
+ currentSession: ctx.currentSession,
208
+ skillParams: ctx.skillParams,
209
+ logger: ctx.logger
210
+ };
211
+ for (const guard of guards) {
212
+ let result;
213
+ let failed = false;
214
+ try {
215
+ result = await guard.run(context);
216
+ } catch (error) {
217
+ this.logger.error({ error: error?.message ?? error, guard: guard.name }, "[AGENT] Guard failed");
218
+ failed = true;
219
+ result = { passed: false, reason: `Guard failed: ${error?.message ?? error}` };
220
+ }
221
+ if (result.passed) continue;
222
+ const reply = failed ? GUARD_FAILURE_REPLY : guard.reply;
223
+ userMessage.excludeFromContext = true;
224
+ this.reply(`${reply}
225
+
226
+ Ref: ${guard.ref}`, true);
227
+ this.currentChat.addTrace({ node: guard.name, kind: "guard", reasoning: `${guard.type} guard, Ref ${guard.ref}: ${result.reason ?? "Blocked"}` });
228
+ return false;
229
+ }
230
+ return true;
231
+ }
232
+ async finishBlocked() {
233
+ this.currentChat.state?.setStatus(AgentStatus.IDLE);
234
+ this.currentChat.state?.setCurrentActivity("stopped");
235
+ await this.persist();
236
+ await this.disconnectMcpServers();
182
237
  }
183
238
  async postRunner() {
184
239
  for (const hook of this._postHooks) {
@@ -441,10 +496,10 @@ class Agent {
441
496
  const startIndex = (page - 1) * limit;
442
497
  return matchedTools.slice(startIndex, startIndex + limit);
443
498
  }
444
- reply(content) {
499
+ reply(content, excludeFromContext) {
445
500
  const isFirstReply = this.replyCount === 0;
446
501
  this.replyCount++;
447
- this.currentChat.pushMessage({ _id: isFirstReply ? this.answerId : void 0, answerId: this.answerId, role: "assistant", content });
502
+ this.currentChat.pushMessage({ _id: isFirstReply ? this.answerId : void 0, answerId: this.answerId, role: "assistant", content, excludeFromContext });
448
503
  }
449
504
  get baseParams() {
450
505
  return {
@@ -5,15 +5,17 @@ export interface ChatMessageProps extends BaseEntityProps {
5
5
  role?: Roles;
6
6
  content?: string;
7
7
  answerId?: string | ObjectId;
8
+ excludeFromContext?: boolean;
8
9
  }
9
10
  export declare class ChatMessage extends BaseEntity {
10
11
  private readonly props;
11
12
  role?: Roles | undefined;
12
13
  content?: string | undefined;
13
14
  answerId?: ObjectId | undefined;
15
+ excludeFromContext?: boolean | undefined;
14
16
  static factory(message: ChatMessageProps): ChatMessage;
15
17
  static fromJSON(props: ChatMessageProps): ChatMessage;
16
- constructor(props: ChatMessageProps, role?: Roles | undefined, content?: string | undefined, answerId?: ObjectId | undefined);
18
+ constructor(props: ChatMessageProps, role?: Roles | undefined, content?: string | undefined, answerId?: ObjectId | undefined, excludeFromContext?: boolean | undefined);
17
19
  toJSON(): ChatMessageProps;
18
20
  }
19
21
  export {};
@@ -24,17 +24,19 @@ module.exports = __toCommonJS(chat_message_entity_exports);
24
24
  var import_mongodb = require("mongodb");
25
25
  var import_base = require("../../../common/base/base.entity.js");
26
26
  class ChatMessage extends import_base.BaseEntity {
27
- constructor(props, role, content, answerId) {
27
+ constructor(props, role, content, answerId, excludeFromContext) {
28
28
  super(props);
29
29
  this.props = props;
30
30
  this.role = role;
31
31
  this.content = content;
32
32
  this.answerId = answerId;
33
+ this.excludeFromContext = excludeFromContext;
33
34
  }
34
35
  props;
35
36
  role;
36
37
  content;
37
38
  answerId;
39
+ excludeFromContext;
38
40
  static factory(message) {
39
41
  const messageId = message._id && import_mongodb.ObjectId.isValid(message._id) ? new import_mongodb.ObjectId(message._id) : new import_mongodb.ObjectId();
40
42
  return ChatMessage.fromJSON({ ...message, _id: messageId });
@@ -44,7 +46,8 @@ class ChatMessage extends import_base.BaseEntity {
44
46
  props,
45
47
  props.role,
46
48
  props.content,
47
- import_base.BaseEntity.toObjectId(props.answerId)
49
+ import_base.BaseEntity.toObjectId(props.answerId),
50
+ props.excludeFromContext
48
51
  );
49
52
  }
50
53
  toJSON() {
@@ -52,7 +55,8 @@ class ChatMessage extends import_base.BaseEntity {
52
55
  ...super.toJSON(),
53
56
  role: this.role,
54
57
  content: this.content,
55
- answerId: this.answerId
58
+ answerId: this.answerId,
59
+ excludeFromContext: this.excludeFromContext || void 0
56
60
  };
57
61
  }
58
62
  }
@@ -2,17 +2,19 @@ import "../../../chunk-CF3WOMB3.mjs";
2
2
  import { ObjectId } from "mongodb";
3
3
  import { BaseEntity } from "../../../common/base/base.entity.js";
4
4
  class ChatMessage extends BaseEntity {
5
- constructor(props, role, content, answerId) {
5
+ constructor(props, role, content, answerId, excludeFromContext) {
6
6
  super(props);
7
7
  this.props = props;
8
8
  this.role = role;
9
9
  this.content = content;
10
10
  this.answerId = answerId;
11
+ this.excludeFromContext = excludeFromContext;
11
12
  }
12
13
  props;
13
14
  role;
14
15
  content;
15
16
  answerId;
17
+ excludeFromContext;
16
18
  static factory(message) {
17
19
  const messageId = message._id && ObjectId.isValid(message._id) ? new ObjectId(message._id) : new ObjectId();
18
20
  return ChatMessage.fromJSON({ ...message, _id: messageId });
@@ -22,7 +24,8 @@ class ChatMessage extends BaseEntity {
22
24
  props,
23
25
  props.role,
24
26
  props.content,
25
- BaseEntity.toObjectId(props.answerId)
27
+ BaseEntity.toObjectId(props.answerId),
28
+ props.excludeFromContext
26
29
  );
27
30
  }
28
31
  toJSON() {
@@ -30,7 +33,8 @@ class ChatMessage extends BaseEntity {
30
33
  ...super.toJSON(),
31
34
  role: this.role,
32
35
  content: this.content,
33
- answerId: this.answerId
36
+ answerId: this.answerId,
37
+ excludeFromContext: this.excludeFromContext || void 0
34
38
  };
35
39
  }
36
40
  }
@@ -13,7 +13,7 @@ export interface AgentTrace {
13
13
  reasoning?: string;
14
14
  taskId?: string;
15
15
  timestamp?: Date | string;
16
- kind?: 'skill' | 'node' | 'agent';
16
+ kind?: 'skill' | 'node' | 'agent' | 'guard';
17
17
  iteration?: number;
18
18
  durationMs?: number;
19
19
  }
@@ -57,7 +57,7 @@ class Chat extends import_base.BaseEntity {
57
57
  tasks = [];
58
58
  pendingTraces = [];
59
59
  get lastAnswer() {
60
- return this.messages?.slice().reverse().find((message) => message.role === "assistant")?.content;
60
+ return this.messages?.slice().reverse().find((message) => message.role === "assistant" && !message.excludeFromContext)?.content;
61
61
  }
62
62
  get activeTask() {
63
63
  if (!this.state?.activeTaskId) return void 0;
@@ -78,7 +78,7 @@ class Chat extends import_base.BaseEntity {
78
78
  return created;
79
79
  }
80
80
  lastHistoryMessages(count = 6) {
81
- return this.messages?.slice(-count, -1);
81
+ return this.messages?.filter((message) => !message.excludeFromContext).slice(-count, -1);
82
82
  }
83
83
  addTrace(entry) {
84
84
  this.pendingTraces.push({
@@ -35,7 +35,7 @@ class Chat extends BaseEntity {
35
35
  tasks = [];
36
36
  pendingTraces = [];
37
37
  get lastAnswer() {
38
- return this.messages?.slice().reverse().find((message) => message.role === "assistant")?.content;
38
+ return this.messages?.slice().reverse().find((message) => message.role === "assistant" && !message.excludeFromContext)?.content;
39
39
  }
40
40
  get activeTask() {
41
41
  if (!this.state?.activeTaskId) return void 0;
@@ -56,7 +56,7 @@ class Chat extends BaseEntity {
56
56
  return created;
57
57
  }
58
58
  lastHistoryMessages(count = 6) {
59
- return this.messages?.slice(-count, -1);
59
+ return this.messages?.filter((message) => !message.excludeFromContext).slice(-count, -1);
60
60
  }
61
61
  addTrace(entry) {
62
62
  this.pendingTraces.push({
@@ -8,7 +8,7 @@ export interface AgentTraceEntryProps extends BaseEntityProps {
8
8
  timestamp?: Date | string;
9
9
  answerId?: string | ObjectId;
10
10
  messageId?: string | ObjectId;
11
- kind?: 'skill' | 'node' | 'agent';
11
+ kind?: 'skill' | 'node' | 'agent' | 'guard';
12
12
  iteration?: number;
13
13
  durationMs?: number;
14
14
  }
@@ -21,10 +21,10 @@ export declare class AgentTraceEntry extends BaseEntity {
21
21
  timestamp?: Date | undefined;
22
22
  answerId?: ObjectId | undefined;
23
23
  messageId?: ObjectId | undefined;
24
- kind?: "skill" | "node" | "agent" | undefined;
24
+ kind?: "skill" | "node" | "agent" | "guard" | undefined;
25
25
  iteration?: number | undefined;
26
26
  durationMs?: number | undefined;
27
27
  static fromJSON(props: AgentTraceEntryProps): AgentTraceEntry;
28
- constructor(props: AgentTraceEntryProps, chatId?: ObjectId | undefined, taskId?: ObjectId | undefined, node?: string | undefined, reasoning?: string | undefined, timestamp?: Date | undefined, answerId?: ObjectId | undefined, messageId?: ObjectId | undefined, kind?: "skill" | "node" | "agent" | undefined, iteration?: number | undefined, durationMs?: number | undefined);
28
+ constructor(props: AgentTraceEntryProps, chatId?: ObjectId | undefined, taskId?: ObjectId | undefined, node?: string | undefined, reasoning?: string | undefined, timestamp?: Date | undefined, answerId?: ObjectId | undefined, messageId?: ObjectId | undefined, kind?: "skill" | "node" | "agent" | "guard" | undefined, iteration?: number | undefined, durationMs?: number | undefined);
29
29
  toJSON(): AgentTraceEntryProps;
30
30
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openloops",
3
- "version": "0.1.35",
3
+ "version": "0.1.36",
4
4
  "description": "Framework to build AI Agents",
5
5
  "author": {
6
6
  "name": "Jose Barcos",
@@ -43,6 +43,10 @@
43
43
  "types": "./dist/loops/index.d.ts",
44
44
  "default": "./dist/loops/index.js"
45
45
  },
46
+ "./guardrails": {
47
+ "types": "./dist/guardrails/index.d.ts",
48
+ "default": "./dist/guardrails/index.js"
49
+ },
46
50
  "./authentication": {
47
51
  "types": "./dist/services/authentication/index.d.ts",
48
52
  "default": "./dist/services/authentication/index.js"