openloops 0.1.32 → 0.1.33

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.
@@ -30,6 +30,40 @@ const SEARCH_DESCRIPTION_CHARS = 300;
30
30
  const SEARCH_OUTPUT_CHARS = 5500;
31
31
  const DEFAULT_READ_CHARS = 4e3;
32
32
  const MAX_READ_CHARS = 5e3;
33
+ const MAX_FIND_MATCHES = 20;
34
+ const FIND_RECORD_CHARS = 600;
35
+ const FIND_MAX_NODES = 2e5;
36
+ const FIND_MAX_DEPTH = 12;
37
+ function squash(text) {
38
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
39
+ }
40
+ function findRecords(root, query) {
41
+ const wanted = squash(query);
42
+ const words = query.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
43
+ if (!wanted) return [];
44
+ const search = (matches) => {
45
+ const found = [];
46
+ const seen = /* @__PURE__ */ new Set();
47
+ let nodes = 0;
48
+ const walk = (value, path, parent, depth) => {
49
+ if (nodes++ > FIND_MAX_NODES || depth > FIND_MAX_DEPTH) return;
50
+ if (typeof value === "string") {
51
+ const record = parent !== null && typeof parent === "object" && !Array.isArray(parent) ? parent : value;
52
+ if (matches(value) && !seen.has(record)) {
53
+ seen.add(record);
54
+ found.push({ path, record });
55
+ }
56
+ return;
57
+ }
58
+ if (Array.isArray(value)) value.forEach((item, index) => walk(item, `${path}[${index}]`, value, depth + 1));
59
+ else if (value !== null && typeof value === "object") Object.entries(value).forEach(([key, item]) => walk(item, path ? `${path}.${key}` : key, value, depth + 1));
60
+ };
61
+ walk(root, "", null, 0);
62
+ return found;
63
+ };
64
+ const exact = search((text) => squash(text).includes(wanted));
65
+ return exact.length || words.length < 2 ? exact : search((text) => words.every((word) => squash(text).includes(squash(word))));
66
+ }
33
67
  const NATIVE_TOOLS = [
34
68
  {
35
69
  name: "search_tools",
@@ -57,12 +91,13 @@ const NATIVE_TOOLS = [
57
91
  },
58
92
  {
59
93
  name: "read_context",
60
- description: 'Read a workspace item: a note saved with save_context, or a large tool output (use the "workspace_ref" name from its result). Supports a path into structured content and paging for long text.',
94
+ description: 'Read a workspace item: a note saved with save_context, or a large tool output (use the "workspace_ref" name from its result as "name"). Supports a path into structured content, paging for long text, and "find" to locate entries inside a large result by text.',
61
95
  parameters: {
62
96
  type: "object",
63
97
  properties: {
64
98
  name: { type: "string", description: "Name of the workspace item" },
65
99
  path: { type: "string", description: "Optional path into structured content, like results[0].id" },
100
+ find: { type: "string", description: 'Text to look for inside the item (or inside "path"). Case, spaces, hyphens and underscores are ignored. Returns only the matching entries with their path, so you do not have to read a long list' },
66
101
  offset: { type: "integer", description: "Character offset to start reading from (default 0)" },
67
102
  max_chars: { type: "integer", description: `Maximum characters to return (default ${DEFAULT_READ_CHARS}, max ${MAX_READ_CHARS})` }
68
103
  },
@@ -153,10 +188,28 @@ class NativeTools {
153
188
  }
154
189
  async readContext(task, args) {
155
190
  const item = await this.deps.workspace.get(String(args.name), { taskId: task.id });
156
- if (!item) return { found: false };
191
+ if (!item) {
192
+ const available = await this.deps.workspace.list({ taskId: task.id }).then((items) => items.map((entry) => entry.name).slice(0, 30)).catch(() => []);
193
+ return { found: false, error: `There is no workspace item named "${args.name}". This does not mean a search had no results.`, available };
194
+ }
157
195
  const path = args.path ? String(args.path).replace(/^(?=[\w-])/, ".") : void 0;
158
196
  const value = (0, import_agent_task.readPath)(item.content, path);
159
197
  if (value === void 0) return { found: true, name: item.name, path_found: false };
198
+ if (typeof args.find === "string" && args.find.trim()) {
199
+ const found = findRecords(value, args.find);
200
+ return {
201
+ name: item.name,
202
+ find: args.find,
203
+ total_matches: found.length,
204
+ matches: found.slice(0, MAX_FIND_MATCHES).map(({ path: matchPath, record }) => {
205
+ const text2 = typeof record === "string" ? record : JSON.stringify(record);
206
+ return { path: matchPath, record: text2.length > FIND_RECORD_CHARS ? text2.slice(0, FIND_RECORD_CHARS) : record };
207
+ }),
208
+ ...found.length > MAX_FIND_MATCHES ? { note: `Showing the first ${MAX_FIND_MATCHES} matches: use a more specific text.` } : {},
209
+ ...found.length ? {} : { hint: "No entry contains this text. Try a shorter or different part of it, or read the item with a path." },
210
+ ...item.truncated ? { stored_truncated: true } : {}
211
+ };
212
+ }
160
213
  const text = typeof value === "string" ? value : JSON.stringify(value);
161
214
  const offset = Math.max(Number(args.offset) || 0, 0);
162
215
  const max = Math.min(Math.max(Number(args.max_chars) || DEFAULT_READ_CHARS, 1), MAX_READ_CHARS);
@@ -7,6 +7,40 @@ const SEARCH_DESCRIPTION_CHARS = 300;
7
7
  const SEARCH_OUTPUT_CHARS = 5500;
8
8
  const DEFAULT_READ_CHARS = 4e3;
9
9
  const MAX_READ_CHARS = 5e3;
10
+ const MAX_FIND_MATCHES = 20;
11
+ const FIND_RECORD_CHARS = 600;
12
+ const FIND_MAX_NODES = 2e5;
13
+ const FIND_MAX_DEPTH = 12;
14
+ function squash(text) {
15
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]/gu, "");
16
+ }
17
+ function findRecords(root, query) {
18
+ const wanted = squash(query);
19
+ const words = query.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
20
+ if (!wanted) return [];
21
+ const search = (matches) => {
22
+ const found = [];
23
+ const seen = /* @__PURE__ */ new Set();
24
+ let nodes = 0;
25
+ const walk = (value, path, parent, depth) => {
26
+ if (nodes++ > FIND_MAX_NODES || depth > FIND_MAX_DEPTH) return;
27
+ if (typeof value === "string") {
28
+ const record = parent !== null && typeof parent === "object" && !Array.isArray(parent) ? parent : value;
29
+ if (matches(value) && !seen.has(record)) {
30
+ seen.add(record);
31
+ found.push({ path, record });
32
+ }
33
+ return;
34
+ }
35
+ if (Array.isArray(value)) value.forEach((item, index) => walk(item, `${path}[${index}]`, value, depth + 1));
36
+ else if (value !== null && typeof value === "object") Object.entries(value).forEach(([key, item]) => walk(item, path ? `${path}.${key}` : key, value, depth + 1));
37
+ };
38
+ walk(root, "", null, 0);
39
+ return found;
40
+ };
41
+ const exact = search((text) => squash(text).includes(wanted));
42
+ return exact.length || words.length < 2 ? exact : search((text) => words.every((word) => squash(text).includes(squash(word))));
43
+ }
10
44
  const NATIVE_TOOLS = [
11
45
  {
12
46
  name: "search_tools",
@@ -34,12 +68,13 @@ const NATIVE_TOOLS = [
34
68
  },
35
69
  {
36
70
  name: "read_context",
37
- description: 'Read a workspace item: a note saved with save_context, or a large tool output (use the "workspace_ref" name from its result). Supports a path into structured content and paging for long text.',
71
+ description: 'Read a workspace item: a note saved with save_context, or a large tool output (use the "workspace_ref" name from its result as "name"). Supports a path into structured content, paging for long text, and "find" to locate entries inside a large result by text.',
38
72
  parameters: {
39
73
  type: "object",
40
74
  properties: {
41
75
  name: { type: "string", description: "Name of the workspace item" },
42
76
  path: { type: "string", description: "Optional path into structured content, like results[0].id" },
77
+ find: { type: "string", description: 'Text to look for inside the item (or inside "path"). Case, spaces, hyphens and underscores are ignored. Returns only the matching entries with their path, so you do not have to read a long list' },
43
78
  offset: { type: "integer", description: "Character offset to start reading from (default 0)" },
44
79
  max_chars: { type: "integer", description: `Maximum characters to return (default ${DEFAULT_READ_CHARS}, max ${MAX_READ_CHARS})` }
45
80
  },
@@ -130,10 +165,28 @@ class NativeTools {
130
165
  }
131
166
  async readContext(task, args) {
132
167
  const item = await this.deps.workspace.get(String(args.name), { taskId: task.id });
133
- if (!item) return { found: false };
168
+ if (!item) {
169
+ const available = await this.deps.workspace.list({ taskId: task.id }).then((items) => items.map((entry) => entry.name).slice(0, 30)).catch(() => []);
170
+ return { found: false, error: `There is no workspace item named "${args.name}". This does not mean a search had no results.`, available };
171
+ }
134
172
  const path = args.path ? String(args.path).replace(/^(?=[\w-])/, ".") : void 0;
135
173
  const value = readPath(item.content, path);
136
174
  if (value === void 0) return { found: true, name: item.name, path_found: false };
175
+ if (typeof args.find === "string" && args.find.trim()) {
176
+ const found = findRecords(value, args.find);
177
+ return {
178
+ name: item.name,
179
+ find: args.find,
180
+ total_matches: found.length,
181
+ matches: found.slice(0, MAX_FIND_MATCHES).map(({ path: matchPath, record }) => {
182
+ const text2 = typeof record === "string" ? record : JSON.stringify(record);
183
+ return { path: matchPath, record: text2.length > FIND_RECORD_CHARS ? text2.slice(0, FIND_RECORD_CHARS) : record };
184
+ }),
185
+ ...found.length > MAX_FIND_MATCHES ? { note: `Showing the first ${MAX_FIND_MATCHES} matches: use a more specific text.` } : {},
186
+ ...found.length ? {} : { hint: "No entry contains this text. Try a shorter or different part of it, or read the item with a path." },
187
+ ...item.truncated ? { stored_truncated: true } : {}
188
+ };
189
+ }
137
190
  const text = typeof value === "string" ? value : JSON.stringify(value);
138
191
  const offset = Math.max(Number(args.offset) || 0, 0);
139
192
  const max = Math.min(Math.max(Number(args.max_chars) || DEFAULT_READ_CHARS, 1), MAX_READ_CHARS);
@@ -27,6 +27,7 @@ var import_agent_task = require("../services/tasks/entities/agent-task.entity.js
27
27
  var import_tool_catalog = require("./tool-catalog");
28
28
  var import_native_tools = require("./native-tools");
29
29
  var import_describe_shape = require("./utils/describe-shape");
30
+ var import_grounding = require("./utils/grounding");
30
31
  const DEFAULT_OFFLOAD_THRESHOLD_CHARS = 1e5;
31
32
  const DEFAULT_STUB_THRESHOLD_CHARS = 4e3;
32
33
  const TRANSIENT_PATTERN = /timeout|timed out|econn|enotfound|network|socket|\b50[234]\b|\b429\b|rate limit|temporar|unavailable|overloaded/i;
@@ -60,7 +61,9 @@ class ToolPipeline {
60
61
  const similar = this.deps.tools().map((tool) => tool.name).filter((toolName) => toolName.toLowerCase().endsWith(suffix));
61
62
  if (similar.length) return `${base} Tool names include the server prefix, written in full. Did you mean ${similar.map((toolName) => `"${toolName}"`).join(" or ")}?`;
62
63
  if (!invokers.length) return `${base} Use the exact tool names from your tool list.`;
63
- const example = JSON.stringify({ tool: invokers[0], arguments: { name, arguments: {} } });
64
+ const namespace = `${invokers[0].slice(0, invokers[0].indexOf("__"))}__`;
65
+ const bare = name.startsWith(namespace) ? name.slice(namespace.length) : name;
66
+ const example = JSON.stringify({ tool: invokers[0], arguments: { name: bare, arguments: {} } });
64
67
  return `${base} It is a hidden tool of a server, so it cannot be called directly. Run it through the server's invoke tool (${invokers.join(", ")}) like this: ${example}, filling "arguments" with the input schema returned by the server's search.`;
65
68
  }
66
69
  searchUnavailableMessage() {
@@ -99,6 +102,11 @@ class ToolPipeline {
99
102
  action.markFailed({ message: `Unresolved references in arguments: ${unresolved.join(", ")}. The referenced step output or path does not exist.`, retryable: false });
100
103
  return action;
101
104
  }
105
+ const invented = await (0, import_grounding.ungroundedIdentifiers)(task, this.deps.workspace, (0, import_grounding.collectStrings)(args));
106
+ if (invented.length) {
107
+ action.markFailed({ message: `The identifier${invented.length > 1 ? "s" : ""} ${invented.map((id) => `"${id}"`).join(", ")} in the arguments of "${action.name}" ${invented.length > 1 ? "were" : "was"} ${import_grounding.UNGROUNDED_PHRASE}, so ${invented.length > 1 ? "they look" : "it looks"} invented. Identifiers cannot be guessed: get the value from a tool that lists or looks up that entity, or ask the user. If the user gave it earlier in the conversation, ask them to confirm it.`, retryable: false });
108
+ return action;
109
+ }
102
110
  const failedBefore = task.findExecuted(action.name, args, { status: "failed", exclude: action });
103
111
  if (failedBefore && !TRANSIENT_PATTERN.test(failedBefore.error?.message ?? "")) {
104
112
  const previous = String(failedBefore.error?.message ?? "").slice(0, 500);
@@ -5,6 +5,7 @@ import { AgentTask, NATIVE_TOOL_NAMES, SEARCH_TOOLS } from "../services/tasks/en
5
5
  import { needsSearch } from "./tool-catalog";
6
6
  import { NativeTools } from "./native-tools";
7
7
  import { describeShapeWithin } from "./utils/describe-shape";
8
+ import { collectStrings, ungroundedIdentifiers, UNGROUNDED_PHRASE } from "./utils/grounding";
8
9
  const DEFAULT_OFFLOAD_THRESHOLD_CHARS = 1e5;
9
10
  const DEFAULT_STUB_THRESHOLD_CHARS = 4e3;
10
11
  const TRANSIENT_PATTERN = /timeout|timed out|econn|enotfound|network|socket|\b50[234]\b|\b429\b|rate limit|temporar|unavailable|overloaded/i;
@@ -38,7 +39,9 @@ class ToolPipeline {
38
39
  const similar = this.deps.tools().map((tool) => tool.name).filter((toolName) => toolName.toLowerCase().endsWith(suffix));
39
40
  if (similar.length) return `${base} Tool names include the server prefix, written in full. Did you mean ${similar.map((toolName) => `"${toolName}"`).join(" or ")}?`;
40
41
  if (!invokers.length) return `${base} Use the exact tool names from your tool list.`;
41
- const example = JSON.stringify({ tool: invokers[0], arguments: { name, arguments: {} } });
42
+ const namespace = `${invokers[0].slice(0, invokers[0].indexOf("__"))}__`;
43
+ const bare = name.startsWith(namespace) ? name.slice(namespace.length) : name;
44
+ const example = JSON.stringify({ tool: invokers[0], arguments: { name: bare, arguments: {} } });
42
45
  return `${base} It is a hidden tool of a server, so it cannot be called directly. Run it through the server's invoke tool (${invokers.join(", ")}) like this: ${example}, filling "arguments" with the input schema returned by the server's search.`;
43
46
  }
44
47
  searchUnavailableMessage() {
@@ -77,6 +80,11 @@ class ToolPipeline {
77
80
  action.markFailed({ message: `Unresolved references in arguments: ${unresolved.join(", ")}. The referenced step output or path does not exist.`, retryable: false });
78
81
  return action;
79
82
  }
83
+ const invented = await ungroundedIdentifiers(task, this.deps.workspace, collectStrings(args));
84
+ if (invented.length) {
85
+ action.markFailed({ message: `The identifier${invented.length > 1 ? "s" : ""} ${invented.map((id) => `"${id}"`).join(", ")} in the arguments of "${action.name}" ${invented.length > 1 ? "were" : "was"} ${UNGROUNDED_PHRASE}, so ${invented.length > 1 ? "they look" : "it looks"} invented. Identifiers cannot be guessed: get the value from a tool that lists or looks up that entity, or ask the user. If the user gave it earlier in the conversation, ask them to confirm it.`, retryable: false });
86
+ return action;
87
+ }
80
88
  const failedBefore = task.findExecuted(action.name, args, { status: "failed", exclude: action });
81
89
  if (failedBefore && !TRANSIENT_PATTERN.test(failedBefore.error?.message ?? "")) {
82
90
  const previous = String(failedBefore.error?.message ?? "").slice(0, 500);
@@ -0,0 +1,6 @@
1
+ import { AgentTask } from '../../services/tasks/entities/agent-task.entity.js';
2
+ import { Workspace } from '../workspace';
3
+ export declare const UNGROUNDED_PHRASE = "not found in the user's messages or in any result";
4
+ export declare function collectStrings(value: any, found?: string[], depth?: number): string[];
5
+ export declare function opaqueIdentifiers(texts: string[]): string[];
6
+ export declare function ungroundedIdentifiers(task: AgentTask, workspace: Workspace, texts: string[]): Promise<string[]>;
@@ -0,0 +1,79 @@
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 grounding_exports = {};
20
+ __export(grounding_exports, {
21
+ UNGROUNDED_PHRASE: () => UNGROUNDED_PHRASE,
22
+ collectStrings: () => collectStrings,
23
+ opaqueIdentifiers: () => opaqueIdentifiers,
24
+ ungroundedIdentifiers: () => ungroundedIdentifiers
25
+ });
26
+ module.exports = __toCommonJS(grounding_exports);
27
+ const IDENTIFIER_IN_TEXT = /\b(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,64})\b/gi;
28
+ const USER_ANSWER_PREFIX = "user_answer_";
29
+ const MAX_DEPTH = 8;
30
+ const UNGROUNDED_PHRASE = "not found in the user's messages or in any result";
31
+ function collectStrings(value, found = [], depth = 0) {
32
+ if (depth > MAX_DEPTH) return found;
33
+ if (typeof value === "string") found.push(value);
34
+ else if (Array.isArray(value)) value.forEach((item) => collectStrings(item, found, depth + 1));
35
+ else if (value !== null && typeof value === "object") Object.values(value).forEach((item) => collectStrings(item, found, depth + 1));
36
+ return found;
37
+ }
38
+ function opaqueIdentifiers(texts) {
39
+ const found = /* @__PURE__ */ new Set();
40
+ for (const text of texts) {
41
+ for (const match of text.match(IDENTIFIER_IN_TEXT) ?? []) {
42
+ if (/\d/.test(match)) found.add(match);
43
+ }
44
+ }
45
+ return Array.from(found);
46
+ }
47
+ async function groundingCorpus(task, workspace) {
48
+ const parts = [task.opening ?? ""];
49
+ for (const [key, value] of Object.entries(task.known ?? {})) {
50
+ if (key.startsWith(USER_ANSWER_PREFIX)) parts.push(String(value));
51
+ }
52
+ for (const action of task.actions) {
53
+ if (action.error?.message && !String(action.error.message).includes(UNGROUNDED_PHRASE)) parts.push(String(action.error.message));
54
+ if (action.output !== void 0) parts.push(JSON.stringify(action.output));
55
+ if (action.outputRef) {
56
+ try {
57
+ const item = await workspace.get(action.outputRef, { taskId: task.id });
58
+ if (item?.content !== void 0) parts.push(typeof item.content === "string" ? item.content : JSON.stringify(item.content));
59
+ } catch {
60
+ return void 0;
61
+ }
62
+ }
63
+ }
64
+ return parts.join("\n").toLowerCase();
65
+ }
66
+ async function ungroundedIdentifiers(task, workspace, texts) {
67
+ const candidates = opaqueIdentifiers(texts);
68
+ if (!candidates.length) return [];
69
+ const corpus = await groundingCorpus(task, workspace);
70
+ if (corpus === void 0) return [];
71
+ return candidates.filter((candidate) => !corpus.includes(candidate.toLowerCase()));
72
+ }
73
+ // Annotate the CommonJS export names for ESM import in node:
74
+ 0 && (module.exports = {
75
+ UNGROUNDED_PHRASE,
76
+ collectStrings,
77
+ opaqueIdentifiers,
78
+ ungroundedIdentifiers
79
+ });
@@ -0,0 +1,53 @@
1
+ import "../../chunk-CF3WOMB3.mjs";
2
+ const IDENTIFIER_IN_TEXT = /\b(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,64})\b/gi;
3
+ const USER_ANSWER_PREFIX = "user_answer_";
4
+ const MAX_DEPTH = 8;
5
+ const UNGROUNDED_PHRASE = "not found in the user's messages or in any result";
6
+ function collectStrings(value, found = [], depth = 0) {
7
+ if (depth > MAX_DEPTH) return found;
8
+ if (typeof value === "string") found.push(value);
9
+ else if (Array.isArray(value)) value.forEach((item) => collectStrings(item, found, depth + 1));
10
+ else if (value !== null && typeof value === "object") Object.values(value).forEach((item) => collectStrings(item, found, depth + 1));
11
+ return found;
12
+ }
13
+ function opaqueIdentifiers(texts) {
14
+ const found = /* @__PURE__ */ new Set();
15
+ for (const text of texts) {
16
+ for (const match of text.match(IDENTIFIER_IN_TEXT) ?? []) {
17
+ if (/\d/.test(match)) found.add(match);
18
+ }
19
+ }
20
+ return Array.from(found);
21
+ }
22
+ async function groundingCorpus(task, workspace) {
23
+ const parts = [task.opening ?? ""];
24
+ for (const [key, value] of Object.entries(task.known ?? {})) {
25
+ if (key.startsWith(USER_ANSWER_PREFIX)) parts.push(String(value));
26
+ }
27
+ for (const action of task.actions) {
28
+ if (action.error?.message && !String(action.error.message).includes(UNGROUNDED_PHRASE)) parts.push(String(action.error.message));
29
+ if (action.output !== void 0) parts.push(JSON.stringify(action.output));
30
+ if (action.outputRef) {
31
+ try {
32
+ const item = await workspace.get(action.outputRef, { taskId: task.id });
33
+ if (item?.content !== void 0) parts.push(typeof item.content === "string" ? item.content : JSON.stringify(item.content));
34
+ } catch {
35
+ return void 0;
36
+ }
37
+ }
38
+ }
39
+ return parts.join("\n").toLowerCase();
40
+ }
41
+ async function ungroundedIdentifiers(task, workspace, texts) {
42
+ const candidates = opaqueIdentifiers(texts);
43
+ if (!candidates.length) return [];
44
+ const corpus = await groundingCorpus(task, workspace);
45
+ if (corpus === void 0) return [];
46
+ return candidates.filter((candidate) => !corpus.includes(candidate.toLowerCase()));
47
+ }
48
+ export {
49
+ UNGROUNDED_PHRASE,
50
+ collectStrings,
51
+ opaqueIdentifiers,
52
+ ungroundedIdentifiers
53
+ };
@@ -24,11 +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;
33
+ const MAX_ANSWER_REJECTIONS = 1;
34
+ const WARN_WORKSPACE_TURNS = 3;
35
+ const MAX_WORKSPACE_TURNS = 7;
32
36
  const SUMMARY_CHARS = 400;
33
37
  const BLOCK_DUPLICATES = false;
34
38
  class AgiLoop extends import_harness.AgentLoop {
@@ -91,15 +95,18 @@ class AgiLoop extends import_harness.AgentLoop {
91
95
  task.answerQuestion(ctx.currentMessage);
92
96
  const streak = task.sameToolStreak;
93
97
  const exhausted = task.turnCount >= MAX_TURNS || task.toolCallCount >= MAX_TOOL_CALLS;
98
+ const workspaceTurns = task.workspaceStreak;
94
99
  const stuck = streak.count >= MAX_SAME_TOOL;
95
- 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` : void 0;
100
+ const lost = workspaceTurns >= MAX_WORKSPACE_TURNS;
101
+ 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;
102
+ 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
103
  const lastCompletedTask = ctx.chat.lastCompletedTask();
97
104
  const catalog = await ctx.toolCatalog();
98
105
  const result = await import_reasoning_engine.reasoningEngine.run({
99
106
  ...ctx.skillParams,
100
107
  history: task.history({
101
108
  budget: { turns_left: MAX_TURNS - task.turnCount, tool_calls_left: MAX_TOOL_CALLS - task.toolCallCount },
102
- ...streak.count >= WARN_SAME_TOOL ? { warning: `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.` } : {},
109
+ ...warning ? { warning } : {},
103
110
  ...task.known ? { known: task.known } : {},
104
111
  ...task.schemas ? { schemas: task.schemas } : {},
105
112
  ...stopReason ? { stop_reason: stopReason } : {}
@@ -147,6 +154,12 @@ class AgiLoop extends import_harness.AgentLoop {
147
154
  }
148
155
  const answer = task.pendingAnswer;
149
156
  if (answer !== void 0) {
157
+ const invented = task.rejectedAnswers < MAX_ANSWER_REJECTIONS ? await (0, import_grounding.ungroundedIdentifiers)(task, ctx.workspace, [answer]) : [];
158
+ if (invented.length) {
159
+ 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.`);
160
+ ctx.setNextNode(this.nodes.reasoning_engine);
161
+ return;
162
+ }
150
163
  task.deliverAnswer();
151
164
  ctx.reply(answer);
152
165
  ctx.chat.completeTask(task.id, answer.slice(0, SUMMARY_CHARS));
@@ -2,11 +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;
11
+ const MAX_ANSWER_REJECTIONS = 1;
12
+ const WARN_WORKSPACE_TURNS = 3;
13
+ const MAX_WORKSPACE_TURNS = 7;
10
14
  const SUMMARY_CHARS = 400;
11
15
  const BLOCK_DUPLICATES = false;
12
16
  class AgiLoop extends AgentLoop {
@@ -69,15 +73,18 @@ class AgiLoop extends AgentLoop {
69
73
  task.answerQuestion(ctx.currentMessage);
70
74
  const streak = task.sameToolStreak;
71
75
  const exhausted = task.turnCount >= MAX_TURNS || task.toolCallCount >= MAX_TOOL_CALLS;
76
+ const workspaceTurns = task.workspaceStreak;
72
77
  const stuck = streak.count >= MAX_SAME_TOOL;
73
- 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` : void 0;
78
+ const lost = workspaceTurns >= MAX_WORKSPACE_TURNS;
79
+ 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;
80
+ 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
81
  const lastCompletedTask = ctx.chat.lastCompletedTask();
75
82
  const catalog = await ctx.toolCatalog();
76
83
  const result = await reasoningEngine.run({
77
84
  ...ctx.skillParams,
78
85
  history: task.history({
79
86
  budget: { turns_left: MAX_TURNS - task.turnCount, tool_calls_left: MAX_TOOL_CALLS - task.toolCallCount },
80
- ...streak.count >= WARN_SAME_TOOL ? { warning: `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.` } : {},
87
+ ...warning ? { warning } : {},
81
88
  ...task.known ? { known: task.known } : {},
82
89
  ...task.schemas ? { schemas: task.schemas } : {},
83
90
  ...stopReason ? { stop_reason: stopReason } : {}
@@ -125,6 +132,12 @@ class AgiLoop extends AgentLoop {
125
132
  }
126
133
  const answer = task.pendingAnswer;
127
134
  if (answer !== void 0) {
135
+ const invented = task.rejectedAnswers < MAX_ANSWER_REJECTIONS ? await ungroundedIdentifiers(task, ctx.workspace, [answer]) : [];
136
+ if (invented.length) {
137
+ 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.`);
138
+ ctx.setNextNode(this.nodes.reasoning_engine);
139
+ return;
140
+ }
128
141
  task.deliverAnswer();
129
142
  ctx.reply(answer);
130
143
  ctx.chat.completeTask(task.id, answer.slice(0, SUMMARY_CHARS));
@@ -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.",
@@ -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
- const STUB_NOTE = "Partial view: the preview is only the beginning of the result. Do not take values from it as the ones you need; load the part you need with read_context.";
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: STUB_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
- const STUB_NOTE = "Partial view: the preview is only the beginning of the result. Do not take values from it as the ones you need; load the part you need with read_context.";
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: STUB_NOTE
195
+ note: stubNote(offloaded.ref)
194
196
  };
195
197
  }
196
198
  offloadOutput(offloaded) {
@@ -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 {
@@ -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;
@@ -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 === action.requestedName ? `"${action.requestedName}" is a hidden tool and cannot be called directly, so it ran through "${action.name}". Call hidden tools like that from now on: tool "${action.name}", arguments {"name": "${action.requestedName}", "arguments": {...}}.` : `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.`;
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("|");
@@ -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 hidden = !resolved && written && opts?.invoker && opts.declaredTools && !opts.declaredTools.includes(written) && !NATIVE_TOOL_NAMES.includes(written) && this.schemas?.[written] && !badArguments;
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: written, arguments: given } : given;
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) {
@@ -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 === action.requestedName ? `"${action.requestedName}" is a hidden tool and cannot be called directly, so it ran through "${action.name}". Call hidden tools like that from now on: tool "${action.name}", arguments {"name": "${action.requestedName}", "arguments": {...}}.` : `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.`;
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("|");
@@ -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 hidden = !resolved && written && opts?.invoker && opts.declaredTools && !opts.declaredTools.includes(written) && !NATIVE_TOOL_NAMES.includes(written) && this.schemas?.[written] && !badArguments;
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: written, arguments: given } : given;
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) {
@@ -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.32",
3
+ "version": "0.1.33",
4
4
  "description": "Framework to build AI Agents",
5
5
  "author": {
6
6
  "name": "Jose Barcos",