@exulu/backend 5.13.0 → 5.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-RNZ4IDCT.js → chunk-KLPCQWM3.js} +74 -18
- package/dist/{chunk-4W3V7IHR.js → chunk-NBDSN45T.js} +22 -0
- package/dist/{chunk-URX7KJQV.js → chunk-S4UXKMN5.js} +3641 -1701
- package/dist/{convert-exulu-tools-to-ai-sdk-tools-IYEO2RV6.js → convert-exulu-tools-to-ai-sdk-tools-GLRM3PM6.js} +2 -2
- package/dist/doc_processor-SVOSOVOY.js +12 -0
- package/dist/index.cjs +3736 -1579
- package/dist/index.d.cts +91 -3
- package/dist/index.d.ts +91 -3
- package/dist/index.js +202 -196
- package/ee/invoke-skills/artifact-filter.test.ts +42 -1
- package/ee/invoke-skills/artifact-filter.ts +37 -0
- package/ee/invoke-skills/create-sandbox.env.test.ts +7 -1
- package/ee/invoke-skills/create-sandbox.readonly-skills.sandbox.test.ts +221 -0
- package/ee/invoke-skills/create-sandbox.readonly-skills.test.ts +290 -0
- package/ee/invoke-skills/create-sandbox.run-command.test.ts +135 -0
- package/ee/invoke-skills/create-sandbox.skill-actions.test.ts +176 -0
- package/ee/invoke-skills/create-sandbox.ts +268 -88
- package/ee/invoke-skills/safe-fs.test.ts +59 -1
- package/ee/invoke-skills/safe-fs.ts +61 -2
- package/ee/invoke-skills/skill-actions/load.test.ts +88 -0
- package/ee/invoke-skills/skill-actions/load.ts +107 -0
- package/ee/invoke-skills/skill-actions/schema.test.ts +72 -0
- package/ee/invoke-skills/skill-actions/schema.ts +97 -0
- package/ee/invoke-skills/skill-actions/tool.test.ts +464 -0
- package/ee/invoke-skills/skill-actions/tool.ts +415 -0
- package/ee/python/documents/processing/doc_processor.limits.test.ts +257 -0
- package/ee/python/documents/processing/doc_processor.progress.test.ts +151 -0
- package/ee/python/documents/processing/doc_processor.ts +115 -13
- package/ee/python/documents/processing/limits.test.ts +35 -0
- package/ee/python/documents/processing/limits.ts +54 -0
- package/package.json +2 -1
- package/dist/doc_processor-E5GCE2ZT.js +0 -10
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { ExuluAgentToolConfig } from "@EXULU_TYPES/models/exulu-agent-tool-config";
|
|
6
|
+
import type { ExuluContext } from "@SRC/exulu/context";
|
|
7
|
+
import { ExuluTool } from "@SRC/exulu/tool";
|
|
8
|
+
import { findContextItems, readContextItem } from "@SRC/templates/tools/context-read-tools";
|
|
9
|
+
import { contextToolSegment } from "@SRC/templates/tools/context-write-tools";
|
|
10
|
+
import { ACTION_INPUTS_DIR, splitArtifactsBlock } from "../artifact-filter";
|
|
11
|
+
import type { SessionSandboxHandle } from "../create-sandbox";
|
|
12
|
+
import { ensureRealDirectory, removeEntryInside, writeFileInside } from "../safe-fs";
|
|
13
|
+
import { describeActions, type LoadedSkillActions } from "./load";
|
|
14
|
+
import type { ActionInput } from "./schema";
|
|
15
|
+
|
|
16
|
+
export const RUN_SKILL_ACTION_TOOL_ID = "run_skill_action";
|
|
17
|
+
|
|
18
|
+
const TEXT_MAX_CHARS = 10_000;
|
|
19
|
+
const ITEMS_DEFAULT_LIMIT = 50;
|
|
20
|
+
const ITEMS_MAX_LIMIT = 500;
|
|
21
|
+
const ARGS_FILE_STEM = "args";
|
|
22
|
+
|
|
23
|
+
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
|
|
24
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
25
|
+
|
|
26
|
+
const listOrNone = (names: string[]) => (names.length ? names.join(", ") : "(none)");
|
|
27
|
+
|
|
28
|
+
type Resolved =
|
|
29
|
+
| { name: string; type: "item"; context: ExuluContext; input: ActionInput & { type: "item" }; ref: { id?: string; external_id?: string } }
|
|
30
|
+
| { name: string; type: "items"; context: ExuluContext; input: ActionInput & { type: "items" }; where?: Record<string, unknown>; limit?: number }
|
|
31
|
+
| { name: string; type: "text"; value: string };
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The one tool through which the agent starts a skill action (actions.yaml).
|
|
35
|
+
*
|
|
36
|
+
* Caller-supplied values never reach the shell: the command is exactly
|
|
37
|
+
* `action.run` from the file. Ids, filters and text reach the script only as
|
|
38
|
+
* files in a per-run directory (`$EXULU_INPUTS_DIR`), which the backend writes
|
|
39
|
+
* itself with the link-refusing safe-fs helpers and removes when the command
|
|
40
|
+
* ends, whatever the outcome. Every input is resolved before anything is
|
|
41
|
+
* written or run; any refusal means nothing runs.
|
|
42
|
+
*/
|
|
43
|
+
export const createRunSkillActionTool = (deps: {
|
|
44
|
+
handle: Pick<SessionSandboxHandle, "sessionDir" | "runCommand">;
|
|
45
|
+
loaded: LoadedSkillActions;
|
|
46
|
+
contexts: ExuluContext[];
|
|
47
|
+
connectedContextIds: Set<string>;
|
|
48
|
+
/** Cuts `text` to about `charLimit` characters (plus a truncation marker). */
|
|
49
|
+
truncate: (text: string, kind: "stdout" | "stderr", charLimit: number) => string;
|
|
50
|
+
/**
|
|
51
|
+
* The generic tool-output guard's cap in characters (serialized result). The result is
|
|
52
|
+
* kept under it, so the guard never collapses it to a preview that drops the links.
|
|
53
|
+
*/
|
|
54
|
+
resultCharLimit: number;
|
|
55
|
+
}): ExuluTool => {
|
|
56
|
+
const { handle, loaded, contexts, connectedContextIds, truncate, resultCharLimit } = deps;
|
|
57
|
+
|
|
58
|
+
const description =
|
|
59
|
+
"Run a declared action of a skill. The platform reads the knowledge-base items the action needs " +
|
|
60
|
+
"with the current user's rights, hands them to the skill's script as files, runs the script in the " +
|
|
61
|
+
"session sandbox and returns its exit code and output (files it creates come back as download links). " +
|
|
62
|
+
"Pass ids, filters and text only in `inputs`. Item inputs take an id string or { external_id }; " +
|
|
63
|
+
`items inputs take { where?, limit? } (default ${ITEMS_DEFAULT_LIMIT}, max ${ITEMS_MAX_LIMIT}); ` +
|
|
64
|
+
`text inputs take a string (max ${TEXT_MAX_CHARS} characters). Available actions:\n` +
|
|
65
|
+
describeActions(loaded);
|
|
66
|
+
|
|
67
|
+
return new ExuluTool({
|
|
68
|
+
id: RUN_SKILL_ACTION_TOOL_ID,
|
|
69
|
+
name: RUN_SKILL_ACTION_TOOL_ID,
|
|
70
|
+
category: "skills",
|
|
71
|
+
description,
|
|
72
|
+
type: "function",
|
|
73
|
+
inputSchema: z.object({
|
|
74
|
+
skill: z.string().describe("The skill's name, as listed in this description."),
|
|
75
|
+
action: z.string().describe("The action's name within that skill."),
|
|
76
|
+
inputs: z
|
|
77
|
+
.record(z.string(), z.unknown())
|
|
78
|
+
.optional()
|
|
79
|
+
.describe("The action's inputs by name, as listed in this description."),
|
|
80
|
+
}),
|
|
81
|
+
config: [],
|
|
82
|
+
needsApproval: false,
|
|
83
|
+
execute: async (params: any) => {
|
|
84
|
+
const refuse = (message: string) => ({ result: `Not run: ${message}` });
|
|
85
|
+
const skillName = params?.skill;
|
|
86
|
+
const actionName = params?.action;
|
|
87
|
+
|
|
88
|
+
// ── Skill and action (own properties only: "__proto__" must not resolve) ──
|
|
89
|
+
if (typeof skillName !== "string" || !Object.hasOwn(loaded.bySkill, skillName)) {
|
|
90
|
+
return refuse(
|
|
91
|
+
`unknown skill "${String(skillName)}". Available: ${listOrNone(Object.keys(loaded.bySkill))}.`,
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
const skill = loaded.bySkill[skillName]!;
|
|
95
|
+
if (typeof actionName !== "string" || !Object.hasOwn(skill.actions, actionName)) {
|
|
96
|
+
return refuse(
|
|
97
|
+
`unknown action "${String(actionName)}" for skill "${skillName}". Available: ${listOrNone(Object.keys(skill.actions))}.`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
const action = skill.actions[actionName]!;
|
|
101
|
+
const label = `${skillName} / ${actionName}`;
|
|
102
|
+
const declaredNames = Object.keys(action.inputs);
|
|
103
|
+
const inputList = `Inputs of ${label}: ${listOrNone(declaredNames)}.`;
|
|
104
|
+
|
|
105
|
+
// ── Input names ──
|
|
106
|
+
const given = params?.inputs === undefined || params?.inputs === null ? {} : params.inputs;
|
|
107
|
+
if (!isPlainObject(given)) {
|
|
108
|
+
return refuse(`inputs must be an object keyed by input name. ${inputList}`);
|
|
109
|
+
}
|
|
110
|
+
for (const key of Object.keys(given)) {
|
|
111
|
+
if (!Object.hasOwn(action.inputs, key)) {
|
|
112
|
+
return refuse(`unknown input "${key}". ${inputList}`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const argsInput = Object.hasOwn(action.inputs, ARGS_FILE_STEM) ? action.inputs[ARGS_FILE_STEM] : undefined;
|
|
116
|
+
if (argsInput && argsInput.type !== "text") {
|
|
117
|
+
return refuse(
|
|
118
|
+
`${label} cannot run: its ${argsInput.type} input is named "${ARGS_FILE_STEM}", which collides with ` +
|
|
119
|
+
`${ARGS_FILE_STEM}.json (the file of the text inputs). The skill's actions.yaml must rename it.`,
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── Shapes ──
|
|
124
|
+
const resolved: Resolved[] = [];
|
|
125
|
+
for (const [name, input] of Object.entries(action.inputs)) {
|
|
126
|
+
const value = Object.hasOwn(given, name) ? given[name] : undefined;
|
|
127
|
+
if (input.type === "text") {
|
|
128
|
+
if (value === undefined || value === null) {
|
|
129
|
+
if (input.required) return refuse(`input "${name}" is required. ${inputList}`);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (typeof value !== "string") return refuse(`input "${name}" must be a string.`);
|
|
133
|
+
if (value.length > TEXT_MAX_CHARS) {
|
|
134
|
+
return refuse(`input "${name}" is ${value.length} characters long; the maximum is ${TEXT_MAX_CHARS}.`);
|
|
135
|
+
}
|
|
136
|
+
resolved.push({ name, type: "text", value });
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const context = contexts.find((c) => c.id === input.context);
|
|
141
|
+
if (!connectedContextIds.has(input.context) || !context) {
|
|
142
|
+
return refuse(
|
|
143
|
+
`input "${name}" reads the knowledge base "${input.context}", which is not connected to this agent.`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (input.type === "item") {
|
|
148
|
+
if (value === undefined || value === null) return refuse(`input "${name}" is required. ${inputList}`);
|
|
149
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
150
|
+
resolved.push({ name, type: "item", context, input, ref: { id: value } });
|
|
151
|
+
} else if (
|
|
152
|
+
isPlainObject(value) &&
|
|
153
|
+
Object.keys(value).length === 1 &&
|
|
154
|
+
typeof value.external_id === "string" &&
|
|
155
|
+
value.external_id.trim() !== ""
|
|
156
|
+
) {
|
|
157
|
+
resolved.push({ name, type: "item", context, input, ref: { external_id: value.external_id } });
|
|
158
|
+
} else {
|
|
159
|
+
return refuse(`input "${name}" must be an item id (a non-empty string) or { "external_id": "<id>" }.`);
|
|
160
|
+
}
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// items
|
|
165
|
+
if (value !== undefined && value !== null && !isPlainObject(value)) {
|
|
166
|
+
return refuse(`input "${name}" must be { "where"?: {...}, "limit"?: number } or omitted.`);
|
|
167
|
+
}
|
|
168
|
+
const spec = (value ?? {}) as Record<string, unknown>;
|
|
169
|
+
const surplus = Object.keys(spec).filter((k) => k !== "where" && k !== "limit");
|
|
170
|
+
if (surplus.length) {
|
|
171
|
+
return refuse(`input "${name}" has unknown key "${surplus[0]}"; it takes only "where" and "limit".`);
|
|
172
|
+
}
|
|
173
|
+
if (spec.where !== undefined && !isPlainObject(spec.where)) {
|
|
174
|
+
return refuse(`input "${name}": "where" must be an object of field filters.`);
|
|
175
|
+
}
|
|
176
|
+
if (spec.limit !== undefined && !(typeof spec.limit === "number" && Number.isInteger(spec.limit) && spec.limit >= 1)) {
|
|
177
|
+
return refuse(`input "${name}": "limit" must be a whole number of at least 1 (maximum ${ITEMS_MAX_LIMIT}).`);
|
|
178
|
+
}
|
|
179
|
+
// The yaml's fixed `where` is AND-ed with the caller's: one object,
|
|
180
|
+
// and a field named by both is refused rather than letting one win.
|
|
181
|
+
const fixed = input.where ?? {};
|
|
182
|
+
const callerWhere = (spec.where ?? {}) as Record<string, unknown>;
|
|
183
|
+
const clash = Object.keys(callerWhere).find((k) => Object.hasOwn(fixed, k));
|
|
184
|
+
if (clash) {
|
|
185
|
+
return refuse(
|
|
186
|
+
`input "${name}": the field "${clash}" is already filtered by the action itself and cannot be filtered again.`,
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
const where = { ...fixed, ...callerWhere };
|
|
190
|
+
resolved.push({
|
|
191
|
+
name,
|
|
192
|
+
type: "items",
|
|
193
|
+
context,
|
|
194
|
+
input,
|
|
195
|
+
where: Object.keys(where).length ? where : undefined,
|
|
196
|
+
limit: spec.limit as number | undefined,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ── Read every input as the speaking user, before anything is written ──
|
|
201
|
+
const caller = { user: params?.user, req: params?.req };
|
|
202
|
+
const files: Array<{ file: string; content: unknown }> = [];
|
|
203
|
+
const warnings: string[] = [];
|
|
204
|
+
const textArgs: Record<string, string> = {};
|
|
205
|
+
for (const r of resolved) {
|
|
206
|
+
if (r.type === "text") {
|
|
207
|
+
textArgs[r.name] = r.value;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (r.type === "item") {
|
|
211
|
+
const outcome = await readContextItem(r.context, { ...r.ref, fields: r.input.fields }, caller);
|
|
212
|
+
if (!outcome.ok) return refuse(`input "${r.name}": ${outcome.message}`);
|
|
213
|
+
files.push({ file: `${r.name}.json`, content: outcome.item });
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
const outcome = await findContextItems(
|
|
217
|
+
r.context,
|
|
218
|
+
{ where: r.where, limit: r.limit ?? ITEMS_DEFAULT_LIMIT, maxLimit: ITEMS_MAX_LIMIT, fields: r.input.fields },
|
|
219
|
+
caller,
|
|
220
|
+
);
|
|
221
|
+
if (!outcome.ok) return refuse(`input "${r.name}": ${outcome.message}`);
|
|
222
|
+
files.push({
|
|
223
|
+
file: `${r.name}.json`,
|
|
224
|
+
content: { items: outcome.items, limit: outcome.limit, truncated: outcome.truncated },
|
|
225
|
+
});
|
|
226
|
+
if (outcome.truncated) warnings.push(`warning: input "${r.name}" was cut at ${outcome.limit} items`);
|
|
227
|
+
}
|
|
228
|
+
if (resolved.some((r) => r.type === "text")) {
|
|
229
|
+
files.push({ file: `${ARGS_FILE_STEM}.json`, content: textArgs });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ── Write, run, always clean up ──
|
|
233
|
+
const sessionDir = handle.sessionDir;
|
|
234
|
+
const runId = randomUUID();
|
|
235
|
+
const runRelative = `${ACTION_INPUTS_DIR}/${runId}`;
|
|
236
|
+
try {
|
|
237
|
+
const parent = await ensureRealDirectory(sessionDir, ACTION_INPUTS_DIR);
|
|
238
|
+
await mkdir(join(parent, runId), { mode: 0o700 });
|
|
239
|
+
for (const { file, content } of files) {
|
|
240
|
+
await writeFileInside(sessionDir, `${runRelative}/${file}`, JSON.stringify(content));
|
|
241
|
+
}
|
|
242
|
+
const outcome = await handle.runCommand(action.run, {
|
|
243
|
+
extraEnv: {
|
|
244
|
+
EXULU_INPUTS_DIR: join(sessionDir, runRelative),
|
|
245
|
+
EXULU_SKILL_DIR: skill.skillDir,
|
|
246
|
+
},
|
|
247
|
+
timeoutMs: action.timeoutSeconds * 1000,
|
|
248
|
+
});
|
|
249
|
+
const fixed = [`exit_code: ${outcome.exitCode}`];
|
|
250
|
+
if (outcome.timedOut) fixed.push(`timed out after ${action.timeoutSeconds}s`);
|
|
251
|
+
fixed.push(...warnings);
|
|
252
|
+
const { output, block } = splitArtifactsBlock(
|
|
253
|
+
outcome.stdout ?? "",
|
|
254
|
+
(outcome.artifacts ?? []).some((a) => a.url),
|
|
255
|
+
);
|
|
256
|
+
return {
|
|
257
|
+
result: fitResult({
|
|
258
|
+
fixed,
|
|
259
|
+
stdout: output,
|
|
260
|
+
artifactsBlock: block,
|
|
261
|
+
stderr: outcome.stderr ?? "",
|
|
262
|
+
truncate,
|
|
263
|
+
limit: resultCharLimit,
|
|
264
|
+
}),
|
|
265
|
+
};
|
|
266
|
+
} finally {
|
|
267
|
+
await removeEntryInside(sessionDir, runRelative).catch((err) =>
|
|
268
|
+
console.error(`[SKILLS] Could not remove the action inputs directory ${runRelative}:`, err),
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
};
|
|
274
|
+
|
|
275
|
+
/** Room left for JSON escaping estimates and rounding below the guard's cap. */
|
|
276
|
+
const RESULT_MARGIN_CHARS = 256;
|
|
277
|
+
const STDERR_SHARE = 0.3;
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Assembles the result text so that `{ result }`, serialized as the generic guard does,
|
|
281
|
+
* stays under `limit`: the fixed lines and the artifacts block are kept whole, only the
|
|
282
|
+
* script's own stdout and stderr are truncated, against budgets that sum to what is left.
|
|
283
|
+
* Output that already fits is returned unchanged.
|
|
284
|
+
*/
|
|
285
|
+
export const fitResult = (p: {
|
|
286
|
+
fixed: string[];
|
|
287
|
+
stdout: string;
|
|
288
|
+
artifactsBlock: string;
|
|
289
|
+
stderr: string;
|
|
290
|
+
truncate: (text: string, kind: "stdout" | "stderr", charLimit: number) => string;
|
|
291
|
+
limit: number;
|
|
292
|
+
}): string => {
|
|
293
|
+
const assemble = (out: string, err: string) =>
|
|
294
|
+
[...p.fixed, `stdout:\n${out}${p.artifactsBlock}`, `stderr:\n${err}`].join("\n");
|
|
295
|
+
// Measured as the guard measures: the serialized tool result.
|
|
296
|
+
const size = (text: string) => JSON.stringify({ result: text }).length;
|
|
297
|
+
const full = assemble(p.stdout, p.stderr);
|
|
298
|
+
if (size(full) <= p.limit) return full;
|
|
299
|
+
|
|
300
|
+
const room = p.limit - size(assemble("", "")) - RESULT_MARGIN_CHARS;
|
|
301
|
+
if (room <= 0) return assemble("", ""); // the fixed lines and links alone fill the cap
|
|
302
|
+
// Split the room; a stream shorter than its share hands the rest to the other one.
|
|
303
|
+
let errBudget = Math.min(p.stderr.length, Math.floor(room * STDERR_SHARE));
|
|
304
|
+
let outBudget = Math.min(p.stdout.length, room - errBudget);
|
|
305
|
+
errBudget = Math.min(p.stderr.length, room - outBudget);
|
|
306
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
307
|
+
const out = p.stdout.length <= outBudget ? p.stdout : p.truncate(p.stdout, "stdout", Math.max(1, outBudget));
|
|
308
|
+
const err = p.stderr.length <= errBudget ? p.stderr : p.truncate(p.stderr, "stderr", Math.max(1, errBudget));
|
|
309
|
+
const text = assemble(out, err);
|
|
310
|
+
const over = size(text) - p.limit;
|
|
311
|
+
if (over <= 0) return text;
|
|
312
|
+
// Truncation markers and JSON escaping (newlines, quotes) cost more than the raw
|
|
313
|
+
// count; shrink the budgets of the streams being cut by the overshoot and try again.
|
|
314
|
+
// A stream that fits whole keeps its budget, so it is never cut for nothing.
|
|
315
|
+
const outCut = out !== p.stdout;
|
|
316
|
+
const errCut = err !== p.stderr;
|
|
317
|
+
const total = (outCut ? outBudget : 0) + (errCut ? errBudget : 0);
|
|
318
|
+
const scale = Math.max(0, (total - over - RESULT_MARGIN_CHARS) / Math.max(1, total)) * 0.9;
|
|
319
|
+
if (outCut) outBudget = Math.floor(outBudget * scale);
|
|
320
|
+
if (errCut) errBudget = Math.floor(errBudget * scale);
|
|
321
|
+
}
|
|
322
|
+
return assemble("", "");
|
|
323
|
+
};
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* The agentic search's `knowledge_bases` config as it stands BEFORE the audit
|
|
327
|
+
* loop hydrates it, read with the same rules hydrateVariables applies to a
|
|
328
|
+
* json option. Returns the context ids switched off, or null = unusable.
|
|
329
|
+
* Only rows of type json or string carry their value inline; any other type
|
|
330
|
+
* holding a `variable` is resolved from the variables table during hydration,
|
|
331
|
+
* which has not happened yet here, so it counts as unusable.
|
|
332
|
+
*/
|
|
333
|
+
const disabledSearchContexts = (searchConfig: ExuluAgentToolConfig | undefined): Set<string> | null => {
|
|
334
|
+
const row = Array.isArray(searchConfig?.config)
|
|
335
|
+
? searchConfig!.config.find((c) => c?.name === "knowledge_bases")
|
|
336
|
+
: undefined;
|
|
337
|
+
let raw: unknown;
|
|
338
|
+
if (row?.variable) {
|
|
339
|
+
if (row.type !== "json" && row.type !== "string") return null;
|
|
340
|
+
raw = row.variable;
|
|
341
|
+
} else {
|
|
342
|
+
raw = row?.value;
|
|
343
|
+
}
|
|
344
|
+
if (raw === undefined || raw === null) return new Set();
|
|
345
|
+
if (typeof raw === "string") {
|
|
346
|
+
if (raw.trim() === "") return new Set();
|
|
347
|
+
try {
|
|
348
|
+
raw = JSON.parse(raw);
|
|
349
|
+
} catch {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (!isPlainObject(raw)) return null;
|
|
354
|
+
const disabled = new Set<string>();
|
|
355
|
+
for (const [contextId, profile] of Object.entries(raw)) {
|
|
356
|
+
if (!isPlainObject(profile)) return null;
|
|
357
|
+
if (profile.enabled !== undefined && typeof profile.enabled !== "boolean") return null;
|
|
358
|
+
if (profile.enabled === false) disabled.add(contextId);
|
|
359
|
+
}
|
|
360
|
+
return disabled;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Which contexts a skill action may read this turn.
|
|
365
|
+
*
|
|
366
|
+
* Principle (design anti-goal): an action must not read a context the agent
|
|
367
|
+
* could not read with its own tools in the same turn. So the set is exactly
|
|
368
|
+
* what the agent's own tools reach:
|
|
369
|
+
* 1. the contexts of its knowledge_base_editor config (they carry get/find
|
|
370
|
+
* tools), unless BOTH of a context's read tools (get_<ctx>_item,
|
|
371
|
+
* find_<ctx>_items) are disabled this turn — then its own tools cannot
|
|
372
|
+
* read it, whatever its write tools may do,
|
|
373
|
+
* 2. when its configured agentic_context_search is active this turn: every
|
|
374
|
+
* context except those whose `knowledge_bases` entry has enabled === false,
|
|
375
|
+
* 3. otherwise, when a project search was built for this turn: the contexts of
|
|
376
|
+
* the project's items (the set that search is handed).
|
|
377
|
+
* The agent's memory context is never in the set.
|
|
378
|
+
*
|
|
379
|
+
* Two deliberate differences from the search pipeline:
|
|
380
|
+
* - Every context disabled → the search contributes nothing (the pipeline
|
|
381
|
+
* falls back to searching all of them).
|
|
382
|
+
* - A `knowledge_bases` value present but not usable as an object of
|
|
383
|
+
* profiles → the search contributes nothing (fail closed; the pipeline
|
|
384
|
+
* falls back to defaults = everything). Absent or empty means "all enabled".
|
|
385
|
+
*/
|
|
386
|
+
export const deriveConnectedContextIds = (args: {
|
|
387
|
+
/** Every context available this turn (the `contexts` argument of the conversion). */
|
|
388
|
+
contextIds: string[];
|
|
389
|
+
memoryContextId?: string;
|
|
390
|
+
/** Contexts of the agent's knowledge_base_editor config (already limited to existing contexts). */
|
|
391
|
+
editorContextIds: string[];
|
|
392
|
+
/** Tool ids disabled for this turn; an editor context whose two read tools are both in it does not count. */
|
|
393
|
+
disabledToolIds?: ReadonlySet<string>;
|
|
394
|
+
/** Present when the agent's own agentic_context_search is active this turn; its raw agent tool config entry. */
|
|
395
|
+
agenticSearch?: { config?: ExuluAgentToolConfig };
|
|
396
|
+
/** Contexts handed to the project search, when that search (not the agent's own) was built. */
|
|
397
|
+
projectSearchContextIds?: string[];
|
|
398
|
+
}): Set<string> => {
|
|
399
|
+
const ids = new Set<string>();
|
|
400
|
+
for (const id of args.editorContextIds) {
|
|
401
|
+
const segment = contextToolSegment({ id });
|
|
402
|
+
const readToolIds = [`get_${segment}_item`, `find_${segment}_items`];
|
|
403
|
+
if (readToolIds.some((toolId) => !args.disabledToolIds?.has(toolId))) ids.add(id);
|
|
404
|
+
}
|
|
405
|
+
if (args.agenticSearch) {
|
|
406
|
+
const disabled = disabledSearchContexts(args.agenticSearch.config);
|
|
407
|
+
if (disabled) {
|
|
408
|
+
for (const id of args.contextIds) if (!disabled.has(id)) ids.add(id);
|
|
409
|
+
}
|
|
410
|
+
} else if (args.projectSearchContextIds) {
|
|
411
|
+
for (const id of args.projectSearchContextIds) ids.add(id);
|
|
412
|
+
}
|
|
413
|
+
if (args.memoryContextId) ids.delete(args.memoryContextId);
|
|
414
|
+
return ids;
|
|
415
|
+
};
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import * as fs from "fs";
|
|
2
|
+
import * as os from "os";
|
|
3
|
+
import * as path from "path";
|
|
4
|
+
|
|
5
|
+
jest.mock("@EE/entitlements", () => ({ checkLicense: () => ({ "advanced-document-processing": true }) }));
|
|
6
|
+
jest.mock("@SRC/utils/with-retry", () => ({
|
|
7
|
+
// Same attempts as the real helper, without the backoff sleeps.
|
|
8
|
+
withRetry: async (fn: () => Promise<unknown>, max = 3) => {
|
|
9
|
+
let last: unknown;
|
|
10
|
+
for (let i = 0; i < max; i++) {
|
|
11
|
+
try { return await fn(); } catch (e) { last = e; }
|
|
12
|
+
}
|
|
13
|
+
throw last;
|
|
14
|
+
},
|
|
15
|
+
}));
|
|
16
|
+
jest.mock("@SRC/utils/python-executor", () => ({ executePythonScript: jest.fn() }));
|
|
17
|
+
jest.mock("@SRC/exulu/resolve-ocr", () => ({ resolveOcr: jest.fn() }));
|
|
18
|
+
jest.mock("@SRC/exulu/resolve-model", () => ({ resolveModel: jest.fn(async () => ({ languageModel: {} })) }));
|
|
19
|
+
jest.mock("@llamaindex/liteparse", () => ({ LiteParse: jest.fn() }), { virtual: true });
|
|
20
|
+
jest.mock("ai", () => ({ generateText: jest.fn(), Output: { object: (x: unknown) => x } }));
|
|
21
|
+
|
|
22
|
+
import { documentProcessor } from "./doc_processor";
|
|
23
|
+
import { processWideLimiters, VISION_CALL_TIMEOUT_MS, OCR_CALL_TIMEOUT_MS } from "./limits";
|
|
24
|
+
|
|
25
|
+
const { executePythonScript } = require("@SRC/utils/python-executor") as { executePythonScript: jest.Mock };
|
|
26
|
+
const { resolveOcr } = require("@SRC/exulu/resolve-ocr") as { resolveOcr: jest.Mock };
|
|
27
|
+
const { LiteParse } = require("@llamaindex/liteparse") as { LiteParse: jest.Mock };
|
|
28
|
+
const { generateText } = require("ai") as { generateText: jest.Mock };
|
|
29
|
+
|
|
30
|
+
const chunkDir = fs.mkdtempSync(path.join(os.tmpdir(), "chunks-"));
|
|
31
|
+
const chunkFile = path.join(chunkDir, "chunk.pdf");
|
|
32
|
+
fs.writeFileSync(chunkFile, "x");
|
|
33
|
+
|
|
34
|
+
let running = 0;
|
|
35
|
+
let maxRunning = 0;
|
|
36
|
+
|
|
37
|
+
function setupDocument(pageCount: number) {
|
|
38
|
+
executePythonScript.mockResolvedValueOnce({
|
|
39
|
+
stdout: JSON.stringify(Array.from({ length: pageCount }, (_, i) => ({ path: chunkFile, start_page: i, end_page: i + 1 }))),
|
|
40
|
+
stderr: "",
|
|
41
|
+
});
|
|
42
|
+
LiteParse.mockImplementationOnce(() => ({
|
|
43
|
+
screenshot: async () => Array.from({ length: pageCount }, (_, i) => ({ pageNum: i + 1, imageBuffer: Buffer.from(`page-${i + 1}`) })),
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
beforeEach(() => {
|
|
48
|
+
jest.clearAllMocks();
|
|
49
|
+
running = 0;
|
|
50
|
+
maxRunning = 0;
|
|
51
|
+
jest.spyOn(Math, "random").mockReturnValue(0);
|
|
52
|
+
jest.spyOn(console, "log").mockImplementation(() => undefined);
|
|
53
|
+
jest.spyOn(console, "error").mockImplementation(() => undefined);
|
|
54
|
+
let call = 0;
|
|
55
|
+
resolveOcr.mockResolvedValue({
|
|
56
|
+
ocr: async () => {
|
|
57
|
+
running++;
|
|
58
|
+
maxRunning = Math.max(maxRunning, running);
|
|
59
|
+
await new Promise((r) => setTimeout(r, 15));
|
|
60
|
+
running--;
|
|
61
|
+
call++;
|
|
62
|
+
// Every page carries a table so the vision pass looks at it.
|
|
63
|
+
return { pages: [{ index: 0, markdown: `| a | b |\n| 1 | 2 |\nocr text ${call}` }] };
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
generateText.mockResolvedValue({
|
|
67
|
+
output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" },
|
|
68
|
+
});
|
|
69
|
+
});
|
|
70
|
+
afterEach(() => jest.restoreAllMocks());
|
|
71
|
+
|
|
72
|
+
const mistral = (extra: Record<string, unknown> = {}) => ({
|
|
73
|
+
processor: { name: "mistral" as const, model: "vertex-ocr" },
|
|
74
|
+
vlm: { model: "vlm", concurrency: 4 },
|
|
75
|
+
...extra,
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
describe("document processor limits", () => {
|
|
79
|
+
it("chat path: with the process-wide limiters never more than 8 OCR calls at once across two documents, and both finish", async () => {
|
|
80
|
+
setupDocument(12);
|
|
81
|
+
setupDocument(12);
|
|
82
|
+
const config = mistral({ ocr: { concurrency: 8 } });
|
|
83
|
+
const [a, b] = await Promise.all([
|
|
84
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config, limiters: processWideLimiters }),
|
|
85
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config, limiters: processWideLimiters }),
|
|
86
|
+
]);
|
|
87
|
+
expect(a).toHaveLength(12);
|
|
88
|
+
expect(b).toHaveLength(12);
|
|
89
|
+
expect(maxRunning).toBeGreaterThan(3);
|
|
90
|
+
expect(maxRunning).toBeLessThanOrEqual(8);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("knowledge-base path: a direct call is not capped globally, two documents run 16 OCR calls at once", async () => {
|
|
94
|
+
setupDocument(12);
|
|
95
|
+
setupDocument(12);
|
|
96
|
+
const config = mistral({ ocr: { concurrency: 8 } });
|
|
97
|
+
await Promise.all([
|
|
98
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config }),
|
|
99
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config }),
|
|
100
|
+
]);
|
|
101
|
+
expect(maxRunning).toBeGreaterThan(8);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it("knowledge-base path: vision calls follow vlm.concurrency per document with no global cap", async () => {
|
|
105
|
+
setupDocument(10);
|
|
106
|
+
setupDocument(10);
|
|
107
|
+
let visionRunning = 0;
|
|
108
|
+
let visionMax = 0;
|
|
109
|
+
generateText.mockImplementation(async () => {
|
|
110
|
+
visionRunning++;
|
|
111
|
+
visionMax = Math.max(visionMax, visionRunning);
|
|
112
|
+
await new Promise((r) => setTimeout(r, 15));
|
|
113
|
+
visionRunning--;
|
|
114
|
+
return { output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" } };
|
|
115
|
+
});
|
|
116
|
+
const config = mistral({ ocr: { concurrency: 8 }, vlm: { model: "vlm", concurrency: 10 } });
|
|
117
|
+
await Promise.all([
|
|
118
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config }),
|
|
119
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config }),
|
|
120
|
+
]);
|
|
121
|
+
expect(visionMax).toBeGreaterThan(8);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it("chat path: vision calls across two documents are capped at 8", async () => {
|
|
125
|
+
setupDocument(10);
|
|
126
|
+
setupDocument(10);
|
|
127
|
+
let visionRunning = 0;
|
|
128
|
+
let visionMax = 0;
|
|
129
|
+
generateText.mockImplementation(async () => {
|
|
130
|
+
visionRunning++;
|
|
131
|
+
visionMax = Math.max(visionMax, visionRunning);
|
|
132
|
+
await new Promise((r) => setTimeout(r, 15));
|
|
133
|
+
visionRunning--;
|
|
134
|
+
return { output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" } };
|
|
135
|
+
});
|
|
136
|
+
const config = mistral({ ocr: { concurrency: 8 }, vlm: { model: "vlm", concurrency: 10 } });
|
|
137
|
+
await Promise.all([
|
|
138
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config, limiters: processWideLimiters }),
|
|
139
|
+
documentProcessor({ file: Buffer.from("%PDF"), name: "b.pdf", config, limiters: processWideLimiters }),
|
|
140
|
+
]);
|
|
141
|
+
expect(visionMax).toBeGreaterThan(3);
|
|
142
|
+
expect(visionMax).toBeLessThanOrEqual(8);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("honours documentProcessor.ocr.concurrency for one document", async () => {
|
|
146
|
+
setupDocument(20);
|
|
147
|
+
await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral({ ocr: { concurrency: 8 } }) });
|
|
148
|
+
expect(maxRunning).toBe(8);
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("limits one document to documentProcessor.ocr.concurrency (default 3)", async () => {
|
|
152
|
+
setupDocument(9);
|
|
153
|
+
await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() });
|
|
154
|
+
expect(maxRunning).toBe(3);
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
describe("vision call time limit", () => {
|
|
159
|
+
it("is 120 seconds", () => {
|
|
160
|
+
expect(VISION_CALL_TIMEOUT_MS).toBe(120_000);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("knowledge-base path: a direct call creates no abort signal for OCR or vision", async () => {
|
|
164
|
+
setupDocument(2);
|
|
165
|
+
const timeout = jest.spyOn(AbortSignal, "timeout");
|
|
166
|
+
await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() });
|
|
167
|
+
expect(timeout).not.toHaveBeenCalled();
|
|
168
|
+
expect(generateText).toHaveBeenCalled();
|
|
169
|
+
for (const [args] of generateText.mock.calls) expect(args.abortSignal).toBeUndefined();
|
|
170
|
+
expect(resolveOcr.mock.calls[0][0].timeoutMs).toBeUndefined();
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it("chat path: OCR gets the 180 s timeout and vision calls carry a 120 s signal", async () => {
|
|
174
|
+
setupDocument(1);
|
|
175
|
+
const timeout = jest.spyOn(AbortSignal, "timeout");
|
|
176
|
+
await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), limiters: processWideLimiters });
|
|
177
|
+
expect(resolveOcr.mock.calls[0][0].timeoutMs).toBe(OCR_CALL_TIMEOUT_MS);
|
|
178
|
+
expect(OCR_CALL_TIMEOUT_MS).toBe(180_000);
|
|
179
|
+
expect(timeout).toHaveBeenCalledWith(120_000);
|
|
180
|
+
expect(generateText.mock.calls[0][0].abortSignal).toBeInstanceOf(AbortSignal);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("every vision call carries a timeout signal; a stalled call that is aborted counts as a failed attempt", async () => {
|
|
184
|
+
setupDocument(1);
|
|
185
|
+
const controller = new AbortController();
|
|
186
|
+
const timeout = jest.spyOn(AbortSignal, "timeout").mockReturnValue(controller.signal);
|
|
187
|
+
generateText.mockImplementation(
|
|
188
|
+
(args: { abortSignal?: AbortSignal }) =>
|
|
189
|
+
new Promise((_resolve, reject) => {
|
|
190
|
+
args.abortSignal?.addEventListener("abort", () => reject(new Error("timed out")));
|
|
191
|
+
if (args.abortSignal?.aborted) reject(new Error("timed out"));
|
|
192
|
+
}),
|
|
193
|
+
);
|
|
194
|
+
const pending = documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), tolerateVisionFailures: true, limiters: processWideLimiters });
|
|
195
|
+
for (let i = 0; i < 200 && generateText.mock.calls.length === 0; i++) await new Promise((r) => setTimeout(r, 10));
|
|
196
|
+
expect(timeout).toHaveBeenCalledWith(120_000);
|
|
197
|
+
controller.abort();
|
|
198
|
+
const result = await pending;
|
|
199
|
+
// Three attempts (the existing retry count), then the page is flagged instead of hanging.
|
|
200
|
+
expect(generateText).toHaveBeenCalledTimes(3);
|
|
201
|
+
expect(result![0].vlm_failed).toBe(true);
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
describe("vision failures", () => {
|
|
206
|
+
const failPage2 = () =>
|
|
207
|
+
generateText.mockImplementation(async (args: { messages: Array<{ content: Array<{ image?: string }> }> }) => {
|
|
208
|
+
const image = args.messages[0].content[1].image as string;
|
|
209
|
+
const text = Buffer.from(image.split(",")[1], "base64").toString();
|
|
210
|
+
if (text === "page-2") throw new Error("vision outage");
|
|
211
|
+
return { output: { needs_correction: false, corrected_text: null, current_page_table: null, confidence: "high", reasoning: "ok" } };
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("with tolerateVisionFailures a page whose vision call failed three times keeps its OCR text and is flagged", async () => {
|
|
215
|
+
setupDocument(3);
|
|
216
|
+
failPage2();
|
|
217
|
+
const result = await documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral(), tolerateVisionFailures: true });
|
|
218
|
+
expect(result).toHaveLength(3);
|
|
219
|
+
const page2 = result!.find((p) => p.page === 2)!;
|
|
220
|
+
expect(page2.content).toContain("| a | b |");
|
|
221
|
+
expect(page2.vlm_failed).toBe(true);
|
|
222
|
+
expect(result!.filter((p) => p.vlm_failed).map((p) => p.page)).toEqual([2]);
|
|
223
|
+
const failedCalls = generateText.mock.calls.filter((c) => Buffer.from(c[0].messages[0].content[1].image.split(",")[1], "base64").toString() === "page-2");
|
|
224
|
+
expect(failedCalls).toHaveLength(3);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it("without the flag the document fails as before", async () => {
|
|
228
|
+
setupDocument(3);
|
|
229
|
+
failPage2();
|
|
230
|
+
await expect(documentProcessor({ file: Buffer.from("%PDF"), name: "a.pdf", config: mistral() })).rejects.toThrow("vision outage");
|
|
231
|
+
});
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
describe("reconstructTableHeaders", () => {
|
|
235
|
+
const { reconstructTableHeaders } = require("./doc_processor") as typeof import("./doc_processor");
|
|
236
|
+
const tableOn = (headers: string[], is_continuation: boolean) =>
|
|
237
|
+
({ needs_correction: false, confidence: "high", reasoning: "", current_page_table: { headers, is_continuation } }) as never;
|
|
238
|
+
const build = () => [
|
|
239
|
+
{ page: 1, content: "| a | b |\n| - | - |\n| 1 | 2 |" },
|
|
240
|
+
{ page: 2, content: "| 3 | 4 |", vlm_failed: true as boolean | undefined },
|
|
241
|
+
{ page: 3, content: "| 5 | 6 |" },
|
|
242
|
+
];
|
|
243
|
+
const results = () => new Map([[1, tableOn(["a", "b"], false)], [3, tableOn(["x", "y"], true)]]);
|
|
244
|
+
|
|
245
|
+
it("does not hand headers from before a failed page to a later continuation", () => {
|
|
246
|
+
const doc = build();
|
|
247
|
+
reconstructTableHeaders(doc, results());
|
|
248
|
+
expect(doc[2].content).toBe("| 5 | 6 |");
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it("without a failed page the headers carry across as before", () => {
|
|
252
|
+
const doc = build();
|
|
253
|
+
doc[1].vlm_failed = undefined;
|
|
254
|
+
reconstructTableHeaders(doc, results());
|
|
255
|
+
expect(doc[2].content).toBe("| a | b |\n| --- | --- |\n| 5 | 6 |");
|
|
256
|
+
});
|
|
257
|
+
});
|