openloops 0.2.10 → 0.3.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.
@@ -87,7 +87,8 @@ class LLMClient {
87
87
  messages,
88
88
  tools,
89
89
  toolChoice,
90
- temperature = DEFAULT_TEMPERATURE
90
+ temperature = DEFAULT_TEMPERATURE,
91
+ thinking
91
92
  } = params;
92
93
  const { provider, model: modelName } = this.chooseModel(params);
93
94
  const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
@@ -99,7 +100,8 @@ class LLMClient {
99
100
  const context = (0, import_pi_ai_adapter.toPiContext)({ messages, tools }, model);
100
101
  const send = (omitTemperature) => this.withDeadline((signal) => {
101
102
  const options = { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
102
- return resolvedChoice ? models.completeSimple(model, context, { ...options, toolChoice: resolvedChoice }) : models.complete(model, context, options);
103
+ const reasoning = thinking && thinking !== "off" ? thinking : void 0;
104
+ return resolvedChoice || thinking ? models.completeSimple(model, context, { ...options, ...resolvedChoice ? { toolChoice: resolvedChoice } : {}, ...reasoning ? { reasoning } : {} }) : models.complete(model, context, options);
103
105
  });
104
106
  const raw = await this.traced(
105
107
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
@@ -55,7 +55,8 @@ class LLMClient {
55
55
  messages,
56
56
  tools,
57
57
  toolChoice,
58
- temperature = DEFAULT_TEMPERATURE
58
+ temperature = DEFAULT_TEMPERATURE,
59
+ thinking
59
60
  } = params;
60
61
  const { provider, model: modelName } = this.chooseModel(params);
61
62
  const { builtinModels } = await import("@earendil-works/pi-ai/providers/all");
@@ -67,7 +68,8 @@ class LLMClient {
67
68
  const context = toPiContext({ messages, tools }, model);
68
69
  const send = (omitTemperature) => this.withDeadline((signal) => {
69
70
  const options = { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
70
- return resolvedChoice ? models.completeSimple(model, context, { ...options, toolChoice: resolvedChoice }) : models.complete(model, context, options);
71
+ const reasoning = thinking && thinking !== "off" ? thinking : void 0;
72
+ return resolvedChoice || thinking ? models.completeSimple(model, context, { ...options, ...resolvedChoice ? { toolChoice: resolvedChoice } : {}, ...reasoning ? { reasoning } : {} }) : models.complete(model, context, options);
71
73
  });
72
74
  const raw = await this.traced(
73
75
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
@@ -50,6 +50,7 @@ export interface LLMResponse {
50
50
  native?: unknown;
51
51
  }
52
52
  export type LLMToolChoice = 'auto' | 'none' | 'required';
53
+ export type ThinkingEffort = 'off' | 'low' | 'medium' | 'high';
53
54
  export interface LLMChatParams {
54
55
  origin: string;
55
56
  sessionId: string;
@@ -61,4 +62,5 @@ export interface LLMChatParams {
61
62
  provider?: string;
62
63
  modelName?: string;
63
64
  temperature?: number;
65
+ thinking?: ThinkingEffort;
64
66
  }
@@ -53,13 +53,11 @@ class AgentState {
53
53
  props.language,
54
54
  props.lastError,
55
55
  props.activeTaskId,
56
- props.stopRequested,
57
- props.currentActivity
56
+ props.stopRequested
58
57
  );
59
58
  }
60
59
  toJSON() {
61
60
  return {
62
- currentActivity: this.currentActivity,
63
61
  language: this.language,
64
62
  status: this.status,
65
63
  activeTaskId: this.activeTaskId,
@@ -30,13 +30,11 @@ class AgentState {
30
30
  props.language,
31
31
  props.lastError,
32
32
  props.activeTaskId,
33
- props.stopRequested,
34
- props.currentActivity
33
+ props.stopRequested
35
34
  );
36
35
  }
37
36
  toJSON() {
38
37
  return {
39
- currentActivity: this.currentActivity,
40
38
  language: this.language,
41
39
  status: this.status,
42
40
  activeTaskId: this.activeTaskId,
@@ -717,18 +717,19 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
717
717
  }));
718
718
  }
719
719
  async saveChat(props) {
720
- if (this.currentChat?._id) {
721
- this.logger.debug("[AGENT] Updating chat...");
722
- if (!props?.resetStop) {
723
- this.logger.debug("[Agent] Removing stopRequested");
724
- delete this.currentChat.state?.stopRequested;
725
- }
726
- await (0, import_chats.updateChat)({
727
- id: this.currentChat._id.toString(),
728
- payload: this.currentChat.toJSON(),
729
- currentUser: this.currentUser
730
- });
731
- }
720
+ if (!this.currentChat?._id) return;
721
+ if (!props?.resetStop) {
722
+ this.logger.debug("[Agent] Removing stopRequested");
723
+ delete this.currentChat.state?.stopRequested;
724
+ }
725
+ const id = this.currentChat._id.toString();
726
+ const payload = this.currentChat.toJSON();
727
+ const key = `chat:${id}`;
728
+ const current = JSON.stringify(payload);
729
+ if (this.snapshots.get(key) === current) return;
730
+ this.logger.debug("[AGENT] Updating chat...");
731
+ await (0, import_chats.updateChat)({ id, payload, currentUser: this.currentUser });
732
+ this.snapshots.set(key, current);
732
733
  }
733
734
  async checkInterruptionRequest() {
734
735
  const chatId = this.currentChat?._id?.toString();
@@ -702,18 +702,19 @@ Ref: ${guard.ref}`, { source: "harness", excludeFromContext: true });
702
702
  }));
703
703
  }
704
704
  async saveChat(props) {
705
- if (this.currentChat?._id) {
706
- this.logger.debug("[AGENT] Updating chat...");
707
- if (!props?.resetStop) {
708
- this.logger.debug("[Agent] Removing stopRequested");
709
- delete this.currentChat.state?.stopRequested;
710
- }
711
- await updateChat({
712
- id: this.currentChat._id.toString(),
713
- payload: this.currentChat.toJSON(),
714
- currentUser: this.currentUser
715
- });
716
- }
705
+ if (!this.currentChat?._id) return;
706
+ if (!props?.resetStop) {
707
+ this.logger.debug("[Agent] Removing stopRequested");
708
+ delete this.currentChat.state?.stopRequested;
709
+ }
710
+ const id = this.currentChat._id.toString();
711
+ const payload = this.currentChat.toJSON();
712
+ const key = `chat:${id}`;
713
+ const current = JSON.stringify(payload);
714
+ if (this.snapshots.get(key) === current) return;
715
+ this.logger.debug("[AGENT] Updating chat...");
716
+ await updateChat({ id, payload, currentUser: this.currentUser });
717
+ this.snapshots.set(key, current);
717
718
  }
718
719
  async checkInterruptionRequest() {
719
720
  const chatId = this.currentChat?._id?.toString();
@@ -28,6 +28,7 @@ const fastResponder = new import_skill.Skill({
28
28
  version: "2.4.0",
29
29
  description: "Handles general conversations and multipurpose user assistance.",
30
30
  temperature: 0.7,
31
+ thinking: "low",
31
32
  systemInstructions: {
32
33
  instruction_set: {
33
34
  goal: "Provide general assistance in a friendly, empathetic, and natural manner as a close companion.",
@@ -6,6 +6,7 @@ const fastResponder = new Skill({
6
6
  version: "2.4.0",
7
7
  description: "Handles general conversations and multipurpose user assistance.",
8
8
  temperature: 0.7,
9
+ thinking: "low",
9
10
  systemInstructions: {
10
11
  instruction_set: {
11
12
  goal: "Provide general assistance in a friendly, empathetic, and natural manner as a close companion.",
@@ -33,6 +33,8 @@ module.exports = __toCommonJS(get_chat_by_id_use_case_exports);
33
33
  var import_tsyringe = require("tsyringe");
34
34
  var import_base = require("../../../common/base/base.use-case.js");
35
35
  var import_repositories2 = require("../repositories");
36
+ var import_agent_state = require("../../../harness/agent-state.js");
37
+ var import_deprecated_activity = require("../utils/deprecated-activity");
36
38
  let GetChatByIdUseCase = class extends import_base.BaseUseCase {
37
39
  constructor(chatRepository) {
38
40
  super();
@@ -42,6 +44,7 @@ let GetChatByIdUseCase = class extends import_base.BaseUseCase {
42
44
  async execute(params) {
43
45
  const { id, select } = params;
44
46
  const data = await this.chatRepository?.findById(id, select) || {};
47
+ if (data.state?.status === import_agent_state.AgentStatus.PROCESSING) data.state.currentActivity = (0, import_deprecated_activity.deprecatedActivity)(id);
45
48
  return { data };
46
49
  }
47
50
  };
@@ -5,6 +5,8 @@ import {
5
5
  import { autoInjectable, inject } from "tsyringe";
6
6
  import { BaseUseCase } from "../../../common/base/base.use-case.js";
7
7
  import { ChatRepository } from "../repositories";
8
+ import { AgentStatus } from "../../../harness/agent-state.js";
9
+ import { deprecatedActivity } from "../utils/deprecated-activity";
8
10
  let GetChatByIdUseCase = class extends BaseUseCase {
9
11
  constructor(chatRepository) {
10
12
  super();
@@ -14,6 +16,7 @@ let GetChatByIdUseCase = class extends BaseUseCase {
14
16
  async execute(params) {
15
17
  const { id, select } = params;
16
18
  const data = await this.chatRepository?.findById(id, select) || {};
19
+ if (data.state?.status === AgentStatus.PROCESSING) data.state.currentActivity = deprecatedActivity(id);
17
20
  return { data };
18
21
  }
19
22
  };
@@ -0,0 +1 @@
1
+ export declare function deprecatedActivity(chatId: string, now?: number): string;
@@ -0,0 +1,60 @@
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 deprecated_activity_exports = {};
20
+ __export(deprecated_activity_exports, {
21
+ deprecatedActivity: () => deprecatedActivity
22
+ });
23
+ module.exports = __toCommonJS(deprecated_activity_exports);
24
+ const WORDS = [
25
+ "Thinking",
26
+ "Computing",
27
+ "Pondering",
28
+ "Analyzing",
29
+ "Crunching",
30
+ "Reviewing",
31
+ "Checking",
32
+ "Working on it",
33
+ "Reasoning",
34
+ "Digging in",
35
+ "Gathering",
36
+ "Sorting",
37
+ "Calculating",
38
+ "Connecting the dots",
39
+ "Exploring",
40
+ "Piecing it together",
41
+ "Figuring it out",
42
+ "Untangling",
43
+ "Weighing options",
44
+ "Cooking"
45
+ ];
46
+ const WINDOW_IN_MS = 4e3;
47
+ function hash(text) {
48
+ let value = 5381;
49
+ for (const character of text) value = (value << 5) + value + character.charCodeAt(0) >>> 0;
50
+ return value;
51
+ }
52
+ function deprecatedActivity(chatId, now = Date.now()) {
53
+ const window = Math.floor(now / WINDOW_IN_MS);
54
+ const index = hash(`${chatId}:${window}`) % WORDS.length;
55
+ return `${WORDS[index]}...`;
56
+ }
57
+ // Annotate the CommonJS export names for ESM import in node:
58
+ 0 && (module.exports = {
59
+ deprecatedActivity
60
+ });
@@ -0,0 +1,37 @@
1
+ import "../../../chunk-CF3WOMB3.mjs";
2
+ const WORDS = [
3
+ "Thinking",
4
+ "Computing",
5
+ "Pondering",
6
+ "Analyzing",
7
+ "Crunching",
8
+ "Reviewing",
9
+ "Checking",
10
+ "Working on it",
11
+ "Reasoning",
12
+ "Digging in",
13
+ "Gathering",
14
+ "Sorting",
15
+ "Calculating",
16
+ "Connecting the dots",
17
+ "Exploring",
18
+ "Piecing it together",
19
+ "Figuring it out",
20
+ "Untangling",
21
+ "Weighing options",
22
+ "Cooking"
23
+ ];
24
+ const WINDOW_IN_MS = 4e3;
25
+ function hash(text) {
26
+ let value = 5381;
27
+ for (const character of text) value = (value << 5) + value + character.charCodeAt(0) >>> 0;
28
+ return value;
29
+ }
30
+ function deprecatedActivity(chatId, now = Date.now()) {
31
+ const window = Math.floor(now / WINDOW_IN_MS);
32
+ const index = hash(`${chatId}:${window}`) % WORDS.length;
33
+ return `${WORDS[index]}...`;
34
+ }
35
+ export {
36
+ deprecatedActivity
37
+ };
@@ -1,4 +1,4 @@
1
- import { LLMMessage, LLMToolDefinition } from '../clients/llm/llm-types.js';
1
+ import { LLMMessage, LLMToolDefinition, ThinkingEffort } from '../clients/llm/llm-types.js';
2
2
  import { CurrentUser, CurrentSession } from '../common/base/index.js';
3
3
  import type { Chat } from '../services/chats/entities/chat.entity.js';
4
4
  import { SkillMode } from './call-modes';
@@ -8,6 +8,7 @@ export interface SkillProps {
8
8
  version?: string;
9
9
  description?: string;
10
10
  temperature?: number;
11
+ thinking?: ThinkingEffort;
11
12
  systemInstructions: Record<string, any>;
12
13
  systemRole?: boolean;
13
14
  mode?: SkillMode;
@@ -46,6 +47,7 @@ export declare class Skill<TResponse = Record<string, any>> {
46
47
  readonly version?: string;
47
48
  readonly description?: string;
48
49
  readonly temperature?: number;
50
+ readonly thinking?: ThinkingEffort;
49
51
  readonly systemInstructions: Record<string, any>;
50
52
  readonly systemRole: boolean;
51
53
  readonly mode: SkillMode;
@@ -37,6 +37,7 @@ class Skill {
37
37
  version;
38
38
  description;
39
39
  temperature;
40
+ thinking;
40
41
  systemInstructions;
41
42
  systemRole;
42
43
  mode;
@@ -45,6 +46,7 @@ class Skill {
45
46
  this.version = props.version;
46
47
  this.description = props.description;
47
48
  this.temperature = props.temperature;
49
+ this.thinking = props.thinking;
48
50
  this.systemInstructions = props.systemInstructions;
49
51
  this.systemRole = props.systemRole ?? true;
50
52
  this.mode = props.mode ?? import_call_modes.DEFAULT_SKILL_MODE;
@@ -78,7 +80,8 @@ class Skill {
78
80
  messages: call.messages,
79
81
  tools: call.tools,
80
82
  toolChoice: call.toolChoice,
81
- temperature: this.temperature ?? 0.7
83
+ temperature: this.temperature ?? 0.7,
84
+ ...this.thinking ? { thinking: this.thinking } : {}
82
85
  });
83
86
  const reading = (0, import_call_modes.readModeResponse)(mode, this.name, response, { expectActions: Boolean(tools?.length) });
84
87
  if (reading.blocks > 1) {
@@ -13,6 +13,7 @@ class Skill {
13
13
  version;
14
14
  description;
15
15
  temperature;
16
+ thinking;
16
17
  systemInstructions;
17
18
  systemRole;
18
19
  mode;
@@ -21,6 +22,7 @@ class Skill {
21
22
  this.version = props.version;
22
23
  this.description = props.description;
23
24
  this.temperature = props.temperature;
25
+ this.thinking = props.thinking;
24
26
  this.systemInstructions = props.systemInstructions;
25
27
  this.systemRole = props.systemRole ?? true;
26
28
  this.mode = props.mode ?? DEFAULT_SKILL_MODE;
@@ -54,7 +56,8 @@ class Skill {
54
56
  messages: call.messages,
55
57
  tools: call.tools,
56
58
  toolChoice: call.toolChoice,
57
- temperature: this.temperature ?? 0.7
59
+ temperature: this.temperature ?? 0.7,
60
+ ...this.thinking ? { thinking: this.thinking } : {}
58
61
  });
59
62
  const reading = readModeResponse(mode, this.name, response, { expectActions: Boolean(tools?.length) });
60
63
  if (reading.blocks > 1) {
package/docs/agent.md CHANGED
@@ -198,12 +198,13 @@ await agent.run({ input: { chatId, message }, currentUser })
198
198
  stop()
199
199
  ```
200
200
 
201
- The listener receives every change of `state.currentActivity` while the run is in progress, and a last `stopped` when the run ends. It does not receive a value that repeats the previous one. With `AgiLoop` the value is a short sentence written by the model in the language of the conversation, such as `Buscando tus gastos de vuelos de agosto`, shown from the answer that asked for the actions until the next answer. When the model gives none, the generic ones appear: `Starting...`, `Analyzing requirement...`, `Thinking...` or `Running search...`. See [loops](loops.md#agiloop).
201
+ The listener receives every change of the activity of the run while it is in progress, and a last `stopped` when the run ends. This is the only place where the real activity is available: since 0.3.0 it is not saved with the chat, and `state.currentActivity` is deprecated (see [chats](chats.md#statecurrentactivity-is-deprecated)). It does not receive a value that repeats the previous one. With `AgiLoop` the value is a short sentence written by the model in the language of the conversation, such as `Buscando tus gastos de vuelos de agosto`, shown from the answer that asked for the actions until the next answer. When the model gives none, the generic ones appear: `Starting...`, `Analyzing requirement...`, `Thinking...` or `Running search...`. See [loops](loops.md#agiloop).
202
202
 
203
203
  - The listener belongs to that `Agent` instance and to the chat of its current run. Nothing is shared between instances, so concurrent runs in the same process, even of different users, never hear each other. As always, create one `Agent` per run and do not share it between concurrent requests.
204
204
  - It is called synchronously from the loop, so keep it fast and do not await inside it. An error thrown by a listener is logged and ignored, the run goes on and the other listeners still run.
205
205
  - `onActivity` returns a function that removes the listener.
206
- - Past values are not replayed. If a client connects late or loses its connection, read `state.currentActivity` of the chat, which is saved with it.
206
+ - The activity is not saved, so it does not cost a write: the chat is saved only when something else changes, such as a message, the status or the task, and when the run ends.
207
+ - Past values are not replayed. If a client connects late or loses its connection, read the chat and use its `state.status`; a client that still reads `state.currentActivity` gets a generic word while the run is processing, and it will be removed in 0.4.0.
207
208
 
208
209
  ## Stopping a running turn
209
210
 
package/docs/chats.md CHANGED
@@ -10,10 +10,16 @@ import { createChat, getChatById, listChatsByUser, updateChat, deleteChat } from
10
10
 
11
11
  | Field | Meaning |
12
12
  | --- | --- |
13
- | `state` | `status`, detected `language`, `activeTaskId`, `currentActivity`, `lastError` and `stopRequested`. See [agent](agent.md#the-result) for the statuses. |
13
+ | `state` | `status`, detected `language`, `activeTaskId`, `lastError` and `stopRequested`. See [agent](agent.md#the-result) for the statuses. It also has `currentActivity`, which is deprecated (see below). |
14
14
  | `settings` | `modelProvider` and `modelName` (the model the chat uses, saved on every run), `loopName`, `executionMode`, `notifyOnCompletion` and `isPrivateSession`. |
15
15
  | `messages` | The conversation. Each message has `role` (`user` or `assistant`), `source`, `content`, `answerId` and `excludeFromContext`. |
16
16
 
17
+ ### `state.currentActivity` is deprecated
18
+
19
+ Since 0.3.0 the activity of a run is no longer saved with the chat, and `currentActivity` will be removed in 0.4.0. Follow a run with [`agent.onActivity`](agent.md#activity-updates), which tells every change as it happens.
20
+
21
+ For the clients that still poll the chat and read `state.currentActivity`, `getChatById` adds a generic word to it, such as `Thinking...` or `Cooking...`, only while the run is `processing`. It is one word per chat that changes every few seconds. It says nothing about what the agent is really doing, and it is not there in any other status. Move those clients to the listener before 0.4.0.
22
+
17
23
  Every assistant message of one answer shares an `answerId`. It is the id you pass as `messageId` to [usage](usage.md).
18
24
 
19
25
  `role` says on which side of the conversation a message is, and `source` says who produced it:
package/docs/loops.md CHANGED
@@ -17,7 +17,7 @@ import { AgiLoop } from 'openloops/loops'
17
17
  | `reasoning_engine` | Reads the situation or the results of the last actions, rewrites its working state, decides the next actions, reports the language of the conversation and says in one sentence what is happening until its next answer. |
18
18
  | `action_engine` | Runs the actions the reasoning engine asked for, asks the user for confirmation when needed, delivers the final answer. |
19
19
 
20
- The sentences of both nodes become `state.currentActivity`, written in the language of the conversation, so a client can show what the agent is doing instead of a generic `Thinking...`. They are optional: when a node leaves it out or writes something unusable (not a text, empty, `running`, `stopped`), the loop shows the generic activity of that moment. The text is cleaned of markup and line breaks and cut at 80 characters, and each one is kept in the turn that produced it (`turns[].activity`) to audit what the user saw.
20
+ The sentences of both nodes are what [`agent.onActivity`](agent.md#activity-updates) tells, written in the language of the conversation, so a client can show what the agent is doing instead of a generic `Thinking...`. They are optional: when a node leaves it out or writes something unusable (not a text, empty, `running`, `stopped`), the loop shows the generic activity of that moment. The text is cleaned of markup and line breaks and cut at 80 characters, and each one is kept in the turn that produced it (`turns[].activity`) to audit what the user saw.
21
21
 
22
22
  The loop works within a budget per task (20 reasoning turns and 40 tool calls) and stops with an honest answer when the model repeats itself, keeps only reading notes, or runs out of budget. It also rejects final answers that cite identifiers that never appeared in a result or in the user's words.
23
23
 
package/docs/skills.md CHANGED
@@ -44,6 +44,7 @@ export const myResponder = new Skill<ResponseSchema>({
44
44
  | `version` | no | Recorded in the metadata of every call. Bump it whenever the prompt changes. |
45
45
  | `description` | no | What the skill is for. |
46
46
  | `temperature` | no | Sampling temperature. Defaults to `0.7`. |
47
+ | `thinking` | no | How much the model thinks before it answers: `off`, `low`, `medium` or `high`. Thinking costs time and output tokens, so a skill that only classifies or answers briefly can set it low. When it is left out the provider default applies, which is high for the Claude models. The bundled `fast_responder` uses `low`. |
47
48
  | `systemRole` | no | Default `true`: the instructions travel as a system message. |
48
49
  | `mode` | no | How the model is called when tools are given. Defaults to `plain_chat`. |
49
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openloops",
3
- "version": "0.2.10",
3
+ "version": "0.3.0",
4
4
  "description": "Open source harness for AI agents: a TypeScript runtime with persistence, tools, MCP trust, approvals and autonomous jobs, where the loop is pluggable",
5
5
  "author": {
6
6
  "name": "Jose Barcos",