openloops 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,11 +2,27 @@
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
- ## Unreleased
5
+ ## 0.9.0
6
+
7
+ ### Added
8
+
9
+ - `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).
10
+ - `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`.
11
+ - `UsageLimit`, `UsageLimitError`, `USAGE_LIMIT_REACHED` and `AgentRunResult` are exported from `openloops/core`.
12
+ - Examples: `run-agent-with-usage-limit` (one limit per plan) and `run-agent-with-usage-limit-stop` (stopping in the middle of a run).
13
+
14
+ ## 0.8.3
15
+
16
+ ### Added
17
+
18
+ - `productInfo` option of the `Agent`, with `name`, `company` and `about`, injected into the context of the skills next to the identity. Read [product info](docs/agent.md#product-info).
19
+ - `AgentIdentity` and `AgentProductInfo` are exported from `openloops/core`.
6
20
 
7
21
  ### Changed
8
22
 
9
- - The description of the package, the README and the docs index present `openloops` as the harness for building multitenant AI agents for your SaaS, where the model is the engine, `openloops` the chassis and your product the body. The README no longer shows the `CustomerSupportLoop` and `CodeSpecialistLoop` examples, which the package does not ship, and links to the live demo at openloops.xyz.
23
+ - The fast responder (2.6.0) now knows it is the front layer of an agent, adopts `identity` like the reasoning engine does, and delegates to the engine every message about the product, the agent or its capabilities, and the data or advice that belong to the domain described in `productInfo.about`. It no longer lists what the agent can or cannot do, and it delegates when in doubt. Keep `identity.role` short.
24
+ - The reasoning engine (2.5.6) states more firmly that the final answer goes inside the `respond` action and that text written outside the JSON is never delivered, which reduces the plain text answers that were rejected as `invalid_response` and cost an extra call. The message sent back after a response that is not JSON now says that text meant for the user belongs in the `answer` of a `respond` action. It also reads `productInfo` when the user asks about the product or the company.
25
+ - The description of the package, the README and the docs index present `openloops` as the harness for building multitenant AI agents for your SaaS, where the model is the engine, `openloops` the chassis and your interface the body. The README no longer shows the `CustomerSupportLoop` and `CodeSpecialistLoop` examples, which the package does not ship, and links to the live demo at openloops.xyz.
10
26
 
11
27
  ## 0.8.1
12
28
 
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
- # openloops
1
+ # Openloops
2
2
 
3
- **Build enterprise multitenant AI agents for your SaaS in minutes, not days, weeks, or months.** · [openloops.xyz](https://openloops.xyz)
3
+ **Build production-ready, multitenant AI agents for your SaaS in minutes, not days, weeks, or months.** · [openloops.xyz](https://openloops.xyz)
4
4
 
5
- Openloops is an open source **harness** for building AI agents. An agent is three things: a **model** that thinks (the engine), a **harness** that gives it hands, memory and rules (the chassis), and the **product** you build around it (the body). Anthropic and OpenAI give you the engine, Openloops is the chassis, with the AGI loop, the tools and everything an agent needs in production, and you build the body: a customer support agent, a financial auditor, a meeting copilot. Change the model, or the product, and the rest stays the same.
5
+ Openloops is an open source **harness** for building AI agents. An agent is three things: a **model** that thinks (the engine), a **harness** that gives it hands, memory and rules (the chassis), and the **interface** you build on top, with your tools and MCP servers (the body). Anthropic and OpenAI give you the engine. Openloops gives you the chassis, with the AGI loop, the tools and everything an agent needs in production. You build the body: a customer support agent, a financial auditor, a meeting copilot. Change the model, or the product, and the rest stays the same.
6
6
 
7
7
  **Want to see it working?** [Try the live demo](https://openloops.xyz/#demo), a real agent running on Openloops, with nothing to install.
8
8
 
9
9
  <p align="center">
10
- <img src="https://raw.githubusercontent.com/jbarcosdev/openloops/main/docs/assets/harness-car.svg" alt="A car made of an engine (the AI model), a chassis (Openloops) and a body (your product). The body changes between a personal assistant, customer support, a meeting copilot and your own idea, while the engine and the chassis stay the same." width="560">
10
+ <img src="https://raw.githubusercontent.com/jbarcosdev/openloops/main/docs/assets/harness-car.svg" alt="A car made of an engine (the AI model), a chassis (Openloops) and a body (your interface). The body changes between a personal assistant, customer support, a meeting copilot and your own idea, while the engine and the chassis stay the same." width="560">
11
11
  </p>
12
12
 
13
13
  ```typescript
@@ -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.
@@ -158,7 +158,7 @@ This is a comparison against the self-hosted, open-source versions of LangGraph
158
158
  | User management | Included (`openloops/users`, `openloops/authentication`) | Not included, you build your own | Not included, you build your own |
159
159
  | LLM usage/cost tracking | Included (`openloops/llmcalls`): per answer, per chat, and per-user statistics | Not included in OSS, available via paid LangSmith | Third-party integrations such as OpenLIT report token usage and cost |
160
160
  | Observability | Langfuse via env vars, a hook to report errors to the tool you use, and traces stored per chat | Your own tracing setup, or paid LangSmith | Third-party integrations (Langfuse, OpenLIT, Arize Phoenix, Opik, Weave) that you set up |
161
- | What you write | Your tools and MCP servers, and the product you build on top. The loop is included, and you can write your own | Nodes and the graph's edges, explicitly | Agents, tasks, and crew orchestration, declared per role |
161
+ | What you write | Your interface, your tools and MCP servers. The loop is included, and you can write your own | Nodes and the graph's edges, explicitly | Agents, tasks, and crew orchestration, declared per role |
162
162
  | Mental model | A ready-made chassis: you connect your tools and embed the agent in your app | A graph you declare and compile ahead of time | A crew of role-based agents coordinated for you |
163
163
 
164
164
  Neither approach is "wrong." LangGraph's explicit graph declaration is a deliberate design choice that gives you visual tooling (LangGraph Studio) and fine-grained control over parallel execution, and CrewAI's role-based model is a natural fit for problems that map cleanly onto a team of specialists. `openloops` trades some of that explicitness for a much shorter path from "I have an idea for an agent" to "it's running in production, for all my users."
@@ -230,7 +230,9 @@ By default, `openloops` uses a database named `openloops` if `OPENLOOPS_DB_NAME`
230
230
 
231
231
  ### Web search
232
232
 
233
- The built-in `webSearchTool` uses [Serper](https://serper.dev). Create a free API key there and set `SERPER_API_KEY` in your `.env`. See [`docs/tools.md`](docs/tools.md).
233
+ Most agents don't need a search tool. `fetchUrlTool` is built in, free and needs no key: it reads any web page as text, which is enough when the agent already knows the source (a docs page, a price page, an API).
234
+
235
+ The built-in `webSearchTool` is only for when you strictly need to search Google. It uses [Serper](https://serper.dev) and returns Google result snippets, not pages, so the agent still has to read the sources with `fetchUrlTool`. Create a free API key there and set `SERPER_API_KEY` in your `.env`. See [`docs/tools.md`](docs/tools.md).
234
236
 
235
237
  ### Slack
236
238
 
@@ -243,7 +245,7 @@ The built-in `sendSlackMessageTool` posts a message to a channel. Create a Slack
243
245
 
244
246
  ## The AGI loop, and your own if you need it
245
247
 
246
- The logic that makes your agent *your* agent (how it reasons, when it asks for confirmation, whether it answers in one shot or works through a sequence of tools) lives in an `AgentLoop`. Most products never need to write one: `openloops` ships `AgiLoop`, a reasoning loop that answers directly when it can and otherwise works in cycles of think, act and observe until it has a final answer. What you add is your tools and your MCP servers.
248
+ The loop is the transmission of the harness: it decides how the agent reasons, when it asks for confirmation and whether it answers in one shot or works through a sequence of tools, and it lives in an `AgentLoop`. Most products never need to write one: `openloops` ships `AgiLoop`, a reasoning loop that answers directly when it can and otherwise works in cycles of think, act and observe until it has a final answer. What makes your agent yours is the interface you build and the tools and MCP servers you connect.
247
249
 
248
250
  If you need full control, a loop is a single file with a handful of node functions, so writing your own is a matter of an afternoon, not a sprint. See [Building an `AgentLoop`](docs/loops.md).
249
251
 
@@ -13,6 +13,7 @@ import { Workspace } from './workspace';
13
13
  import { ToolPipelineRunOptions } from './tool-pipeline';
14
14
  export interface RunContext {
15
15
  identity?: AgentIdentity;
16
+ productInfo?: AgentProductInfo;
16
17
  task?: AgentTask;
17
18
  chat: Chat;
18
19
  chatOptions?: ChatSettingsProps;
@@ -45,11 +46,16 @@ export interface Harness {
45
46
  reply: (content: string) => void;
46
47
  setNextNode: (node?: string | AgentLoopNode) => void;
47
48
  }
48
- interface AgentIdentity {
49
+ export interface AgentIdentity {
49
50
  name?: string;
50
51
  gender?: string;
51
52
  role?: string;
52
53
  }
54
+ export interface AgentProductInfo {
55
+ name?: string;
56
+ company?: string;
57
+ about?: string;
58
+ }
53
59
  export type AgentLoopNode = (ctx: RunContext, harness: Harness) => Promise<void>;
54
60
  export interface Author {
55
61
  name: string;
@@ -63,4 +69,3 @@ export declare abstract class AgentLoop {
63
69
  abstract get version(): string;
64
70
  abstract get author(): Author;
65
71
  }
66
- export {};
@@ -4,8 +4,9 @@ import { Chat } from '../services/chats/entities/chat.entity.js';
4
4
  import { ChatSettingsProps } from '../services/chats/entities/chat-settings.entity.js';
5
5
  import { Tool } from '../tools/tool.js';
6
6
  import { Guard } from '../guardrails/guard.js';
7
- import { AgentLoop } from './agent-loop';
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,12 +17,8 @@ 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
- interface AgentIdentity {
21
- name?: string;
22
- gender?: string;
23
- role?: string;
24
- }
25
22
  export interface AgentOptions {
26
23
  loop: AgentLoop;
27
24
  tools?: Tool[];
@@ -29,13 +26,25 @@ export interface AgentOptions {
29
26
  guards?: Guard[];
30
27
  maxInputLength?: number;
31
28
  identity?: AgentIdentity;
29
+ productInfo?: AgentProductInfo;
32
30
  maxIterations?: number;
33
31
  strictMode?: boolean;
32
+ stopOnUsageLimit?: boolean;
34
33
  fallbackModel?: {
35
34
  provider: string;
36
35
  model: string;
37
36
  };
38
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
+ }
39
48
  interface ChatInput {
40
49
  message: string;
41
50
  chatId?: string;
@@ -46,8 +55,11 @@ export declare class Agent {
46
55
  private readonly logger;
47
56
  private readonly _loop;
48
57
  private readonly _identity?;
58
+ private readonly _productInfo?;
49
59
  private readonly maxIterations;
50
60
  private readonly strictMode;
61
+ private readonly stopOnUsageLimit;
62
+ private usageLimit?;
51
63
  private readonly fallbackModel?;
52
64
  private model?;
53
65
  private thinkingEffort?;
@@ -91,13 +103,8 @@ export declare class Agent {
91
103
  currentUser: CurrentUser;
92
104
  currentSession?: CurrentSession;
93
105
  mcpTokens?: Record<string, string>;
94
- }): Promise<{
95
- data: Chat;
96
- error?: undefined;
97
- } | {
98
- data: Chat | undefined;
99
- error: any;
100
- }>;
106
+ usageLimit?: UsageLimit;
107
+ }): Promise<AgentRunResult>;
101
108
  stopAgent(): void;
102
109
  addTool(tool: Tool): void;
103
110
  addInternalMcp(mcp: InternalMcp): void;
@@ -112,6 +119,7 @@ export declare class Agent {
112
119
  private resolveConfirmation;
113
120
  private postRunner;
114
121
  private reportFailure;
122
+ private usageLimitResult;
115
123
  private failRun;
116
124
  private fingerprint;
117
125
  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,15 +59,19 @@ 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 {
65
67
  logger = new import_logger.Logger();
66
68
  _loop;
67
69
  _identity;
70
+ _productInfo;
68
71
  maxIterations;
69
72
  strictMode;
73
+ stopOnUsageLimit;
74
+ usageLimit;
70
75
  fallbackModel;
71
76
  model;
72
77
  thinkingEffort;
@@ -120,8 +125,10 @@ class Agent {
120
125
  this._loop = agentOptions.loop;
121
126
  this._tools = agentOptions.tools ?? [];
122
127
  this._identity = agentOptions.identity;
128
+ this._productInfo = agentOptions.productInfo;
123
129
  this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
124
130
  this.strictMode = agentOptions.strictMode ?? false;
131
+ this.stopOnUsageLimit = agentOptions.stopOnUsageLimit ?? false;
125
132
  for (const mcp of agentOptions.internalMcps ?? []) this.addInternalMcp(mcp);
126
133
  if (agentOptions.fallbackModel) {
127
134
  this.fallbackModel = (0, import_model_resolution.toModelRef)(agentOptions.fallbackModel);
@@ -149,7 +156,7 @@ class Agent {
149
156
  }
150
157
  async run(props) {
151
158
  try {
152
- const { input, options, currentUser, currentSession, mcpTokens } = props || {};
159
+ const { input, options, currentUser, currentSession, mcpTokens, usageLimit } = props || {};
153
160
  const { chatId, message } = input || {};
154
161
  this.logger.debug(input, "[AGENT] Agent started");
155
162
  if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
@@ -175,9 +182,19 @@ class Agent {
175
182
  this.mcpTokens = mcpTokens ?? {};
176
183
  this.model = void 0;
177
184
  this.thinkingEffort = void 0;
185
+ this.usageLimit = usageLimit;
186
+ if (usageLimit) (0, import_usage_limit.validateUsageLimit)(usageLimit);
178
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(", ")}`);
179
188
  if (Boolean(options?.modelProvider) !== Boolean(options?.modelName)) throw new Error("[AGENT] Set both modelProvider and modelName, or neither");
180
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);
195
+ throw error;
196
+ }
197
+ }
181
198
  const proceed = await this.preRunner(chatId);
182
199
  if (proceed) {
183
200
  if (await this.resolveConfirmation()) await this.runLoop();
@@ -190,8 +207,11 @@ class Agent {
190
207
  const message = error?.message ?? String(error);
191
208
  this.logger.error({ error: message, stack: error?.stack }, "[AGENT] Run failed");
192
209
  const llmError = error instanceof import_llm_error.LLMError ? error : void 0;
193
- const reported = llmError?.userMessage ?? message;
194
- 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);
195
215
  await this.reportFailure(error, llmError ? { code: llmError.code } : {});
196
216
  return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
197
217
  }
@@ -385,10 +405,13 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
385
405
  async reportFailure(error, details = {}) {
386
406
  await (0, import_error.reportError)(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
387
407
  }
388
- async failRun(message, llmError) {
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) {
389
412
  try {
390
413
  this.currentChat.state?.setStatus(import_agent_state.AgentStatus.FAILED);
391
- 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() });
392
415
  this.currentChat.addTrace({ node: "agent", kind: "agent", reasoning: `Run failed: ${message}` });
393
416
  this.currentChat.failTask();
394
417
  await this.persist();
@@ -773,6 +796,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
773
796
  this.stopLoop = true;
774
797
  break;
775
798
  }
799
+ if (iterations > 0 && this.stopOnUsageLimit && this.usageLimit) await (0, import_usage_limit.checkUsageLimit)(this.usageLimit, this.currentUser);
776
800
  iterations++;
777
801
  this.iteration = iterations;
778
802
  await this.checkInterruptionRequest();
@@ -882,6 +906,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
882
906
  const agent = this;
883
907
  return {
884
908
  identity: this._identity,
909
+ productInfo: this._productInfo,
885
910
  task: this.currentChat.activeTask,
886
911
  chat: this.currentChat,
887
912
  chatOptions: this.chatOptions,
@@ -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,15 +43,19 @@ 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 {
49
51
  logger = new Logger();
50
52
  _loop;
51
53
  _identity;
54
+ _productInfo;
52
55
  maxIterations;
53
56
  strictMode;
57
+ stopOnUsageLimit;
58
+ usageLimit;
54
59
  fallbackModel;
55
60
  model;
56
61
  thinkingEffort;
@@ -104,8 +109,10 @@ class Agent {
104
109
  this._loop = agentOptions.loop;
105
110
  this._tools = agentOptions.tools ?? [];
106
111
  this._identity = agentOptions.identity;
112
+ this._productInfo = agentOptions.productInfo;
107
113
  this.maxIterations = agentOptions.maxIterations ?? DEFAULT_MAX_ITERATIONS;
108
114
  this.strictMode = agentOptions.strictMode ?? false;
115
+ this.stopOnUsageLimit = agentOptions.stopOnUsageLimit ?? false;
109
116
  for (const mcp of agentOptions.internalMcps ?? []) this.addInternalMcp(mcp);
110
117
  if (agentOptions.fallbackModel) {
111
118
  this.fallbackModel = toModelRef(agentOptions.fallbackModel);
@@ -133,7 +140,7 @@ class Agent {
133
140
  }
134
141
  async run(props) {
135
142
  try {
136
- const { input, options, currentUser, currentSession, mcpTokens } = props || {};
143
+ const { input, options, currentUser, currentSession, mcpTokens, usageLimit } = props || {};
137
144
  const { chatId, message } = input || {};
138
145
  this.logger.debug(input, "[AGENT] Agent started");
139
146
  if (!this._loop?.nodes || !this._loop?.initialNode) throw new Error("[AGENT] Loop is missing");
@@ -159,9 +166,19 @@ class Agent {
159
166
  this.mcpTokens = mcpTokens ?? {};
160
167
  this.model = void 0;
161
168
  this.thinkingEffort = void 0;
169
+ this.usageLimit = usageLimit;
170
+ if (usageLimit) validateUsageLimit(usageLimit);
162
171
  if (options?.thinkingEffort !== void 0 && !isSelectableThinkingEffort(options.thinkingEffort)) throw new Error(`[AGENT] thinkingEffort must be one of ${SELECTABLE_THINKING_EFFORTS.join(", ")}`);
163
172
  if (Boolean(options?.modelProvider) !== Boolean(options?.modelName)) throw new Error("[AGENT] Set both modelProvider and modelName, or neither");
164
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);
179
+ throw error;
180
+ }
181
+ }
165
182
  const proceed = await this.preRunner(chatId);
166
183
  if (proceed) {
167
184
  if (await this.resolveConfirmation()) await this.runLoop();
@@ -174,8 +191,11 @@ class Agent {
174
191
  const message = error?.message ?? String(error);
175
192
  this.logger.error({ error: message, stack: error?.stack }, "[AGENT] Run failed");
176
193
  const llmError = error instanceof LLMError ? error : void 0;
177
- const reported = llmError?.userMessage ?? message;
178
- 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);
179
199
  await this.reportFailure(error, llmError ? { code: llmError.code } : {});
180
200
  return { data: this.currentChat?._id ? this.currentChat : void 0, error: reported };
181
201
  }
@@ -369,10 +389,13 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
369
389
  async reportFailure(error, details = {}) {
370
390
  await reportError(error, { source: "agent", chatId: this.currentChat?._id?.toString(), userId: this.currentUser?.userId, ...details });
371
391
  }
372
- async failRun(message, llmError) {
392
+ usageLimitResult(error, data) {
393
+ return { data, error: error.userMessage, errorCode: error.code, usageLimit: { used: error.used, limit: error.limit, period: error.period } };
394
+ }
395
+ async failRun(message, knownError) {
373
396
  try {
374
397
  this.currentChat.state?.setStatus(AgentStatus.FAILED);
375
- this.currentChat.state?.setLastError({ code: llmError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: llmError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
398
+ this.currentChat.state?.setLastError({ code: knownError?.code ?? AGENT_ERROR_CODES.RUN_FAILED, message, isRetryable: knownError?.isRetryable ?? true, timestamp: /* @__PURE__ */ new Date() });
376
399
  this.currentChat.addTrace({ node: "agent", kind: "agent", reasoning: `Run failed: ${message}` });
377
400
  this.currentChat.failTask();
378
401
  await this.persist();
@@ -757,6 +780,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
757
780
  this.stopLoop = true;
758
781
  break;
759
782
  }
783
+ if (iterations > 0 && this.stopOnUsageLimit && this.usageLimit) await checkUsageLimit(this.usageLimit, this.currentUser);
760
784
  iterations++;
761
785
  this.iteration = iterations;
762
786
  await this.checkInterruptionRequest();
@@ -866,6 +890,7 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
866
890
  const agent = this;
867
891
  return {
868
892
  identity: this._identity,
893
+ productInfo: this._productInfo,
869
894
  task: this.currentChat.activeTask,
870
895
  chat: this.currentChat,
871
896
  chatOptions: this.chatOptions,
@@ -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
+ };
@@ -13,6 +13,7 @@ export declare class AgiLoop extends AgentLoop {
13
13
  email: string;
14
14
  website: string;
15
15
  };
16
+ private agentContext;
16
17
  private context;
17
18
  private fastResponder;
18
19
  private reasoningEngine;
@@ -59,11 +59,18 @@ class AgiLoop extends import_harness.AgentLoop {
59
59
  website: "https://openloops.xyz/jose"
60
60
  };
61
61
  }
62
- context(ctx) {
62
+ agentContext(ctx) {
63
63
  const agentIdentity = ctx.identity;
64
- const chatHistory = ctx.chat.lastHistoryMessages();
64
+ const productInfo = ctx.productInfo;
65
65
  return {
66
66
  ...agentIdentity && Object.keys(agentIdentity)?.length ? { agentIdentity } : {},
67
+ ...productInfo && Object.keys(productInfo)?.length ? { productInfo } : {}
68
+ };
69
+ }
70
+ context(ctx) {
71
+ const chatHistory = ctx.chat.lastHistoryMessages();
72
+ return {
73
+ ...this.agentContext(ctx),
67
74
  ...chatHistory?.length ? { chat_history: chatHistory } : {}
68
75
  };
69
76
  }
@@ -73,11 +80,10 @@ class AgiLoop extends import_harness.AgentLoop {
73
80
  return;
74
81
  }
75
82
  const chat_history = ctx.chat.lastHistoryMessages();
76
- const agentIdentity = ctx.identity;
77
83
  const result = await import_skills.fastResponder.run({
78
84
  ...ctx.skillParams,
79
85
  contextInjection: {
80
- ...agentIdentity && Object.keys(agentIdentity)?.length ? { agentIdentity } : {},
86
+ ...this.agentContext(ctx),
81
87
  ...chat_history?.length ? { chat_history } : {},
82
88
  ...ctx.chat.title ? {} : { needs_title: true }
83
89
  }