openloops 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  All notable changes to `openloops` are written here, newest first. The format follows [Keep a Changelog](https://keepachangelog.com) and the versions follow [semantic versioning](https://semver.org), where a minor version can still break the API while the package is in beta. Changes before 0.4.0 are not recorded here, see the commits and the tags.
4
4
 
5
+ ## 0.9.1
6
+
7
+ ### Changed
8
+
9
+ - A run blocked by `usageLimit` that continues an existing chat (`chatId`) now saves the message of the user in it, with no answer, and returns the chat in `data`. Before, nothing was saved and `data` was `undefined`. It still calls no guard, no model and no loop, the status of the chat does not change, a chat with no messages takes the message as its title, and the next run reads the saved message, so the user can say `continue` when the limit is lifted. With no `chatId`, or with one that does not exist, nothing is saved. Read [usage limit](docs/agent.md#usage-limit).
10
+ - The type of `AgentState.currentActivity` is `string`. It listed `'running'` and `'stopped'`, values from the activity that was removed in 0.8.0.
11
+
12
+ ## 0.9.0
13
+
14
+ ### Added
15
+
16
+ - `usageLimit` in `agent.run`, as `{ maxCostUsd, period }` with `period` required (`day`, `week` or `month`, in the time zone of the user). If the cost of all the model calls of the user in that period is equal to or greater than `maxCostUsd`, the run does not start, nothing is saved and the result carries `error`, `errorCode: 'USAGE_LIMIT_REACHED'` and `usageLimit: { used, limit, period }`. Without it nothing changes. A blocked run is not sent to the error reporter. Read [usage limit](docs/agent.md#usage-limit).
17
+ - `stopOnUsageLimit` option of the `Agent`, `false` by default. When `true`, the limit is checked again before each iteration of the loop and the run stops with the chat `failed` and `USAGE_LIMIT_REACHED` in `state.lastError`.
18
+ - `UsageLimit`, `UsageLimitError`, `USAGE_LIMIT_REACHED` and `AgentRunResult` are exported from `openloops/core`.
19
+ - Examples: `run-agent-with-usage-limit` (one limit per plan) and `run-agent-with-usage-limit-stop` (stopping in the middle of a run).
20
+
5
21
  ## 0.8.3
6
22
 
7
23
  ### Added
package/README.md CHANGED
@@ -90,7 +90,7 @@ You know the pattern: before you write a single line of what your agent actually
90
90
  - **Autonomous runs.** The same agent can work without a person in the chat, for scheduled tasks. Whatever needs the user pauses the run in the chat, and the user answers there to continue. See [autonomous mode](docs/agent.md#autonomous-mode).
91
91
  - **Automations.** Tasks that the agent runs by itself, on a schedule (daily, weekly, monthly or once, in the timezone of the user) or when another system sends an event, with signed tokens that can be revoked and a queue per automation. A worker runs what is due, safely across several instances, and keeps a history of every run with its chat. See [automations](docs/automations.md).
92
92
  - **Guardrails.** Input guards block messages with card numbers, emails, code or anything you define, before the model sees them. See [guardrails](docs/guardrails.md).
93
- - **Usage and cost tracking.** Every LLM call is recorded. Get the tokens and cost of a chat or an answer, and per-user statistics by model and by period. See [usage](docs/usage.md).
93
+ - **Usage and cost tracking.** Every LLM call is recorded. Get the tokens and cost of a chat or an answer, and per-user statistics by model and by period. Cap what a user can spend in a day, a week or a month with `usageLimit`. See [usage](docs/usage.md) and [usage limit](docs/agent.md#usage-limit).
94
94
  - **Users and authentication included.** User management and login with tokens, so you don't need a parallel system just to have an identity to hand the `Agent`.
95
95
  - **Any LLM provider, including local ones.** Built on [`@earendil-works/pi-ai`](https://www.npmjs.com/package/@earendil-works/pi-ai), so OpenAI, Anthropic, Google, and self-hosted models (e.g. via Ollama) all work the same way, chosen per chat.
96
96
  - **Observability without ceremony.** Langfuse is built in: set the environment variables and every LLM call is traced. Errors go to one function that you register, so you report them to Sentry or to whatever tool you use. Every node, skill and guard also writes a trace you can read back.
@@ -11,7 +11,7 @@ export interface AgentError {
11
11
  isRetryable: boolean;
12
12
  timestamp: Date;
13
13
  }
14
- type CurrentActivity = 'running' | 'stopped' | (string & {});
14
+ type CurrentActivity = string;
15
15
  export type ActivityListener = (activity: string) => void;
16
16
  export interface AgentStateProps {
17
17
  status?: AgentStatus;
@@ -6,6 +6,7 @@ import { Tool } from '../tools/tool.js';
6
6
  import { Guard } from '../guardrails/guard.js';
7
7
  import { AgentIdentity, AgentLoop, AgentProductInfo } from './agent-loop';
8
8
  import { ActivityListener } from './agent-state';
9
+ import { UsageLimit } from './usage-limit';
9
10
  export interface InternalMcp {
10
11
  name: string;
11
12
  url: string;
@@ -16,6 +17,7 @@ export declare const AGENT_ERROR_CODES: {
16
17
  readonly NODE_NOT_FOUND: "AGENT_NODE_NOT_FOUND";
17
18
  readonly RUN_FAILED: "AGENT_RUN_FAILED";
18
19
  readonly MAX_ITERATIONS_REACHED: "AGENT_MAX_ITERATIONS_REACHED";
20
+ readonly USAGE_LIMIT_REACHED: "USAGE_LIMIT_REACHED";
19
21
  };
20
22
  export interface AgentOptions {
21
23
  loop: AgentLoop;
@@ -27,11 +29,22 @@ export interface AgentOptions {
27
29
  productInfo?: AgentProductInfo;
28
30
  maxIterations?: number;
29
31
  strictMode?: boolean;
32
+ stopOnUsageLimit?: boolean;
30
33
  fallbackModel?: {
31
34
  provider: string;
32
35
  model: string;
33
36
  };
34
37
  }
38
+ export interface AgentRunResult {
39
+ data?: Chat;
40
+ error?: string;
41
+ errorCode?: string;
42
+ usageLimit?: {
43
+ used: number;
44
+ limit: number;
45
+ period: UsageLimit['period'];
46
+ };
47
+ }
35
48
  interface ChatInput {
36
49
  message: string;
37
50
  chatId?: string;
@@ -45,6 +58,8 @@ export declare class Agent {
45
58
  private readonly _productInfo?;
46
59
  private readonly maxIterations;
47
60
  private readonly strictMode;
61
+ private readonly stopOnUsageLimit;
62
+ private usageLimit?;
48
63
  private readonly fallbackModel?;
49
64
  private model?;
50
65
  private thinkingEffort?;
@@ -88,13 +103,8 @@ export declare class Agent {
88
103
  currentUser: CurrentUser;
89
104
  currentSession?: CurrentSession;
90
105
  mcpTokens?: Record<string, string>;
91
- }): Promise<{
92
- data: Chat;
93
- error?: undefined;
94
- } | {
95
- data: Chat | undefined;
96
- error: any;
97
- }>;
106
+ usageLimit?: UsageLimit;
107
+ }): Promise<AgentRunResult>;
98
108
  stopAgent(): void;
99
109
  addTool(tool: Tool): void;
100
110
  addInternalMcp(mcp: InternalMcp): void;
@@ -109,6 +119,8 @@ export declare class Agent {
109
119
  private resolveConfirmation;
110
120
  private postRunner;
111
121
  private reportFailure;
122
+ private saveBlockedMessage;
123
+ private usageLimitResult;
112
124
  private failRun;
113
125
  private fingerprint;
114
126
  private loadTasks;
@@ -46,6 +46,7 @@ var import_tool_pipeline = require("./tool-pipeline");
46
46
  var import_native_tools = require("./native-tools");
47
47
  var import_tool_catalog = require("./tool-catalog");
48
48
  var import_llm_error = require("../clients/llm/llm-error.js");
49
+ var import_usage_limit = require("./usage-limit");
49
50
  var import_llm_types = require("../clients/llm/llm-types.js");
50
51
  var import_model_resolution = require("../clients/llm/model-resolution.js");
51
52
  const MCP_CONNECT_RETRY_DELAYS_MS = [1e3, 2e3];
@@ -58,7 +59,8 @@ const AUTOMATIC_ANSWER_RESULT_CHARS = 1500;
58
59
  const AGENT_ERROR_CODES = {
59
60
  NODE_NOT_FOUND: "AGENT_NODE_NOT_FOUND",
60
61
  RUN_FAILED: "AGENT_RUN_FAILED",
61
- MAX_ITERATIONS_REACHED: "AGENT_MAX_ITERATIONS_REACHED"
62
+ MAX_ITERATIONS_REACHED: "AGENT_MAX_ITERATIONS_REACHED",
63
+ USAGE_LIMIT_REACHED: import_usage_limit.USAGE_LIMIT_REACHED
62
64
  };
63
65
  const DEFAULT_MAX_ITERATIONS = 50;
64
66
  class Agent {
@@ -68,6 +70,8 @@ class Agent {
68
70
  _productInfo;
69
71
  maxIterations;
70
72
  strictMode;
73
+ stopOnUsageLimit;
74
+ usageLimit;
71
75
  fallbackModel;
72
76
  model;
73
77
  thinkingEffort;
@@ -124,6 +128,7 @@ class Agent {
124
128
  this._productInfo = agentOptions.productInfo;
125
129
  this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
126
130
  this.strictMode = agentOptions.strictMode ?? false;
131
+ this.stopOnUsageLimit = agentOptions.stopOnUsageLimit ?? false;
127
132
  for (const mcp of agentOptions.internalMcps ?? []) this.addInternalMcp(mcp);
128
133
  if (agentOptions.fallbackModel) {
129
134
  this.fallbackModel = (0, import_model_resolution.toModelRef)(agentOptions.fallbackModel);
@@ -151,7 +156,7 @@ class Agent {
151
156
  }
152
157
  async run(props) {
153
158
  try {
154
- const { input, options, currentUser, currentSession, mcpTokens } = props || {};
159
+ const { input, options, currentUser, currentSession, mcpTokens, usageLimit } = props || {};
155
160
  const { chatId, message } = input || {};
156
161
  this.logger.debug(input, "[AGENT] Agent started");
157
162
  if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
@@ -177,9 +182,19 @@ class Agent {
177
182
  this.mcpTokens = mcpTokens ?? {};
178
183
  this.model = void 0;
179
184
  this.thinkingEffort = void 0;
185
+ this.usageLimit = usageLimit;
186
+ if (usageLimit) (0, import_usage_limit.validateUsageLimit)(usageLimit);
180
187
  if (options?.thinkingEffort !== void 0 && !(0, import_llm_types.isSelectableThinkingEffort)(options.thinkingEffort)) throw new Error(`[AGENT] thinkingEffort must be one of ${import_llm_types.SELECTABLE_THINKING_EFFORTS.join(", ")}`);
181
188
  if (Boolean(options?.modelProvider) !== Boolean(options?.modelName)) throw new Error("[AGENT] Set both modelProvider and modelName, or neither");
182
189
  this.answerId = new import_mongodb.ObjectId().toString();
190
+ if (usageLimit) {
191
+ try {
192
+ await (0, import_usage_limit.checkUsageLimit)(usageLimit, currentUser);
193
+ } catch (error) {
194
+ if (error instanceof import_usage_limit.UsageLimitError) return this.usageLimitResult(error, await this.saveBlockedMessage(chatId));
195
+ throw error;
196
+ }
197
+ }
183
198
  const proceed = await this.preRunner(chatId);
184
199
  if (proceed) {
185
200
  if (await this.resolveConfirmation()) await this.runLoop();
@@ -192,8 +207,11 @@ class Agent {
192
207
  const message = error?.message ?? String(error);
193
208
  this.logger.error({ error: message, stack: error?.stack }, "[AGENT] Run failed");
194
209
  const llmError = error instanceof import_llm_error.LLMError ? error : void 0;
195
- const reported = llmError?.userMessage ?? message;
196
- await this.failRun(reported, llmError);
210
+ const limitError = error instanceof import_usage_limit.UsageLimitError ? error : void 0;
211
+ const known = llmError ?? limitError;
212
+ const reported = known?.userMessage ?? message;
213
+ await this.failRun(reported, known);
214
+ if (limitError) return this.usageLimitResult(limitError, this.currentChat?._id ? this.currentChat : void 0);
197
215
  await this.reportFailure(error, llmError ? { code: llmError.code } : {});
198
216
  return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
199
217
  }
@@ -387,10 +405,29 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
387
405
  async reportFailure(error, details = {}) {
388
406
  await (0, import_error.reportError)(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
389
407
  }
390
- async failRun(message, llmError) {
408
+ async saveBlockedMessage(chatId) {
409
+ if (!chatId) return void 0;
410
+ try {
411
+ const data = await (0, import_chats.getChatById)({ id: chatId, currentUser: this.currentUser });
412
+ if (!data?._id) return void 0;
413
+ this.currentChat = import_chat.Chat.fromJSON(data);
414
+ if (!this.currentChat.messages?.length) this.currentChat.setTitle(this.currentMessage);
415
+ this.currentChat.pushMessage({ role: "user", content: this.currentMessage, source: "user" });
416
+ await this.saveChat({ resetStop: true });
417
+ return this.currentChat;
418
+ } catch (error) {
419
+ this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to save the message of a run blocked by the usage limit");
420
+ await this.reportFailure(error, { stage: "blocked-message" });
421
+ return void 0;
422
+ }
423
+ }
424
+ usageLimitResult(error, data) {
425
+ return { data, error: error.userMessage, errorCode: error.code, usageLimit: { used: error.used, limit: error.limit, period: error.period } };
426
+ }
427
+ async failRun(message, knownError) {
391
428
  try {
392
429
  this.currentChat.state?.setStatus(import_agent_state.AgentStatus.FAILED);
393
- this.currentChat.state?.setLastError({ code: llmError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: llmError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
430
+ this.currentChat.state?.setLastError({ code: knownError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: knownError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
394
431
  this.currentChat.addTrace({ node: "agent", kind: "agent", reasoning: `Run failed: ${message}` });
395
432
  this.currentChat.failTask();
396
433
  await this.persist();
@@ -775,6 +812,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
775
812
  this.stopLoop = true;
776
813
  break;
777
814
  }
815
+ if (iterations > 0 && this.stopOnUsageLimit && this.usageLimit) await (0, import_usage_limit.checkUsageLimit)(this.usageLimit, this.currentUser);
778
816
  iterations++;
779
817
  this.iteration = iterations;
780
818
  await this.checkInterruptionRequest();
@@ -30,6 +30,7 @@ import { ToolPipeline } from "./tool-pipeline";
30
30
  import { NATIVE_TOOLS } from "./native-tools";
31
31
  import { buildToolCatalog, isDeclarable, needsSearch } from "./tool-catalog";
32
32
  import { LLMError } from "../clients/llm/llm-error.js";
33
+ import { UsageLimitError, USAGE_LIMIT_REACHED, checkUsageLimit, validateUsageLimit } from "./usage-limit";
33
34
  import { isSelectableThinkingEffort, SELECTABLE_THINKING_EFFORTS } from "../clients/llm/llm-types.js";
34
35
  import { resolveModel, toModelRef } from "../clients/llm/model-resolution.js";
35
36
  const MCP_CONNECT_RETRY_DELAYS_MS = [1e3, 2e3];
@@ -42,7 +43,8 @@ const AUTOMATIC_ANSWER_RESULT_CHARS = 1500;
42
43
  const AGENT_ERROR_CODES = {
43
44
  NODE_NOT_FOUND: "AGENT_NODE_NOT_FOUND",
44
45
  RUN_FAILED: "AGENT_RUN_FAILED",
45
- MAX_ITERATIONS_REACHED: "AGENT_MAX_ITERATIONS_REACHED"
46
+ MAX_ITERATIONS_REACHED: "AGENT_MAX_ITERATIONS_REACHED",
47
+ USAGE_LIMIT_REACHED
46
48
  };
47
49
  const DEFAULT_MAX_ITERATIONS = 50;
48
50
  class Agent {
@@ -52,6 +54,8 @@ class Agent {
52
54
  _productInfo;
53
55
  maxIterations;
54
56
  strictMode;
57
+ stopOnUsageLimit;
58
+ usageLimit;
55
59
  fallbackModel;
56
60
  model;
57
61
  thinkingEffort;
@@ -108,6 +112,7 @@ class Agent {
108
112
  this._productInfo = agentOptions.productInfo;
109
113
  this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
110
114
  this.strictMode = agentOptions.strictMode ?? false;
115
+ this.stopOnUsageLimit = agentOptions.stopOnUsageLimit ?? false;
111
116
  for (const mcp of agentOptions.internalMcps ?? []) this.addInternalMcp(mcp);
112
117
  if (agentOptions.fallbackModel) {
113
118
  this.fallbackModel = toModelRef(agentOptions.fallbackModel);
@@ -135,7 +140,7 @@ class Agent {
135
140
  }
136
141
  async run(props) {
137
142
  try {
138
- const { input, options, currentUser, currentSession, mcpTokens } = props || {};
143
+ const { input, options, currentUser, currentSession, mcpTokens, usageLimit } = props || {};
139
144
  const { chatId, message } = input || {};
140
145
  this.logger.debug(input, "[AGENT] Agent started");
141
146
  if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
@@ -161,9 +166,19 @@ class Agent {
161
166
  this.mcpTokens = mcpTokens ?? {};
162
167
  this.model = void 0;
163
168
  this.thinkingEffort = void 0;
169
+ this.usageLimit = usageLimit;
170
+ if (usageLimit) validateUsageLimit(usageLimit);
164
171
  if (options?.thinkingEffort !== void 0 && !isSelectableThinkingEffort(options.thinkingEffort)) throw new Error(`[AGENT] thinkingEffort must be one of ${SELECTABLE_THINKING_EFFORTS.join(", ")}`);
165
172
  if (Boolean(options?.modelProvider) !== Boolean(options?.modelName)) throw new Error("[AGENT] Set both modelProvider and modelName, or neither");
166
173
  this.answerId = new ObjectId().toString();
174
+ if (usageLimit) {
175
+ try {
176
+ await checkUsageLimit(usageLimit, currentUser);
177
+ } catch (error) {
178
+ if (error instanceof UsageLimitError) return this.usageLimitResult(error, await this.saveBlockedMessage(chatId));
179
+ throw error;
180
+ }
181
+ }
167
182
  const proceed = await this.preRunner(chatId);
168
183
  if (proceed) {
169
184
  if (await this.resolveConfirmation()) await this.runLoop();
@@ -176,8 +191,11 @@ class Agent {
176
191
  const message = error?.message ?? String(error);
177
192
  this.logger.error({ error: message, stack: error?.stack }, "[AGENT] Run failed");
178
193
  const llmError = error instanceof LLMError ? error : void 0;
179
- const reported = llmError?.userMessage ?? message;
180
- await this.failRun(reported, llmError);
194
+ const limitError = error instanceof UsageLimitError ? error : void 0;
195
+ const known = llmError ?? limitError;
196
+ const reported = known?.userMessage ?? message;
197
+ await this.failRun(reported, known);
198
+ if (limitError) return this.usageLimitResult(limitError, this.currentChat?._id ? this.currentChat : void 0);
181
199
  await this.reportFailure(error, llmError ? { code: llmError.code } : {});
182
200
  return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
183
201
  }
@@ -371,10 +389,29 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
371
389
  async reportFailure(error, details = {}) {
372
390
  await reportError(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
373
391
  }
374
- async failRun(message, llmError) {
392
+ async saveBlockedMessage(chatId) {
393
+ if (!chatId) return void 0;
394
+ try {
395
+ const data = await getChatById({ id: chatId, currentUser: this.currentUser });
396
+ if (!data?._id) return void 0;
397
+ this.currentChat = Chat.fromJSON(data);
398
+ if (!this.currentChat.messages?.length) this.currentChat.setTitle(this.currentMessage);
399
+ this.currentChat.pushMessage({ role: "user", content: this.currentMessage, source: "user" });
400
+ await this.saveChat({ resetStop: true });
401
+ return this.currentChat;
402
+ } catch (error) {
403
+ this.logger.error({ error: error?.message ?? error }, "[AGENT] Failed to save the message of a run blocked by the usage limit");
404
+ await this.reportFailure(error, { stage: "blocked-message" });
405
+ return void 0;
406
+ }
407
+ }
408
+ usageLimitResult(error, data) {
409
+ return { data, error: error.userMessage, errorCode: error.code, usageLimit: { used: error.used, limit: error.limit, period: error.period } };
410
+ }
411
+ async failRun(message, knownError) {
375
412
  try {
376
413
  this.currentChat.state?.setStatus(AgentStatus.FAILED);
377
- this.currentChat.state?.setLastError({ code: llmError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: llmError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
414
+ this.currentChat.state?.setLastError({ code: knownError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: knownError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
378
415
  this.currentChat.addTrace({ node: "agent", kind: "agent", reasoning: `Run failed: ${message}` });
379
416
  this.currentChat.failTask();
380
417
  await this.persist();
@@ -759,6 +796,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
759
796
  this.stopLoop = true;
760
797
  break;
761
798
  }
799
+ if (iterations > 0 && this.stopOnUsageLimit && this.usageLimit) await checkUsageLimit(this.usageLimit, this.currentUser);
762
800
  iterations++;
763
801
  this.iteration = iterations;
764
802
  await this.checkInterruptionRequest();
@@ -1,3 +1,5 @@
1
1
  export * from './agent-loop';
2
2
  export * from './agent-state';
3
3
  export * from './agent';
4
+ export { UsageLimitError, USAGE_LIMIT_REACHED } from './usage-limit';
5
+ export type { UsageLimit } from './usage-limit';
@@ -3,6 +3,10 @@ var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
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
+ };
6
10
  var __copyProps = (to, from, except, desc) => {
7
11
  if (from && typeof from === "object" || typeof from === "function") {
8
12
  for (let key of __getOwnPropNames(from))
@@ -14,12 +18,19 @@ var __copyProps = (to, from, except, desc) => {
14
18
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
15
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
16
20
  var harness_exports = {};
21
+ __export(harness_exports, {
22
+ USAGE_LIMIT_REACHED: () => import_usage_limit.USAGE_LIMIT_REACHED,
23
+ UsageLimitError: () => import_usage_limit.UsageLimitError
24
+ });
17
25
  module.exports = __toCommonJS(harness_exports);
18
26
  __reExport(harness_exports, require("./agent-loop"), module.exports);
19
27
  __reExport(harness_exports, require("./agent-state"), module.exports);
20
28
  __reExport(harness_exports, require("./agent"), module.exports);
29
+ var import_usage_limit = require("./usage-limit");
21
30
  // Annotate the CommonJS export names for ESM import in node:
22
31
  0 && (module.exports = {
32
+ USAGE_LIMIT_REACHED,
33
+ UsageLimitError,
23
34
  ...require("./agent-loop"),
24
35
  ...require("./agent-state"),
25
36
  ...require("./agent")
@@ -1,3 +1,8 @@
1
1
  export * from "./agent-loop";
2
2
  export * from "./agent-state";
3
3
  export * from "./agent";
4
+ import { UsageLimitError, USAGE_LIMIT_REACHED } from "./usage-limit";
5
+ export {
6
+ USAGE_LIMIT_REACHED,
7
+ UsageLimitError
8
+ };
@@ -0,0 +1,18 @@
1
+ import { CurrentUser } from '../common/base/index.js';
2
+ import { LimitPeriod } from '../services/llmcalls/utils/usage-periods.js';
3
+ export declare const USAGE_LIMIT_REACHED = "USAGE_LIMIT_REACHED";
4
+ export interface UsageLimit {
5
+ maxCostUsd: number;
6
+ period: LimitPeriod;
7
+ }
8
+ export declare class UsageLimitError extends Error {
9
+ readonly used: number;
10
+ readonly limit: number;
11
+ readonly period: LimitPeriod;
12
+ readonly code = "USAGE_LIMIT_REACHED";
13
+ readonly isRetryable = false;
14
+ readonly userMessage: string;
15
+ constructor(used: number, limit: number, period: LimitPeriod);
16
+ }
17
+ export declare function validateUsageLimit(usageLimit: UsageLimit): void;
18
+ export declare function checkUsageLimit(usageLimit: UsageLimit, currentUser: CurrentUser): Promise<void>;
@@ -0,0 +1,63 @@
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 usage_limit_exports = {};
20
+ __export(usage_limit_exports, {
21
+ USAGE_LIMIT_REACHED: () => USAGE_LIMIT_REACHED,
22
+ UsageLimitError: () => UsageLimitError,
23
+ checkUsageLimit: () => checkUsageLimit,
24
+ validateUsageLimit: () => validateUsageLimit
25
+ });
26
+ module.exports = __toCommonJS(usage_limit_exports);
27
+ var import_llmcalls = require("../services/llmcalls/index.js");
28
+ var import_usage_periods = require("../services/llmcalls/utils/usage-periods.js");
29
+ const USAGE_LIMIT_REACHED = "USAGE_LIMIT_REACHED";
30
+ const PERIODS = ["day", "week", "month"];
31
+ class UsageLimitError extends Error {
32
+ constructor(used, limit, period) {
33
+ super(`[Usage limit] ${used} of ${limit} USD spent this ${period}`);
34
+ this.used = used;
35
+ this.limit = limit;
36
+ this.period = period;
37
+ this.userMessage = `The usage limit of this ${period} has been reached.`;
38
+ }
39
+ used;
40
+ limit;
41
+ period;
42
+ code = USAGE_LIMIT_REACHED;
43
+ isRetryable = false;
44
+ userMessage;
45
+ }
46
+ function validateUsageLimit(usageLimit) {
47
+ if (!Number.isFinite(usageLimit.maxCostUsd) || usageLimit.maxCostUsd <= 0) throw new Error("[AGENT] usageLimit.maxCostUsd must be a number greater than 0");
48
+ if (!PERIODS.includes(usageLimit.period)) throw new Error(`[AGENT] usageLimit.period must be one of ${PERIODS.join(", ")}`);
49
+ }
50
+ async function checkUsageLimit(usageLimit, currentUser) {
51
+ const { maxCostUsd, period } = usageLimit;
52
+ const timezone = (0, import_usage_periods.resolveTimezone)(currentUser.preferences?.timezone?.ianaIdentifier);
53
+ const { from, to } = (0, import_usage_periods.resolveLimitRange)(period, timezone);
54
+ const { summary } = await (0, import_llmcalls.getLLMUsageStats)({ filters: { fromDate: from, toDate: to, groupBy: "month" }, currentUser });
55
+ if (summary.totalCost >= maxCostUsd) throw new UsageLimitError(summary.totalCost, maxCostUsd, period);
56
+ }
57
+ // Annotate the CommonJS export names for ESM import in node:
58
+ 0 && (module.exports = {
59
+ USAGE_LIMIT_REACHED,
60
+ UsageLimitError,
61
+ checkUsageLimit,
62
+ validateUsageLimit
63
+ });
@@ -0,0 +1,36 @@
1
+ import { getLLMUsageStats } from "../services/llmcalls/index.js";
2
+ import { resolveLimitRange, resolveTimezone } from "../services/llmcalls/utils/usage-periods.js";
3
+ const USAGE_LIMIT_REACHED = "USAGE_LIMIT_REACHED";
4
+ const PERIODS = ["day", "week", "month"];
5
+ class UsageLimitError extends Error {
6
+ constructor(used, limit, period) {
7
+ super(`[Usage limit] ${used} of ${limit} USD spent this ${period}`);
8
+ this.used = used;
9
+ this.limit = limit;
10
+ this.period = period;
11
+ this.userMessage = `The usage limit of this ${period} has been reached.`;
12
+ }
13
+ used;
14
+ limit;
15
+ period;
16
+ code = USAGE_LIMIT_REACHED;
17
+ isRetryable = false;
18
+ userMessage;
19
+ }
20
+ function validateUsageLimit(usageLimit) {
21
+ if (!Number.isFinite(usageLimit.maxCostUsd) || usageLimit.maxCostUsd <= 0) throw new Error("[AGENT] usageLimit.maxCostUsd must be a number greater than 0");
22
+ if (!PERIODS.includes(usageLimit.period)) throw new Error(`[AGENT] usageLimit.period must be one of ${PERIODS.join(", ")}`);
23
+ }
24
+ async function checkUsageLimit(usageLimit, currentUser) {
25
+ const { maxCostUsd, period } = usageLimit;
26
+ const timezone = resolveTimezone(currentUser.preferences?.timezone?.ianaIdentifier);
27
+ const { from, to } = resolveLimitRange(period, timezone);
28
+ const { summary } = await getLLMUsageStats({ filters: { fromDate: from, toDate: to, groupBy: "month" }, currentUser });
29
+ if (summary.totalCost >= maxCostUsd) throw new UsageLimitError(summary.totalCost, maxCostUsd, period);
30
+ }
31
+ export {
32
+ USAGE_LIMIT_REACHED,
33
+ UsageLimitError,
34
+ checkUsageLimit,
35
+ validateUsageLimit
36
+ };
@@ -22,4 +22,9 @@ export declare const resolveRange: (input: {
22
22
  from: string;
23
23
  to: string;
24
24
  };
25
+ export type LimitPeriod = 'day' | 'week' | 'month';
26
+ export declare const resolveLimitRange: (period: LimitPeriod, timezone: string, now?: Date) => {
27
+ from: string;
28
+ to: string;
29
+ };
25
30
  export declare const enumeratePeriods: (groupBy: UsagePeriod, from: string, to: string) => string[];
@@ -22,6 +22,7 @@ __export(usage_periods_exports, {
22
22
  PERIODS: () => PERIODS,
23
23
  addDays: () => addDays,
24
24
  enumeratePeriods: () => enumeratePeriods,
25
+ resolveLimitRange: () => resolveLimitRange,
25
26
  resolveRange: () => resolveRange,
26
27
  resolveTimezone: () => resolveTimezone,
27
28
  todayIn: () => todayIn
@@ -64,6 +65,16 @@ const resolveRange = (input, timezone, now = /* @__PURE__ */ new Date()) => {
64
65
  if (from > to) throw new Error("fromDate must not be later than toDate");
65
66
  return { from, to };
66
67
  };
68
+ const resolveLimitRange = (period, timezone, now = /* @__PURE__ */ new Date()) => {
69
+ const today = todayIn(timezone, now);
70
+ if (period === "day") return { from: today, to: today };
71
+ if (period === "week") {
72
+ const sinceMonday = ((/* @__PURE__ */ new Date(`${today}T00:00:00Z`)).getUTCDay() + 6) % 7;
73
+ const from = addDays(today, -sinceMonday);
74
+ return { from, to: addDays(from, 6) };
75
+ }
76
+ return resolveRange({}, timezone, now);
77
+ };
67
78
  const enumeratePeriods = (groupBy, from, to) => {
68
79
  const period = PERIODS[groupBy];
69
80
  if (!period) throw new Error(`Invalid groupBy "${groupBy}". Use one of: ${Object.keys(PERIODS).join(", ")}`);
@@ -81,6 +92,7 @@ const enumeratePeriods = (groupBy, from, to) => {
81
92
  PERIODS,
82
93
  addDays,
83
94
  enumeratePeriods,
95
+ resolveLimitRange,
84
96
  resolveRange,
85
97
  resolveTimezone,
86
98
  todayIn
@@ -35,6 +35,16 @@ const resolveRange = (input, timezone, now = /* @__PURE__ */ new Date()) => {
35
35
  if (from > to) throw new Error("fromDate must not be later than toDate");
36
36
  return { from, to };
37
37
  };
38
+ const resolveLimitRange = (period, timezone, now = /* @__PURE__ */ new Date()) => {
39
+ const today = todayIn(timezone, now);
40
+ if (period === "day") return { from: today, to: today };
41
+ if (period === "week") {
42
+ const sinceMonday = ((/* @__PURE__ */ new Date(`${today}T00:00:00Z`)).getUTCDay() + 6) % 7;
43
+ const from = addDays(today, -sinceMonday);
44
+ return { from, to: addDays(from, 6) };
45
+ }
46
+ return resolveRange({}, timezone, now);
47
+ };
38
48
  const enumeratePeriods = (groupBy, from, to) => {
39
49
  const period = PERIODS[groupBy];
40
50
  if (!period) throw new Error(`Invalid groupBy "${groupBy}". Use one of: ${Object.keys(PERIODS).join(", ")}`);
@@ -51,6 +61,7 @@ export {
51
61
  PERIODS,
52
62
  addDays,
53
63
  enumeratePeriods,
64
+ resolveLimitRange,
54
65
  resolveRange,
55
66
  resolveTimezone,
56
67
  todayIn
package/docs/README.md CHANGED
@@ -41,7 +41,7 @@ Start with the [README](../README.md) for what `openloops` is and how to run it.
41
41
  | --- | --- |
42
42
  | [User management](users.md) | `CurrentUser`, creating, listing, updating and deleting users. |
43
43
  | [Authentication](authentication.md) | Login and tokens. |
44
- | [LLM usage tracking](usage.md) | Tokens and cost per chat or answer, and per-user statistics. |
44
+ | [LLM usage tracking](usage.md) | Tokens and cost per chat or answer, per-user statistics, and how to limit the spend of a user. |
45
45
 
46
46
  ## Examples
47
47
 
package/docs/agent.md CHANGED
@@ -34,6 +34,7 @@ const agent = new Agent({
34
34
  | `productInfo` | no | none | Name, company and a short description of the product the agent serves, injected into every skill. |
35
35
  | `maxInputLength` | no | `100000` | Longest message accepted, in characters. Longer messages are blocked by a built-in guard. |
36
36
  | `maxIterations` | no | `50` | Hard limit of loop iterations in one run. When reached, the run fails with `AGENT_MAX_ITERATIONS_REACHED`. |
37
+ | `stopOnUsageLimit` | no | `false` | When `true` and the run has a [`usageLimit`](#usage-limit), the spend is checked again before each loop iteration and the run stops when the limit is reached. When `false`, the limit is checked only before the run starts. |
37
38
  | `fallbackModel` | no | none | `{ provider, model }` used when neither the run, the chat nor the user chose a model. See [configuration](configuration.md#which-model-a-chat-uses). |
38
39
  | `internalMcps` | no | none | MCP servers of your own solution that the user never registers. Also added with `agent.addInternalMcp(mcp)`. See [MCP servers](mcp-servers.md#internal-mcp-servers). |
39
40
  | `strictMode` | no | `false` | When `true`, the user is always asked before the agent uses an MCP server whose tools changed after being approved. See [MCP servers](mcp-servers.md#how-the-agent-uses-the-servers). |
@@ -75,6 +76,54 @@ Omit `chatId` to start a brand-new chat. Pass an existing `chatId` to continue a
75
76
 
76
77
  `mcpTokens` is optional. It gives the token of the user to each [internal MCP server](mcp-servers.md#internal-mcp-servers), by name. It is never saved. In an [autonomous run](#autonomous-mode) with no token for a server, the `autonomousToken` of that server is used, see [automations](automations.md#internal-mcp-servers-in-an-automation).
77
78
 
79
+ ## Usage limit
80
+
81
+ Pass `usageLimit` in the run to cap what a user can spend, in US dollars, in a period:
82
+
83
+ ```typescript
84
+ const result = await agent.run({
85
+ input: { message: 'hi' },
86
+ currentUser,
87
+ usageLimit: { maxCostUsd: 1, period: 'month' },
88
+ })
89
+ ```
90
+
91
+ `period` is required and can be `day`, `week` (Monday to Sunday) or `month`. The period is calculated in the time zone of the user (UTC when it has none) and the spend is the cost of all the model calls of that user in it, from any chat and of any kind. The limit itself belongs to your application: `openloops` only checks it.
92
+
93
+ Before the run starts, if the spend is equal to or greater than `maxCostUsd`, the run does not start: no guard, no model call and no loop run. When the run continues an existing chat (`chatId`), the message of the user is saved in it with no answer, the status of the chat does not change, and the chat is returned in `data`. A chat with no messages takes that message as its title. With no `chatId`, or with one that does not exist, nothing is saved and `data` is `undefined`. The result carries the details:
94
+
95
+ ```typescript
96
+ result.data
97
+ result.error
98
+ result.errorCode
99
+ result.usageLimit
100
+ ```
101
+
102
+ `errorCode` is `USAGE_LIMIT_REACHED` and `usageLimit` is `{ used, limit, period }`. This is an expected rejection, so it is not sent to the [error reporter](error-reporting.md). The message that was saved is part of the history of the chat, so when the limit is lifted the next run reads it and the user can just say `continue`.
103
+
104
+ A run that starts under the limit finishes even if it goes over it, so the last run of a period can spend a little more than `maxCostUsd`. To stop a run between the iterations of the loop, create the agent with `stopOnUsageLimit: true`. The chat is then marked as `failed` with `USAGE_LIMIT_REACHED` (not retryable) in `data.state.lastError`, and the result carries the same `errorCode` and `usageLimit`. It costs one query per iteration.
105
+
106
+ A common setup is one limit per plan, chosen by your application and passed in every run:
107
+
108
+ ```typescript
109
+ const limits = {
110
+ free: { maxCostUsd: 0.1, period: 'month' },
111
+ paid: { maxCostUsd: 1, period: 'month' },
112
+ } as const
113
+
114
+ const result = await agent.run({
115
+ input,
116
+ currentUser,
117
+ usageLimit: limits[userPays ? 'paid' : 'free'],
118
+ })
119
+
120
+ if (result.errorCode === 'USAGE_LIMIT_REACHED') {
121
+ const { used, limit, period } = result.usageLimit!
122
+ }
123
+ ```
124
+
125
+ The spend is the one that [usage tracking](usage.md) reports, so `getLLMUsageStats` shows the same figure that the limit compares. Examples: [limit by plan](../examples/run-agent/run-agent-with-usage-limit.ts) and [stopping in the middle of a run](../examples/run-agent/run-agent-with-usage-limit-stop.ts).
126
+
78
127
  ## Autonomous mode
79
128
 
80
129
  An autonomous run is one where nobody is in the chat while the agent works, for example a scheduled task. Pass the mode in the run:
@@ -118,6 +167,7 @@ data?.state?.status
118
167
 
119
168
  - `data` is the `Chat` after the turn, or `undefined` if the chat could not even be created.
120
169
  - `error` is a message you can show to the user, present only when the run failed. The chat is marked as `failed` and saved.
170
+ - `errorCode` and `usageLimit` are present only when the run was stopped by a [usage limit](#usage-limit).
121
171
 
122
172
  `data.state.status` tells you where the conversation is:
123
173
 
package/docs/usage.md CHANGED
@@ -12,6 +12,8 @@ There are three functions:
12
12
  - `getLLMUsageByChat` answers how much a whole chat used.
13
13
  - `getLLMUsageStats` answers how much a user used in a period, by model and over time.
14
14
 
15
+ To stop a user who spent too much, pass a `usageLimit` in the run: it compares the cost of the period with the amount you choose. Read [usage limit](agent.md#usage-limit).
16
+
15
17
  ## Usage of one answer and of one chat
16
18
 
17
19
  ```typescript
@@ -0,0 +1,45 @@
1
+ import { Agent, AgentStatus } from 'openloops/core'
2
+ import { Logger } from 'openloops/common'
3
+ import { CurrentUser } from 'openloops/base'
4
+ import { AgiLoop } from 'openloops/loops'
5
+
6
+ /**
7
+ * Stops a run in the middle when the user passes the limit.
8
+ *
9
+ * By default the limit is checked only before the run starts, so a long run that starts under the limit finishes even if it
10
+ * goes over it. `stopOnUsageLimit` is an option of the agent, off by default, that checks the spend again before each iteration of
11
+ * the loop. It costs one query per iteration, and it does nothing in a run without `usageLimit`.
12
+ */
13
+ async function runAgentWithUsageLimitStop () {
14
+ const logger = new Logger()
15
+ const currentUser = await CurrentUser.asyncFromDB('6ab56894eb20887d1ef7942c')
16
+
17
+ if (!currentUser) throw new Error('[Demo] current user is not defined')
18
+
19
+ const agent = new Agent({ loop: new AgiLoop(), stopOnUsageLimit: true })
20
+
21
+ const result = await agent.run({
22
+ input: { message: 'research the latest news about electric cars and write a summary' },
23
+ currentUser,
24
+ usageLimit: { maxCostUsd: 0.5, period: 'day' },
25
+ })
26
+
27
+ /**
28
+ * A run stopped in the middle keeps its chat: it is saved as `failed` with the code `USAGE_LIMIT_REACHED`, which is not
29
+ * retryable, and the result carries the same `errorCode` and `usageLimit` as a run blocked before it started. The only
30
+ * difference is that `data` is the chat, with what the agent did until it stopped.
31
+ */
32
+ if (result.errorCode === 'USAGE_LIMIT_REACHED') {
33
+ logger.info({
34
+ usageLimit: result.usageLimit,
35
+ started: Boolean(result.data),
36
+ status: result.data?.state?.status === AgentStatus.FAILED ? 'stopped' : 'blocked',
37
+ lastError: result.data?.state?.lastError?.code,
38
+ }, '[Demo] The limit was reached')
39
+ return
40
+ }
41
+
42
+ logger.info({ error: result.error, answer: result.data?.lastAnswer }, '[Demo] Run')
43
+ }
44
+
45
+ runAgentWithUsageLimitStop()
@@ -0,0 +1,55 @@
1
+ import { Agent, UsageLimit } from 'openloops/core'
2
+ import { Logger } from 'openloops/common'
3
+ import { CurrentUser } from 'openloops/base'
4
+ import { AgiLoop } from 'openloops/loops'
5
+
6
+ /**
7
+ * 1. THE LIMIT BELONGS TO YOUR APPLICATION.
8
+ *
9
+ * `openloops` does not know your plans: you choose the amount and the period for each user and pass it in the run. Here a free
10
+ * user can spend 10 cents a month and a paying user 1 dollar a month.
11
+ */
12
+ const FREE_LIMIT: UsageLimit = { maxCostUsd: 0.1, period: 'month' }
13
+ const PAID_LIMIT: UsageLimit = { maxCostUsd: 1, period: 'month' }
14
+
15
+ async function runAgentWithUsageLimit () {
16
+ const logger = new Logger()
17
+ const currentUser = await CurrentUser.asyncFromDB('6ab56894eb20887d1ef7942c')
18
+
19
+ if (!currentUser) throw new Error('[Demo] current user is not defined')
20
+
21
+ const isPaying = false
22
+ const agent = new Agent({ loop: new AgiLoop() })
23
+
24
+ /**
25
+ * 2. PASS IT IN THE RUN.
26
+ *
27
+ * Before the run starts, `openloops` adds the cost of every model call of the user in the period, from any chat. If the total
28
+ * is equal to or greater than `maxCostUsd`, the run does not start: nothing calls the model. When the run continues a chat
29
+ * (`chatId`), the message is saved in it with no answer, so the user can say `continue` when the limit is lifted. A run that
30
+ * starts under the limit finishes, even if it goes over it.
31
+ */
32
+ const result = await agent.run({
33
+ input: { message: 'hi, how are you?' },
34
+ currentUser,
35
+ usageLimit: isPaying ? PAID_LIMIT : FREE_LIMIT,
36
+ })
37
+
38
+ /**
39
+ * 3. HANDLE THE REJECTION.
40
+ *
41
+ * `agent.run` does not throw. A blocked run comes back with `errorCode: 'USAGE_LIMIT_REACHED'`, the amounts in `usageLimit`
42
+ * and, when it continued a chat, the chat in `data` with the saved message. Answer your client with the status that fits, for example 429, and let the app show its own message. This
43
+ * rejection is expected, so it is not sent to the error reporter.
44
+ */
45
+ if (result.errorCode === 'USAGE_LIMIT_REACHED') {
46
+ const { used, limit, period } = result.usageLimit!
47
+
48
+ logger.info({ used, limit, period }, '[Demo] The user reached the limit of the period')
49
+ return
50
+ }
51
+
52
+ logger.info({ error: result.error, answer: result.data?.lastAnswer }, '[Demo] Run')
53
+ }
54
+
55
+ runAgentWithUsageLimit()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openloops",
3
- "version": "0.8.3",
3
+ "version": "0.9.1",
4
4
  "description": "Open source harness for building multitenant AI agents for your SaaS: a TypeScript runtime with persistence, tools, MCP trust, approvals and autonomous automations",
5
5
  "author": {
6
6
  "name": "Jose Barcos",