openloops 0.1.33 → 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 (58) hide show
  1. package/dist/clients/llm-client.d.ts +2 -0
  2. package/dist/clients/llm-client.js +15 -3
  3. package/dist/clients/llm-client.mjs +16 -4
  4. package/dist/clients/llm-error.d.ts +2 -1
  5. package/dist/clients/llm-error.js +10 -0
  6. package/dist/clients/llm-error.mjs +9 -0
  7. package/dist/common/base/base.entity.d.ts +2 -1
  8. package/dist/common/constants/harness.d.ts +3 -0
  9. package/dist/common/constants/harness.js +34 -0
  10. package/dist/common/constants/harness.mjs +9 -0
  11. package/dist/common/constants/index.d.ts +1 -0
  12. package/dist/common/constants/index.js +22 -0
  13. package/dist/common/constants/index.mjs +1 -0
  14. package/dist/guardrails/guard.d.ts +40 -0
  15. package/dist/guardrails/guard.js +65 -0
  16. package/dist/guardrails/guard.mjs +42 -0
  17. package/dist/guardrails/index.d.ts +2 -0
  18. package/dist/guardrails/index.js +41 -0
  19. package/dist/guardrails/index.mjs +6 -0
  20. package/dist/guardrails/input/block-card.d.ts +2 -0
  21. package/dist/guardrails/input/block-card.js +57 -0
  22. package/dist/guardrails/input/block-card.mjs +34 -0
  23. package/dist/guardrails/input/block-code.d.ts +2 -0
  24. package/dist/guardrails/input/block-code.js +37 -0
  25. package/dist/guardrails/input/block-code.mjs +14 -0
  26. package/dist/guardrails/input/block-email.d.ts +2 -0
  27. package/dist/guardrails/input/block-email.js +37 -0
  28. package/dist/guardrails/input/block-email.mjs +14 -0
  29. package/dist/guardrails/input/create-block-input-oversize.d.ts +2 -0
  30. package/dist/guardrails/input/create-block-input-oversize.js +38 -0
  31. package/dist/guardrails/input/create-block-input-oversize.mjs +15 -0
  32. package/dist/guardrails/input/diagnostic-sanity.d.ts +2 -0
  33. package/dist/guardrails/input/diagnostic-sanity.js +49 -0
  34. package/dist/guardrails/input/diagnostic-sanity.mjs +26 -0
  35. package/dist/guardrails/input/index.d.ts +3 -0
  36. package/dist/guardrails/input/index.js +26 -0
  37. package/dist/guardrails/input/index.mjs +3 -0
  38. package/dist/guardrails/input/input-check.d.ts +2 -0
  39. package/dist/guardrails/input/input-check.js +51 -0
  40. package/dist/guardrails/input/input-check.mjs +28 -0
  41. package/dist/harness/agent.d.ts +7 -0
  42. package/dist/harness/agent.js +62 -5
  43. package/dist/harness/agent.mjs +63 -6
  44. package/dist/loops/agi/loop.js +2 -3
  45. package/dist/loops/agi/loop.mjs +2 -3
  46. package/dist/services/chats/entities/chat-message.entity.d.ts +3 -1
  47. package/dist/services/chats/entities/chat-message.entity.js +7 -3
  48. package/dist/services/chats/entities/chat-message.entity.mjs +7 -3
  49. package/dist/services/chats/entities/chat.entity.d.ts +1 -1
  50. package/dist/services/chats/entities/chat.entity.js +5 -3
  51. package/dist/services/chats/entities/chat.entity.mjs +5 -3
  52. package/dist/services/chats/lambdas/update-chat/update-chat.use-case.js +5 -0
  53. package/dist/services/chats/lambdas/update-chat/update-chat.use-case.mjs +5 -0
  54. package/dist/services/tasks/entities/agent-task.entity.d.ts +4 -4
  55. package/dist/services/tasks/entities/agent-task.entity.js +7 -7
  56. package/dist/services/tasks/entities/agent-task.entity.mjs +7 -7
  57. package/dist/services/traces/entities/agent-trace-entry.entity.d.ts +3 -3
  58. package/package.json +9 -2
@@ -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) {
@@ -235,6 +290,8 @@ class Agent {
235
290
  this.snapshots.set(`task:${task.id}`, this.fingerprint(task));
236
291
  }
237
292
  this.currentChat.tasks = tasks;
293
+ const finished = [import_agent_task.TaskStatus.COMPLETED, import_agent_task.TaskStatus.FAILED, import_agent_task.TaskStatus.CANCELLED, import_agent_task.TaskStatus.ABANDONED];
294
+ if (this.currentChat.activeTask?.status && finished.includes(this.currentChat.activeTask.status)) this.currentChat.state?.setActiveTaskId(void 0);
238
295
  const activeTask = this.currentChat.activeTask;
239
296
  if (activeTask) await this.hydrateTask(activeTask);
240
297
  }
@@ -454,10 +511,10 @@ class Agent {
454
511
  const startIndex = (page - 1) * limit;
455
512
  return matchedTools.slice(startIndex, startIndex + limit);
456
513
  }
457
- reply(content) {
514
+ reply(content, excludeFromContext) {
458
515
  const isFirstReply = this.replyCount === 0;
459
516
  this.replyCount++;
460
- 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 });
461
518
  }
462
519
  get baseParams() {
463
520
  return {
@@ -14,10 +14,13 @@ import {
14
14
  updateAgentAction,
15
15
  listAgentActionsByTask
16
16
  } from "../services/tasks/index.js";
17
- import { AgentTask } from "../services/tasks/entities/agent-task.entity.js";
17
+ import { AgentTask, TaskStatus } from "../services/tasks/entities/agent-task.entity.js";
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) {
@@ -220,6 +275,8 @@ class Agent {
220
275
  this.snapshots.set(`task:${task.id}`, this.fingerprint(task));
221
276
  }
222
277
  this.currentChat.tasks = tasks;
278
+ const finished = [TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED, TaskStatus.ABANDONED];
279
+ if (this.currentChat.activeTask?.status && finished.includes(this.currentChat.activeTask.status)) this.currentChat.state?.setActiveTaskId(void 0);
223
280
  const activeTask = this.currentChat.activeTask;
224
281
  if (activeTask) await this.hydrateTask(activeTask);
225
282
  }
@@ -439,10 +496,10 @@ class Agent {
439
496
  const startIndex = (page - 1) * limit;
440
497
  return matchedTools.slice(startIndex, startIndex + limit);
441
498
  }
442
- reply(content) {
499
+ reply(content, excludeFromContext) {
443
500
  const isFirstReply = this.replyCount === 0;
444
501
  this.replyCount++;
445
- 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 });
446
503
  }
447
504
  get baseParams() {
448
505
  return {
@@ -33,7 +33,6 @@ const MAX_SAME_TOOL = 6;
33
33
  const MAX_ANSWER_REJECTIONS = 1;
34
34
  const WARN_WORKSPACE_TURNS = 3;
35
35
  const MAX_WORKSPACE_TURNS = 7;
36
- const SUMMARY_CHARS = 400;
37
36
  const BLOCK_DUPLICATES = false;
38
37
  class AgiLoop extends import_harness.AgentLoop {
39
38
  get initialNode() {
@@ -124,7 +123,7 @@ class AgiLoop extends import_harness.AgentLoop {
124
123
  if (stopReason) {
125
124
  const answer = task.forceAnswer(`I could not finish the task: ${stopReason}.`);
126
125
  ctx.reply(answer);
127
- task.summary = answer.slice(0, SUMMARY_CHARS);
126
+ task.summary = answer;
128
127
  ctx.chat.failTask(task.id);
129
128
  ctx.chat.state?.setStatus(import_harness.AgentStatus.IDLE);
130
129
  ctx.setNextNode(this.nodes.fast_responder);
@@ -162,7 +161,7 @@ class AgiLoop extends import_harness.AgentLoop {
162
161
  }
163
162
  task.deliverAnswer();
164
163
  ctx.reply(answer);
165
- ctx.chat.completeTask(task.id, answer.slice(0, SUMMARY_CHARS));
164
+ ctx.chat.completeTask(task.id, answer);
166
165
  ctx.chat.state?.setStatus(import_harness.AgentStatus.IDLE);
167
166
  ctx.setNextNode(this.nodes.fast_responder);
168
167
  return;