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.
Files changed (30) hide show
  1. package/dist/clients/llm-client.d.ts +2 -0
  2. package/dist/clients/llm-client.js +15 -3
  3. package/dist/clients/llm-client.mjs +16 -4
  4. package/dist/clients/llm-error.d.ts +2 -1
  5. package/dist/clients/llm-error.js +10 -0
  6. package/dist/clients/llm-error.mjs +9 -0
  7. package/dist/common/base/base.entity.d.ts +2 -1
  8. package/dist/harness/agent.js +2 -0
  9. package/dist/harness/agent.mjs +3 -1
  10. package/dist/harness/native-tools.js +55 -2
  11. package/dist/harness/native-tools.mjs +55 -2
  12. package/dist/harness/tool-pipeline.js +9 -1
  13. package/dist/harness/tool-pipeline.mjs +9 -1
  14. package/dist/harness/utils/grounding.d.ts +6 -0
  15. package/dist/harness/utils/grounding.js +79 -0
  16. package/dist/harness/utils/grounding.mjs +53 -0
  17. package/dist/loops/agi/loop.js +17 -5
  18. package/dist/loops/agi/loop.mjs +17 -5
  19. package/dist/loops/agi/skills/reasoning-engine.js +2 -1
  20. package/dist/loops/agi/skills/reasoning-engine.mjs +2 -1
  21. package/dist/services/chats/entities/chat.entity.js +3 -1
  22. package/dist/services/chats/entities/chat.entity.mjs +3 -1
  23. package/dist/services/chats/lambdas/update-chat/update-chat.use-case.js +5 -0
  24. package/dist/services/chats/lambdas/update-chat/update-chat.use-case.mjs +5 -0
  25. package/dist/services/tasks/entities/agent-action.entity.js +4 -2
  26. package/dist/services/tasks/entities/agent-action.entity.mjs +4 -2
  27. package/dist/services/tasks/entities/agent-task.entity.d.ts +8 -4
  28. package/dist/services/tasks/entities/agent-task.entity.js +40 -10
  29. package/dist/services/tasks/entities/agent-task.entity.mjs +39 -10
  30. package/package.json +5 -2
@@ -2,12 +2,14 @@ import type { KnownProvider, Message, AssistantMessage } from '@earendil-works/p
2
2
  import { CurrentUser } from '../common/base/index.js';
3
3
  import { LLMChatParams, LLMResponse } from './llm-types';
4
4
  export declare class LLMClient {
5
+ private static readonly modelsWithoutTemperature;
5
6
  private readonly logger;
6
7
  private readonly langfuse?;
7
8
  private readonly langfuseEnabled;
8
9
  constructor();
9
10
  chat(params: LLMChatParams): Promise<LLMResponse>;
10
11
  complete(params: LLMCompletionParams): Promise<AssistantMessage>;
12
+ private withoutRejectedTemperature;
11
13
  private waitingOnRateLimit;
12
14
  private traced;
13
15
  private postResponse;
@@ -44,6 +44,7 @@ const DEFAULT_TEMPERATURE = 0.7;
44
44
  const MAX_RETRIES = 4;
45
45
  const MAX_RATE_LIMIT_WAITS = 2;
46
46
  class LLMClient {
47
+ static modelsWithoutTemperature = /* @__PURE__ */ new Set();
47
48
  logger = new import_logger.Logger();
48
49
  langfuse;
49
50
  langfuseEnabled;
@@ -78,11 +79,14 @@ class LLMClient {
78
79
  const model = models.getModel(provider, modelName);
79
80
  if (!model) throw new Error("[LLM Client] model not found");
80
81
  const context = (0, import_pi_ai_adapter.toPiContext)({ messages, tools }, model);
81
- const options = { temperature, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
82
+ const send = (omitTemperature) => {
83
+ const options = { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
84
+ return toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options);
85
+ };
82
86
  const raw = await this.traced(
83
87
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
84
88
  context,
85
- () => this.waitingOnRateLimit(() => toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options))
89
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, send)
86
90
  );
87
91
  if (raw.stopReason === "error" || raw.stopReason === "aborted") {
88
92
  throw import_llm_error.LLMError.fromProvider(raw.errorMessage ?? `request ${raw.stopReason}`);
@@ -115,9 +119,17 @@ class LLMClient {
115
119
  return this.traced(
116
120
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
117
121
  context,
118
- () => this.waitingOnRateLimit(() => models.complete(model, context, { temperature, maxRetries: MAX_RETRIES }))
122
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, (omitTemperature) => models.complete(model, context, { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES }))
119
123
  );
120
124
  }
125
+ async withoutRejectedTemperature(key, send) {
126
+ const known = LLMClient.modelsWithoutTemperature.has(key);
127
+ const response = await this.waitingOnRateLimit(() => send(known));
128
+ if (known || response.stopReason !== "error" || !(0, import_llm_error.rejectsSamplingParameter)(response.errorMessage)) return response;
129
+ LLMClient.modelsWithoutTemperature.add(key);
130
+ this.logger.warn({ model: key, error: response.errorMessage }, "[LLM Service] The model rejected the temperature setting, retrying without it");
131
+ return this.waitingOnRateLimit(() => send(true));
132
+ }
121
133
  async waitingOnRateLimit(run) {
122
134
  let response = await run();
123
135
  for (let waits = 0; waits < MAX_RATE_LIMIT_WAITS && response.stopReason === "error"; waits++) {
@@ -5,13 +5,14 @@ import { Logger } from "../common/logger/index.js";
5
5
  import { extractJSON } from "../common/helpers/index.js";
6
6
  import { createLLMCall } from "../services/llmcalls/index.js";
7
7
  import { toPiContext, fromPiMessage } from "./pi-ai-adapter";
8
- import { LLMError, retryDelayMs } from "./llm-error";
8
+ import { LLMError, retryDelayMs, rejectsSamplingParameter } from "./llm-error";
9
9
  const DEFAULT_PROVIDER = "openai";
10
10
  const DEFAULT_MODEL = "gpt-4o-mini";
11
11
  const DEFAULT_TEMPERATURE = 0.7;
12
12
  const MAX_RETRIES = 4;
13
13
  const MAX_RATE_LIMIT_WAITS = 2;
14
14
  class LLMClient {
15
+ static modelsWithoutTemperature = /* @__PURE__ */ new Set();
15
16
  logger = new Logger();
16
17
  langfuse;
17
18
  langfuseEnabled;
@@ -46,11 +47,14 @@ class LLMClient {
46
47
  const model = models.getModel(provider, modelName);
47
48
  if (!model) throw new Error("[LLM Client] model not found");
48
49
  const context = toPiContext({ messages, tools }, model);
49
- const options = { temperature, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
50
+ const send = (omitTemperature) => {
51
+ const options = { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, ...sessionId ? { sessionId } : {} };
52
+ return toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options);
53
+ };
50
54
  const raw = await this.traced(
51
55
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
52
56
  context,
53
- () => this.waitingOnRateLimit(() => toolChoice ? models.completeSimple(model, context, { ...options, toolChoice }) : models.complete(model, context, options))
57
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, send)
54
58
  );
55
59
  if (raw.stopReason === "error" || raw.stopReason === "aborted") {
56
60
  throw LLMError.fromProvider(raw.errorMessage ?? `request ${raw.stopReason}`);
@@ -83,9 +87,17 @@ class LLMClient {
83
87
  return this.traced(
84
88
  { origin, sessionId, answerId, currentUser, modelName, provider, temperature },
85
89
  context,
86
- () => this.waitingOnRateLimit(() => models.complete(model, context, { temperature, maxRetries: MAX_RETRIES }))
90
+ () => this.withoutRejectedTemperature(`${provider}/${modelName}`, (omitTemperature) => models.complete(model, context, { ...omitTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES }))
87
91
  );
88
92
  }
93
+ async withoutRejectedTemperature(key, send) {
94
+ const known = LLMClient.modelsWithoutTemperature.has(key);
95
+ const response = await this.waitingOnRateLimit(() => send(known));
96
+ if (known || response.stopReason !== "error" || !rejectsSamplingParameter(response.errorMessage)) return response;
97
+ LLMClient.modelsWithoutTemperature.add(key);
98
+ this.logger.warn({ model: key, error: response.errorMessage }, "[LLM Service] The model rejected the temperature setting, retrying without it");
99
+ return this.waitingOnRateLimit(() => send(true));
100
+ }
89
101
  async waitingOnRateLimit(run) {
90
102
  let response = await run();
91
103
  for (let waits = 0; waits < MAX_RATE_LIMIT_WAITS && response.stopReason === "error"; waits++) {
@@ -1,4 +1,4 @@
1
- export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_FAILED';
1
+ export type LLMErrorCode = 'LLM_RATE_LIMITED' | 'LLM_QUOTA_EXCEEDED' | 'LLM_UNAVAILABLE' | 'LLM_UNSUPPORTED_PARAMETER' | 'LLM_FAILED';
2
2
  export declare class LLMError extends Error {
3
3
  readonly code: LLMErrorCode;
4
4
  readonly isRetryable: boolean;
@@ -6,4 +6,5 @@ export declare class LLMError extends Error {
6
6
  constructor(code: LLMErrorCode, detail: string);
7
7
  static fromProvider(detail: string): LLMError;
8
8
  }
9
+ export declare function rejectsSamplingParameter(detail?: string): boolean;
9
10
  export declare function retryDelayMs(detail?: string): number | undefined;
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var llm_error_exports = {};
20
20
  __export(llm_error_exports, {
21
21
  LLMError: () => LLMError,
22
+ rejectsSamplingParameter: () => rejectsSamplingParameter,
22
23
  retryDelayMs: () => retryDelayMs
23
24
  });
24
25
  module.exports = __toCommonJS(llm_error_exports);
@@ -26,15 +27,19 @@ const USER_MESSAGES = {
26
27
  LLM_RATE_LIMITED: "The model is receiving too many requests right now. Please try again in a few seconds.",
27
28
  LLM_QUOTA_EXCEEDED: "The usage quota of the model provider has been exhausted. Please check the plan and billing of the provider.",
28
29
  LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
30
+ LLM_UNSUPPORTED_PARAMETER: "The model does not accept one of the request settings. Please try again.",
29
31
  LLM_FAILED: "The model request failed. Please try again."
30
32
  };
31
33
  const RETRYABLE = {
32
34
  LLM_RATE_LIMITED: true,
33
35
  LLM_QUOTA_EXCEEDED: false,
34
36
  LLM_UNAVAILABLE: true,
37
+ LLM_UNSUPPORTED_PARAMETER: true,
35
38
  LLM_FAILED: true
36
39
  };
37
40
  const MAX_WAIT_MS = 6e4;
41
+ const SAMPLING_PARAMETER = /\b(?:temperature|top_p|top_k)\b/i;
42
+ const REJECTION = /unsupported|not supported|does not support|doesn't support|deprecated|not allowed|only the default|no longer|removed|cannot be|can't be|must be|invalid/i;
38
43
  class LLMError extends Error {
39
44
  code;
40
45
  isRetryable;
@@ -49,7 +54,11 @@ class LLMError extends Error {
49
54
  return new LLMError(classify(detail), detail);
50
55
  }
51
56
  }
57
+ function rejectsSamplingParameter(detail) {
58
+ return Boolean(detail) && SAMPLING_PARAMETER.test(detail) && REJECTION.test(detail);
59
+ }
52
60
  function classify(detail) {
61
+ if (rejectsSamplingParameter(detail)) return "LLM_UNSUPPORTED_PARAMETER";
53
62
  if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
54
63
  if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
55
64
  if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
@@ -65,5 +74,6 @@ function retryDelayMs(detail) {
65
74
  // Annotate the CommonJS export names for ESM import in node:
66
75
  0 && (module.exports = {
67
76
  LLMError,
77
+ rejectsSamplingParameter,
68
78
  retryDelayMs
69
79
  });
@@ -3,15 +3,19 @@ const USER_MESSAGES = {
3
3
  LLM_RATE_LIMITED: "The model is receiving too many requests right now. Please try again in a few seconds.",
4
4
  LLM_QUOTA_EXCEEDED: "The usage quota of the model provider has been exhausted. Please check the plan and billing of the provider.",
5
5
  LLM_UNAVAILABLE: "The model provider is temporarily unavailable. Please try again in a moment.",
6
+ LLM_UNSUPPORTED_PARAMETER: "The model does not accept one of the request settings. Please try again.",
6
7
  LLM_FAILED: "The model request failed. Please try again."
7
8
  };
8
9
  const RETRYABLE = {
9
10
  LLM_RATE_LIMITED: true,
10
11
  LLM_QUOTA_EXCEEDED: false,
11
12
  LLM_UNAVAILABLE: true,
13
+ LLM_UNSUPPORTED_PARAMETER: true,
12
14
  LLM_FAILED: true
13
15
  };
14
16
  const MAX_WAIT_MS = 6e4;
17
+ const SAMPLING_PARAMETER = /\b(?:temperature|top_p|top_k)\b/i;
18
+ const REJECTION = /unsupported|not supported|does not support|doesn't support|deprecated|not allowed|only the default|no longer|removed|cannot be|can't be|must be|invalid/i;
15
19
  class LLMError extends Error {
16
20
  code;
17
21
  isRetryable;
@@ -26,7 +30,11 @@ class LLMError extends Error {
26
30
  return new LLMError(classify(detail), detail);
27
31
  }
28
32
  }
33
+ function rejectsSamplingParameter(detail) {
34
+ return Boolean(detail) && SAMPLING_PARAMETER.test(detail) && REJECTION.test(detail);
35
+ }
29
36
  function classify(detail) {
37
+ if (rejectsSamplingParameter(detail)) return "LLM_UNSUPPORTED_PARAMETER";
30
38
  if (/PerDay|per day|billing|insufficient_quota|exceeded your current quota[\s\S]*(daily|day)/i.test(detail) && !/per.?min/i.test(detail)) return "LLM_QUOTA_EXCEEDED";
31
39
  if (/\b429\b|rate.?limit|RESOURCE_EXHAUSTED|too many requests/i.test(detail)) return "LLM_RATE_LIMITED";
32
40
  if (/\b50[0-9]\b|unavailable|overloaded|timeout|timed out|econn|network/i.test(detail)) return "LLM_UNAVAILABLE";
@@ -41,5 +49,6 @@ function retryDelayMs(detail) {
41
49
  }
42
50
  export {
43
51
  LLMError,
52
+ rejectsSamplingParameter,
44
53
  retryDelayMs
45
54
  };
@@ -15,6 +15,7 @@ export interface BaseEntityProps {
15
15
  archivedAt?: string | Date;
16
16
  archivedBy?: string | ObjectId;
17
17
  sharedWith?: string[] | ObjectId[];
18
+ toUnset?: Record<string, unknown>;
18
19
  }
19
20
  export interface Document extends BaseEntityProps {
20
21
  toUnset?: Record<string, unknown>;
@@ -33,7 +34,7 @@ export declare class BaseEntity {
33
34
  archivedAt?: Date;
34
35
  archivedBy?: ObjectId;
35
36
  sharedWith?: ObjectId[];
36
- private toUnset?;
37
+ toUnset?: Record<string, unknown>;
37
38
  static toObjectId(id?: string | ObjectId): ObjectId | undefined;
38
39
  private static toDate;
39
40
  private static toNumber;
@@ -235,6 +235,8 @@ class Agent {
235
235
  this.snapshots.set(`task:${task.id}`, this.fingerprint(task));
236
236
  }
237
237
  this.currentChat.tasks = tasks;
238
+ const finished = [import_agent_task.TaskStatus.COMPLETED, import_agent_task.TaskStatus.FAILED, import_agent_task.TaskStatus.CANCELLED, import_agent_task.TaskStatus.ABANDONED];
239
+ if (this.currentChat.activeTask?.status && finished.includes(this.currentChat.activeTask.status)) this.currentChat.state?.setActiveTaskId(void 0);
238
240
  const activeTask = this.currentChat.activeTask;
239
241
  if (activeTask) await this.hydrateTask(activeTask);
240
242
  }
@@ -14,7 +14,7 @@ import {
14
14
  updateAgentAction,
15
15
  listAgentActionsByTask
16
16
  } from "../services/tasks/index.js";
17
- import { AgentTask } from "../services/tasks/entities/agent-task.entity.js";
17
+ import { AgentTask, TaskStatus } from "../services/tasks/entities/agent-task.entity.js";
18
18
  import { AgentAction } from "../services/tasks/entities/agent-action.entity.js";
19
19
  import { createAgentTraces } from "../services/traces/index.js";
20
20
  import { Tool } from "../tools/tool.js";
@@ -220,6 +220,8 @@ class Agent {
220
220
  this.snapshots.set(`task:${task.id}`, this.fingerprint(task));
221
221
  }
222
222
  this.currentChat.tasks = tasks;
223
+ const finished = [TaskStatus.COMPLETED, TaskStatus.FAILED, TaskStatus.CANCELLED, TaskStatus.ABANDONED];
224
+ if (this.currentChat.activeTask?.status && finished.includes(this.currentChat.activeTask.status)) this.currentChat.state?.setActiveTaskId(void 0);
223
225
  const activeTask = this.currentChat.activeTask;
224
226
  if (activeTask) await this.hydrateTask(activeTask);
225
227
  }
@@ -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
+ };