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
@@ -2,12 +2,14 @@ import type { KnownProvider, Message, AssistantMessage } from '@earendil-works/p
2
2
  import { CurrentUser } from '../common/base/index.js';
3
3
  import { LLMChatParams, LLMResponse } from './llm-types';
4
4
  export declare class LLMClient {
5
+ private static readonly modelsWithoutTemperature;
5
6
  private readonly logger;
6
7
  private readonly langfuse?;
7
8
  private readonly langfuseEnabled;
8
9
  constructor();
9
10
  chat(params: LLMChatParams): Promise<LLMResponse>;
10
11
  complete(params: LLMCompletionParams): Promise<AssistantMessage>;
12
+ private withoutRejectedTemperature;
11
13
  private waitingOnRateLimit;
12
14
  private traced;
13
15
  private postResponse;
@@ -44,6 +44,7 @@ const DEFAULT_TEMPERATURE = 0.7;
44
44
  const MAX_RETRIES = 4;
45
45
  const MAX_RATE_LIMIT_WAITS = 2;
46
46
  class LLMClient {
47
+ static modelsWithoutTemperature = /* @__PURE__ */ new Set();
47
48
  logger = new import_logger.Logger();
48
49
  langfuse;
49
50
  langfuseEnabled;
@@ -78,11 +79,14 @@ class LLMClient {
78
79
  const model = models.getModel(provider, modelName);
79
80
  if (!model) throw new Error("[LLM Client] model not found");
80
81
  const context = (0, import_pi_ai_adapter.toPiContext)({ messages, tools }, model);
81
- const options = { temperature, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
82
+ const send = (omitTemperature) => {
83
+ const options = { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
84
+ return toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options);
85
+ };
82
86
  const raw = await this.traced(
83
87
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
84
88
  context,
85
- () => this.waitingOnRateLimit(() => toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options))
89
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, send)
86
90
  );
87
91
  if (raw.stopReason === "error" || raw.stopReason === "aborted") {
88
92
  throw import_llm_error.LLMError.fromProvider(raw.errorMessage ?? `request ${raw.stopReason}`);
@@ -115,9 +119,17 @@ class LLMClient {
115
119
  return this.traced(
116
120
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
117
121
  context,
118
- () => this.waitingOnRateLimit(() => models.complete(model, context, { temperature, maxRetries: MAX_RETRIES }))
122
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, (omitTemperature) => models.complete(model, context, { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES }))
119
123
  );
120
124
  }
125
+ async withoutRejectedTemperature(key, send) {
126
+ const known = LLMClient.modelsWithoutTemperature.has(key);
127
+ const response = await this.waitingOnRateLimit(() => send(known));
128
+ if (known || response.stopReason !== "error" || !(0, import_llm_error.rejectsSamplingParameter)(response.errorMessage)) return response;
129
+ LLMClient.modelsWithoutTemperature.add(key);
130
+ this.logger.warn({ model: key, error: response.errorMessage }, "[LLM Service] The model rejected the temperature setting, retrying without it");
131
+ return this.waitingOnRateLimit(() => send(true));
132
+ }
121
133
  async waitingOnRateLimit(run) {
122
134
  let response = await run();
123
135
  for (let waits = 0; waits < MAX_RATE_LIMIT_WAITS && response.stopReason === "error"; waits++) {
@@ -5,13 +5,14 @@ import { Logger } from "../common/logger/index.js";
5
5
  import { extractJSON } from "../common/helpers/index.js";
6
6
  import { createLLMCall } from "../services/llmcalls/index.js";
7
7
  import { toPiContext, fromPiMessage } from "./pi-ai-adapter";
8
- import { LLMError, retryDelayMs } from "./llm-error";
8
+ import { LLMError, retryDelayMs, rejectsSamplingParameter } from "./llm-error";
9
9
  const DEFAULT_PROVIDER = "openai";
10
10
  const DEFAULT_MODEL = "gpt-4o-mini";
11
11
  const DEFAULT_TEMPERATURE = 0.7;
12
12
  const MAX_RETRIES = 4;
13
13
  const MAX_RATE_LIMIT_WAITS = 2;
14
14
  class LLMClient {
15
+ static modelsWithoutTemperature = /* @__PURE__ */ new Set();
15
16
  logger = new Logger();
16
17
  langfuse;
17
18
  langfuseEnabled;
@@ -46,11 +47,14 @@ class LLMClient {
46
47
  const model = models.getModel(provider, modelName);
47
48
  if (!model) throw new Error("[LLM Client] model not found");
48
49
  const context = toPiContext({ messages, tools }, model);
49
- const options = { temperature, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
50
+ const send = (omitTemperature) => {
51
+ const options = { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
52
+ return toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options);
53
+ };
50
54
  const raw = await this.traced(
51
55
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
52
56
  context,
53
- () => this.waitingOnRateLimit(() => toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options))
57
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, send)
54
58
  );
55
59
  if (raw.stopReason === "error" || raw.stopReason === "aborted") {
56
60
  throw LLMError.fromProvider(raw.errorMessage ?? `request ${raw.stopReason}`);
@@ -83,9 +87,17 @@ class LLMClient {
83
87
  return this.traced(
84
88
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
85
89
  context,
86
- () => this.waitingOnRateLimit(() => models.complete(model, context, { temperature, maxRetries: MAX_RETRIES }))
90
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, (omitTemperature) => models.complete(model, context, { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES }))
87
91
  );
88
92
  }
93
+ async withoutRejectedTemperature(key, send) {
94
+ const known = LLMClient.modelsWithoutTemperature.has(key);
95
+ const response = await this.waitingOnRateLimit(() => send(known));
96
+ if (known || response.stopReason !== "error" || !rejectsSamplingParameter(response.errorMessage)) return response;
97
+ LLMClient.modelsWithoutTemperature.add(key);
98
+ this.logger.warn({ model: key, error: response.errorMessage }, "[LLM Service] The model rejected the temperature setting, retrying without it");
99
+ return this.waitingOnRateLimit(() => send(true));
100
+ }
89
101
  async waitingOnRateLimit(run) {
90
102
  let response = await run();
91
103
  for (let waits = 0; waits < MAX_RATE_LIMIT_WAITS && response.stopReason === "error"; waits++) {
@@ -1,4 +1,4 @@
1
- export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_FAILED';
1
+ export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_UNSUPPORTED_PARAMETER' | 'LLM_FAILED';
2
2
  export declare class LLMError extends Error {
3
3
  readonly code: LLMErrorCode;
4
4
  readonly isRetryable: boolean;
@@ -6,4 +6,5 @@ export declare class LLMError extends Error {
6
6
  constructor(code: LLMErrorCode, detail: string);
7
7
  static fromProvider(detail: string): LLMError;
8
8
  }
9
+ export declare function rejectsSamplingParameter(detail?: string): boolean;
9
10
  export declare function retryDelayMs(detail?: string): number | undefined;
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var llm_error_exports = {};
20
20
  __export(llm_error_exports, {
21
21
  LLMError: () => LLMError,
22
+ rejectsSamplingParameter: () => rejectsSamplingParameter,
22
23
  retryDelayMs: () => retryDelayMs
23
24
  });
24
25
  module.exports = __toCommonJS(llm_error_exports);
@@ -26,15 +27,19 @@ const USER_MESSAGES = {
26
27
  LLM_RATE_LIMITED: "The model is receiving too many requests right now. Please try again in a few seconds.",
27
28
  LLM_QUOTA_EXCEEDED: "The usage quota of the model provider has been exhausted. Please check the plan and billing of the provider.",
28
29
  LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
30
+ LLM_UNSUPPORTED_PARAMETER: "The model does not accept one of the request settings. Please try again.",
29
31
  LLM_FAILED: "The model request failed. Please try again."
30
32
  };
31
33
  const RETRYABLE = {
32
34
  LLM_RATE_LIMITED: true,
33
35
  LLM_QUOTA_EXCEEDED: false,
34
36
  LLM_UNAVAILABLE: true,
37
+ LLM_UNSUPPORTED_PARAMETER: true,
35
38
  LLM_FAILED: true
36
39
  };
37
40
  const MAX_WAIT_MS = 6e4;
41
+ const SAMPLING_PARAMETER = /\b(?:temperature|top_p|top_k)\b/i;
42
+ const REJECTION = /unsupported|not supported|does not support|doesn't support|deprecated|not allowed|only the default|no longer|removed|cannot be|can't be|must be|invalid/i;
38
43
  class LLMError extends Error {
39
44
  code;
40
45
  isRetryable;
@@ -49,7 +54,11 @@ class LLMError extends Error {
49
54
  return new LLMError(classify(detail), detail);
50
55
  }
51
56
  }
57
+ function rejectsSamplingParameter(detail) {
58
+ return Boolean(detail) && SAMPLING_PARAMETER.test(detail) && REJECTION.test(detail);
59
+ }
52
60
  function classify(detail) {
61
+ if (rejectsSamplingParameter(detail)) return "LLM_UNSUPPORTED_PARAMETER";
53
62
  if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
54
63
  if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
55
64
  if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
@@ -65,5 +74,6 @@ function retryDelayMs(detail) {
65
74
  // Annotate the CommonJS export names for ESM import in node:
66
75
  0 && (module.exports = {
67
76
  LLMError,
77
+ rejectsSamplingParameter,
68
78
  retryDelayMs
69
79
  });
@@ -3,15 +3,19 @@ const USER_MESSAGES = {
3
3
  LLM_RATE_LIMITED: "The model is receiving too many requests right now. Please try again in a few seconds.",
4
4
  LLM_QUOTA_EXCEEDED: "The usage quota of the model provider has been exhausted. Please check the plan and billing of the provider.",
5
5
  LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
6
+ LLM_UNSUPPORTED_PARAMETER: "The model does not accept one of the request settings. Please try again.",
6
7
  LLM_FAILED: "The model request failed. Please try again."
7
8
  };
8
9
  const RETRYABLE = {
9
10
  LLM_RATE_LIMITED: true,
10
11
  LLM_QUOTA_EXCEEDED: false,
11
12
  LLM_UNAVAILABLE: true,
13
+ LLM_UNSUPPORTED_PARAMETER: true,
12
14
  LLM_FAILED: true
13
15
  };
14
16
  const MAX_WAIT_MS = 6e4;
17
+ const SAMPLING_PARAMETER = /\b(?:temperature|top_p|top_k)\b/i;
18
+ const REJECTION = /unsupported|not supported|does not support|doesn't support|deprecated|not allowed|only the default|no longer|removed|cannot be|can't be|must be|invalid/i;
15
19
  class LLMError extends Error {
16
20
  code;
17
21
  isRetryable;
@@ -26,7 +30,11 @@ class LLMError extends Error {
26
30
  return new LLMError(classify(detail), detail);
27
31
  }
28
32
  }
33
+ function rejectsSamplingParameter(detail) {
34
+ return Boolean(detail) && SAMPLING_PARAMETER.test(detail) && REJECTION.test(detail);
35
+ }
29
36
  function classify(detail) {
37
+ if (rejectsSamplingParameter(detail)) return "LLM_UNSUPPORTED_PARAMETER";
30
38
  if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
31
39
  if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
32
40
  if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
@@ -41,5 +49,6 @@ function retryDelayMs(detail) {
41
49
  }
42
50
  export {
43
51
  LLMError,
52
+ rejectsSamplingParameter,
44
53
  retryDelayMs
45
54
  };
@@ -15,6 +15,7 @@ export interface BaseEntityProps {
15
15
  archivedAt?: string | Date;
16
16
  archivedBy?: string | ObjectId;
17
17
  sharedWith?: string[] | ObjectId[];
18
+ toUnset?: Record<string, unknown>;
18
19
  }
19
20
  export interface Document extends BaseEntityProps {
20
21
  toUnset?: Record<string, unknown>;
@@ -33,7 +34,7 @@ export declare class BaseEntity {
33
34
  archivedAt?: Date;
34
35
  archivedBy?: ObjectId;
35
36
  sharedWith?: ObjectId[];
36
- private toUnset?;
37
+ toUnset?: Record<string, unknown>;
37
38
  static toObjectId(id?: string | ObjectId): ObjectId | undefined;
38
39
  private static toDate;
39
40
  private static toNumber;
@@ -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
+ });