openloops 0.7.6 → 0.8.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 +66 -11
- package/README.md +5 -8
- package/dist/clients/llm/llm-error.d.ts +1 -1
- package/dist/clients/llm/llm-error.js +12 -0
- package/dist/clients/llm/llm-error.mjs +12 -0
- package/dist/common/error/error-reporter.d.ts +11 -0
- package/dist/common/error/error-reporter.js +36 -0
- package/dist/common/error/error-reporter.mjs +11 -0
- package/dist/common/error/index.d.ts +1 -0
- package/dist/common/error/index.js +3 -1
- package/dist/common/error/index.mjs +1 -0
- package/dist/common/error/reportError.js +10 -0
- package/dist/common/error/reportError.mjs +10 -0
- package/dist/common/error/sentry-client.d.ts +2 -2
- package/dist/common/error/sentry-client.js +19 -24
- package/dist/common/error/sentry-client.mjs +19 -14
- package/dist/common/helpers/index.d.ts +1 -0
- package/dist/common/helpers/index.js +3 -1
- package/dist/common/helpers/index.mjs +1 -0
- package/dist/common/helpers/sanitize-string.js +5 -15
- package/dist/common/helpers/sanitize-string.mjs +5 -5
- package/dist/common/helpers/strip-blocks.d.ts +1 -0
- package/dist/common/helpers/strip-blocks.js +45 -0
- package/dist/common/helpers/strip-blocks.mjs +21 -0
- package/dist/common/index.d.ts +2 -0
- package/dist/common/index.js +9 -0
- package/dist/common/index.mjs +4 -0
- package/dist/common/logger/pino.js +12 -3
- package/dist/common/logger/pino.mjs +12 -3
- package/dist/common/repositories/mongo-db.client.js +1 -1
- package/dist/common/repositories/mongo-db.client.mjs +1 -1
- package/dist/common/repositories/mongo-db.repository.js +1 -1
- package/dist/common/repositories/mongo-db.repository.mjs +1 -1
- package/dist/common/utils/secret-manager.js +1 -1
- package/dist/common/utils/secret-manager.mjs +1 -1
- package/dist/db/index.d.ts +1 -0
- package/dist/db/index.js +3 -1
- package/dist/db/index.mjs +1 -0
- package/dist/db/migrations/chat-titles.d.ts +10 -0
- package/dist/db/migrations/chat-titles.js +55 -0
- package/dist/db/migrations/chat-titles.mjs +31 -0
- package/dist/harness/agent-state.d.ts +0 -1
- package/dist/harness/agent.d.ts +1 -0
- package/dist/harness/agent.js +9 -0
- package/dist/harness/agent.mjs +9 -0
- package/dist/loops/agi/loop.js +4 -2
- package/dist/loops/agi/loop.mjs +4 -2
- package/dist/loops/shared/skills/fast-responder.d.ts +1 -0
- package/dist/loops/shared/skills/fast-responder.js +4 -2
- package/dist/loops/shared/skills/fast-responder.mjs +4 -2
- package/dist/services/automations/runner/automation-runner.js +6 -1
- package/dist/services/automations/runner/automation-runner.mjs +6 -1
- package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.d.ts +2 -1
- package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.js +2 -2
- package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.mjs +2 -2
- package/dist/services/automations/use-cases/sync-automation-run.use-case.d.ts +1 -0
- package/dist/services/automations/use-cases/sync-automation-run.use-case.js +6 -2
- package/dist/services/automations/use-cases/sync-automation-run.use-case.mjs +5 -2
- package/dist/services/chats/entities/chat.entity.d.ts +3 -0
- package/dist/services/chats/entities/chat.entity.js +8 -0
- package/dist/services/chats/entities/chat.entity.mjs +8 -0
- package/dist/services/chats/use-cases/get-chat-by-id.use-case.js +1 -5
- package/dist/services/chats/use-cases/get-chat-by-id.use-case.mjs +1 -5
- package/dist/services/chats/use-cases/list-chats-by-user.use-case.d.ts +2 -1
- package/dist/services/chats/use-cases/list-chats-by-user.use-case.js +3 -2
- package/dist/services/chats/use-cases/list-chats-by-user.use-case.mjs +3 -2
- package/dist/services/chats/utils/title.d.ts +2 -0
- package/dist/services/chats/utils/title.js +37 -0
- package/dist/services/chats/utils/title.mjs +12 -0
- package/dist/tools/core/fetch-url/html-to-text.js +3 -20
- package/dist/tools/core/fetch-url/html-to-text.mjs +3 -20
- package/docs/README.md +2 -1
- package/docs/agent.md +20 -3
- package/docs/automations.md +3 -3
- package/docs/chats.md +41 -8
- package/docs/configuration.md +6 -2
- package/docs/error-reporting.md +219 -0
- package/docs/integration-guide.md +6 -2
- package/docs/llms.txt +2 -1
- package/docs/loops.md +1 -1
- package/examples/chats/search-chats.ts +30 -0
- package/examples/errors/error-reporting.ts +75 -0
- package/package.json +23 -12
- package/dist/services/chats/utils/deprecated-activity.d.ts +0 -1
- package/dist/services/chats/utils/deprecated-activity.js +0 -60
- package/dist/services/chats/utils/deprecated-activity.mjs +0 -36
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from "node:crypto";
|
|
2
2
|
import { hostname } from "node:os";
|
|
3
3
|
import { Logger } from "../../../common/logger/index.js";
|
|
4
|
+
import { reportError } from "../../../common/error/index.js";
|
|
4
5
|
import { CurrentUser, CurrentSession } from "../../../common/base/index.js";
|
|
5
6
|
import { Agent } from "../../../harness/agent.js";
|
|
6
7
|
import { AgiLoop } from "../../../loops/agi/loop.js";
|
|
@@ -59,6 +60,7 @@ class AutomationRunner {
|
|
|
59
60
|
await new SyncAutomationRunsUseCase().execute({});
|
|
60
61
|
} catch (error) {
|
|
61
62
|
this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] Failed to sync the open runs");
|
|
63
|
+
await reportError(error, { source: "automations", stage: "sync" });
|
|
62
64
|
}
|
|
63
65
|
if (capacity <= 0) return;
|
|
64
66
|
const data = await new ClaimDueAutomationsUseCase().execute({ workerId: this.workerId, limit: capacity, leaseMs: this.options.leaseMs ?? defaultLeaseMs() });
|
|
@@ -77,8 +79,9 @@ class AutomationRunner {
|
|
|
77
79
|
}
|
|
78
80
|
async loop() {
|
|
79
81
|
while (this.running) {
|
|
80
|
-
this.ticking = this.tick().catch((error) => {
|
|
82
|
+
this.ticking = this.tick().catch(async (error) => {
|
|
81
83
|
this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] The worker failed to check the due automations");
|
|
84
|
+
await reportError(error, { source: "automations", stage: "tick" });
|
|
82
85
|
});
|
|
83
86
|
await this.ticking;
|
|
84
87
|
if (!this.running) break;
|
|
@@ -112,6 +115,7 @@ class AutomationRunner {
|
|
|
112
115
|
} catch (failure) {
|
|
113
116
|
error = { code: failure?.code ?? "RUNNER_ERROR", message: failure?.message ?? String(failure) };
|
|
114
117
|
this.logger.error({ error: error.message, automationId, runId }, "[AUTOMATIONS] A run failed");
|
|
118
|
+
await reportError(failure, { source: "automations", stage: "run", automationId, runId });
|
|
115
119
|
} finally {
|
|
116
120
|
clearInterval(heartbeat);
|
|
117
121
|
}
|
|
@@ -153,6 +157,7 @@ class AutomationRunner {
|
|
|
153
157
|
await this.options.onRunFinished(event);
|
|
154
158
|
} catch (error) {
|
|
155
159
|
this.logger.error({ error: error?.message ?? error }, "[AUTOMATIONS] The onRunFinished callback failed");
|
|
160
|
+
await reportError(error, { source: "automations", stage: "onRunFinished" });
|
|
156
161
|
}
|
|
157
162
|
}
|
|
158
163
|
}
|
package/dist/services/automations/use-cases/list-automation-runs-by-automation.use-case.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { QueryOptions } from '../../../common/repositories/index.js';
|
|
2
2
|
import { BaseUseCase, BaseUseCaseParams } from '../../../common/base/base.use-case.js';
|
|
3
|
-
import { AutomationRunProps } from '../entities';
|
|
3
|
+
import { AutomationRunProps, AutomationRunStatus } from '../entities';
|
|
4
4
|
import { AutomationRunRepository } from '../repositories';
|
|
5
5
|
export interface Params extends BaseUseCaseParams {
|
|
6
6
|
automationId: string;
|
|
7
|
+
status?: AutomationRunStatus;
|
|
7
8
|
options?: QueryOptions;
|
|
8
9
|
}
|
|
9
10
|
export interface Output {
|
|
@@ -32,12 +32,12 @@ class ListAutomationRunsByAutomationUseCase extends import_base.BaseUseCase {
|
|
|
32
32
|
}
|
|
33
33
|
automationRunRepository;
|
|
34
34
|
async execute(params) {
|
|
35
|
-
const { automationId, options, currentUser } = params;
|
|
35
|
+
const { automationId, status, options, currentUser } = params;
|
|
36
36
|
if (!automationId) throw new Error("Missing automationId");
|
|
37
37
|
const { page = 1, limit = 10, sortBy = { createdAt: -1 } } = options || {};
|
|
38
38
|
const result = await this.automationRunRepository._.findManyPaginated({
|
|
39
39
|
scope: params.scope ?? import_repositories.Scope.canView(currentUser),
|
|
40
|
-
where: { automationId: new import_mongodb.ObjectId(automationId) },
|
|
40
|
+
where: { automationId: new import_mongodb.ObjectId(automationId), ...status ? { status } : {} },
|
|
41
41
|
options: { page, limit, sortBy }
|
|
42
42
|
});
|
|
43
43
|
return { items: result?.items ?? [], hasMore: result?.hasMore ?? false };
|
|
@@ -9,12 +9,12 @@ class ListAutomationRunsByAutomationUseCase extends BaseUseCase {
|
|
|
9
9
|
}
|
|
10
10
|
automationRunRepository;
|
|
11
11
|
async execute(params) {
|
|
12
|
-
const { automationId, options, currentUser } = params;
|
|
12
|
+
const { automationId, status, options, currentUser } = params;
|
|
13
13
|
if (!automationId) throw new Error("Missing automationId");
|
|
14
14
|
const { page = 1, limit = 10, sortBy = { createdAt: -1 } } = options || {};
|
|
15
15
|
const result = await this.automationRunRepository._.findManyPaginated({
|
|
16
16
|
scope: params.scope ?? Scope.canView(currentUser),
|
|
17
|
-
where: { automationId: new ObjectId(automationId) },
|
|
17
|
+
where: { automationId: new ObjectId(automationId), ...status ? { status } : {} },
|
|
18
18
|
options: { page, limit, sortBy }
|
|
19
19
|
});
|
|
20
20
|
return { items: result?.items ?? [], hasMore: result?.hasMore ?? false };
|
|
@@ -6,6 +6,7 @@ export interface Params extends BaseUseCaseParams {
|
|
|
6
6
|
now?: Date;
|
|
7
7
|
}
|
|
8
8
|
export type Output = AutomationRunProps | null;
|
|
9
|
+
export declare const CHAT_DELETED_MESSAGE = "The chat of this run was deleted while it waited for the user";
|
|
9
10
|
export declare const LOST_WORKER_MESSAGE = "The worker that was running this automation was lost before it finished";
|
|
10
11
|
export declare class SyncAutomationRunUseCase extends BaseUseCase<Params, Output> {
|
|
11
12
|
private readonly automationRepository;
|
|
@@ -18,6 +18,7 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
var sync_automation_run_use_case_exports = {};
|
|
20
20
|
__export(sync_automation_run_use_case_exports, {
|
|
21
|
+
CHAT_DELETED_MESSAGE: () => CHAT_DELETED_MESSAGE,
|
|
21
22
|
LOST_WORKER_MESSAGE: () => LOST_WORKER_MESSAGE,
|
|
22
23
|
SyncAutomationRunUseCase: () => SyncAutomationRunUseCase
|
|
23
24
|
});
|
|
@@ -27,6 +28,7 @@ var import_chats = require("../../chats/index.js");
|
|
|
27
28
|
var import_entities = require("../entities");
|
|
28
29
|
var import_repositories = require("../repositories");
|
|
29
30
|
var import_runner_scope = require("../utils/runner-scope");
|
|
31
|
+
const CHAT_DELETED_MESSAGE = "The chat of this run was deleted while it waited for the user";
|
|
30
32
|
const LOST_WORKER_MESSAGE = "The worker that was running this automation was lost before it finished";
|
|
31
33
|
class SyncAutomationRunUseCase extends import_base.BaseUseCase {
|
|
32
34
|
constructor(automationRepository = new import_repositories.AutomationRepository(), automationRunRepository = new import_repositories.AutomationRunRepository()) {
|
|
@@ -47,9 +49,10 @@ class SyncAutomationRunUseCase extends import_base.BaseUseCase {
|
|
|
47
49
|
async syncPaused(run, now) {
|
|
48
50
|
if (!run.chatId) return run;
|
|
49
51
|
const chat = await (0, import_chats.getChatById)({ id: String(run.chatId), scope: import_runner_scope.runnerScope });
|
|
50
|
-
|
|
52
|
+
if (!chat) return await this.settle(run, "failed", now, { code: "CHAT_DELETED", message: CHAT_DELETED_MESSAGE });
|
|
53
|
+
const status = chat.state?.status;
|
|
51
54
|
if (status === "idle") return await this.settle(run, "completed", now);
|
|
52
|
-
if (status === "failed") return await this.settle(run, "failed", now, { code: chat
|
|
55
|
+
if (status === "failed") return await this.settle(run, "failed", now, { code: chat.state?.lastError?.code, message: chat.state?.lastError?.message ?? "The run failed" });
|
|
53
56
|
return run;
|
|
54
57
|
}
|
|
55
58
|
async syncRunning(run, now) {
|
|
@@ -67,6 +70,7 @@ class SyncAutomationRunUseCase extends import_base.BaseUseCase {
|
|
|
67
70
|
}
|
|
68
71
|
// Annotate the CommonJS export names for ESM import in node:
|
|
69
72
|
0 && (module.exports = {
|
|
73
|
+
CHAT_DELETED_MESSAGE,
|
|
70
74
|
LOST_WORKER_MESSAGE,
|
|
71
75
|
SyncAutomationRunUseCase
|
|
72
76
|
});
|
|
@@ -3,6 +3,7 @@ import { getChatById } from "../../chats/index.js";
|
|
|
3
3
|
import { AutomationRun } from "../entities";
|
|
4
4
|
import { AutomationRepository, AutomationRunRepository } from "../repositories";
|
|
5
5
|
import { runnerScope } from "../utils/runner-scope";
|
|
6
|
+
const CHAT_DELETED_MESSAGE = "The chat of this run was deleted while it waited for the user";
|
|
6
7
|
const LOST_WORKER_MESSAGE = "The worker that was running this automation was lost before it finished";
|
|
7
8
|
class SyncAutomationRunUseCase extends BaseUseCase {
|
|
8
9
|
constructor(automationRepository = new AutomationRepository(), automationRunRepository = new AutomationRunRepository()) {
|
|
@@ -23,9 +24,10 @@ class SyncAutomationRunUseCase extends BaseUseCase {
|
|
|
23
24
|
async syncPaused(run, now) {
|
|
24
25
|
if (!run.chatId) return run;
|
|
25
26
|
const chat = await getChatById({ id: String(run.chatId), scope: runnerScope });
|
|
26
|
-
|
|
27
|
+
if (!chat) return await this.settle(run, "failed", now, { code: "CHAT_DELETED", message: CHAT_DELETED_MESSAGE });
|
|
28
|
+
const status = chat.state?.status;
|
|
27
29
|
if (status === "idle") return await this.settle(run, "completed", now);
|
|
28
|
-
if (status === "failed") return await this.settle(run, "failed", now, { code: chat
|
|
30
|
+
if (status === "failed") return await this.settle(run, "failed", now, { code: chat.state?.lastError?.code, message: chat.state?.lastError?.message ?? "The run failed" });
|
|
29
31
|
return run;
|
|
30
32
|
}
|
|
31
33
|
async syncRunning(run, now) {
|
|
@@ -42,6 +44,7 @@ class SyncAutomationRunUseCase extends BaseUseCase {
|
|
|
42
44
|
}
|
|
43
45
|
}
|
|
44
46
|
export {
|
|
47
|
+
CHAT_DELETED_MESSAGE,
|
|
45
48
|
LOST_WORKER_MESSAGE,
|
|
46
49
|
SyncAutomationRunUseCase
|
|
47
50
|
};
|
|
@@ -4,6 +4,7 @@ import { AgentTask } from '../../tasks/entities/agent-task.entity.js';
|
|
|
4
4
|
import { ChatMessage, ChatMessageProps } from './chat-message.entity';
|
|
5
5
|
import { ChatSettings, ChatSettingsProps } from './chat-settings.entity';
|
|
6
6
|
export interface ChatProps extends BaseEntityProps {
|
|
7
|
+
title?: string;
|
|
7
8
|
state?: AgentStateProps;
|
|
8
9
|
settings?: ChatSettingsProps;
|
|
9
10
|
messages?: ChatMessageProps[];
|
|
@@ -24,6 +25,7 @@ export declare class Chat extends BaseEntity {
|
|
|
24
25
|
messages?: ChatMessage[] | undefined;
|
|
25
26
|
static withDefaults(loopName?: string): Chat;
|
|
26
27
|
static fromJSON(props: ChatProps): Chat;
|
|
28
|
+
title?: string;
|
|
27
29
|
tasks: AgentTask[];
|
|
28
30
|
clearedFields: Record<string, ''>;
|
|
29
31
|
private pendingTraces;
|
|
@@ -31,6 +33,7 @@ export declare class Chat extends BaseEntity {
|
|
|
31
33
|
get lastAnswer(): string | undefined;
|
|
32
34
|
get activeTask(): AgentTask | undefined;
|
|
33
35
|
toJSON(): ChatProps;
|
|
36
|
+
setTitle(text?: string): void;
|
|
34
37
|
pushMessage(message: ChatMessageProps): ChatMessage;
|
|
35
38
|
lastHistoryMessages(count?: number): ChatMessage[] | undefined;
|
|
36
39
|
addTrace(entry: Omit<AgentTrace, 'timestamp'>): void;
|
|
@@ -26,6 +26,7 @@ var import_agent_state = require("../../../harness/agent-state.js");
|
|
|
26
26
|
var import_agent_task = require("../../tasks/entities/agent-task.entity.js");
|
|
27
27
|
var import_chat_message = require("./chat-message.entity");
|
|
28
28
|
var import_chat_settings = require("./chat-settings.entity");
|
|
29
|
+
var import_title = require("../utils/title");
|
|
29
30
|
class Chat extends import_base.BaseEntity {
|
|
30
31
|
constructor(props, state, settings, messages) {
|
|
31
32
|
super(props);
|
|
@@ -33,6 +34,7 @@ class Chat extends import_base.BaseEntity {
|
|
|
33
34
|
this.state = state;
|
|
34
35
|
this.settings = settings;
|
|
35
36
|
this.messages = messages;
|
|
37
|
+
this.title = import_base.BaseEntity.toText(props.title);
|
|
36
38
|
}
|
|
37
39
|
props;
|
|
38
40
|
state;
|
|
@@ -54,6 +56,7 @@ class Chat extends import_base.BaseEntity {
|
|
|
54
56
|
props.messages?.map((message) => import_chat_message.ChatMessage.factory(message))
|
|
55
57
|
);
|
|
56
58
|
}
|
|
59
|
+
title;
|
|
57
60
|
tasks = [];
|
|
58
61
|
clearedFields = {};
|
|
59
62
|
pendingTraces = [];
|
|
@@ -67,11 +70,16 @@ class Chat extends import_base.BaseEntity {
|
|
|
67
70
|
toJSON() {
|
|
68
71
|
return {
|
|
69
72
|
...super.toJSON(),
|
|
73
|
+
title: this.title,
|
|
70
74
|
state: this.state?.toJSON(),
|
|
71
75
|
settings: this.settings?.toJSON(),
|
|
72
76
|
messages: this.messages?.map((message) => message.toJSON())
|
|
73
77
|
};
|
|
74
78
|
}
|
|
79
|
+
setTitle(text) {
|
|
80
|
+
if (this.title) return;
|
|
81
|
+
this.title = import_base.BaseEntity.toText((0, import_title.normalizeTitle)(text));
|
|
82
|
+
}
|
|
75
83
|
pushMessage(message) {
|
|
76
84
|
this.messages ??= [];
|
|
77
85
|
const created = import_chat_message.ChatMessage.factory(message);
|
|
@@ -3,6 +3,7 @@ import { AgentState } from "../../../harness/agent-state.js";
|
|
|
3
3
|
import { AgentTask, TaskStatus } from "../../tasks/entities/agent-task.entity.js";
|
|
4
4
|
import { ChatMessage } from "./chat-message.entity";
|
|
5
5
|
import { ChatSettings } from "./chat-settings.entity";
|
|
6
|
+
import { normalizeTitle } from "../utils/title";
|
|
6
7
|
class Chat extends BaseEntity {
|
|
7
8
|
constructor(props, state, settings, messages) {
|
|
8
9
|
super(props);
|
|
@@ -10,6 +11,7 @@ class Chat extends BaseEntity {
|
|
|
10
11
|
this.state = state;
|
|
11
12
|
this.settings = settings;
|
|
12
13
|
this.messages = messages;
|
|
14
|
+
this.title = BaseEntity.toText(props.title);
|
|
13
15
|
}
|
|
14
16
|
props;
|
|
15
17
|
state;
|
|
@@ -31,6 +33,7 @@ class Chat extends BaseEntity {
|
|
|
31
33
|
props.messages?.map((message) => ChatMessage.factory(message))
|
|
32
34
|
);
|
|
33
35
|
}
|
|
36
|
+
title;
|
|
34
37
|
tasks = [];
|
|
35
38
|
clearedFields = {};
|
|
36
39
|
pendingTraces = [];
|
|
@@ -44,11 +47,16 @@ class Chat extends BaseEntity {
|
|
|
44
47
|
toJSON() {
|
|
45
48
|
return {
|
|
46
49
|
...super.toJSON(),
|
|
50
|
+
title: this.title,
|
|
47
51
|
state: this.state?.toJSON(),
|
|
48
52
|
settings: this.settings?.toJSON(),
|
|
49
53
|
messages: this.messages?.map((message) => message.toJSON())
|
|
50
54
|
};
|
|
51
55
|
}
|
|
56
|
+
setTitle(text) {
|
|
57
|
+
if (this.title) return;
|
|
58
|
+
this.title = BaseEntity.toText(normalizeTitle(text));
|
|
59
|
+
}
|
|
52
60
|
pushMessage(message) {
|
|
53
61
|
this.messages ??= [];
|
|
54
62
|
const created = ChatMessage.factory(message);
|
|
@@ -24,8 +24,6 @@ module.exports = __toCommonJS(get_chat_by_id_use_case_exports);
|
|
|
24
24
|
var import_repositories = require("../../../common/repositories/index.js");
|
|
25
25
|
var import_base = require("../../../common/base/base.use-case.js");
|
|
26
26
|
var import_repositories2 = require("../repositories");
|
|
27
|
-
var import_agent_state = require("../../../harness/agent-state.js");
|
|
28
|
-
var import_deprecated_activity = require("../utils/deprecated-activity");
|
|
29
27
|
class GetChatByIdUseCase extends import_base.BaseUseCase {
|
|
30
28
|
constructor(chatRepository = new import_repositories2.ChatRepository()) {
|
|
31
29
|
super();
|
|
@@ -34,9 +32,7 @@ class GetChatByIdUseCase extends import_base.BaseUseCase {
|
|
|
34
32
|
chatRepository;
|
|
35
33
|
async execute(params) {
|
|
36
34
|
const { id, select, currentUser } = params;
|
|
37
|
-
|
|
38
|
-
if (data?.state?.status === import_agent_state.AgentStatus.PROCESSING) data.state.currentActivity = (0, import_deprecated_activity.deprecatedActivity)(id);
|
|
39
|
-
return data;
|
|
35
|
+
return await this.chatRepository.findById(id, params.scope ?? import_repositories.Scope.canView(currentUser), select);
|
|
40
36
|
}
|
|
41
37
|
}
|
|
42
38
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import { Scope } from "../../../common/repositories/index.js";
|
|
2
2
|
import { BaseUseCase } from "../../../common/base/base.use-case.js";
|
|
3
3
|
import { ChatRepository } from "../repositories";
|
|
4
|
-
import { AgentStatus } from "../../../harness/agent-state.js";
|
|
5
|
-
import { deprecatedActivity } from "../utils/deprecated-activity";
|
|
6
4
|
class GetChatByIdUseCase extends BaseUseCase {
|
|
7
5
|
constructor(chatRepository = new ChatRepository()) {
|
|
8
6
|
super();
|
|
@@ -11,9 +9,7 @@ class GetChatByIdUseCase extends BaseUseCase {
|
|
|
11
9
|
chatRepository;
|
|
12
10
|
async execute(params) {
|
|
13
11
|
const { id, select, currentUser } = params;
|
|
14
|
-
|
|
15
|
-
if (data?.state?.status === AgentStatus.PROCESSING) data.state.currentActivity = deprecatedActivity(id);
|
|
16
|
-
return data;
|
|
12
|
+
return await this.chatRepository.findById(id, params.scope ?? Scope.canView(currentUser), select);
|
|
17
13
|
}
|
|
18
14
|
}
|
|
19
15
|
export {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { QueryOptions } from '../../../common/repositories/index.js';
|
|
1
|
+
import { QueryOptions, QueryParams } from '../../../common/repositories/index.js';
|
|
2
2
|
import { BaseUseCase, BaseUseCaseParams } from '../../../common/base/base.use-case.js';
|
|
3
3
|
import { ChatRepository } from '../repositories';
|
|
4
4
|
import { ChatProps, ExecutionMode } from '../entities';
|
|
@@ -6,6 +6,7 @@ export interface Params extends BaseUseCaseParams {
|
|
|
6
6
|
filters?: Partial<ChatProps>;
|
|
7
7
|
executionMode?: ExecutionMode;
|
|
8
8
|
search?: string;
|
|
9
|
+
select?: QueryParams<ChatProps>['select'];
|
|
9
10
|
options?: QueryOptions;
|
|
10
11
|
}
|
|
11
12
|
export interface Output {
|
|
@@ -33,7 +33,7 @@ class ListChatsByUserUseCase extends import_base.BaseUseCase {
|
|
|
33
33
|
}
|
|
34
34
|
chatRepository;
|
|
35
35
|
async execute(params) {
|
|
36
|
-
const { options, executionMode, search, currentUser } = params;
|
|
36
|
+
const { options, executionMode, search, select, currentUser } = params;
|
|
37
37
|
const { page = 1, limit: pageSize = 10 } = options || {};
|
|
38
38
|
const term = (0, import_helpers.escapeRegex)(search?.trim());
|
|
39
39
|
const result = await this.chatRepository._.findManyPaginated({
|
|
@@ -42,8 +42,9 @@ class ListChatsByUserUseCase extends import_base.BaseUseCase {
|
|
|
42
42
|
ownerId: new import_mongodb.ObjectId(currentUser?.userId),
|
|
43
43
|
...executionMode === "autonomous" ? { "settings.executionMode": "autonomous" } : {},
|
|
44
44
|
...executionMode === "interactive" ? { "settings.executionMode": { $ne: "autonomous" } } : {},
|
|
45
|
-
...term ? { "messages.content": { $regex: term, $options: "i" } } : {}
|
|
45
|
+
...term ? { $or: [{ title: { $regex: term, $options: "i" } }, { "messages.content": { $regex: term, $options: "i" } }] } : {}
|
|
46
46
|
},
|
|
47
|
+
...select ? { select } : {},
|
|
47
48
|
options: { page, limit: pageSize, sortBy: { updatedAt: -1 } }
|
|
48
49
|
});
|
|
49
50
|
return { items: result?.items ?? [], hasMore: result?.hasMore ?? false };
|
|
@@ -10,7 +10,7 @@ class ListChatsByUserUseCase extends BaseUseCase {
|
|
|
10
10
|
}
|
|
11
11
|
chatRepository;
|
|
12
12
|
async execute(params) {
|
|
13
|
-
const { options, executionMode, search, currentUser } = params;
|
|
13
|
+
const { options, executionMode, search, select, currentUser } = params;
|
|
14
14
|
const { page = 1, limit: pageSize = 10 } = options || {};
|
|
15
15
|
const term = escapeRegex(search?.trim());
|
|
16
16
|
const result = await this.chatRepository._.findManyPaginated({
|
|
@@ -19,8 +19,9 @@ class ListChatsByUserUseCase extends BaseUseCase {
|
|
|
19
19
|
ownerId: new ObjectId(currentUser?.userId),
|
|
20
20
|
...executionMode === "autonomous" ? { "settings.executionMode": "autonomous" } : {},
|
|
21
21
|
...executionMode === "interactive" ? { "settings.executionMode": { $ne: "autonomous" } } : {},
|
|
22
|
-
...term ? { "messages.content": { $regex: term, $options: "i" } } : {}
|
|
22
|
+
...term ? { $or: [{ title: { $regex: term, $options: "i" } }, { "messages.content": { $regex: term, $options: "i" } }] } : {}
|
|
23
23
|
},
|
|
24
|
+
...select ? { select } : {},
|
|
24
25
|
options: { page, limit: pageSize, sortBy: { updatedAt: -1 } }
|
|
25
26
|
});
|
|
26
27
|
return { items: result?.items ?? [], hasMore: result?.hasMore ?? false };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var title_exports = {};
|
|
20
|
+
__export(title_exports, {
|
|
21
|
+
MAX_TITLE_LENGTH: () => MAX_TITLE_LENGTH,
|
|
22
|
+
normalizeTitle: () => normalizeTitle
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(title_exports);
|
|
25
|
+
var import_helpers = require("../../../common/helpers/index.js");
|
|
26
|
+
const MAX_TITLE_LENGTH = 80;
|
|
27
|
+
function normalizeTitle(text) {
|
|
28
|
+
if (typeof text !== "string") return void 0;
|
|
29
|
+
const clean = (0, import_helpers.sanitizeString)(text) ?? "";
|
|
30
|
+
const title = Array.from(clean.replace(/\s+/g, " ").trim()).slice(0, MAX_TITLE_LENGTH).join("").trim();
|
|
31
|
+
return title || void 0;
|
|
32
|
+
}
|
|
33
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
34
|
+
0 && (module.exports = {
|
|
35
|
+
MAX_TITLE_LENGTH,
|
|
36
|
+
normalizeTitle
|
|
37
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { sanitizeString } from "../../../common/helpers/index.js";
|
|
2
|
+
const MAX_TITLE_LENGTH = 80;
|
|
3
|
+
function normalizeTitle(text) {
|
|
4
|
+
if (typeof text !== "string") return void 0;
|
|
5
|
+
const clean = sanitizeString(text) ?? "";
|
|
6
|
+
const title = Array.from(clean.replace(/\s+/g, " ").trim()).slice(0, MAX_TITLE_LENGTH).join("").trim();
|
|
7
|
+
return title || void 0;
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
MAX_TITLE_LENGTH,
|
|
11
|
+
normalizeTitle
|
|
12
|
+
};
|
|
@@ -21,6 +21,7 @@ __export(html_to_text_exports, {
|
|
|
21
21
|
htmlToText: () => htmlToText
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(html_to_text_exports);
|
|
24
|
+
var import_helpers = require("../../../common/helpers/index.js");
|
|
24
25
|
const REMOVED_ELEMENTS = ["script", "style", "noscript", "svg", "head", "template", "iframe", "object", "canvas"];
|
|
25
26
|
const LINE = "";
|
|
26
27
|
const PARAGRAPH = "";
|
|
@@ -66,24 +67,6 @@ const ENTITIES = {
|
|
|
66
67
|
Ntilde: "\xD1",
|
|
67
68
|
Uuml: "\xDC"
|
|
68
69
|
};
|
|
69
|
-
function asciiLower(text) {
|
|
70
|
-
return text.replace(/[A-Z]/g, (char) => String.fromCharCode(char.charCodeAt(0) + 32));
|
|
71
|
-
}
|
|
72
|
-
function strip(html, open, close, end, isElement) {
|
|
73
|
-
const lower = asciiLower(html);
|
|
74
|
-
let result = "";
|
|
75
|
-
let cursor = 0;
|
|
76
|
-
while (cursor < html.length) {
|
|
77
|
-
let start = lower.indexOf(open, cursor);
|
|
78
|
-
while (isElement && start !== -1 && /[a-z0-9]/.test(lower.charAt(start + open.length))) start = lower.indexOf(open, start + 1);
|
|
79
|
-
if (start === -1) break;
|
|
80
|
-
result += html.slice(cursor, start);
|
|
81
|
-
const closing = lower.indexOf(close, start + open.length);
|
|
82
|
-
const stop = closing === -1 ? -1 : lower.indexOf(end, closing);
|
|
83
|
-
cursor = stop === -1 ? html.length : stop + end.length;
|
|
84
|
-
}
|
|
85
|
-
return result + html.slice(cursor);
|
|
86
|
-
}
|
|
87
70
|
function decodeEntities(text) {
|
|
88
71
|
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+[0-9]*);/gi, (match, entity) => {
|
|
89
72
|
if (entity[0] === "#") {
|
|
@@ -103,8 +86,8 @@ function absolute(href, baseUrl) {
|
|
|
103
86
|
}
|
|
104
87
|
}
|
|
105
88
|
function htmlToText(html, baseUrl) {
|
|
106
|
-
let text =
|
|
107
|
-
for (const tag of REMOVED_ELEMENTS) text =
|
|
89
|
+
let text = (0, import_helpers.stripBlocks)(html, "<!--", "-->", "-->", false);
|
|
90
|
+
for (const tag of REMOVED_ELEMENTS) text = (0, import_helpers.stripBlocks)(text, `<${tag}`, `</${tag}`, ">", true);
|
|
108
91
|
text = text.slice(0, text.lastIndexOf(">") + 1).replace(/<[!?][^>]*>/g, "").replace(/[\u0001-\u0003]/g, "").replace(/\s+/g, " ");
|
|
109
92
|
const links = [];
|
|
110
93
|
text = text.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9]*)([^>]*)>/g, (match, slash, rawName, attributes) => {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { stripBlocks } from "../../../common/helpers/index.js";
|
|
1
2
|
const REMOVED_ELEMENTS = ["script", "style", "noscript", "svg", "head", "template", "iframe", "object", "canvas"];
|
|
2
3
|
const LINE = "";
|
|
3
4
|
const PARAGRAPH = "";
|
|
@@ -43,24 +44,6 @@ const ENTITIES = {
|
|
|
43
44
|
Ntilde: "\xD1",
|
|
44
45
|
Uuml: "\xDC"
|
|
45
46
|
};
|
|
46
|
-
function asciiLower(text) {
|
|
47
|
-
return text.replace(/[A-Z]/g, (char) => String.fromCharCode(char.charCodeAt(0) + 32));
|
|
48
|
-
}
|
|
49
|
-
function strip(html, open, close, end, isElement) {
|
|
50
|
-
const lower = asciiLower(html);
|
|
51
|
-
let result = "";
|
|
52
|
-
let cursor = 0;
|
|
53
|
-
while (cursor < html.length) {
|
|
54
|
-
let start = lower.indexOf(open, cursor);
|
|
55
|
-
while (isElement && start !== -1 && /[a-z0-9]/.test(lower.charAt(start + open.length))) start = lower.indexOf(open, start + 1);
|
|
56
|
-
if (start === -1) break;
|
|
57
|
-
result += html.slice(cursor, start);
|
|
58
|
-
const closing = lower.indexOf(close, start + open.length);
|
|
59
|
-
const stop = closing === -1 ? -1 : lower.indexOf(end, closing);
|
|
60
|
-
cursor = stop === -1 ? html.length : stop + end.length;
|
|
61
|
-
}
|
|
62
|
-
return result + html.slice(cursor);
|
|
63
|
-
}
|
|
64
47
|
function decodeEntities(text) {
|
|
65
48
|
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+[0-9]*);/gi, (match, entity) => {
|
|
66
49
|
if (entity[0] === "#") {
|
|
@@ -80,8 +63,8 @@ function absolute(href, baseUrl) {
|
|
|
80
63
|
}
|
|
81
64
|
}
|
|
82
65
|
function htmlToText(html, baseUrl) {
|
|
83
|
-
let text =
|
|
84
|
-
for (const tag of REMOVED_ELEMENTS) text =
|
|
66
|
+
let text = stripBlocks(html, "<!--", "-->", "-->", false);
|
|
67
|
+
for (const tag of REMOVED_ELEMENTS) text = stripBlocks(text, `<${tag}`, `</${tag}`, ">", true);
|
|
85
68
|
text = text.slice(0, text.lastIndexOf(">") + 1).replace(/<[!?][^>]*>/g, "").replace(/[\u0001-\u0003]/g, "").replace(/\s+/g, " ");
|
|
86
69
|
const links = [];
|
|
87
70
|
text = text.replace(/<(\/?)([a-zA-Z][a-zA-Z0-9]*)([^>]*)>/g, (match, slash, rawName, attributes) => {
|
package/docs/README.md
CHANGED
|
@@ -15,8 +15,9 @@ Start with the [README](../README.md) for what `openloops` is and how to run it.
|
|
|
15
15
|
| --- | --- |
|
|
16
16
|
| [The `Agent`](agent.md) | Options, running a turn, the result and its statuses, confirmations, autonomous mode, hooks and interruption. |
|
|
17
17
|
| [Configuration](configuration.md) | Environment variables, choosing the model and what is recorded. |
|
|
18
|
+
| [Reporting errors](error-reporting.md) | Declare one function, once, to send the errors that the package catches to Sentry or to the tool you use: what it receives, what is reported, serverless and moving from `SENTRY_DSN`. |
|
|
18
19
|
| [Automations](automations.md) | Tasks that the agent runs by itself, on a schedule, when an event arrives or both: triggers, tokens, the queue, the history of runs and the runner that executes them. If you used `agentic-jobs`, read [the migration steps](automations.md#migrating-from-agentic-jobs). Updating to 0.5.0 breaks the shape of the triggers, read [the migration to 0.5.0](automations.md#migrating-to-050). |
|
|
19
|
-
| [Chats](chats.md) | The chat record, its messages and their `source`, listing, reading and deleting chats. |
|
|
20
|
+
| [Chats](chats.md) | The chat record, its title and messages and their `source`, listing and searching chats, reading and deleting them. Updating to 0.8.0 needs [a migration of the titles](chats.md#migrating-to-080). |
|
|
20
21
|
|
|
21
22
|
## Shape how the agent works
|
|
22
23
|
|
package/docs/agent.md
CHANGED
|
@@ -199,13 +199,13 @@ await agent.run({ input: { chatId, message }, currentUser })
|
|
|
199
199
|
stop()
|
|
200
200
|
```
|
|
201
201
|
|
|
202
|
-
The listener receives every change of the activity of the run while it is in progress. It gets no start or end marker: the run is over when `agent.run()` resolves. This is the only place where the
|
|
202
|
+
The listener receives every change of the activity of the run while it is in progress. It gets no start or end marker: the run is over when `agent.run()` resolves. This is the only place where the activity is available: it is not saved with the chat. 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 `Searching your flight expenses for August`, shown from the answer that asked for the actions until the next answer. When the model gives none, the listener hears nothing and the client keeps what it shows. See [loops](loops.md#agiloop).
|
|
203
203
|
|
|
204
204
|
- 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.
|
|
205
205
|
- 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.
|
|
206
206
|
- `onActivity` returns a function that removes the listener.
|
|
207
207
|
- 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.
|
|
208
|
-
- Past values are not replayed. If a client connects late or loses its connection, read the chat and use its `state.status
|
|
208
|
+
- Past values are not replayed. If a client connects late or loses its connection, read the chat and use its `state.status`.
|
|
209
209
|
|
|
210
210
|
## Stopping a running turn
|
|
211
211
|
|
|
@@ -223,4 +223,21 @@ For every chat, `openloops` persists the chat and its messages, the tasks, every
|
|
|
223
223
|
|
|
224
224
|
## Error handling
|
|
225
225
|
|
|
226
|
-
If a turn fails for any reason, `Agent` marks the chat as failed, saves it, closes any open MCP session and returns the error in `result.error`. LLM failures such as rate limits, exhausted quota or a model that does not answer in time (`LLM_TIMEOUT`) carry a user-facing message and a retryable flag in `data.state.lastError
|
|
226
|
+
If a turn fails for any reason, `Agent` marks the chat as failed, saves it, closes any open MCP session and returns the error in `result.error`. LLM failures such as rate limits, exhausted quota or a model that does not answer in time (`LLM_TIMEOUT`) carry a user-facing message and a retryable flag in `data.state.lastError`, together with a code that says what failed:
|
|
227
|
+
|
|
228
|
+
| Code | Meaning | Retryable |
|
|
229
|
+
| --- | --- | --- |
|
|
230
|
+
| `LLM_RATE_LIMITED` | Too many requests. | yes |
|
|
231
|
+
| `LLM_QUOTA_EXCEEDED` | The quota of the provider is exhausted. | no |
|
|
232
|
+
| `LLM_UNAVAILABLE` | The provider is unavailable or overloaded. | yes |
|
|
233
|
+
| `LLM_TIMEOUT` | The model did not answer in time. | yes |
|
|
234
|
+
| `LLM_UNSUPPORTED_PARAMETER` | The model rejects a request setting. | yes |
|
|
235
|
+
| `LLM_AUTH_FAILED` | The provider rejected the credentials. | no |
|
|
236
|
+
| `LLM_CONTEXT_TOO_LONG` | The conversation does not fit in the context of the model. | no |
|
|
237
|
+
| `LLM_CONTENT_FILTERED` | The provider blocked the request or the answer. | no |
|
|
238
|
+
| `LLM_INCOMPLETE_RESPONSE` | The model stopped before it finished. | yes |
|
|
239
|
+
| `LLM_FAILED` | Anything else. | yes |
|
|
240
|
+
|
|
241
|
+
The provider tells these apart with free text, so a message that does not match any of them ends in `LLM_FAILED`.
|
|
242
|
+
|
|
243
|
+
A failed run is also handed to the error reporter you registered, with the `code`, the `chatId` and the `userId`. See [reporting errors](error-reporting.md).
|
package/docs/automations.md
CHANGED
|
@@ -246,7 +246,7 @@ A revoked token is checked after its signature, so an invalid token never reache
|
|
|
246
246
|
Every execution is a run.
|
|
247
247
|
|
|
248
248
|
```typescript
|
|
249
|
-
const byAutomation = await listAutomationRunsByAutomation({ automationId, options: { page: 1, limit: 20 }, currentUser })
|
|
249
|
+
const byAutomation = await listAutomationRunsByAutomation({ automationId, status: 'paused', options: { page: 1, limit: 20 }, currentUser })
|
|
250
250
|
|
|
251
251
|
const byUser = await listAutomationRunsByUser({ status: 'failed', currentUser })
|
|
252
252
|
```
|
|
@@ -267,8 +267,8 @@ const byUser = await listAutomationRunsByUser({ status: 'failed', currentUser })
|
|
|
267
267
|
| `queued` | An event waiting for its turn. |
|
|
268
268
|
| `running` | In progress. |
|
|
269
269
|
| `completed` | The agent finished its task. |
|
|
270
|
-
| `paused` | The agent needs the user: it asked for the approval of a tool or an MCP server, or asked a question. The chat is waiting. When the user answers in the chat and it finishes, the run becomes `completed` or `failed`. |
|
|
271
|
-
| `failed` | It failed. `error` says why: the model did not answer in time, a guardrail blocked the instructions, the owner no longer exists, or the
|
|
270
|
+
| `paused` | The agent needs the user: it asked for the approval of a tool or an MCP server, or asked a question. The chat is waiting. When the user answers in the chat and it finishes, the run becomes `completed` or `failed`. If the chat is deleted while the run waits, the runner closes it as `failed` with the code `CHAT_DELETED`, so the automation runs again on its next occurrence. |
|
|
271
|
+
| `failed` | It failed. `error` says why: the model did not answer in time, a guardrail blocked the instructions, the owner no longer exists, the worker was lost (`WORKER_LOST`), or the chat was deleted while the run waited for the user (`CHAT_DELETED`). |
|
|
272
272
|
| `skipped` | It was not started and `skipReason` says why: a scheduled run was due but the previous one was still `paused`, an event found the queue full, or the event trigger was turned off or removed, or the automation deleted, while the event waited. It is recorded so you can notify the user. |
|
|
273
273
|
|
|
274
274
|
## The runner
|