@uipath/agent-tool 1.203.0-preview.205 → 1.204.0-preview.206
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/THIRD-PARTY-NOTICES.md +43 -5
- package/dist/{agent-tool-OK5DK57D-rjan4r3q.js → agent-tool-OK5DK57D-w2sn5ft0.js} +3 -2
- package/dist/{embedded-file-reader-0sjt4nkj.js → embedded-file-reader-v8c2yj2a.js} +2 -2
- package/dist/executor-tool.js +7 -3
- package/dist/{index-s1mvhfbj.js → index-2gm7tb8q.js} +448 -980
- package/dist/index-q0fkqv6h.js +5339 -0
- package/dist/index-rgfg9t8f.js +663 -0
- package/dist/index.js +8 -4
- package/dist/memory-runtime-service-8b2j31ww.js +138 -0
- package/dist/packager-tool-22e4nhzm.js +1176 -0
- package/dist/packager-tool-af0drshm.js +988 -0
- package/dist/{packager-tool-byvnxap3.js → packager-tool-c6sb5jfp.js} +16 -1183
- package/dist/packager-tool-cxp7cwv2.js +5075 -0
- package/dist/packager-tool-kb4fk2pb.js +540 -0
- package/dist/packager-tool-nqcmgnpm.js +36786 -0
- package/dist/{packager-tool-tnz82jk0.js → packager-tool-ryge2f2x.js} +1826 -5310
- package/dist/packager-tool-xhvv7tkq.js +1376 -0
- package/dist/{packager-tool-zfzk9gj1.js → packager-tool-ygxda1hn.js} +948 -2752
- package/dist/packager-tool.js +5 -5
- package/dist/tool.js +8 -4
- package/package.json +2 -2
- package/dist/packager-tool-3te47qhk.js +0 -1751
|
@@ -0,0 +1,988 @@
|
|
|
1
|
+
import {
|
|
2
|
+
bundleSolution,
|
|
3
|
+
finalizeZip64,
|
|
4
|
+
uploadOrOverwriteSolution
|
|
5
|
+
} from "./packager-tool-cxp7cwv2.js";
|
|
6
|
+
import {
|
|
7
|
+
findSolutionFile,
|
|
8
|
+
updateSolutionFile,
|
|
9
|
+
updateUipxSolutionId
|
|
10
|
+
} from "./packager-tool-kb4fk2pb.js";
|
|
11
|
+
import {
|
|
12
|
+
AttachmentsApi,
|
|
13
|
+
JobAttachmentUploadError,
|
|
14
|
+
PersonalWorkspacesApi,
|
|
15
|
+
createApiClient,
|
|
16
|
+
uploadJobAttachment
|
|
17
|
+
} from "./packager-tool-nqcmgnpm.js";
|
|
18
|
+
import {
|
|
19
|
+
getLoginStatusAsync
|
|
20
|
+
} from "./packager-tool-xhvv7tkq.js";
|
|
21
|
+
import {
|
|
22
|
+
OutputFormatter,
|
|
23
|
+
catchError,
|
|
24
|
+
extractErrorDetails,
|
|
25
|
+
extractErrorMessage,
|
|
26
|
+
getFileSystem,
|
|
27
|
+
logger,
|
|
28
|
+
parseAttachmentSpec,
|
|
29
|
+
readAttachmentSpecs
|
|
30
|
+
} from "./packager-tool-ryge2f2x.js";
|
|
31
|
+
import {
|
|
32
|
+
zipSync
|
|
33
|
+
} from "./packager-tool-b098y4a2.js";
|
|
34
|
+
|
|
35
|
+
// src/services/agent-builder-migrations.ts
|
|
36
|
+
var warnedLegacyToolGuardrailPolicies = false;
|
|
37
|
+
function migrateLegacyToolGuardrailPolicies(builder) {
|
|
38
|
+
let migrated = false;
|
|
39
|
+
for (const resource of builder.resources ?? []) {
|
|
40
|
+
if (resource.$resourceType !== "tool" || !Array.isArray(resource.guardrailPolicies)) {
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (!resource.guardrail?.policies?.length) {
|
|
44
|
+
resource.guardrail = { policies: resource.guardrailPolicies };
|
|
45
|
+
migrated = true;
|
|
46
|
+
}
|
|
47
|
+
delete resource.guardrailPolicies;
|
|
48
|
+
}
|
|
49
|
+
if (migrated && !warnedLegacyToolGuardrailPolicies) {
|
|
50
|
+
OutputFormatter.log({
|
|
51
|
+
Warning: "Migrated legacy guardrailPolicies to guardrail.policies."
|
|
52
|
+
});
|
|
53
|
+
warnedLegacyToolGuardrailPolicies = true;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// src/services/agent-project-service.ts
|
|
58
|
+
class AgentProjectService {
|
|
59
|
+
fs = getFileSystem();
|
|
60
|
+
resolvedAgentDirs = new Map;
|
|
61
|
+
getAgentDir(projectPath) {
|
|
62
|
+
const cached = this.resolvedAgentDirs.get(projectPath);
|
|
63
|
+
if (cached) {
|
|
64
|
+
return cached;
|
|
65
|
+
}
|
|
66
|
+
return projectPath;
|
|
67
|
+
}
|
|
68
|
+
async resolveAgentDir(projectPath) {
|
|
69
|
+
const cached = this.resolvedAgentDirs.get(projectPath);
|
|
70
|
+
if (cached) {
|
|
71
|
+
return cached;
|
|
72
|
+
}
|
|
73
|
+
const flatAgent = this.fs.path.join(projectPath, "agent.json");
|
|
74
|
+
if (await this.fs.stat(flatAgent)) {
|
|
75
|
+
this.resolvedAgentDirs.set(projectPath, projectPath);
|
|
76
|
+
return projectPath;
|
|
77
|
+
}
|
|
78
|
+
const entries = await this.fs.readdir(projectPath);
|
|
79
|
+
for (const entry of entries) {
|
|
80
|
+
if (entry.startsWith(".") || entry === "evals" || entry === "features" || entry === "resources" || entry === "userProfile") {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const candidate = this.fs.path.join(projectPath, entry);
|
|
84
|
+
const candidateStat = await this.fs.stat(candidate);
|
|
85
|
+
if (!candidateStat?.isDirectory())
|
|
86
|
+
continue;
|
|
87
|
+
const agentStat = await this.fs.stat(this.fs.path.join(candidate, "agent.json"));
|
|
88
|
+
if (agentStat) {
|
|
89
|
+
this.resolvedAgentDirs.set(projectPath, candidate);
|
|
90
|
+
return candidate;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
this.resolvedAgentDirs.set(projectPath, projectPath);
|
|
94
|
+
return projectPath;
|
|
95
|
+
}
|
|
96
|
+
async readAgentJson(projectPath) {
|
|
97
|
+
const agentDir = this.getAgentDir(projectPath);
|
|
98
|
+
const raw = await this.fs.readFile(this.fs.path.join(agentDir, "agent.json"), "utf-8");
|
|
99
|
+
return JSON.parse(raw);
|
|
100
|
+
}
|
|
101
|
+
async writeAgentJson(projectPath, agent) {
|
|
102
|
+
const agentDir = this.getAgentDir(projectPath);
|
|
103
|
+
await this.fs.writeFile(this.fs.path.join(agentDir, "agent.json"), `${JSON.stringify(agent, null, 2)}
|
|
104
|
+
`);
|
|
105
|
+
const builderDir = this.fs.path.join(agentDir, ".agent-builder");
|
|
106
|
+
await this.safeMkdir(builderDir);
|
|
107
|
+
let existingBuilder;
|
|
108
|
+
const [builderReadError, builderRaw] = await catchError(this.fs.readFile(this.fs.path.join(builderDir, "agent.json"), "utf-8"));
|
|
109
|
+
if (!builderReadError && builderRaw) {
|
|
110
|
+
try {
|
|
111
|
+
existingBuilder = JSON.parse(builderRaw);
|
|
112
|
+
migrateLegacyToolGuardrailPolicies(existingBuilder);
|
|
113
|
+
} catch {}
|
|
114
|
+
}
|
|
115
|
+
const builderAgent = {
|
|
116
|
+
id: agent.projectId,
|
|
117
|
+
name: existingBuilder?.name ?? "Agent",
|
|
118
|
+
...agent,
|
|
119
|
+
resources: existingBuilder?.resources ?? agent.resources ?? [],
|
|
120
|
+
features: existingBuilder?.features ?? agent.features ?? []
|
|
121
|
+
};
|
|
122
|
+
await this.fs.writeFile(this.fs.path.join(builderDir, "agent.json"), `${JSON.stringify(builderAgent, null, 2)}
|
|
123
|
+
`);
|
|
124
|
+
}
|
|
125
|
+
async readSolutionStorage(projectPath) {
|
|
126
|
+
const raw = await this.fs.readFile(this.fs.path.join(projectPath, "SolutionStorage.json"), "utf-8");
|
|
127
|
+
return JSON.parse(raw);
|
|
128
|
+
}
|
|
129
|
+
async writeSolutionStorage(projectPath, storage) {
|
|
130
|
+
await this.fs.writeFile(this.fs.path.join(projectPath, "SolutionStorage.json"), `${JSON.stringify(storage, null, 2)}
|
|
131
|
+
`);
|
|
132
|
+
}
|
|
133
|
+
async readEvaluator(projectPath, fileName) {
|
|
134
|
+
const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators", fileName);
|
|
135
|
+
const raw = await this.fs.readFile(filePath, "utf-8");
|
|
136
|
+
return JSON.parse(raw);
|
|
137
|
+
}
|
|
138
|
+
async writeEvaluator(projectPath, evaluator) {
|
|
139
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators");
|
|
140
|
+
await this.safeMkdir(dir);
|
|
141
|
+
await this.fs.writeFile(this.fs.path.join(dir, evaluator.fileName), `${JSON.stringify(evaluator, null, 2)}
|
|
142
|
+
`);
|
|
143
|
+
}
|
|
144
|
+
async listEvaluators(projectPath) {
|
|
145
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators");
|
|
146
|
+
const [error, files] = await catchError(this.fs.readdir(dir));
|
|
147
|
+
if (error) {
|
|
148
|
+
return [];
|
|
149
|
+
}
|
|
150
|
+
const evaluators = [];
|
|
151
|
+
for (const file of files) {
|
|
152
|
+
if (file.endsWith(".json")) {
|
|
153
|
+
const raw = await this.fs.readFile(this.fs.path.join(dir, file), "utf-8");
|
|
154
|
+
evaluators.push(JSON.parse(raw));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return evaluators;
|
|
158
|
+
}
|
|
159
|
+
async deleteEvaluator(projectPath, fileName) {
|
|
160
|
+
const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "evaluators", fileName);
|
|
161
|
+
await this.fs.rm(filePath);
|
|
162
|
+
}
|
|
163
|
+
async readEvalSet(projectPath, fileName) {
|
|
164
|
+
const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets", fileName);
|
|
165
|
+
const raw = await this.fs.readFile(filePath, "utf-8");
|
|
166
|
+
return JSON.parse(raw);
|
|
167
|
+
}
|
|
168
|
+
async writeEvalSet(projectPath, evalSet, fileName) {
|
|
169
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets");
|
|
170
|
+
await this.safeMkdir(dir);
|
|
171
|
+
await this.fs.writeFile(this.fs.path.join(dir, fileName), `${JSON.stringify(evalSet, null, 2)}
|
|
172
|
+
`);
|
|
173
|
+
}
|
|
174
|
+
async listEvalSets(projectPath) {
|
|
175
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets");
|
|
176
|
+
const [error, files] = await catchError(this.fs.readdir(dir));
|
|
177
|
+
if (error) {
|
|
178
|
+
return [];
|
|
179
|
+
}
|
|
180
|
+
const sets = [];
|
|
181
|
+
for (const file of files) {
|
|
182
|
+
if (file.endsWith(".json")) {
|
|
183
|
+
const raw = await this.fs.readFile(this.fs.path.join(dir, file), "utf-8");
|
|
184
|
+
sets.push(JSON.parse(raw));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return sets;
|
|
188
|
+
}
|
|
189
|
+
async deleteEvalSet(projectPath, fileName) {
|
|
190
|
+
const filePath = this.fs.path.join(this.getAgentDir(projectPath), "evals", "eval-sets", fileName);
|
|
191
|
+
await this.fs.rm(filePath);
|
|
192
|
+
}
|
|
193
|
+
async writeFeature(projectPath, featureName, feature) {
|
|
194
|
+
this.validateFeatureName(featureName);
|
|
195
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "features", featureName);
|
|
196
|
+
await this.safeMkdir(dir);
|
|
197
|
+
await this.fs.writeFile(this.fs.path.join(dir, "feature.json"), `${JSON.stringify(feature, null, 2)}
|
|
198
|
+
`);
|
|
199
|
+
}
|
|
200
|
+
async readFeature(projectPath, featureName) {
|
|
201
|
+
this.validateFeatureName(featureName);
|
|
202
|
+
const filePath = this.fs.path.join(this.getAgentDir(projectPath), "features", featureName, "feature.json");
|
|
203
|
+
const raw = await this.fs.readFile(filePath, "utf-8");
|
|
204
|
+
if (!raw) {
|
|
205
|
+
throw new Error(`Feature file not found: ${filePath}`);
|
|
206
|
+
}
|
|
207
|
+
const parsed = JSON.parse(raw);
|
|
208
|
+
if (!parsed) {
|
|
209
|
+
throw new Error(`Feature file is empty: ${filePath}`);
|
|
210
|
+
}
|
|
211
|
+
return parsed;
|
|
212
|
+
}
|
|
213
|
+
async listFeatureDirs(projectPath) {
|
|
214
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "features");
|
|
215
|
+
const [error, entries] = await catchError(this.fs.readdir(dir));
|
|
216
|
+
if (error) {
|
|
217
|
+
return [];
|
|
218
|
+
}
|
|
219
|
+
return entries;
|
|
220
|
+
}
|
|
221
|
+
async deleteFeature(projectPath, featureName) {
|
|
222
|
+
this.validateFeatureName(featureName);
|
|
223
|
+
const dir = this.fs.path.join(this.getAgentDir(projectPath), "features", featureName);
|
|
224
|
+
await this.fs.rm(dir);
|
|
225
|
+
}
|
|
226
|
+
async safeMkdir(dir) {
|
|
227
|
+
await this.fs.mkdir(dir);
|
|
228
|
+
}
|
|
229
|
+
async writeJsonFile(filePath, data) {
|
|
230
|
+
await this.fs.writeFile(filePath, `${JSON.stringify(data, null, 2)}
|
|
231
|
+
`);
|
|
232
|
+
}
|
|
233
|
+
validateFeatureName(featureName) {
|
|
234
|
+
if (featureName.trim().length === 0 || featureName === "." || featureName === ".." || featureName.includes("/") || featureName.includes("\\") || featureName.includes("\x00") || featureName !== this.fs.path.basename(featureName)) {
|
|
235
|
+
throw new Error(`Invalid feature name: "${featureName}"`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// src/services/attachment-inputs.ts
|
|
241
|
+
class AttachmentInputError extends Error {
|
|
242
|
+
errorCode;
|
|
243
|
+
instructions;
|
|
244
|
+
constructor(message, errorCode, instructions) {
|
|
245
|
+
super(message);
|
|
246
|
+
this.errorCode = errorCode;
|
|
247
|
+
this.instructions = instructions;
|
|
248
|
+
this.name = "AttachmentInputError";
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
var AGENT_ATTACHMENT_INSTRUCTIONS = `Provide --attachment as 'field=path': 'field' is an inputSchema property of agent.json declared as { "$ref": "#/definitions/job-attachment" } and 'path' is a readable local file resolved from the current directory. Repeat the flag for more files; repeat the same field only when its schema is an array of job-attachments. Nothing was uploaded.`;
|
|
252
|
+
var AGENT_JSON_NOT_FOUND_INSTRUCTIONS = "Pass the agent project directory (the folder containing agent.json, or its parent for solutions pulled from Studio Web). --attachment needs agent.json to check which inputs are job-attachment fields. Nothing was uploaded.";
|
|
253
|
+
var JOB_ATTACHMENT_KIND = "JobAttachment";
|
|
254
|
+
var CANONICAL_REF = "#/definitions/job-attachment";
|
|
255
|
+
var REF_PATTERN = /^#\/(definitions|\$defs)\/(.+)$/;
|
|
256
|
+
var MAX_REF_DEPTH = 8;
|
|
257
|
+
function isObject(value) {
|
|
258
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
259
|
+
}
|
|
260
|
+
function definitionsOf(schema) {
|
|
261
|
+
return {
|
|
262
|
+
...isObject(schema.definitions) ? schema.definitions : {},
|
|
263
|
+
...isObject(schema.$defs) ? schema.$defs : {}
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
function refName(encoded) {
|
|
267
|
+
const [error, decoded] = catchError(() => decodeURIComponent(encoded));
|
|
268
|
+
return error ? encoded : decoded;
|
|
269
|
+
}
|
|
270
|
+
function isAttachmentNode(node, defs, depth = 0) {
|
|
271
|
+
if (!isObject(node) || depth > MAX_REF_DEPTH)
|
|
272
|
+
return false;
|
|
273
|
+
if (node["x-uipath-resource-kind"] === JOB_ATTACHMENT_KIND)
|
|
274
|
+
return true;
|
|
275
|
+
if (typeof node.$ref !== "string")
|
|
276
|
+
return false;
|
|
277
|
+
const match = REF_PATTERN.exec(node.$ref);
|
|
278
|
+
if (!match)
|
|
279
|
+
return false;
|
|
280
|
+
const target = defs[refName(match[2])];
|
|
281
|
+
if (target === undefined)
|
|
282
|
+
return node.$ref === CANONICAL_REF;
|
|
283
|
+
return isAttachmentNode(target, defs, depth + 1);
|
|
284
|
+
}
|
|
285
|
+
function hasType(node, type) {
|
|
286
|
+
return node.type === type || Array.isArray(node.type) && node.type.includes(type);
|
|
287
|
+
}
|
|
288
|
+
function findJobAttachmentFields(inputSchema) {
|
|
289
|
+
if (!isObject(inputSchema) || !isObject(inputSchema.properties))
|
|
290
|
+
return [];
|
|
291
|
+
const defs = definitionsOf(inputSchema);
|
|
292
|
+
const fields = [];
|
|
293
|
+
for (const [name, property] of Object.entries(inputSchema.properties)) {
|
|
294
|
+
if (!isObject(property))
|
|
295
|
+
continue;
|
|
296
|
+
if (isAttachmentNode(property, defs)) {
|
|
297
|
+
fields.push({ name, kind: "single" });
|
|
298
|
+
} else if (hasType(property, "array") && isAttachmentNode(property.items, defs)) {
|
|
299
|
+
fields.push({ name, kind: "array" });
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return fields;
|
|
303
|
+
}
|
|
304
|
+
function describeInputFields(inputSchema, fields) {
|
|
305
|
+
const attachmentNames = fields.map((f) => f.name);
|
|
306
|
+
const properties = isObject(inputSchema) && isObject(inputSchema.properties) ? inputSchema.properties : {};
|
|
307
|
+
const otherNames = Object.keys(properties).filter((n) => !attachmentNames.includes(n));
|
|
308
|
+
const typeOf = (name) => {
|
|
309
|
+
const property = properties[name];
|
|
310
|
+
if (!isObject(property))
|
|
311
|
+
return "unknown";
|
|
312
|
+
if (typeof property.type === "string")
|
|
313
|
+
return property.type;
|
|
314
|
+
if (Array.isArray(property.type))
|
|
315
|
+
return property.type.join(" | ");
|
|
316
|
+
if (typeof property.$ref === "string")
|
|
317
|
+
return `$ref ${property.$ref}`;
|
|
318
|
+
return "unknown";
|
|
319
|
+
};
|
|
320
|
+
return { attachmentNames, otherNames, typeOf };
|
|
321
|
+
}
|
|
322
|
+
var list = (names) => names.length ? `[${names.join(", ")}]` : "none";
|
|
323
|
+
function referencedDefinitionName(inputSchema, name) {
|
|
324
|
+
if (!isObject(inputSchema) || !isObject(inputSchema.properties)) {
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
const property = inputSchema.properties[name];
|
|
328
|
+
if (!isObject(property))
|
|
329
|
+
return;
|
|
330
|
+
const node = hasType(property, "array") && isObject(property.items) ? property.items : property;
|
|
331
|
+
if (typeof node.$ref !== "string")
|
|
332
|
+
return;
|
|
333
|
+
const match = REF_PATTERN.exec(node.$ref);
|
|
334
|
+
if (!match)
|
|
335
|
+
return;
|
|
336
|
+
const defName = refName(match[2]);
|
|
337
|
+
return definitionsOf(inputSchema)[defName] === undefined ? undefined : defName;
|
|
338
|
+
}
|
|
339
|
+
function validateAttachmentSpecs(specs, fields, inputSchema) {
|
|
340
|
+
const described = describeInputFields(inputSchema, fields);
|
|
341
|
+
const byName = new Map(fields.map((f) => [f.name, f]));
|
|
342
|
+
const counts = new Map;
|
|
343
|
+
for (const spec of specs) {
|
|
344
|
+
counts.set(spec.name, (counts.get(spec.name) ?? 0) + 1);
|
|
345
|
+
if (byName.has(spec.name))
|
|
346
|
+
continue;
|
|
347
|
+
const declared = described.otherNames.includes(spec.name);
|
|
348
|
+
const inventory = fields.length === 0 ? "This agent declares no job-attachment inputs." : `Job-attachment inputs: ${list(described.attachmentNames)}.`;
|
|
349
|
+
const defName = declared ? referencedDefinitionName(inputSchema, spec.name) : undefined;
|
|
350
|
+
if (defName !== undefined) {
|
|
351
|
+
throw new AttachmentInputError(`--attachment field '${spec.name}' references definition '${defName}' which does not carry "x-uipath-resource-kind": "JobAttachment", so it is not a job-attachment input. ${inventory}`, "invalid_argument", `Add "x-uipath-resource-kind": "JobAttachment" to the '${defName}' definition (copy the canonical job-attachment block from the agent docs), then run 'uip agent refresh <project-path>'. Nothing was uploaded.`);
|
|
352
|
+
}
|
|
353
|
+
if (declared) {
|
|
354
|
+
throw new AttachmentInputError(`--attachment field '${spec.name}' is declared as type '${described.typeOf(spec.name)}' in agent.json inputSchema, not as a job-attachment. ${inventory}`, "invalid_argument", `Pass a plain value for '${spec.name}' through --inputs, or change its schema to { "$ref": "#/definitions/job-attachment" } with the job-attachment definition and run 'uip agent refresh <project-path>'. Nothing was uploaded.`);
|
|
355
|
+
}
|
|
356
|
+
throw new AttachmentInputError(`--attachment field '${spec.name}' is not an input of this agent. ${inventory} Other inputs: ${list(described.otherNames)}.`, "invalid_argument", `Use --attachment <field>=<path> with one of the job-attachment inputs listed in Message, or add the field to agent.json inputSchema.properties as { "$ref": "#/definitions/job-attachment" } together with the canonical 'job-attachment' definition (x-uipath-resource-kind: JobAttachment), then run 'uip agent refresh <project-path>'. Nothing was uploaded.`);
|
|
357
|
+
}
|
|
358
|
+
for (const [name, count] of counts) {
|
|
359
|
+
if (count > 1 && byName.get(name)?.kind === "single") {
|
|
360
|
+
throw new AttachmentInputError(`--attachment field '${name}' was given ${count} times but its schema is a single job-attachment, not an array.`, "invalid_argument", `Pass one --attachment per single job-attachment field. Repeat a field only when its schema is { "type": "array", "items": { "$ref": "#/definitions/job-attachment" } }. Nothing was uploaded.`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function applyAttachmentReferences(inputs, bound) {
|
|
365
|
+
const merged = { ...inputs };
|
|
366
|
+
const arrays = new Map;
|
|
367
|
+
for (const b of bound) {
|
|
368
|
+
if (b.kind === "array") {
|
|
369
|
+
const refs = arrays.get(b.field) ?? [];
|
|
370
|
+
refs.push(b.reference);
|
|
371
|
+
arrays.set(b.field, refs);
|
|
372
|
+
merged[b.field] = refs;
|
|
373
|
+
} else {
|
|
374
|
+
merged[b.field] = b.reference;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return merged;
|
|
378
|
+
}
|
|
379
|
+
function toAttachmentSummaries(bound) {
|
|
380
|
+
return bound.map((b) => ({
|
|
381
|
+
Field: b.field,
|
|
382
|
+
AttachmentId: b.reference.ID,
|
|
383
|
+
FileName: b.reference.FullName,
|
|
384
|
+
MimeType: b.reference.MimeType,
|
|
385
|
+
Size: Number(b.reference.Metadata?.size ?? 0)
|
|
386
|
+
}));
|
|
387
|
+
}
|
|
388
|
+
var LARGE_FILE_WARN_BYTES = 100 * 1024 * 1024;
|
|
389
|
+
async function prepareAttachmentInputs(projectPath, attachmentArgs, inputs) {
|
|
390
|
+
const [specError, specs] = catchError(() => attachmentArgs.map(parseAttachmentSpec));
|
|
391
|
+
if (specError) {
|
|
392
|
+
throw new AttachmentInputError(specError.message, "invalid_argument", AGENT_ATTACHMENT_INSTRUCTIONS);
|
|
393
|
+
}
|
|
394
|
+
const projectService = new AgentProjectService;
|
|
395
|
+
const [agentError, agent] = await catchError((async () => {
|
|
396
|
+
await projectService.resolveAgentDir(projectPath);
|
|
397
|
+
return projectService.readAgentJson(projectPath);
|
|
398
|
+
})());
|
|
399
|
+
if (agentError) {
|
|
400
|
+
const parseFailed = agentError instanceof SyntaxError;
|
|
401
|
+
throw new AttachmentInputError(`Cannot read agent.json under '${projectPath}': ${agentError.message}`, parseFailed ? "invalid_argument" : "not_found", parseFailed ? "Fix the JSON syntax of agent.json (run 'uip agent validate <project-path>' to see the error), then retry. Nothing was uploaded." : AGENT_JSON_NOT_FOUND_INSTRUCTIONS);
|
|
402
|
+
}
|
|
403
|
+
const parsed = agent;
|
|
404
|
+
if (parsed === null) {
|
|
405
|
+
throw new AttachmentInputError(`No agent.json found under '${projectPath}'.`, "not_found", AGENT_JSON_NOT_FOUND_INSTRUCTIONS);
|
|
406
|
+
}
|
|
407
|
+
if (!isObject(parsed)) {
|
|
408
|
+
throw new AttachmentInputError(`agent.json under '${projectPath}' is not a JSON object.`, "invalid_argument", "Fix agent.json (run 'uip agent validate <project-path>' to see the error), then retry. Nothing was uploaded.");
|
|
409
|
+
}
|
|
410
|
+
const fields = findJobAttachmentFields(agent.inputSchema);
|
|
411
|
+
validateAttachmentSpecs(specs, fields, agent.inputSchema);
|
|
412
|
+
const kindOf = new Map(fields.map((f) => [f.name, f.kind]));
|
|
413
|
+
const fs = getFileSystem();
|
|
414
|
+
for (const spec of specs) {
|
|
415
|
+
const [statError, stats] = await catchError(fs.stat(spec.path));
|
|
416
|
+
if (statError) {
|
|
417
|
+
const details = await extractErrorDetails(statError);
|
|
418
|
+
throw new AttachmentInputError(`Cannot access --attachment '${spec.path}' for field '${spec.name}': ${details.message}`, details.errorCode, AGENT_ATTACHMENT_INSTRUCTIONS);
|
|
419
|
+
}
|
|
420
|
+
if (!stats) {
|
|
421
|
+
throw new AttachmentInputError(`--attachment '${spec.path}' for field '${spec.name}' was not found.`, "not_found", "Check the path given to --attachment; it is resolved from the current working directory, not from the agent project directory. Nothing was uploaded.");
|
|
422
|
+
}
|
|
423
|
+
if (stats.isDirectory()) {
|
|
424
|
+
throw new AttachmentInputError(`--attachment '${spec.path}' for field '${spec.name}' is a directory, not a file.`, "invalid_argument", AGENT_ATTACHMENT_INSTRUCTIONS);
|
|
425
|
+
}
|
|
426
|
+
if (stats.size === 0) {
|
|
427
|
+
throw new AttachmentInputError(`--attachment '${spec.path}' for field '${spec.name}' is empty (0 bytes).`, "invalid_argument", AGENT_ATTACHMENT_INSTRUCTIONS);
|
|
428
|
+
}
|
|
429
|
+
if (stats.size > LARGE_FILE_WARN_BYTES) {
|
|
430
|
+
logger.warn(`--attachment '${spec.path}' is ${stats.size} bytes; Orchestrator may reject very large attachments.`);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
const [readError, prepared] = await catchError(readAttachmentSpecs(specs));
|
|
434
|
+
if (readError) {
|
|
435
|
+
const details = await extractErrorDetails(readError);
|
|
436
|
+
throw new AttachmentInputError(readError.message, details.errorCode, AGENT_ATTACHMENT_INSTRUCTIONS);
|
|
437
|
+
}
|
|
438
|
+
const boundNames = new Set(specs.map((s) => s.name));
|
|
439
|
+
for (const name of boundNames) {
|
|
440
|
+
if (name in inputs) {
|
|
441
|
+
logger.warn(`--attachment '${name}' overrides the value provided in --inputs.`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
const required = Array.isArray(agent.inputSchema?.required) ? agent.inputSchema.required : [];
|
|
445
|
+
for (const field of fields) {
|
|
446
|
+
if (required.includes(field.name) && !boundNames.has(field.name) && !(field.name in inputs)) {
|
|
447
|
+
logger.warn(`Required job-attachment input '${field.name}' has no --attachment and no --inputs value; the run will likely fault.`);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
return prepared.map((p) => ({
|
|
451
|
+
field: p.name,
|
|
452
|
+
path: p.path,
|
|
453
|
+
fileName: p.fileName,
|
|
454
|
+
bytes: p.bytes,
|
|
455
|
+
kind: kindOf.get(p.name) ?? "single"
|
|
456
|
+
}));
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// src/services/agent-debug-service.ts
|
|
460
|
+
import { randomUUID } from "node:crypto";
|
|
461
|
+
|
|
462
|
+
// src/services/pack-helpers.ts
|
|
463
|
+
async function collectProjectFiles(rootDir) {
|
|
464
|
+
const files = [];
|
|
465
|
+
await collectRecursive(rootDir, rootDir, files);
|
|
466
|
+
return files;
|
|
467
|
+
}
|
|
468
|
+
async function collectRecursive(rootDir, currentDir, files) {
|
|
469
|
+
const fs = getFileSystem();
|
|
470
|
+
const entries = await fs.readdir(currentDir);
|
|
471
|
+
for (const entry of entries) {
|
|
472
|
+
const fullPath = fs.path.join(currentDir, entry);
|
|
473
|
+
const stats = await fs.stat(fullPath);
|
|
474
|
+
if (stats?.isDirectory()) {
|
|
475
|
+
await collectRecursive(rootDir, fullPath, files);
|
|
476
|
+
} else if (stats) {
|
|
477
|
+
files.push(fs.path.relative(rootDir, fullPath).replace(/\\/g, "/"));
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
function matchesExclude(relPath, exclude) {
|
|
482
|
+
for (const pattern of exclude) {
|
|
483
|
+
const cleaned = pattern.replace(/^\.\//, "").replace(/\/\*$/, "");
|
|
484
|
+
if (cleaned.startsWith("*")) {
|
|
485
|
+
const suffix = cleaned.slice(1).replace(/^\//, "");
|
|
486
|
+
if (relPath.includes(`/${suffix}/`) || relPath.includes(`/${suffix}`)) {
|
|
487
|
+
return true;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
if (relPath === cleaned || relPath.startsWith(`${cleaned}/`)) {
|
|
491
|
+
return true;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
return false;
|
|
495
|
+
}
|
|
496
|
+
async function createArchive(sourceDir, outputPath, exclude) {
|
|
497
|
+
const fs = getFileSystem();
|
|
498
|
+
const files = await collectProjectFiles(sourceDir);
|
|
499
|
+
const zippable = {};
|
|
500
|
+
for (const relPath of files) {
|
|
501
|
+
if (exclude && matchesExclude(relPath, exclude)) {
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
const data = await fs.readFile(fs.path.join(sourceDir, relPath));
|
|
505
|
+
if (data !== null) {
|
|
506
|
+
zippable[relPath] = new Uint8Array(data);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
await fs.writeFile(outputPath, finalizeZip64(zipSync(zippable, { level: 6 })));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// src/services/agent-local-workspace-eval-preparer.ts
|
|
513
|
+
var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
514
|
+
function isUUID(value) {
|
|
515
|
+
return UUID_PATTERN.test(value);
|
|
516
|
+
}
|
|
517
|
+
function isRecord(value) {
|
|
518
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
519
|
+
}
|
|
520
|
+
function toForwardSlash(path) {
|
|
521
|
+
return path.replace(/\\/g, "/");
|
|
522
|
+
}
|
|
523
|
+
async function resolveStudioWebConfig() {
|
|
524
|
+
const [loginError, login] = await catchError(getLoginStatusAsync());
|
|
525
|
+
if (loginError) {
|
|
526
|
+
throw new Error(loginError.message);
|
|
527
|
+
}
|
|
528
|
+
if (login.loginStatus !== "Logged in" || !login.baseUrl) {
|
|
529
|
+
throw new Error("Not logged in. Run 'uip login' first.");
|
|
530
|
+
}
|
|
531
|
+
if (!login.accessToken) {
|
|
532
|
+
throw new Error("Access token not available from login.");
|
|
533
|
+
}
|
|
534
|
+
if (!login.organizationName) {
|
|
535
|
+
throw new Error("Organization name not available from login. Required for Studio Web evaluation.");
|
|
536
|
+
}
|
|
537
|
+
return {
|
|
538
|
+
baseUrl: login.baseUrl,
|
|
539
|
+
tenantId: login.tenantId,
|
|
540
|
+
authToken: login.accessToken,
|
|
541
|
+
organizationName: login.organizationName
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
class AgentLocalWorkspaceEvalPreparer {
|
|
546
|
+
fs;
|
|
547
|
+
constructor(fs = getFileSystem()) {
|
|
548
|
+
this.fs = fs;
|
|
549
|
+
}
|
|
550
|
+
async isLocalWorkspace(projectPath) {
|
|
551
|
+
return await this.readLocalWorkspaceMarker(projectPath) !== undefined;
|
|
552
|
+
}
|
|
553
|
+
async prepare(projectPath, config, existingSolutionIdOverride) {
|
|
554
|
+
const absoluteProjectPath = this.fs.path.resolve(projectPath);
|
|
555
|
+
const marker = await this.readLocalWorkspaceMarker(absoluteProjectPath);
|
|
556
|
+
const packageRoot = marker?.rootPath ?? absoluteProjectPath;
|
|
557
|
+
const projectService = new AgentProjectService;
|
|
558
|
+
const agentDir = await projectService.resolveAgentDir(absoluteProjectPath);
|
|
559
|
+
const agent = await projectService.readAgentJson(absoluteProjectPath);
|
|
560
|
+
const projectFilePath = this.fs.path.join(agentDir, "project.uiproj");
|
|
561
|
+
if (!await this.fs.exists(projectFilePath)) {
|
|
562
|
+
throw new Error(`Not a valid agent project directory: missing project.uiproj in ${agentDir}`);
|
|
563
|
+
}
|
|
564
|
+
const projectFileContent = await this.fs.readFile(projectFilePath, "utf-8");
|
|
565
|
+
const [projectFileError, parsedProjectFile] = catchError(() => JSON.parse(String(projectFileContent)));
|
|
566
|
+
if (projectFileError || !isRecord(parsedProjectFile)) {
|
|
567
|
+
throw new Error(`Invalid project.uiproj in ${agentDir}: ${projectFileError?.message ?? "expected a JSON object"}`);
|
|
568
|
+
}
|
|
569
|
+
const projectFile = {
|
|
570
|
+
Name: typeof parsedProjectFile.Name === "string" ? parsedProjectFile.Name : undefined
|
|
571
|
+
};
|
|
572
|
+
const solutionInfo = await findSolutionFile(this.fs, agentDir);
|
|
573
|
+
const solutionId = existingSolutionIdOverride ?? marker?.solutionId ?? solutionInfo?.solutionId;
|
|
574
|
+
const solutionName = projectFile.Name ?? agent.metadata.name ?? this.fs.path.basename(agentDir);
|
|
575
|
+
const safeSolutionName = solutionName.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
576
|
+
const stagingDir = this.fs.path.join(this.fs.env.tmpdir(), `.agent-eval-staging-${safeSolutionName}-${Date.now()}`);
|
|
577
|
+
await this.fs.mkdir(stagingDir);
|
|
578
|
+
const uisPath = this.fs.path.join(stagingDir, `${safeSolutionName}.uis`);
|
|
579
|
+
try {
|
|
580
|
+
logger.info("Building agent package for local workspace eval...");
|
|
581
|
+
await createArchive(packageRoot, uisPath, [
|
|
582
|
+
"./.agent-builder/*",
|
|
583
|
+
"*/.agent-builder/*",
|
|
584
|
+
".sw-path-marker",
|
|
585
|
+
"*/.sw-path-marker"
|
|
586
|
+
]);
|
|
587
|
+
logger.info("Uploading local workspace agent for eval...");
|
|
588
|
+
const importResult = await uploadOrOverwriteSolution({
|
|
589
|
+
baseUrl: config.baseUrl,
|
|
590
|
+
tenantId: config.tenantId,
|
|
591
|
+
authToken: config.authToken
|
|
592
|
+
}, config.organizationName, uisPath, solutionId, this.fs);
|
|
593
|
+
const matchedProject = this.resolveImportedProject(importResult, solutionName);
|
|
594
|
+
await this.persistSolutionStorage(projectService, absoluteProjectPath, packageRoot, projectFilePath, importResult.id, agent.projectId, matchedProject.id);
|
|
595
|
+
if (packageRoot !== absoluteProjectPath) {
|
|
596
|
+
await this.persistSolutionStorage(projectService, packageRoot, packageRoot, projectFilePath, importResult.id, agent.projectId, matchedProject.id);
|
|
597
|
+
}
|
|
598
|
+
await updateSolutionFile(this.fs, agentDir, importResult.id);
|
|
599
|
+
if (marker) {
|
|
600
|
+
await this.updateLocalWorkspaceMarker(marker.rootPath, importResult.id);
|
|
601
|
+
}
|
|
602
|
+
return {
|
|
603
|
+
solutionId: importResult.id,
|
|
604
|
+
agentProjectId: matchedProject.id
|
|
605
|
+
};
|
|
606
|
+
} finally {
|
|
607
|
+
const [cleanupError] = await catchError(this.fs.rm(stagingDir, { recursive: true }));
|
|
608
|
+
if (cleanupError) {
|
|
609
|
+
logger.warn(`Cleanup failed: ${cleanupError.message}`);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
async readLocalWorkspaceMarker(projectPath) {
|
|
614
|
+
const absoluteProjectPath = this.fs.path.resolve(projectPath);
|
|
615
|
+
const candidates = [
|
|
616
|
+
absoluteProjectPath,
|
|
617
|
+
this.fs.path.dirname(absoluteProjectPath)
|
|
618
|
+
];
|
|
619
|
+
for (const candidate of candidates) {
|
|
620
|
+
const markerPath = this.fs.path.join(candidate, ".sw-path-marker");
|
|
621
|
+
if (!await this.fs.exists(markerPath)) {
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
const content = String(await this.fs.readFile(markerPath, "utf-8"));
|
|
625
|
+
const solutionId = content.trim();
|
|
626
|
+
return {
|
|
627
|
+
rootPath: candidate,
|
|
628
|
+
...isUUID(solutionId) ? { solutionId } : {}
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
resolveImportedProject(importResult, agentName) {
|
|
634
|
+
const exactProject = importResult.projects.find((project) => project.name === agentName);
|
|
635
|
+
if (exactProject?.id) {
|
|
636
|
+
return exactProject;
|
|
637
|
+
}
|
|
638
|
+
const [onlyProject] = importResult.projects;
|
|
639
|
+
if (importResult.projects.length === 1 && onlyProject?.id) {
|
|
640
|
+
return onlyProject;
|
|
641
|
+
}
|
|
642
|
+
throw new Error(`Upload response had ${importResult.projects.length} projects and none matched "${agentName}"; refusing to guess.`);
|
|
643
|
+
}
|
|
644
|
+
async persistSolutionStorage(projectService, storagePath, packageRoot, projectFilePath, solutionId, localProjectId, cloudProjectId) {
|
|
645
|
+
const projectRelativePath = toForwardSlash(this.fs.path.relative(packageRoot, projectFilePath));
|
|
646
|
+
const projectEntry = {
|
|
647
|
+
ProjectId: localProjectId,
|
|
648
|
+
ProjectRelativePath: projectRelativePath || "project.uiproj",
|
|
649
|
+
CloudProjectId: cloudProjectId
|
|
650
|
+
};
|
|
651
|
+
const [, existingStorage] = await catchError(projectService.readSolutionStorage(storagePath));
|
|
652
|
+
const existingProjects = existingStorage?.Projects ?? [];
|
|
653
|
+
const projectIndex = existingProjects.findIndex((project) => project.ProjectId === localProjectId);
|
|
654
|
+
const projects = projectIndex === -1 ? [...existingProjects, projectEntry] : existingProjects.map((project, index) => index === projectIndex ? { ...project, ...projectEntry } : project);
|
|
655
|
+
await projectService.writeSolutionStorage(storagePath, {
|
|
656
|
+
SolutionId: solutionId,
|
|
657
|
+
Projects: projects
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
async updateLocalWorkspaceMarker(workspaceRoot, solutionId) {
|
|
661
|
+
await this.fs.writeFile(this.fs.path.join(workspaceRoot, ".sw-path-marker"), solutionId);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// src/services/agent-debug-service.ts
|
|
666
|
+
class AgentDebugCancelledError extends Error {
|
|
667
|
+
jobKey;
|
|
668
|
+
attachments;
|
|
669
|
+
constructor(jobKey, startInFlight) {
|
|
670
|
+
super(cancelledMessage(jobKey, startInFlight));
|
|
671
|
+
this.name = "AgentDebugCancelledError";
|
|
672
|
+
this.jobKey = jobKey;
|
|
673
|
+
this.attachments = startInFlight?.attachments ?? [];
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function cancelledMessage(jobKey, startInFlight) {
|
|
677
|
+
if (jobKey) {
|
|
678
|
+
return `Debug run cancelled. Job ${jobKey} may still be running on the serverless runtime.`;
|
|
679
|
+
}
|
|
680
|
+
if (!startInFlight) {
|
|
681
|
+
return "Debug run cancelled before the job started.";
|
|
682
|
+
}
|
|
683
|
+
const kept = startInFlight.attachments.length > 0 ? ` The uploaded attachments (${startInFlight.attachments.map((a) => a.reference.ID).join(", ")}) were kept, since that job would reference them.` : "";
|
|
684
|
+
return `Debug run cancelled while the start request was in flight. A job may have started; check the Orchestrator personal workspace.${kept}`;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
class AgentDebugAttachmentUploadError extends Error {
|
|
688
|
+
field;
|
|
689
|
+
path;
|
|
690
|
+
constructor(field, path, message, cause) {
|
|
691
|
+
super(message, { cause });
|
|
692
|
+
this.field = field;
|
|
693
|
+
this.path = path;
|
|
694
|
+
this.name = "AgentDebugAttachmentUploadError";
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
class AgentDebugStartOutcomeUnknownError extends Error {
|
|
699
|
+
errorCode;
|
|
700
|
+
bound;
|
|
701
|
+
constructor(message, errorCode, bound = [], options) {
|
|
702
|
+
super(message, options);
|
|
703
|
+
this.errorCode = errorCode;
|
|
704
|
+
this.bound = bound;
|
|
705
|
+
this.name = "AgentDebugStartOutcomeUnknownError";
|
|
706
|
+
}
|
|
707
|
+
withAttachments(bound) {
|
|
708
|
+
return new AgentDebugStartOutcomeUnknownError(this.message, this.errorCode, bound, { cause: this.cause });
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
var TERMINAL_STATES = new Set([
|
|
712
|
+
"Successful",
|
|
713
|
+
"Faulted",
|
|
714
|
+
"Stopped",
|
|
715
|
+
"Suspended"
|
|
716
|
+
]);
|
|
717
|
+
var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
718
|
+
|
|
719
|
+
class AgentDebugService {
|
|
720
|
+
fs = getFileSystem();
|
|
721
|
+
projectService = new AgentProjectService;
|
|
722
|
+
async debug(options, auth) {
|
|
723
|
+
throwIfAborted(options.signal);
|
|
724
|
+
const projectId = await this.resolveProjectId(options.projectPath);
|
|
725
|
+
throwIfAborted(options.signal);
|
|
726
|
+
const folderKey = await this.resolvePersonalWorkspaceKey();
|
|
727
|
+
throwIfAborted(options.signal);
|
|
728
|
+
const bound = await this.uploadAttachments(options.attachments ?? [], auth.tenantName, options.signal);
|
|
729
|
+
const inputs = applyAttachmentReferences(options.inputs, bound);
|
|
730
|
+
if (options.signal?.aborted) {
|
|
731
|
+
await this.deleteAttachmentsBestEffort(bound, auth.tenantName);
|
|
732
|
+
throw new AgentDebugCancelledError;
|
|
733
|
+
}
|
|
734
|
+
const [startError, started] = await catchError(this.startDebugJob(auth, folderKey, projectId, inputs, options.signal));
|
|
735
|
+
if (startError) {
|
|
736
|
+
if (startError instanceof AgentDebugStartOutcomeUnknownError) {
|
|
737
|
+
throw startError.withAttachments(bound);
|
|
738
|
+
}
|
|
739
|
+
if (isAbortError(startError)) {
|
|
740
|
+
throw new AgentDebugCancelledError(undefined, {
|
|
741
|
+
attachments: bound
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
await this.deleteAttachmentsBestEffort(bound, auth.tenantName);
|
|
745
|
+
throw startError;
|
|
746
|
+
}
|
|
747
|
+
const job = await asCancellation(() => this.pollJob(auth, folderKey, started.jobKey, options), started.jobKey);
|
|
748
|
+
return {
|
|
749
|
+
jobKey: started.jobKey,
|
|
750
|
+
traceId: started.traceId,
|
|
751
|
+
finalState: job.state,
|
|
752
|
+
success: job.state === "Successful",
|
|
753
|
+
output: job.output,
|
|
754
|
+
info: job.info,
|
|
755
|
+
attachments: bound
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
async uploadAttachments(prepared, tenant, signal) {
|
|
759
|
+
if (prepared.length === 0) {
|
|
760
|
+
return [];
|
|
761
|
+
}
|
|
762
|
+
const settled = await Promise.allSettled(prepared.map((p) => uploadJobAttachment(p.bytes, p.fileName, { tenant, signal })));
|
|
763
|
+
const bound = [];
|
|
764
|
+
const failures = [];
|
|
765
|
+
settled.forEach((result, index) => {
|
|
766
|
+
const input = prepared[index];
|
|
767
|
+
if (result.status === "fulfilled") {
|
|
768
|
+
bound.push({
|
|
769
|
+
field: input.field,
|
|
770
|
+
path: input.path,
|
|
771
|
+
kind: input.kind,
|
|
772
|
+
reference: result.value
|
|
773
|
+
});
|
|
774
|
+
logger.info(`Uploaded '${input.path}' as attachment ${result.value.ID} (field '${input.field}').`);
|
|
775
|
+
} else {
|
|
776
|
+
failures.push({ input, reason: result.reason });
|
|
777
|
+
}
|
|
778
|
+
});
|
|
779
|
+
if (failures.length > 0) {
|
|
780
|
+
await this.deleteAttachmentsBestEffort(bound, tenant);
|
|
781
|
+
for (const { input: input2, reason: reason2 } of failures) {
|
|
782
|
+
if (reason2 instanceof JobAttachmentUploadError && reason2.stage === "upload" && reason2.attachmentId !== undefined && reason2.recordDeleted === false) {
|
|
783
|
+
logger.warn(`Attachment record ${reason2.attachmentId} for '${input2.path}' could not be removed after its upload failed; delete it manually.`);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
const [{ input, reason }] = failures;
|
|
787
|
+
if (signal?.aborted) {
|
|
788
|
+
throw new AgentDebugCancelledError;
|
|
789
|
+
}
|
|
790
|
+
const detail = reason instanceof JobAttachmentUploadError ? reason.message : await extractErrorMessage(reason);
|
|
791
|
+
throw new AgentDebugAttachmentUploadError(input.field, input.path, `Failed to upload --attachment '${input.path}' for field '${input.field}': ${detail}`, reason);
|
|
792
|
+
}
|
|
793
|
+
return bound;
|
|
794
|
+
}
|
|
795
|
+
async deleteAttachmentsBestEffort(bound, tenant) {
|
|
796
|
+
if (bound.length === 0) {
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
const [clientError, api] = await catchError(createApiClient(AttachmentsApi, { tenant }));
|
|
800
|
+
if (clientError) {
|
|
801
|
+
logger.warn(`Could not clean up attachments ${bound.map((b) => b.reference.ID).join(", ")}: ${clientError.message}`);
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
for (const b of bound) {
|
|
805
|
+
const [deleteError] = await catchError(api.attachmentsDeleteById({ key: b.reference.ID }));
|
|
806
|
+
if (deleteError) {
|
|
807
|
+
logger.warn(`Could not delete attachment ${b.reference.ID}: ${deleteError.message}`);
|
|
808
|
+
} else {
|
|
809
|
+
logger.info(`Deleted attachment ${b.reference.ID}: the debug job did not start.`);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
async resolveProjectId(projectPath) {
|
|
814
|
+
const preparer = new AgentLocalWorkspaceEvalPreparer;
|
|
815
|
+
if (await preparer.isLocalWorkspace(projectPath)) {
|
|
816
|
+
const [, storage] = await catchError(this.projectService.readSolutionStorage(projectPath));
|
|
817
|
+
const config = await resolveStudioWebConfig();
|
|
818
|
+
const prepared = await preparer.prepare(projectPath, config, storage?.SolutionId);
|
|
819
|
+
return prepared.agentProjectId;
|
|
820
|
+
}
|
|
821
|
+
return this.uploadSolutionAndResolveProjectId(projectPath);
|
|
822
|
+
}
|
|
823
|
+
async uploadSolutionAndResolveProjectId(projectPath) {
|
|
824
|
+
const solution = await findSolutionFile(this.fs, projectPath);
|
|
825
|
+
if (!solution) {
|
|
826
|
+
throw new Error(`No enclosing .uipx solution found for '${projectPath}'. Create one with 'uip solution init' and add the agent to it.`);
|
|
827
|
+
}
|
|
828
|
+
const config = await resolveStudioWebConfig();
|
|
829
|
+
const solutionDir = this.fs.path.resolve(projectPath, "..");
|
|
830
|
+
const tempDir = await this.fs.getTempDir();
|
|
831
|
+
try {
|
|
832
|
+
const bundle = await bundleSolution(this.fs, solutionDir, tempDir);
|
|
833
|
+
const importResult = await uploadOrOverwriteSolution(config, config.organizationName, bundle.uisPath, bundle.solutionId, this.fs);
|
|
834
|
+
if (importResult.id && bundle.uipxPath) {
|
|
835
|
+
await updateUipxSolutionId(this.fs, bundle.uipxPath, importResult.id);
|
|
836
|
+
}
|
|
837
|
+
const projectName = await this.readProjectName(projectPath);
|
|
838
|
+
const byName = importResult.projects.find((p) => p.name === projectName);
|
|
839
|
+
if (byName?.id) {
|
|
840
|
+
return byName.id;
|
|
841
|
+
}
|
|
842
|
+
const [only] = importResult.projects;
|
|
843
|
+
if (importResult.projects.length === 1 && only?.id) {
|
|
844
|
+
return only.id;
|
|
845
|
+
}
|
|
846
|
+
throw new Error(`Could not resolve the Studio Web project for "${projectName}": the upload returned ${importResult.projects.length} projects and none is named "${projectName}". Ensure the Name in project.uiproj matches the agent project in the solution.`);
|
|
847
|
+
} finally {
|
|
848
|
+
const [cleanupError] = await catchError(this.fs.rm(tempDir));
|
|
849
|
+
if (cleanupError) {
|
|
850
|
+
logger.debug(`Failed to clean up temp dir: ${cleanupError.message}`);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
async readProjectName(projectPath) {
|
|
855
|
+
const [, content] = await catchError(this.fs.readFile(this.fs.path.join(projectPath, "project.uiproj"), "utf-8"));
|
|
856
|
+
const [, parsed] = catchError(() => JSON.parse(String(content)));
|
|
857
|
+
return parsed?.Name ?? this.fs.path.basename(projectPath);
|
|
858
|
+
}
|
|
859
|
+
async resolvePersonalWorkspaceKey() {
|
|
860
|
+
const wsApi = await createApiClient(PersonalWorkspacesApi, {});
|
|
861
|
+
const workspace = await wsApi.personalWorkspacesGetPersonalWorkspace();
|
|
862
|
+
if (!workspace?.key) {
|
|
863
|
+
throw new Error("Could not resolve your personal workspace. Ensure it is enabled for your account.");
|
|
864
|
+
}
|
|
865
|
+
return workspace.key;
|
|
866
|
+
}
|
|
867
|
+
orchestratorBaseUrl(auth) {
|
|
868
|
+
return `${auth.baseUrl}/${auth.organizationId}/${auth.tenantName}/orchestrator_`;
|
|
869
|
+
}
|
|
870
|
+
async startDebugJob(auth, folderKey, projectId, inputs, signal) {
|
|
871
|
+
const traceId = randomUUID();
|
|
872
|
+
const inputArguments = JSON.stringify({
|
|
873
|
+
Command: "debug",
|
|
874
|
+
EntryPoint: "agent.json",
|
|
875
|
+
Input: JSON.stringify(inputs),
|
|
876
|
+
args: "--attach=none"
|
|
877
|
+
});
|
|
878
|
+
const [fetchError, response] = await catchError(fetch(`${this.orchestratorBaseUrl(auth)}/api/serverless/jobs`, {
|
|
879
|
+
method: "POST",
|
|
880
|
+
headers: {
|
|
881
|
+
Authorization: `Bearer ${auth.accessToken}`,
|
|
882
|
+
"Content-Type": "application/json",
|
|
883
|
+
"X-UIPATH-FolderKey": folderKey
|
|
884
|
+
},
|
|
885
|
+
body: JSON.stringify({
|
|
886
|
+
JobType: "PythonAgent",
|
|
887
|
+
InputArguments: inputArguments,
|
|
888
|
+
Source: "StudioWeb",
|
|
889
|
+
RunAsMe: true,
|
|
890
|
+
EnvironmentVariables: `UIPATH_PROJECT_ID=${projectId}`,
|
|
891
|
+
TraceId: traceId,
|
|
892
|
+
Reference: randomUUID()
|
|
893
|
+
}),
|
|
894
|
+
signal
|
|
895
|
+
}));
|
|
896
|
+
if (fetchError) {
|
|
897
|
+
if (isAbortError(fetchError)) {
|
|
898
|
+
throw fetchError;
|
|
899
|
+
}
|
|
900
|
+
throw new AgentDebugStartOutcomeUnknownError(`Failed to start debug job: ${await extractErrorMessage(fetchError)}`, "network_error", [], { cause: fetchError });
|
|
901
|
+
}
|
|
902
|
+
if (!response.ok) {
|
|
903
|
+
const message = `Failed to start debug job: ${response.status} ${await response.text()}`;
|
|
904
|
+
if (response.status >= 500) {
|
|
905
|
+
throw new AgentDebugStartOutcomeUnknownError(message, "server_error");
|
|
906
|
+
}
|
|
907
|
+
throw new Error(message);
|
|
908
|
+
}
|
|
909
|
+
const [bodyError, data] = await catchError(response.json());
|
|
910
|
+
if (bodyError && isAbortError(bodyError)) {
|
|
911
|
+
throw bodyError;
|
|
912
|
+
}
|
|
913
|
+
const jobKey = bodyError ? undefined : data?.key;
|
|
914
|
+
if (!jobKey) {
|
|
915
|
+
throw new AgentDebugStartOutcomeUnknownError("Debug job started but no job key was returned.", "server_error");
|
|
916
|
+
}
|
|
917
|
+
return { jobKey, traceId };
|
|
918
|
+
}
|
|
919
|
+
async pollJob(auth, folderKey, jobKey, options) {
|
|
920
|
+
const url = `${this.orchestratorBaseUrl(auth)}/odata/Jobs/UiPath.Server.Configuration.OData.GetByKey(identifier=${jobKey})`;
|
|
921
|
+
const headers = {
|
|
922
|
+
Authorization: `Bearer ${auth.accessToken}`,
|
|
923
|
+
"X-UIPATH-FolderKey": folderKey
|
|
924
|
+
};
|
|
925
|
+
let lastState = "";
|
|
926
|
+
let consecutiveErrors = 0;
|
|
927
|
+
const maxConsecutiveErrors = 3;
|
|
928
|
+
for (let poll = 0;poll < options.maxPolls; poll++) {
|
|
929
|
+
await delay(options.pollIntervalMs);
|
|
930
|
+
throwIfAborted(options.signal, jobKey);
|
|
931
|
+
const response = await fetch(url, {
|
|
932
|
+
headers,
|
|
933
|
+
signal: options.signal
|
|
934
|
+
});
|
|
935
|
+
if (!response.ok) {
|
|
936
|
+
consecutiveErrors++;
|
|
937
|
+
if (response.status < 500 || consecutiveErrors > maxConsecutiveErrors) {
|
|
938
|
+
const body = await response.text();
|
|
939
|
+
throw new Error(`Failed to poll debug job (HTTP ${response.status}): ${body.slice(0, 300)}`);
|
|
940
|
+
}
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
consecutiveErrors = 0;
|
|
944
|
+
const job = await response.json();
|
|
945
|
+
if (job.State !== lastState) {
|
|
946
|
+
lastState = job.State;
|
|
947
|
+
options.onState?.(job.State);
|
|
948
|
+
}
|
|
949
|
+
if (TERMINAL_STATES.has(job.State)) {
|
|
950
|
+
return {
|
|
951
|
+
state: job.State,
|
|
952
|
+
output: parseOutput(job.OutputArguments),
|
|
953
|
+
info: job.Info?.trim() || undefined
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
throw new Error(`Debug run did not reach a terminal state within the timeout (last state: ${lastState || "unknown"}). Increase --timeout and retry.`);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
function throwIfAborted(signal, jobKey) {
|
|
961
|
+
if (signal?.aborted) {
|
|
962
|
+
throw new AgentDebugCancelledError(jobKey);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
async function asCancellation(step, jobKey) {
|
|
966
|
+
try {
|
|
967
|
+
return await step();
|
|
968
|
+
} catch (error) {
|
|
969
|
+
if (isAbortError(error)) {
|
|
970
|
+
throw new AgentDebugCancelledError(jobKey);
|
|
971
|
+
}
|
|
972
|
+
throw error;
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
function isAbortError(error) {
|
|
976
|
+
return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError");
|
|
977
|
+
}
|
|
978
|
+
function parseOutput(outputArguments) {
|
|
979
|
+
if (!outputArguments) {
|
|
980
|
+
return;
|
|
981
|
+
}
|
|
982
|
+
const [error, parsed] = catchError(() => JSON.parse(outputArguments));
|
|
983
|
+
return error ? outputArguments : parsed;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
export { migrateLegacyToolGuardrailPolicies, AgentProjectService, resolveStudioWebConfig, AgentLocalWorkspaceEvalPreparer, AttachmentInputError, toAttachmentSummaries, prepareAttachmentInputs, AgentDebugCancelledError, AgentDebugAttachmentUploadError, AgentDebugStartOutcomeUnknownError, AgentDebugService };
|
|
987
|
+
|
|
988
|
+
//# debugId=A063F33B50DA89E964756E2164756E21
|