openloops 0.1.32 → 0.1.35
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/dist/clients/llm-client.d.ts +2 -0
- package/dist/clients/llm-client.js +15 -3
- package/dist/clients/llm-client.mjs +16 -4
- package/dist/clients/llm-error.d.ts +2 -1
- package/dist/clients/llm-error.js +10 -0
- package/dist/clients/llm-error.mjs +9 -0
- package/dist/common/base/base.entity.d.ts +2 -1
- package/dist/harness/agent.js +2 -0
- package/dist/harness/agent.mjs +3 -1
- package/dist/harness/native-tools.js +55 -2
- package/dist/harness/native-tools.mjs +55 -2
- package/dist/harness/tool-pipeline.js +9 -1
- package/dist/harness/tool-pipeline.mjs +9 -1
- package/dist/harness/utils/grounding.d.ts +6 -0
- package/dist/harness/utils/grounding.js +79 -0
- package/dist/harness/utils/grounding.mjs +53 -0
- package/dist/loops/agi/loop.js +17 -5
- package/dist/loops/agi/loop.mjs +17 -5
- package/dist/loops/agi/skills/reasoning-engine.js +2 -1
- package/dist/loops/agi/skills/reasoning-engine.mjs +2 -1
- package/dist/services/chats/entities/chat.entity.js +3 -1
- package/dist/services/chats/entities/chat.entity.mjs +3 -1
- package/dist/services/chats/lambdas/update-chat/update-chat.use-case.js +5 -0
- package/dist/services/chats/lambdas/update-chat/update-chat.use-case.mjs +5 -0
- package/dist/services/tasks/entities/agent-action.entity.js +4 -2
- package/dist/services/tasks/entities/agent-action.entity.mjs +4 -2
- package/dist/services/tasks/entities/agent-task.entity.d.ts +8 -4
- package/dist/services/tasks/entities/agent-task.entity.js +40 -10
- package/dist/services/tasks/entities/agent-task.entity.mjs +39 -10
- package/package.json +5 -2
package/dist/loops/agi/loop.js
CHANGED
|
@@ -24,12 +24,15 @@ module.exports = __toCommonJS(loop_exports);
|
|
|
24
24
|
var import_harness = require("../../harness/index.js");
|
|
25
25
|
var import_agent_task = require("../../services/tasks/entities/agent-task.entity.js");
|
|
26
26
|
var import_skills = require("../shared/skills");
|
|
27
|
+
var import_grounding = require("../../harness/utils/grounding.js");
|
|
27
28
|
var import_reasoning_engine = require("./skills/reasoning-engine");
|
|
28
29
|
const MAX_TURNS = 20;
|
|
29
30
|
const MAX_TOOL_CALLS = 40;
|
|
30
31
|
const WARN_SAME_TOOL = 3;
|
|
31
32
|
const MAX_SAME_TOOL = 6;
|
|
32
|
-
const
|
|
33
|
+
const MAX_ANSWER_REJECTIONS = 1;
|
|
34
|
+
const WARN_WORKSPACE_TURNS = 3;
|
|
35
|
+
const MAX_WORKSPACE_TURNS = 7;
|
|
33
36
|
const BLOCK_DUPLICATES = false;
|
|
34
37
|
class AgiLoop extends import_harness.AgentLoop {
|
|
35
38
|
get initialNode() {
|
|
@@ -91,15 +94,18 @@ class AgiLoop extends import_harness.AgentLoop {
|
|
|
91
94
|
task.answerQuestion(ctx.currentMessage);
|
|
92
95
|
const streak = task.sameToolStreak;
|
|
93
96
|
const exhausted = task.turnCount >= MAX_TURNS || task.toolCallCount >= MAX_TOOL_CALLS;
|
|
97
|
+
const workspaceTurns = task.workspaceStreak;
|
|
94
98
|
const stuck = streak.count >= MAX_SAME_TOOL;
|
|
95
|
-
const
|
|
99
|
+
const lost = workspaceTurns >= MAX_WORKSPACE_TURNS;
|
|
100
|
+
const warning = streak.count >= WARN_SAME_TOOL ? `You ran ${streak.name} ${streak.count} turns in a row. Do not repeat it with small rewordings: follow what its results suggest, change approach, or tell the user what is missing.` : workspaceTurns >= WARN_WORKSPACE_TURNS && !lost ? `You spent ${workspaceTurns} turns in a row only reading and saving notes. Stop handling data by hand: locate what you need with read_context using 'find', then act with a tool, or tell the user what is missing.` : void 0;
|
|
101
|
+
const stopReason = exhausted ? "The task reached its limit of turns or tool calls" : stuck ? `The same tool (${streak.name}) was called ${streak.count} turns in a row without getting anywhere` : lost ? `${workspaceTurns} turns in a row went into reading and saving notes without running any tool` : void 0;
|
|
96
102
|
const lastCompletedTask = ctx.chat.lastCompletedTask();
|
|
97
103
|
const catalog = await ctx.toolCatalog();
|
|
98
104
|
const result = await import_reasoning_engine.reasoningEngine.run({
|
|
99
105
|
...ctx.skillParams,
|
|
100
106
|
history: task.history({
|
|
101
107
|
budget: { turns_left: MAX_TURNS - task.turnCount, tool_calls_left: MAX_TOOL_CALLS - task.toolCallCount },
|
|
102
|
-
...
|
|
108
|
+
...warning ? { warning } : {},
|
|
103
109
|
...task.known ? { known: task.known } : {},
|
|
104
110
|
...task.schemas ? { schemas: task.schemas } : {},
|
|
105
111
|
...stopReason ? { stop_reason: stopReason } : {}
|
|
@@ -117,7 +123,7 @@ class AgiLoop extends import_harness.AgentLoop {
|
|
|
117
123
|
if (stopReason) {
|
|
118
124
|
const answer = task.forceAnswer(`I could not finish the task: ${stopReason}.`);
|
|
119
125
|
ctx.reply(answer);
|
|
120
|
-
task.summary = answer
|
|
126
|
+
task.summary = answer;
|
|
121
127
|
ctx.chat.failTask(task.id);
|
|
122
128
|
ctx.chat.state?.setStatus(import_harness.AgentStatus.IDLE);
|
|
123
129
|
ctx.setNextNode(this.nodes.fast_responder);
|
|
@@ -147,9 +153,15 @@ class AgiLoop extends import_harness.AgentLoop {
|
|
|
147
153
|
}
|
|
148
154
|
const answer = task.pendingAnswer;
|
|
149
155
|
if (answer !== void 0) {
|
|
156
|
+
const invented = task.rejectedAnswers < MAX_ANSWER_REJECTIONS ? await (0, import_grounding.ungroundedIdentifiers)(task, ctx.workspace, [answer]) : [];
|
|
157
|
+
if (invented.length) {
|
|
158
|
+
task.rejectAnswer(`Your answer cites the identifier${invented.length > 1 ? "s" : ""} ${invented.map((id) => `"${id}"`).join(", ")}, which ${invented.length > 1 ? "were" : "was"} ${import_grounding.UNGROUNDED_PHRASE}. Do not state values you did not get from a result or from the user: remove ${invented.length > 1 ? "them" : "it"}, or obtain ${invented.length > 1 ? "them" : "it"} with a tool, and answer again.`);
|
|
159
|
+
ctx.setNextNode(this.nodes.reasoning_engine);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
150
162
|
task.deliverAnswer();
|
|
151
163
|
ctx.reply(answer);
|
|
152
|
-
ctx.chat.completeTask(task.id, answer
|
|
164
|
+
ctx.chat.completeTask(task.id, answer);
|
|
153
165
|
ctx.chat.state?.setStatus(import_harness.AgentStatus.IDLE);
|
|
154
166
|
ctx.setNextNode(this.nodes.fast_responder);
|
|
155
167
|
return;
|
package/dist/loops/agi/loop.mjs
CHANGED
|
@@ -2,12 +2,15 @@ import "../../chunk-CF3WOMB3.mjs";
|
|
|
2
2
|
import { AgentLoop, AgentStatus } from "../../harness/index.js";
|
|
3
3
|
import { AgentTask, findInvoker } from "../../services/tasks/entities/agent-task.entity.js";
|
|
4
4
|
import { fastResponder, confirmationGate } from "../shared/skills";
|
|
5
|
+
import { ungroundedIdentifiers, UNGROUNDED_PHRASE } from "../../harness/utils/grounding.js";
|
|
5
6
|
import { reasoningEngine } from "./skills/reasoning-engine";
|
|
6
7
|
const MAX_TURNS = 20;
|
|
7
8
|
const MAX_TOOL_CALLS = 40;
|
|
8
9
|
const WARN_SAME_TOOL = 3;
|
|
9
10
|
const MAX_SAME_TOOL = 6;
|
|
10
|
-
const
|
|
11
|
+
const MAX_ANSWER_REJECTIONS = 1;
|
|
12
|
+
const WARN_WORKSPACE_TURNS = 3;
|
|
13
|
+
const MAX_WORKSPACE_TURNS = 7;
|
|
11
14
|
const BLOCK_DUPLICATES = false;
|
|
12
15
|
class AgiLoop extends AgentLoop {
|
|
13
16
|
get initialNode() {
|
|
@@ -69,15 +72,18 @@ class AgiLoop extends AgentLoop {
|
|
|
69
72
|
task.answerQuestion(ctx.currentMessage);
|
|
70
73
|
const streak = task.sameToolStreak;
|
|
71
74
|
const exhausted = task.turnCount >= MAX_TURNS || task.toolCallCount >= MAX_TOOL_CALLS;
|
|
75
|
+
const workspaceTurns = task.workspaceStreak;
|
|
72
76
|
const stuck = streak.count >= MAX_SAME_TOOL;
|
|
73
|
-
const
|
|
77
|
+
const lost = workspaceTurns >= MAX_WORKSPACE_TURNS;
|
|
78
|
+
const warning = streak.count >= WARN_SAME_TOOL ? `You ran ${streak.name} ${streak.count} turns in a row. Do not repeat it with small rewordings: follow what its results suggest, change approach, or tell the user what is missing.` : workspaceTurns >= WARN_WORKSPACE_TURNS && !lost ? `You spent ${workspaceTurns} turns in a row only reading and saving notes. Stop handling data by hand: locate what you need with read_context using 'find', then act with a tool, or tell the user what is missing.` : void 0;
|
|
79
|
+
const stopReason = exhausted ? "The task reached its limit of turns or tool calls" : stuck ? `The same tool (${streak.name}) was called ${streak.count} turns in a row without getting anywhere` : lost ? `${workspaceTurns} turns in a row went into reading and saving notes without running any tool` : void 0;
|
|
74
80
|
const lastCompletedTask = ctx.chat.lastCompletedTask();
|
|
75
81
|
const catalog = await ctx.toolCatalog();
|
|
76
82
|
const result = await reasoningEngine.run({
|
|
77
83
|
...ctx.skillParams,
|
|
78
84
|
history: task.history({
|
|
79
85
|
budget: { turns_left: MAX_TURNS - task.turnCount, tool_calls_left: MAX_TOOL_CALLS - task.toolCallCount },
|
|
80
|
-
...
|
|
86
|
+
...warning ? { warning } : {},
|
|
81
87
|
...task.known ? { known: task.known } : {},
|
|
82
88
|
...task.schemas ? { schemas: task.schemas } : {},
|
|
83
89
|
...stopReason ? { stop_reason: stopReason } : {}
|
|
@@ -95,7 +101,7 @@ class AgiLoop extends AgentLoop {
|
|
|
95
101
|
if (stopReason) {
|
|
96
102
|
const answer = task.forceAnswer(`I could not finish the task: ${stopReason}.`);
|
|
97
103
|
ctx.reply(answer);
|
|
98
|
-
task.summary = answer
|
|
104
|
+
task.summary = answer;
|
|
99
105
|
ctx.chat.failTask(task.id);
|
|
100
106
|
ctx.chat.state?.setStatus(AgentStatus.IDLE);
|
|
101
107
|
ctx.setNextNode(this.nodes.fast_responder);
|
|
@@ -125,9 +131,15 @@ class AgiLoop extends AgentLoop {
|
|
|
125
131
|
}
|
|
126
132
|
const answer = task.pendingAnswer;
|
|
127
133
|
if (answer !== void 0) {
|
|
134
|
+
const invented = task.rejectedAnswers < MAX_ANSWER_REJECTIONS ? await ungroundedIdentifiers(task, ctx.workspace, [answer]) : [];
|
|
135
|
+
if (invented.length) {
|
|
136
|
+
task.rejectAnswer(`Your answer cites the identifier${invented.length > 1 ? "s" : ""} ${invented.map((id) => `"${id}"`).join(", ")}, which ${invented.length > 1 ? "were" : "was"} ${UNGROUNDED_PHRASE}. Do not state values you did not get from a result or from the user: remove ${invented.length > 1 ? "them" : "it"}, or obtain ${invented.length > 1 ? "them" : "it"} with a tool, and answer again.`);
|
|
137
|
+
ctx.setNextNode(this.nodes.reasoning_engine);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
128
140
|
task.deliverAnswer();
|
|
129
141
|
ctx.reply(answer);
|
|
130
|
-
ctx.chat.completeTask(task.id, answer
|
|
142
|
+
ctx.chat.completeTask(task.id, answer);
|
|
131
143
|
ctx.chat.state?.setStatus(AgentStatus.IDLE);
|
|
132
144
|
ctx.setNextNode(this.nodes.fast_responder);
|
|
133
145
|
return;
|
|
@@ -51,9 +51,10 @@ const reasoningEngine = new import_skill.Skill({
|
|
|
51
51
|
"NEVER_ASSUME_SCHEMA: Never assume what a tool accepts. Before the first call to any tool, read everything its server gives you about it: its description (often a short tutorial with required steps), its input schema, its annotations and any notes or examples in earlier results. If you have not seen the input schema of a tool, get it first, for example with the server's own search tool, since a name that appears in a listing does not tell you its arguments. Use the exact argument names of the schema and pass values from the user as they wrote them, never transformed into identifiers you invented. When a result gives you the schema of a tool you are going to use, copy its exact name and required arguments into 'state.progress' in that same cycle, because the full result is replaced by a stub in later cycles. If the information is not available, ask the user instead of guessing.",
|
|
52
52
|
`TWO_LAYERS: Some servers hide their real catalog behind their own meta tools, for example 'server__search_tools' and 'server__invoke_tool'. Those are external tools of that server, different from your native search_tools. In that case first run the server's own search tool (following its description, including its language rules) to get the real tool name and input schema, then run the real tool through the server's invoke tool with that exact name and its arguments. Two layers means two steps: search first, invoke after. Names returned by a server's search are never in your tool list, so never call them directly. Example action: {"tool": "server__invoke_tool", "arguments": {"name": "real_tool_name", "arguments": {"site_id": "..."}}}.`,
|
|
53
53
|
`REFERENCES: Every observation has a 'ref'. To pass a value forward without copying it, write "{{step_<ref>.output.<path>}}" in a later argument, for example "{{step_2_1.output.items[0].id}}". A placeholder that fills a whole argument keeps its original type.`,
|
|
54
|
-
`WORKSPACE: You see a large tool output in full only in the cycle right after it arrives. In later cycles it appears as a stub with the 'workspace_ref' name, its outline and a preview. So when a large result arrives, extract in that same cycle what you will need and write it in 'state.progress'. When you later need something that is not in your state or in the preview, load it with read_context using the 'workspace_ref' name and a path to the section you need, or reference the data with a placeholder. Never state details of a result that you have not read in full or loaded. Use save_context to keep facts, decisions or intermediate results you will need later, and reference a note with "{{context.<name>}}".`,
|
|
54
|
+
`WORKSPACE: You see a large tool output in full only in the cycle right after it arrives. In later cycles it appears as a stub with the 'workspace_ref' name, its outline and a preview. So when a large result arrives, extract in that same cycle what you will need and write it in 'state.progress'. When you later need something that is not in your state or in the preview, load it with read_context using the 'workspace_ref' name and a path to the section you need, or reference the data with a placeholder. To locate an entity inside a large result, such as a site, user or record by name, use read_context with 'find' and the text (case, spaces and separators are ignored) instead of reading the whole list; you cannot run code, so never compare or filter long lists by eye, and never list candidates you have not seen in a result. Never state details of a result that you have not read in full or loaded. Use save_context to keep facts, decisions or intermediate results you will need later, and reference a note with "{{context.<name>}}".`,
|
|
55
55
|
"CONFIRMATION: Some external tools change or delete data. When you include one in your actions, the system itself pauses and asks the user for explicit confirmation before it runs, so never ask for that confirmation yourself. When HARNESS.pending_confirmation is present, return a single 'respond' action whose answer states exactly what will be done (the tool, its key arguments and the impact) and asks the user to confirm or decline.",
|
|
56
56
|
"ENTITY_RESOLUTION: A name the user wrote is not necessarily how the system stores it, so one 'not found' does not prove that the entity does not exist. Before concluding that, check the name against the system's own listing or search for that kind of entity, finding the tool for it first if needed. Compare ignoring case, spaces, underscores and dashes: equal after normalizing is a match, containing is not. With one exact match, use it without asking and prefer its identifier over its name. With only similar candidates, confirm with the user by ask_user, naming them in plain words. With nothing similar, say that you could not find it. A suggestion inside an error is a hint to verify against the listing, never the answer. When the user picks a candidate, take its identifier from the list yourself. Do not retry an entity that already failed.",
|
|
57
|
+
"ARGUMENT_SOURCES: Before you write an action, check where the value of each required argument comes from: the user's message, an earlier result, or the user's answer to a question. If a value has no such origin, getting it is your next action: use a tool that lists or looks up that entity, or ask the user. Never write an identifier, id or code that you did not see in a result or in the user's words, in an action or in your final answer; the harness rejects them. Say in your final answer only what the results show, and when something failed, report what you actually did and where it stopped, without attributing the failure to the system or the entity unless a result says so.",
|
|
57
58
|
"IDENTIFIERS: A name is not a unique key and systems may match names loosely, so once you know the unique identifier of an entity, from a listing or an earlier result, pass the identifier in every later call instead of the name. When the user answers a question by choosing among options, resolve their choice to the identifier yourself. Even an exact name can match several entities: then pass the identifier of the one the user chose in the same argument that took the name, and never ask again for a choice the user already made.",
|
|
58
59
|
"USER_CHOICES: When you ask the user to choose among options, write the identifier of each option in 'state.progress' before pausing, so you can resolve their answer yourself. Once the user has chosen an option, that choice stands for the rest of the conversation: if the same options appear again, because a result lists them again or a system matches names loosely, apply the choice without asking again. Ask again only if the options are different or the user changes their mind.",
|
|
59
60
|
"ASK_USER: Use ask_user, not respond, when you cannot continue without something that belongs to the user, such as their intent, the entity they mean when it stays ambiguous, or a detail only they know. It pauses this same task and keeps your state, and the answer comes back as the observation of that action. Do not ask about how to do the work: when several tools or approaches are read-only and cheap, pick the most plausible one, run it, and mention the alternative in your final answer. Ask when the options differ a lot in cost, effects or in what the user gets. Always write the question in the user's language and in terms of what they want, never with internal tool names. Ask one concise question and never ask for something a tool can find. respond is only for delivering a result or for stating that something is impossible.",
|
|
@@ -29,9 +29,10 @@ const reasoningEngine = new Skill({
|
|
|
29
29
|
"NEVER_ASSUME_SCHEMA: Never assume what a tool accepts. Before the first call to any tool, read everything its server gives you about it: its description (often a short tutorial with required steps), its input schema, its annotations and any notes or examples in earlier results. If you have not seen the input schema of a tool, get it first, for example with the server's own search tool, since a name that appears in a listing does not tell you its arguments. Use the exact argument names of the schema and pass values from the user as they wrote them, never transformed into identifiers you invented. When a result gives you the schema of a tool you are going to use, copy its exact name and required arguments into 'state.progress' in that same cycle, because the full result is replaced by a stub in later cycles. If the information is not available, ask the user instead of guessing.",
|
|
30
30
|
`TWO_LAYERS: Some servers hide their real catalog behind their own meta tools, for example 'server__search_tools' and 'server__invoke_tool'. Those are external tools of that server, different from your native search_tools. In that case first run the server's own search tool (following its description, including its language rules) to get the real tool name and input schema, then run the real tool through the server's invoke tool with that exact name and its arguments. Two layers means two steps: search first, invoke after. Names returned by a server's search are never in your tool list, so never call them directly. Example action: {"tool": "server__invoke_tool", "arguments": {"name": "real_tool_name", "arguments": {"site_id": "..."}}}.`,
|
|
31
31
|
`REFERENCES: Every observation has a 'ref'. To pass a value forward without copying it, write "{{step_<ref>.output.<path>}}" in a later argument, for example "{{step_2_1.output.items[0].id}}". A placeholder that fills a whole argument keeps its original type.`,
|
|
32
|
-
`WORKSPACE: You see a large tool output in full only in the cycle right after it arrives. In later cycles it appears as a stub with the 'workspace_ref' name, its outline and a preview. So when a large result arrives, extract in that same cycle what you will need and write it in 'state.progress'. When you later need something that is not in your state or in the preview, load it with read_context using the 'workspace_ref' name and a path to the section you need, or reference the data with a placeholder. Never state details of a result that you have not read in full or loaded. Use save_context to keep facts, decisions or intermediate results you will need later, and reference a note with "{{context.<name>}}".`,
|
|
32
|
+
`WORKSPACE: You see a large tool output in full only in the cycle right after it arrives. In later cycles it appears as a stub with the 'workspace_ref' name, its outline and a preview. So when a large result arrives, extract in that same cycle what you will need and write it in 'state.progress'. When you later need something that is not in your state or in the preview, load it with read_context using the 'workspace_ref' name and a path to the section you need, or reference the data with a placeholder. To locate an entity inside a large result, such as a site, user or record by name, use read_context with 'find' and the text (case, spaces and separators are ignored) instead of reading the whole list; you cannot run code, so never compare or filter long lists by eye, and never list candidates you have not seen in a result. Never state details of a result that you have not read in full or loaded. Use save_context to keep facts, decisions or intermediate results you will need later, and reference a note with "{{context.<name>}}".`,
|
|
33
33
|
"CONFIRMATION: Some external tools change or delete data. When you include one in your actions, the system itself pauses and asks the user for explicit confirmation before it runs, so never ask for that confirmation yourself. When HARNESS.pending_confirmation is present, return a single 'respond' action whose answer states exactly what will be done (the tool, its key arguments and the impact) and asks the user to confirm or decline.",
|
|
34
34
|
"ENTITY_RESOLUTION: A name the user wrote is not necessarily how the system stores it, so one 'not found' does not prove that the entity does not exist. Before concluding that, check the name against the system's own listing or search for that kind of entity, finding the tool for it first if needed. Compare ignoring case, spaces, underscores and dashes: equal after normalizing is a match, containing is not. With one exact match, use it without asking and prefer its identifier over its name. With only similar candidates, confirm with the user by ask_user, naming them in plain words. With nothing similar, say that you could not find it. A suggestion inside an error is a hint to verify against the listing, never the answer. When the user picks a candidate, take its identifier from the list yourself. Do not retry an entity that already failed.",
|
|
35
|
+
"ARGUMENT_SOURCES: Before you write an action, check where the value of each required argument comes from: the user's message, an earlier result, or the user's answer to a question. If a value has no such origin, getting it is your next action: use a tool that lists or looks up that entity, or ask the user. Never write an identifier, id or code that you did not see in a result or in the user's words, in an action or in your final answer; the harness rejects them. Say in your final answer only what the results show, and when something failed, report what you actually did and where it stopped, without attributing the failure to the system or the entity unless a result says so.",
|
|
35
36
|
"IDENTIFIERS: A name is not a unique key and systems may match names loosely, so once you know the unique identifier of an entity, from a listing or an earlier result, pass the identifier in every later call instead of the name. When the user answers a question by choosing among options, resolve their choice to the identifier yourself. Even an exact name can match several entities: then pass the identifier of the one the user chose in the same argument that took the name, and never ask again for a choice the user already made.",
|
|
36
37
|
"USER_CHOICES: When you ask the user to choose among options, write the identifier of each option in 'state.progress' before pausing, so you can resolve their answer yourself. Once the user has chosen an option, that choice stands for the rest of the conversation: if the same options appear again, because a result lists them again or a system matches names loosely, apply the choice without asking again. Ask again only if the options are different or the user changes their mind.",
|
|
37
38
|
"ASK_USER: Use ask_user, not respond, when you cannot continue without something that belongs to the user, such as their intent, the entity they mean when it stays ambiguous, or a detail only they know. It pauses this same task and keeps your state, and the answer comes back as the observation of that action. Do not ask about how to do the work: when several tools or approaches are read-only and cheap, pick the most plausible one, run it, and mention the alternative in your final answer. Ask when the options differ a lot in cost, effects or in what the user gets. Always write the question in the user's language and in terms of what they want, never with internal tool names. Ask one concise question and never ask for something a tool can find. respond is only for delivering a result or for stating that something is impossible.",
|
|
@@ -113,7 +113,7 @@ class Chat extends import_base.BaseEntity {
|
|
|
113
113
|
previousTaskId: opts?.continuesFrom,
|
|
114
114
|
loopName: this.settings?.loopName
|
|
115
115
|
});
|
|
116
|
-
newTask.threadId ??= newTask.
|
|
116
|
+
newTask.threadId ??= newTask._id;
|
|
117
117
|
this.tasks.push(newTask);
|
|
118
118
|
this.state?.setActiveTaskId(newTask.id);
|
|
119
119
|
return newTask;
|
|
@@ -143,12 +143,14 @@ class Chat extends import_base.BaseEntity {
|
|
|
143
143
|
clearActiveTaskIdIfMatches(task) {
|
|
144
144
|
if (task?.id === this.state?.activeTaskId) {
|
|
145
145
|
this.state?.setActiveTaskId(void 0);
|
|
146
|
+
this.unset(["state.activeTaskId"]);
|
|
146
147
|
}
|
|
147
148
|
}
|
|
148
149
|
switchLoop(loopName) {
|
|
149
150
|
if (this.settings?.loopName && this.settings.loopName !== loopName) {
|
|
150
151
|
this.activeTask?.pause();
|
|
151
152
|
this.state?.setActiveTaskId(void 0);
|
|
153
|
+
this.unset(["state.activeTaskId"]);
|
|
152
154
|
}
|
|
153
155
|
this.settings?.setLoopName(loopName);
|
|
154
156
|
}
|
|
@@ -91,7 +91,7 @@ class Chat extends BaseEntity {
|
|
|
91
91
|
previousTaskId: opts?.continuesFrom,
|
|
92
92
|
loopName: this.settings?.loopName
|
|
93
93
|
});
|
|
94
|
-
newTask.threadId ??= newTask.
|
|
94
|
+
newTask.threadId ??= newTask._id;
|
|
95
95
|
this.tasks.push(newTask);
|
|
96
96
|
this.state?.setActiveTaskId(newTask.id);
|
|
97
97
|
return newTask;
|
|
@@ -121,12 +121,14 @@ class Chat extends BaseEntity {
|
|
|
121
121
|
clearActiveTaskIdIfMatches(task) {
|
|
122
122
|
if (task?.id === this.state?.activeTaskId) {
|
|
123
123
|
this.state?.setActiveTaskId(void 0);
|
|
124
|
+
this.unset(["state.activeTaskId"]);
|
|
124
125
|
}
|
|
125
126
|
}
|
|
126
127
|
switchLoop(loopName) {
|
|
127
128
|
if (this.settings?.loopName && this.settings.loopName !== loopName) {
|
|
128
129
|
this.activeTask?.pause();
|
|
129
130
|
this.state?.setActiveTaskId(void 0);
|
|
131
|
+
this.unset(["state.activeTaskId"]);
|
|
130
132
|
}
|
|
131
133
|
this.settings?.setLoopName(loopName);
|
|
132
134
|
}
|
|
@@ -50,6 +50,11 @@ let UpdateChatUseCase = class extends import_base.BaseUseCase {
|
|
|
50
50
|
}
|
|
51
51
|
const chat = import_entities.Chat.fromJSON({ ...payload, _id: id });
|
|
52
52
|
chat.setUpdatedBy(currentUser);
|
|
53
|
+
if (payload.toUnset) {
|
|
54
|
+
const flat = chat.toFlatDocument();
|
|
55
|
+
const fields = Object.keys(payload.toUnset).filter((field) => flat[field] === void 0);
|
|
56
|
+
if (fields.length) chat.unset(fields);
|
|
57
|
+
}
|
|
53
58
|
const result = await this.chatRepository?.update(chat);
|
|
54
59
|
if (!result) {
|
|
55
60
|
throw new Error("Chat not found or update failed");
|
|
@@ -22,6 +22,11 @@ let UpdateChatUseCase = class extends BaseUseCase {
|
|
|
22
22
|
}
|
|
23
23
|
const chat = Chat.fromJSON({ ...payload, _id: id });
|
|
24
24
|
chat.setUpdatedBy(currentUser);
|
|
25
|
+
if (payload.toUnset) {
|
|
26
|
+
const flat = chat.toFlatDocument();
|
|
27
|
+
const fields = Object.keys(payload.toUnset).filter((field) => flat[field] === void 0);
|
|
28
|
+
if (fields.length) chat.unset(fields);
|
|
29
|
+
}
|
|
25
30
|
const result = await this.chatRepository?.update(chat);
|
|
26
31
|
if (!result) {
|
|
27
32
|
throw new Error("Chat not found or update failed");
|
|
@@ -25,7 +25,9 @@ module.exports = __toCommonJS(agent_action_entity_exports);
|
|
|
25
25
|
var import_mongodb = require("mongodb");
|
|
26
26
|
var import_logger = require("../../../common/logger/index.js");
|
|
27
27
|
var import_base = require("../../../common/base/base.entity.js");
|
|
28
|
-
|
|
28
|
+
function stubNote(ref) {
|
|
29
|
+
return `Partial view: the preview is only the beginning of the result. Do not take values from it as the ones you need. Load them with read_context using name "${ref}": add "path" for a section, or "find" with the text to locate an entity by name inside the result. You cannot compare long lists by eye.`;
|
|
30
|
+
}
|
|
29
31
|
const CLEARABLE_FIELDS = ["error", "startedAt", "completedAt", "outputRef", "outputChars", "outputStub"];
|
|
30
32
|
function truncateForPrompt(value, maxChars = 3e3) {
|
|
31
33
|
if (value === void 0 || value === null) return value;
|
|
@@ -213,7 +215,7 @@ class AgentAction extends import_base.BaseEntity {
|
|
|
213
215
|
total_chars: offloaded.totalChars,
|
|
214
216
|
outline: offloaded.outline,
|
|
215
217
|
preview: offloaded.preview,
|
|
216
|
-
note:
|
|
218
|
+
note: stubNote(offloaded.ref)
|
|
217
219
|
};
|
|
218
220
|
}
|
|
219
221
|
offloadOutput(offloaded) {
|
|
@@ -2,7 +2,9 @@ import "../../../chunk-CF3WOMB3.mjs";
|
|
|
2
2
|
import { ObjectId } from "mongodb";
|
|
3
3
|
import { Logger } from "../../../common/logger/index.js";
|
|
4
4
|
import { BaseEntity } from "../../../common/base/base.entity.js";
|
|
5
|
-
|
|
5
|
+
function stubNote(ref) {
|
|
6
|
+
return `Partial view: the preview is only the beginning of the result. Do not take values from it as the ones you need. Load them with read_context using name "${ref}": add "path" for a section, or "find" with the text to locate an entity by name inside the result. You cannot compare long lists by eye.`;
|
|
7
|
+
}
|
|
6
8
|
const CLEARABLE_FIELDS = ["error", "startedAt", "completedAt", "outputRef", "outputChars", "outputStub"];
|
|
7
9
|
function truncateForPrompt(value, maxChars = 3e3) {
|
|
8
10
|
if (value === void 0 || value === null) return value;
|
|
@@ -190,7 +192,7 @@ class AgentAction extends BaseEntity {
|
|
|
190
192
|
total_chars: offloaded.totalChars,
|
|
191
193
|
outline: offloaded.outline,
|
|
192
194
|
preview: offloaded.preview,
|
|
193
|
-
note:
|
|
195
|
+
note: stubNote(offloaded.ref)
|
|
194
196
|
};
|
|
195
197
|
}
|
|
196
198
|
offloadOutput(offloaded) {
|
|
@@ -17,7 +17,7 @@ export interface AgentTaskProps extends BaseEntityProps {
|
|
|
17
17
|
status?: TaskStatus;
|
|
18
18
|
goal?: string;
|
|
19
19
|
nextNode?: string;
|
|
20
|
-
threadId?: string;
|
|
20
|
+
threadId?: string | ObjectId;
|
|
21
21
|
previousTaskId?: string;
|
|
22
22
|
summary?: string;
|
|
23
23
|
loopName?: string;
|
|
@@ -76,6 +76,7 @@ export declare function findInvoker(tools: {
|
|
|
76
76
|
name: string;
|
|
77
77
|
parameters?: Record<string, any>;
|
|
78
78
|
}[]): string | undefined;
|
|
79
|
+
export declare function seenHiddenTool(written: string, invoker: string, schemas?: Record<string, unknown>): string | undefined;
|
|
79
80
|
export declare function stableStringify(value: any): string;
|
|
80
81
|
export declare function readPath(value: any, path?: string): any;
|
|
81
82
|
export declare class AgentTask extends BaseEntity {
|
|
@@ -84,7 +85,7 @@ export declare class AgentTask extends BaseEntity {
|
|
|
84
85
|
status?: TaskStatus | undefined;
|
|
85
86
|
goal?: string | undefined;
|
|
86
87
|
nextNode?: string | undefined;
|
|
87
|
-
threadId?:
|
|
88
|
+
threadId?: ObjectId | undefined;
|
|
88
89
|
previousTaskId?: string | undefined;
|
|
89
90
|
summary?: string | undefined;
|
|
90
91
|
loopName?: string | undefined;
|
|
@@ -101,7 +102,7 @@ export declare class AgentTask extends BaseEntity {
|
|
|
101
102
|
static collectRefs(value: any): CollectedRefs;
|
|
102
103
|
actions: AgentAction[];
|
|
103
104
|
hydrated: boolean;
|
|
104
|
-
constructor(props: AgentTaskProps, chatId?: ObjectId | undefined, status?: TaskStatus | undefined, goal?: string | undefined, nextNode?: string | undefined, threadId?:
|
|
105
|
+
constructor(props: AgentTaskProps, chatId?: ObjectId | undefined, status?: TaskStatus | undefined, goal?: string | undefined, nextNode?: string | undefined, threadId?: ObjectId | undefined, previousTaskId?: string | undefined, summary?: string | undefined, loopName?: string | undefined, planCount?: number, planOffset?: number, executedOffset?: number, scratch?: Record<string, any> | undefined, opening?: string | undefined, turns?: TurnRecord[], known?: Record<string, string> | undefined, schemas?: Record<string, ToolSchemaSummary> | undefined);
|
|
105
106
|
toJSON(): AgentTaskProps;
|
|
106
107
|
get id(): string;
|
|
107
108
|
get clearedFields(): Record<string, ''>;
|
|
@@ -127,6 +128,8 @@ export declare class AgentTask extends BaseEntity {
|
|
|
127
128
|
answerQuestion(answer: string): boolean;
|
|
128
129
|
get state(): Record<string, any> | undefined;
|
|
129
130
|
get pendingAnswer(): string | undefined;
|
|
131
|
+
get rejectedAnswers(): number;
|
|
132
|
+
rejectAnswer(message: string): void;
|
|
130
133
|
forceAnswer(fallback: string): string;
|
|
131
134
|
static answerFrom(output: TurnOutput): string | undefined;
|
|
132
135
|
deliverAnswer(): void;
|
|
@@ -138,6 +141,7 @@ export declare class AgentTask extends BaseEntity {
|
|
|
138
141
|
invoker?: string;
|
|
139
142
|
}): AgentAction[];
|
|
140
143
|
history(notice?: Record<string, any>): LLMMessage[];
|
|
144
|
+
get workspaceStreak(): number;
|
|
141
145
|
get sameToolStreak(): {
|
|
142
146
|
name?: string;
|
|
143
147
|
count: number;
|
|
@@ -145,9 +149,9 @@ export declare class AgentTask extends BaseEntity {
|
|
|
145
149
|
get discoveredToolNames(): string[];
|
|
146
150
|
get failedActions(): AgentAction[];
|
|
147
151
|
get executedActions(): AgentAction[];
|
|
148
|
-
get lastExecutedAction(): AgentAction | undefined;
|
|
149
152
|
get replanCount(): number;
|
|
150
153
|
get executedSinceOpen(): number;
|
|
154
|
+
get lastExecutedAction(): AgentAction | undefined;
|
|
151
155
|
executionHistory(maxChars?: number): {
|
|
152
156
|
ref: string;
|
|
153
157
|
tool: string | undefined;
|
|
@@ -27,6 +27,7 @@ __export(agent_task_entity_exports, {
|
|
|
27
27
|
findInvoker: () => findInvoker,
|
|
28
28
|
readPath: () => readPath,
|
|
29
29
|
resolveToolName: () => resolveToolName,
|
|
30
|
+
seenHiddenTool: () => seenHiddenTool,
|
|
30
31
|
stableStringify: () => stableStringify
|
|
31
32
|
});
|
|
32
33
|
module.exports = __toCommonJS(agent_task_entity_exports);
|
|
@@ -90,9 +91,17 @@ function findInvoker(tools) {
|
|
|
90
91
|
const invokers = tools.filter((tool) => tool.name.endsWith("__invoke_tool") && tool.parameters?.properties?.name && tool.parameters?.properties?.arguments);
|
|
91
92
|
return invokers.length === 1 ? invokers[0].name : void 0;
|
|
92
93
|
}
|
|
94
|
+
function seenHiddenTool(written, invoker, schemas) {
|
|
95
|
+
if (!schemas) return void 0;
|
|
96
|
+
const separator = written.indexOf("__");
|
|
97
|
+
const namespace = invoker.slice(0, invoker.indexOf("__"));
|
|
98
|
+
if (separator > 0 && normalizeToolName(written.slice(0, separator)) !== normalizeToolName(namespace)) return void 0;
|
|
99
|
+
const bare = normalizeToolName(separator > 0 ? written.slice(separator + 2) : written);
|
|
100
|
+
return Object.keys(schemas).find((key) => normalizeToolName(key) === bare);
|
|
101
|
+
}
|
|
93
102
|
function routeNote(action) {
|
|
94
103
|
if (!action.requestedName) return void 0;
|
|
95
|
-
return action.args?.name
|
|
104
|
+
return action.name?.endsWith("__invoke_tool") && action.args?.name && !/(^|__)invoke_tool$/.test(action.requestedName) ? `"${action.requestedName}" is a hidden tool and cannot be called directly, so it ran through "${action.name}" as "${action.args?.name}". Call hidden tools like that from now on: tool "${action.name}", arguments {"name": "${action.args?.name}", "arguments": {...}}, with the name written without the server prefix.` : `You wrote "${action.requestedName}" but the tool is named "${action.name}": the server prefix is part of the name. It ran as "${action.name}". Write the full name next time.`;
|
|
96
105
|
}
|
|
97
106
|
function propertyLabel(name, property) {
|
|
98
107
|
const type = Array.isArray(property?.type) ? property.type.join("|") : property?.type ?? property?.anyOf?.map((option) => option?.type).filter((option) => option && option !== "null").join("|");
|
|
@@ -253,7 +262,7 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
253
262
|
props.status,
|
|
254
263
|
props.goal,
|
|
255
264
|
props.nextNode,
|
|
256
|
-
props.threadId,
|
|
265
|
+
import_base.BaseEntity.toObjectId(props.threadId),
|
|
257
266
|
props.previousTaskId,
|
|
258
267
|
props.summary,
|
|
259
268
|
props.loopName,
|
|
@@ -283,9 +292,9 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
283
292
|
previousTaskId: this.previousTaskId,
|
|
284
293
|
summary: this.summary,
|
|
285
294
|
loopName: this.loopName,
|
|
286
|
-
planCount: this.planCount,
|
|
287
|
-
planOffset: this.planOffset,
|
|
288
|
-
executedOffset: this.executedOffset,
|
|
295
|
+
planCount: this.planCount || void 0,
|
|
296
|
+
planOffset: this.planOffset || void 0,
|
|
297
|
+
executedOffset: this.executedOffset || void 0,
|
|
289
298
|
scratch: this.scratch,
|
|
290
299
|
opening: this.opening,
|
|
291
300
|
turns: this.turns.length ? this.turns : void 0,
|
|
@@ -408,6 +417,12 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
408
417
|
const respond = this.actions.find((a) => a.name === RESPOND && a.status === "pending");
|
|
409
418
|
return respond ? String(respond.args?.answer ?? "") : void 0;
|
|
410
419
|
}
|
|
420
|
+
get rejectedAnswers() {
|
|
421
|
+
return this.actions.filter((a) => a.name === RESPOND && a.status === "failed").length;
|
|
422
|
+
}
|
|
423
|
+
rejectAnswer(message) {
|
|
424
|
+
this.actions.find((a) => a.name === RESPOND && a.status === "pending")?.markFailed({ message, retryable: false });
|
|
425
|
+
}
|
|
411
426
|
forceAnswer(fallback) {
|
|
412
427
|
const answer = this.pendingAnswer || fallback;
|
|
413
428
|
this.skipPending();
|
|
@@ -464,9 +479,10 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
464
479
|
const written = typeof request?.tool === "string" && request.tool.trim() ? request.tool.trim().replace(TOOL_NAMESPACE, "") : void 0;
|
|
465
480
|
const resolved = written && opts?.declaredTools ? resolveToolName(written, opts.declaredTools) : void 0;
|
|
466
481
|
const { args: given, invalid: badArguments } = parseArguments(request?.arguments);
|
|
467
|
-
const
|
|
482
|
+
const hiddenName = !resolved && written && opts?.invoker && opts.declaredTools && !opts.declaredTools.includes(written) && !NATIVE_TOOL_NAMES.includes(written) && !badArguments ? seenHiddenTool(written, opts.invoker, this.schemas) : void 0;
|
|
483
|
+
const hidden = Boolean(hiddenName);
|
|
468
484
|
const name = hidden ? opts.invoker : resolved ?? written;
|
|
469
|
-
const args = hidden ? { name:
|
|
485
|
+
const args = hidden ? { name: hiddenName, arguments: given } : given;
|
|
470
486
|
const action = this.addAction({ name: name ?? INVALID_ACTION, args, stepId: `${turn}_${position + 1}`, turn, author: opts?.author, requestedName: resolved || hidden ? written : void 0 });
|
|
471
487
|
const invalid = !name ? 'Each action needs a "tool" name' : badArguments ? badArguments : name === ASK_USER && !String(args.question ?? "").trim() ? 'ask_user requires a non-empty "question"' : name === RESPOND && !String(args.answer ?? "").trim() ? 'respond requires a non-empty "answer"' : void 0;
|
|
472
488
|
if (invalid) action.markFailed({ message: invalid, retryable: false });
|
|
@@ -522,6 +538,19 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
522
538
|
}
|
|
523
539
|
return messages;
|
|
524
540
|
}
|
|
541
|
+
get workspaceStreak() {
|
|
542
|
+
const turns = /* @__PURE__ */ new Map();
|
|
543
|
+
for (const action of this.actions) {
|
|
544
|
+
if (action.turn === void 0 || !action.name) continue;
|
|
545
|
+
turns.set(action.turn, [...turns.get(action.turn) ?? [], action.name]);
|
|
546
|
+
}
|
|
547
|
+
let count = 0;
|
|
548
|
+
for (const turn of Array.from(turns.keys()).sort((a, b) => b - a)) {
|
|
549
|
+
if (!turns.get(turn).every((name) => name === "read_context" || name === "save_context")) break;
|
|
550
|
+
count++;
|
|
551
|
+
}
|
|
552
|
+
return count;
|
|
553
|
+
}
|
|
525
554
|
get sameToolStreak() {
|
|
526
555
|
const turns = /* @__PURE__ */ new Map();
|
|
527
556
|
for (const action of this.actions) {
|
|
@@ -549,15 +578,15 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
549
578
|
get executedActions() {
|
|
550
579
|
return this.actions.filter((a) => a.isTerminal);
|
|
551
580
|
}
|
|
552
|
-
get lastExecutedAction() {
|
|
553
|
-
return this.actions.slice().reverse().find((a) => a.isTerminal);
|
|
554
|
-
}
|
|
555
581
|
get replanCount() {
|
|
556
582
|
return Math.max(0, this.planCount - this.planOffset - 1);
|
|
557
583
|
}
|
|
558
584
|
get executedSinceOpen() {
|
|
559
585
|
return Math.max(0, this.executedActions.length - this.executedOffset);
|
|
560
586
|
}
|
|
587
|
+
get lastExecutedAction() {
|
|
588
|
+
return this.actions.slice().reverse().find((a) => a.isTerminal);
|
|
589
|
+
}
|
|
561
590
|
executionHistory(maxChars = 1500) {
|
|
562
591
|
return this.executedActions.map((a) => a.promptView(maxChars));
|
|
563
592
|
}
|
|
@@ -661,5 +690,6 @@ class AgentTask extends import_base.BaseEntity {
|
|
|
661
690
|
findInvoker,
|
|
662
691
|
readPath,
|
|
663
692
|
resolveToolName,
|
|
693
|
+
seenHiddenTool,
|
|
664
694
|
stableStringify
|
|
665
695
|
});
|
|
@@ -59,9 +59,17 @@ function findInvoker(tools) {
|
|
|
59
59
|
const invokers = tools.filter((tool) => tool.name.endsWith("__invoke_tool") && tool.parameters?.properties?.name && tool.parameters?.properties?.arguments);
|
|
60
60
|
return invokers.length === 1 ? invokers[0].name : void 0;
|
|
61
61
|
}
|
|
62
|
+
function seenHiddenTool(written, invoker, schemas) {
|
|
63
|
+
if (!schemas) return void 0;
|
|
64
|
+
const separator = written.indexOf("__");
|
|
65
|
+
const namespace = invoker.slice(0, invoker.indexOf("__"));
|
|
66
|
+
if (separator > 0 && normalizeToolName(written.slice(0, separator)) !== normalizeToolName(namespace)) return void 0;
|
|
67
|
+
const bare = normalizeToolName(separator > 0 ? written.slice(separator + 2) : written);
|
|
68
|
+
return Object.keys(schemas).find((key) => normalizeToolName(key) === bare);
|
|
69
|
+
}
|
|
62
70
|
function routeNote(action) {
|
|
63
71
|
if (!action.requestedName) return void 0;
|
|
64
|
-
return action.args?.name
|
|
72
|
+
return action.name?.endsWith("__invoke_tool") && action.args?.name && !/(^|__)invoke_tool$/.test(action.requestedName) ? `"${action.requestedName}" is a hidden tool and cannot be called directly, so it ran through "${action.name}" as "${action.args?.name}". Call hidden tools like that from now on: tool "${action.name}", arguments {"name": "${action.args?.name}", "arguments": {...}}, with the name written without the server prefix.` : `You wrote "${action.requestedName}" but the tool is named "${action.name}": the server prefix is part of the name. It ran as "${action.name}". Write the full name next time.`;
|
|
65
73
|
}
|
|
66
74
|
function propertyLabel(name, property) {
|
|
67
75
|
const type = Array.isArray(property?.type) ? property.type.join("|") : property?.type ?? property?.anyOf?.map((option) => option?.type).filter((option) => option && option !== "null").join("|");
|
|
@@ -222,7 +230,7 @@ class AgentTask extends BaseEntity {
|
|
|
222
230
|
props.status,
|
|
223
231
|
props.goal,
|
|
224
232
|
props.nextNode,
|
|
225
|
-
props.threadId,
|
|
233
|
+
BaseEntity.toObjectId(props.threadId),
|
|
226
234
|
props.previousTaskId,
|
|
227
235
|
props.summary,
|
|
228
236
|
props.loopName,
|
|
@@ -252,9 +260,9 @@ class AgentTask extends BaseEntity {
|
|
|
252
260
|
previousTaskId: this.previousTaskId,
|
|
253
261
|
summary: this.summary,
|
|
254
262
|
loopName: this.loopName,
|
|
255
|
-
planCount: this.planCount,
|
|
256
|
-
planOffset: this.planOffset,
|
|
257
|
-
executedOffset: this.executedOffset,
|
|
263
|
+
planCount: this.planCount || void 0,
|
|
264
|
+
planOffset: this.planOffset || void 0,
|
|
265
|
+
executedOffset: this.executedOffset || void 0,
|
|
258
266
|
scratch: this.scratch,
|
|
259
267
|
opening: this.opening,
|
|
260
268
|
turns: this.turns.length ? this.turns : void 0,
|
|
@@ -377,6 +385,12 @@ class AgentTask extends BaseEntity {
|
|
|
377
385
|
const respond = this.actions.find((a) => a.name === RESPOND && a.status === "pending");
|
|
378
386
|
return respond ? String(respond.args?.answer ?? "") : void 0;
|
|
379
387
|
}
|
|
388
|
+
get rejectedAnswers() {
|
|
389
|
+
return this.actions.filter((a) => a.name === RESPOND && a.status === "failed").length;
|
|
390
|
+
}
|
|
391
|
+
rejectAnswer(message) {
|
|
392
|
+
this.actions.find((a) => a.name === RESPOND && a.status === "pending")?.markFailed({ message, retryable: false });
|
|
393
|
+
}
|
|
380
394
|
forceAnswer(fallback) {
|
|
381
395
|
const answer = this.pendingAnswer || fallback;
|
|
382
396
|
this.skipPending();
|
|
@@ -433,9 +447,10 @@ class AgentTask extends BaseEntity {
|
|
|
433
447
|
const written = typeof request?.tool === "string" && request.tool.trim() ? request.tool.trim().replace(TOOL_NAMESPACE, "") : void 0;
|
|
434
448
|
const resolved = written && opts?.declaredTools ? resolveToolName(written, opts.declaredTools) : void 0;
|
|
435
449
|
const { args: given, invalid: badArguments } = parseArguments(request?.arguments);
|
|
436
|
-
const
|
|
450
|
+
const hiddenName = !resolved && written && opts?.invoker && opts.declaredTools && !opts.declaredTools.includes(written) && !NATIVE_TOOL_NAMES.includes(written) && !badArguments ? seenHiddenTool(written, opts.invoker, this.schemas) : void 0;
|
|
451
|
+
const hidden = Boolean(hiddenName);
|
|
437
452
|
const name = hidden ? opts.invoker : resolved ?? written;
|
|
438
|
-
const args = hidden ? { name:
|
|
453
|
+
const args = hidden ? { name: hiddenName, arguments: given } : given;
|
|
439
454
|
const action = this.addAction({ name: name ?? INVALID_ACTION, args, stepId: `${turn}_${position + 1}`, turn, author: opts?.author, requestedName: resolved || hidden ? written : void 0 });
|
|
440
455
|
const invalid = !name ? 'Each action needs a "tool" name' : badArguments ? badArguments : name === ASK_USER && !String(args.question ?? "").trim() ? 'ask_user requires a non-empty "question"' : name === RESPOND && !String(args.answer ?? "").trim() ? 'respond requires a non-empty "answer"' : void 0;
|
|
441
456
|
if (invalid) action.markFailed({ message: invalid, retryable: false });
|
|
@@ -491,6 +506,19 @@ class AgentTask extends BaseEntity {
|
|
|
491
506
|
}
|
|
492
507
|
return messages;
|
|
493
508
|
}
|
|
509
|
+
get workspaceStreak() {
|
|
510
|
+
const turns = /* @__PURE__ */ new Map();
|
|
511
|
+
for (const action of this.actions) {
|
|
512
|
+
if (action.turn === void 0 || !action.name) continue;
|
|
513
|
+
turns.set(action.turn, [...turns.get(action.turn) ?? [], action.name]);
|
|
514
|
+
}
|
|
515
|
+
let count = 0;
|
|
516
|
+
for (const turn of Array.from(turns.keys()).sort((a, b) => b - a)) {
|
|
517
|
+
if (!turns.get(turn).every((name) => name === "read_context" || name === "save_context")) break;
|
|
518
|
+
count++;
|
|
519
|
+
}
|
|
520
|
+
return count;
|
|
521
|
+
}
|
|
494
522
|
get sameToolStreak() {
|
|
495
523
|
const turns = /* @__PURE__ */ new Map();
|
|
496
524
|
for (const action of this.actions) {
|
|
@@ -518,15 +546,15 @@ class AgentTask extends BaseEntity {
|
|
|
518
546
|
get executedActions() {
|
|
519
547
|
return this.actions.filter((a) => a.isTerminal);
|
|
520
548
|
}
|
|
521
|
-
get lastExecutedAction() {
|
|
522
|
-
return this.actions.slice().reverse().find((a) => a.isTerminal);
|
|
523
|
-
}
|
|
524
549
|
get replanCount() {
|
|
525
550
|
return Math.max(0, this.planCount - this.planOffset - 1);
|
|
526
551
|
}
|
|
527
552
|
get executedSinceOpen() {
|
|
528
553
|
return Math.max(0, this.executedActions.length - this.executedOffset);
|
|
529
554
|
}
|
|
555
|
+
get lastExecutedAction() {
|
|
556
|
+
return this.actions.slice().reverse().find((a) => a.isTerminal);
|
|
557
|
+
}
|
|
530
558
|
executionHistory(maxChars = 1500) {
|
|
531
559
|
return this.executedActions.map((a) => a.promptView(maxChars));
|
|
532
560
|
}
|
|
@@ -629,5 +657,6 @@ export {
|
|
|
629
657
|
findInvoker,
|
|
630
658
|
readPath,
|
|
631
659
|
resolveToolName,
|
|
660
|
+
seenHiddenTool,
|
|
632
661
|
stableStringify
|
|
633
662
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "openloops",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.35",
|
|
4
4
|
"description": "Framework to build AI Agents",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Jose Barcos",
|
|
@@ -72,7 +72,10 @@
|
|
|
72
72
|
"prepublishOnly": "yarn build",
|
|
73
73
|
"check-size": "npm pack --dry-run",
|
|
74
74
|
"release": "npm version patch && npm publish --access public",
|
|
75
|
-
"push": "git push --follow-tags"
|
|
75
|
+
"push": "git push --follow-tags",
|
|
76
|
+
"test": "jest",
|
|
77
|
+
"test:watch": "jest --watch",
|
|
78
|
+
"test:coverage": "jest --coverage"
|
|
76
79
|
},
|
|
77
80
|
"dependencies": {
|
|
78
81
|
"@earendil-works/pi-ai": "^1.0.4",
|