@swmansion/argent 0.18.1-next.8 → 0.19.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/cli-cmds.mjs CHANGED
@@ -5,7 +5,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function __require() {
8
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a2, b) => (typeof require !== "undefined" ? require : a2)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined") return require.apply(this, arguments);
12
+ throw Error('Dynamic require of "' + x + '" is not supported');
13
+ });
14
+ var __commonJS = (cb, mod) => function __require2() {
9
15
  try {
10
16
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
11
17
  } catch (e) {
@@ -33,6 +39,325 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
33
39
  mod
34
40
  ));
35
41
 
42
+ // ../../node_modules/dotenv/lib/main.js
43
+ var require_main = __commonJS({
44
+ "../../node_modules/dotenv/lib/main.js"(exports, module) {
45
+ var fs12 = __require("fs");
46
+ var path17 = __require("path");
47
+ var os3 = __require("os");
48
+ var crypto3 = __require("crypto");
49
+ var TIPS = [
50
+ "\u25C8 encrypted .env [www.dotenvx.com]",
51
+ "\u25C8 secrets for agents [www.dotenvx.com]",
52
+ "\u2301 auth for agents [www.vestauth.com]",
53
+ "\u2318 custom filepath { path: '/custom/path/.env' }",
54
+ "\u2318 enable debugging { debug: true }",
55
+ "\u2318 override existing { override: true }",
56
+ "\u2318 suppress logs { quiet: true }",
57
+ "\u2318 multiple files { path: ['.env.local', '.env'] }"
58
+ ];
59
+ function _getRandomTip() {
60
+ return TIPS[Math.floor(Math.random() * TIPS.length)];
61
+ }
62
+ function parseBoolean(value) {
63
+ if (typeof value === "string") {
64
+ return !["false", "0", "no", "off", ""].includes(value.toLowerCase());
65
+ }
66
+ return Boolean(value);
67
+ }
68
+ function supportsAnsi() {
69
+ return process.stdout.isTTY;
70
+ }
71
+ function dim(text2) {
72
+ return supportsAnsi() ? `\x1B[2m${text2}\x1B[0m` : text2;
73
+ }
74
+ var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
75
+ function parse(src) {
76
+ const obj = {};
77
+ let lines = src.toString();
78
+ lines = lines.replace(/\r\n?/mg, "\n");
79
+ let match;
80
+ while ((match = LINE.exec(lines)) != null) {
81
+ const key = match[1];
82
+ let value = match[2] || "";
83
+ value = value.trim();
84
+ const maybeQuote = value[0];
85
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
86
+ if (maybeQuote === '"') {
87
+ value = value.replace(/\\n/g, "\n");
88
+ value = value.replace(/\\r/g, "\r");
89
+ }
90
+ obj[key] = value;
91
+ }
92
+ return obj;
93
+ }
94
+ function _parseVault(options) {
95
+ options = options || {};
96
+ const vaultPath = _vaultPath(options);
97
+ options.path = vaultPath;
98
+ const result = DotenvModule.configDotenv(options);
99
+ if (!result.parsed) {
100
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
101
+ err.code = "MISSING_DATA";
102
+ throw err;
103
+ }
104
+ const keys = _dotenvKey(options).split(",");
105
+ const length = keys.length;
106
+ let decrypted;
107
+ for (let i2 = 0; i2 < length; i2++) {
108
+ try {
109
+ const key = keys[i2].trim();
110
+ const attrs = _instructions(result, key);
111
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
112
+ break;
113
+ } catch (error) {
114
+ if (i2 + 1 >= length) {
115
+ throw error;
116
+ }
117
+ }
118
+ }
119
+ return DotenvModule.parse(decrypted);
120
+ }
121
+ function _warn(message) {
122
+ console.error(`\u26A0 ${message}`);
123
+ }
124
+ function _debug(message) {
125
+ console.log(`\u2506 ${message}`);
126
+ }
127
+ function _log(message) {
128
+ console.log(`\u25C7 ${message}`);
129
+ }
130
+ function _dotenvKey(options) {
131
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
132
+ return options.DOTENV_KEY;
133
+ }
134
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
135
+ return process.env.DOTENV_KEY;
136
+ }
137
+ return "";
138
+ }
139
+ function _instructions(result, dotenvKey) {
140
+ let uri;
141
+ try {
142
+ uri = new URL(dotenvKey);
143
+ } catch (error) {
144
+ if (error.code === "ERR_INVALID_URL") {
145
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
146
+ err.code = "INVALID_DOTENV_KEY";
147
+ throw err;
148
+ }
149
+ throw error;
150
+ }
151
+ const key = uri.password;
152
+ if (!key) {
153
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
154
+ err.code = "INVALID_DOTENV_KEY";
155
+ throw err;
156
+ }
157
+ const environment = uri.searchParams.get("environment");
158
+ if (!environment) {
159
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
160
+ err.code = "INVALID_DOTENV_KEY";
161
+ throw err;
162
+ }
163
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
164
+ const ciphertext = result.parsed[environmentKey];
165
+ if (!ciphertext) {
166
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
167
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
168
+ throw err;
169
+ }
170
+ return { ciphertext, key };
171
+ }
172
+ function _vaultPath(options) {
173
+ let possibleVaultPath = null;
174
+ if (options && options.path && options.path.length > 0) {
175
+ if (Array.isArray(options.path)) {
176
+ for (const filepath of options.path) {
177
+ if (fs12.existsSync(filepath)) {
178
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
179
+ }
180
+ }
181
+ } else {
182
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
183
+ }
184
+ } else {
185
+ possibleVaultPath = path17.resolve(process.cwd(), ".env.vault");
186
+ }
187
+ if (fs12.existsSync(possibleVaultPath)) {
188
+ return possibleVaultPath;
189
+ }
190
+ return null;
191
+ }
192
+ function _resolveHome(envPath) {
193
+ return envPath[0] === "~" ? path17.join(os3.homedir(), envPath.slice(1)) : envPath;
194
+ }
195
+ function _configVault(options) {
196
+ const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
197
+ const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
198
+ if (debug || !quiet) {
199
+ _log("loading env from encrypted .env.vault");
200
+ }
201
+ const parsed = DotenvModule._parseVault(options);
202
+ let processEnv = process.env;
203
+ if (options && options.processEnv != null) {
204
+ processEnv = options.processEnv;
205
+ }
206
+ DotenvModule.populate(processEnv, parsed, options);
207
+ return { parsed };
208
+ }
209
+ function configDotenv(options) {
210
+ const dotenvPath = path17.resolve(process.cwd(), ".env");
211
+ let encoding = "utf8";
212
+ let processEnv = process.env;
213
+ if (options && options.processEnv != null) {
214
+ processEnv = options.processEnv;
215
+ }
216
+ let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
217
+ let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
218
+ if (options && options.encoding) {
219
+ encoding = options.encoding;
220
+ } else {
221
+ if (debug) {
222
+ _debug("no encoding is specified (UTF-8 is used by default)");
223
+ }
224
+ }
225
+ let optionPaths = [dotenvPath];
226
+ if (options && options.path) {
227
+ if (!Array.isArray(options.path)) {
228
+ optionPaths = [_resolveHome(options.path)];
229
+ } else {
230
+ optionPaths = [];
231
+ for (const filepath of options.path) {
232
+ optionPaths.push(_resolveHome(filepath));
233
+ }
234
+ }
235
+ }
236
+ let lastError;
237
+ const parsedAll = {};
238
+ for (const path18 of optionPaths) {
239
+ try {
240
+ const parsed = DotenvModule.parse(fs12.readFileSync(path18, { encoding }));
241
+ DotenvModule.populate(parsedAll, parsed, options);
242
+ } catch (e) {
243
+ if (debug) {
244
+ _debug(`failed to load ${path18} ${e.message}`);
245
+ }
246
+ lastError = e;
247
+ }
248
+ }
249
+ const populated = DotenvModule.populate(processEnv, parsedAll, options);
250
+ debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
251
+ quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
252
+ if (debug || !quiet) {
253
+ const keysCount = Object.keys(populated).length;
254
+ const shortPaths = [];
255
+ for (const filePath of optionPaths) {
256
+ try {
257
+ const relative4 = path17.relative(process.cwd(), filePath);
258
+ shortPaths.push(relative4);
259
+ } catch (e) {
260
+ if (debug) {
261
+ _debug(`failed to load ${filePath} ${e.message}`);
262
+ }
263
+ lastError = e;
264
+ }
265
+ }
266
+ _log(`injected env (${keysCount}) from ${shortPaths.join(",")} ${dim(`// tip: ${_getRandomTip()}`)}`);
267
+ }
268
+ if (lastError) {
269
+ return { parsed: parsedAll, error: lastError };
270
+ } else {
271
+ return { parsed: parsedAll };
272
+ }
273
+ }
274
+ function config2(options) {
275
+ if (_dotenvKey(options).length === 0) {
276
+ return DotenvModule.configDotenv(options);
277
+ }
278
+ const vaultPath = _vaultPath(options);
279
+ if (!vaultPath) {
280
+ _warn(`you set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}`);
281
+ return DotenvModule.configDotenv(options);
282
+ }
283
+ return DotenvModule._configVault(options);
284
+ }
285
+ function decrypt(encrypted, keyStr) {
286
+ const key = Buffer.from(keyStr.slice(-64), "hex");
287
+ let ciphertext = Buffer.from(encrypted, "base64");
288
+ const nonce = ciphertext.subarray(0, 12);
289
+ const authTag = ciphertext.subarray(-16);
290
+ ciphertext = ciphertext.subarray(12, -16);
291
+ try {
292
+ const aesgcm = crypto3.createDecipheriv("aes-256-gcm", key, nonce);
293
+ aesgcm.setAuthTag(authTag);
294
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
295
+ } catch (error) {
296
+ const isRange = error instanceof RangeError;
297
+ const invalidKeyLength = error.message === "Invalid key length";
298
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
299
+ if (isRange || invalidKeyLength) {
300
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
301
+ err.code = "INVALID_DOTENV_KEY";
302
+ throw err;
303
+ } else if (decryptionFailed) {
304
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
305
+ err.code = "DECRYPTION_FAILED";
306
+ throw err;
307
+ } else {
308
+ throw error;
309
+ }
310
+ }
311
+ }
312
+ function populate(processEnv, parsed, options = {}) {
313
+ const debug = Boolean(options && options.debug);
314
+ const override = Boolean(options && options.override);
315
+ const populated = {};
316
+ if (typeof parsed !== "object") {
317
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
318
+ err.code = "OBJECT_REQUIRED";
319
+ throw err;
320
+ }
321
+ for (const key of Object.keys(parsed)) {
322
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
323
+ if (override === true) {
324
+ processEnv[key] = parsed[key];
325
+ populated[key] = parsed[key];
326
+ }
327
+ if (debug) {
328
+ if (override === true) {
329
+ _debug(`"${key}" is already defined and WAS overwritten`);
330
+ } else {
331
+ _debug(`"${key}" is already defined and was NOT overwritten`);
332
+ }
333
+ }
334
+ } else {
335
+ processEnv[key] = parsed[key];
336
+ populated[key] = parsed[key];
337
+ }
338
+ }
339
+ return populated;
340
+ }
341
+ var DotenvModule = {
342
+ configDotenv,
343
+ _configVault,
344
+ _parseVault,
345
+ config: config2,
346
+ decrypt,
347
+ parse,
348
+ populate
349
+ };
350
+ module.exports.configDotenv = DotenvModule.configDotenv;
351
+ module.exports._configVault = DotenvModule._configVault;
352
+ module.exports._parseVault = DotenvModule._parseVault;
353
+ module.exports.config = DotenvModule.config;
354
+ module.exports.decrypt = DotenvModule.decrypt;
355
+ module.exports.parse = DotenvModule.parse;
356
+ module.exports.populate = DotenvModule.populate;
357
+ module.exports = DotenvModule;
358
+ }
359
+ });
360
+
36
361
  // ../../node_modules/picocolors/picocolors.js
37
362
  var require_picocolors = __commonJS({
38
363
  "../../node_modules/picocolors/picocolors.js"(exports, module) {
@@ -162,8 +487,8 @@ var require_src = __commonJS({
162
487
  });
163
488
 
164
489
  // ../argent-cli/src/run.ts
165
- import * as fs8 from "node:fs";
166
- import * as path11 from "node:path";
490
+ import * as fs9 from "node:fs";
491
+ import * as path12 from "node:path";
167
492
 
168
493
  // ../argent-tools-client/src/launcher.ts
169
494
  import * as net from "node:net";
@@ -204,7 +529,7 @@ function generateAuthToken() {
204
529
  return generateToken();
205
530
  }
206
531
  function findFreePort() {
207
- return new Promise((resolve9, reject) => {
532
+ return new Promise((resolve10, reject) => {
208
533
  const srv = net.createServer();
209
534
  srv.listen(0, "127.0.0.1", () => {
210
535
  const addr = srv.address();
@@ -215,7 +540,7 @@ function findFreePort() {
215
540
  const port = addr.port;
216
541
  srv.close((err) => {
217
542
  if (err) reject(err);
218
- else resolve9(port);
543
+ else resolve10(port);
219
544
  });
220
545
  });
221
546
  srv.on("error", reject);
@@ -316,7 +641,7 @@ function killSpawnedChild(child, pid) {
316
641
  }
317
642
  }
318
643
  function spawnToolsServer(paths, port, options = {}) {
319
- return new Promise((resolve9, reject) => {
644
+ return new Promise((resolve10, reject) => {
320
645
  let logFd;
321
646
  try {
322
647
  fs.mkdirSync(STATE_DIR, { recursive: true });
@@ -353,7 +678,7 @@ function spawnToolsServer(paths, port, options = {}) {
353
678
  rl.close();
354
679
  child.stdout?.resume();
355
680
  child.stdout?.unref?.();
356
- settle(() => resolve9({ port: actualPort, pid }));
681
+ settle(() => resolve10({ port: actualPort, pid }));
357
682
  }
358
683
  });
359
684
  child.on("error", (err) => {
@@ -742,16 +1067,16 @@ function parseLinkTarget(input) {
742
1067
  const host = u3.hostname.startsWith("[") ? u3.hostname.slice(1, -1) : u3.hostname;
743
1068
  if (!host) throw new Error(`URL "${input}" is missing a host.`);
744
1069
  const port = u3.port ? Number(u3.port) : u3.protocol === "https:" ? 443 : 80;
745
- const path16 = u3.pathname === "/" ? "" : u3.pathname.replace(/\/+$/, "");
746
- const url = `${u3.protocol}//${u3.host}${path16}`;
1070
+ const path17 = u3.pathname === "/" ? "" : u3.pathname.replace(/\/+$/, "");
1071
+ const url = `${u3.protocol}//${u3.host}${path17}`;
747
1072
  const token = u3.username ? decodeURIComponent(u3.username) : void 0;
748
1073
  return { url, host, port, ...token ? { token } : {} };
749
1074
  }
750
1075
 
751
1076
  // ../argent-tools-client/src/file-inputs.ts
752
- import { createHash as createHash2, randomUUID } from "node:crypto";
1077
+ import { createHash as createHash2, randomUUID as randomUUID3 } from "node:crypto";
753
1078
  import { createReadStream } from "node:fs";
754
- import { mkdir as mkdir3, readFile as readFile3, rm as rm2, stat, writeFile as writeFile3 } from "node:fs/promises";
1079
+ import { mkdir as mkdir3, readFile as readFile3, rm as rm2, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
755
1080
  import { tmpdir } from "node:os";
756
1081
  import * as path3 from "node:path";
757
1082
 
@@ -857,193 +1182,525 @@ async function safeExtractTarGz(tarPath, destDir, expectedName) {
857
1182
  return resolveMember(destDir, expectedName);
858
1183
  }
859
1184
 
860
- // ../argent-tools-client/src/file-inputs.ts
861
- var FILE_INPUT_MARKER = "__argentFileInput";
862
- var CLIENT_FILE_MARKER = "__argentClientFile";
863
- var MAX_CONTENT_BYTES = 32 * 1024 * 1024;
864
- function interpolatePath(template, args) {
865
- let missing = false;
866
- const out = template.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_m, name) => {
867
- const v = args[name];
868
- if (typeof v !== "string" || v.length === 0) {
869
- missing = true;
870
- return "";
871
- }
872
- return v;
873
- });
874
- return missing ? null : out;
875
- }
876
- async function tarball(sourcePath) {
877
- const tarPath = path3.join(tmpdir(), `argent-upload-${randomUUID()}.tar.gz`);
878
- await createTarGzFile(sourcePath, tarPath);
879
- return tarPath;
880
- }
881
- function sha256File(filePath) {
882
- return new Promise((resolve9, reject) => {
883
- const hash = createHash2("sha256");
884
- createReadStream(filePath).on("data", (chunk) => hash.update(chunk)).on("end", () => resolve9(hash.digest("hex"))).on("error", reject);
885
- });
886
- }
887
- async function uploadTar(tarPath, endpoint) {
888
- const init2 = {
889
- method: "POST",
890
- headers: {
891
- "content-type": "application/gzip",
892
- ...endpoint.token ? { Authorization: `Bearer ${endpoint.token}` } : {}
893
- },
894
- body: createReadStream(tarPath),
895
- duplex: "half"
896
- };
897
- const res = await fetch(`${endpoint.url}/upload`, init2);
898
- if (!res.ok) {
899
- throw new Error(`Upload to ${endpoint.url}/upload failed: ${res.status} ${res.statusText}`);
900
- }
901
- const json = await res.json();
902
- return json.uploadId;
903
- }
904
- async function prepareFileInputs(specs, args, opts) {
905
- if (!specs || specs.length === 0 || typeof args !== "object" || args === null) {
906
- return args;
907
- }
908
- const record = args;
909
- let out = null;
910
- for (const spec of specs) {
911
- if (spec.target in record && typeof record[spec.target] !== "string") continue;
912
- const filePath = interpolatePath(spec.path, record);
913
- if (filePath === null) continue;
914
- if (spec.target in record && record[spec.target] !== filePath) continue;
915
- const wire = { [FILE_INPUT_MARKER]: true, path: filePath };
916
- if (spec.kind === "file") {
917
- try {
918
- const st = await stat(filePath);
919
- if (st.isFile()) {
920
- wire.size = st.size;
921
- wire.mtimeMs = st.mtimeMs;
922
- if (opts.includeContent && st.size <= MAX_CONTENT_BYTES) {
923
- wire.content = (await readFile3(filePath)).toString("base64");
924
- } else if (opts.includeContent) {
925
- wire.contentOmitted = "size-limit";
926
- }
927
- }
928
- } catch {
929
- }
930
- }
931
- if (spec.kind === "tar-upload") {
932
- const st = await stat(filePath).catch(() => null);
933
- if (st) {
934
- wire.size = st.size;
935
- wire.mtimeMs = st.mtimeMs;
936
- }
937
- if (opts.uploadEndpoint && st) {
938
- let tarPath = null;
939
- try {
940
- process.stderr.write(
941
- `Uploading ${path3.basename(filePath)} to the remote tool-server...
942
- `
943
- );
944
- tarPath = await tarball(filePath);
945
- wire.contentHash = await sha256File(tarPath);
946
- wire.uploadId = await uploadTar(tarPath, opts.uploadEndpoint);
947
- } finally {
948
- if (tarPath) await rm2(tarPath, { force: true }).catch(() => {
949
- });
950
- }
951
- }
952
- }
953
- out = out ?? { ...record };
954
- out[spec.target] = wire;
955
- }
956
- return out ?? args;
957
- }
958
- function isAllowedClientFilePath(p) {
959
- if (!path3.isAbsolute(p)) return false;
960
- const segments = p.split(/[\\/]+/);
961
- if (segments.includes("..")) return false;
962
- const file = segments[segments.length - 1] ?? "";
963
- if (!/^[A-Za-z0-9_-]+\.yaml$/.test(file)) return false;
964
- return segments[segments.length - 3] === ".argent" && segments[segments.length - 2] === "flows";
965
- }
966
- function isClientFileDirective(value) {
967
- return !!value && typeof value === "object" && value[CLIENT_FILE_MARKER] === true && typeof value.path === "string" && typeof value.content === "string";
968
- }
969
- async function applyClientFileDirectives(result) {
970
- const written = [];
971
- async function walk(value) {
972
- if (isClientFileDirective(value)) {
973
- if (!isAllowedClientFilePath(value.path)) return null;
974
- try {
975
- await mkdir3(path3.dirname(value.path), { recursive: true });
976
- await writeFile3(value.path, value.content, "utf8");
977
- written.push(value.path);
978
- return value.path;
979
- } catch {
980
- return null;
981
- }
982
- }
983
- if (Array.isArray(value)) {
984
- return Promise.all(value.map(walk));
985
- }
986
- if (value && typeof value === "object") {
987
- const out = {};
988
- for (const [k, v] of Object.entries(value)) {
989
- out[k] = await walk(v);
990
- }
991
- return out;
992
- }
993
- return value;
994
- }
995
- const rewritten = await walk(result);
996
- return { result: rewritten, written };
997
- }
1185
+ // ../registry/src/artifacts.ts
1186
+ import { stat } from "node:fs/promises";
1187
+ import { randomUUID } from "node:crypto";
1188
+ import { basename as basename2, extname } from "node:path";
998
1189
 
999
- // ../argent-tools-client/src/tools-client.ts
1000
- function authHeaders2(token) {
1001
- return token ? { Authorization: `Bearer ${token}` } : {};
1002
- }
1003
- async function consumeToolStream(body, onProgress) {
1004
- let final;
1005
- const handleLine = (line) => {
1006
- if (!line.trim()) return;
1007
- const msg = JSON.parse(line);
1008
- if (msg.event === "progress") onProgress(msg.data);
1009
- else if (msg.event === "result") final = { data: msg.data, note: msg.note };
1010
- else if (msg.event === "error") throw new Error(msg.error ?? "tool invocation failed");
1011
- };
1012
- const reader = body.getReader();
1013
- const decoder = new TextDecoder();
1014
- let buffered = "";
1015
- try {
1016
- for (; ; ) {
1017
- const { done, value } = await reader.read();
1018
- if (done) break;
1019
- buffered += decoder.decode(value, { stream: true });
1020
- let newline;
1021
- while ((newline = buffered.indexOf("\n")) !== -1) {
1022
- const line = buffered.slice(0, newline);
1023
- buffered = buffered.slice(newline + 1);
1024
- handleLine(line);
1025
- }
1026
- }
1027
- buffered += decoder.decode();
1028
- if (buffered.trim()) handleLine(buffered);
1029
- } catch (err) {
1030
- void reader.cancel().catch(() => {
1031
- });
1032
- throw err;
1033
- }
1034
- if (!final) {
1035
- throw new Error("tool stream ended without a result \u2014 connection lost mid-run?");
1036
- }
1037
- const { result: data } = await applyClientFileDirectives(final.data);
1038
- return { data, note: final.note };
1039
- }
1040
- function createToolsClient(options = {}) {
1041
- let cached2 = null;
1042
- async function baseUrl() {
1043
- const resolved = await getResolvedToolsUrl();
1044
- if (resolved.url) {
1045
- return { url: resolved.url, token: resolved.token ?? "" };
1046
- }
1190
+ // ../registry/src/file-inputs.ts
1191
+ var FLOW_NAME_CHARSET = "[A-Za-z0-9_-]+";
1192
+ var FLOW_NAME_PATTERN = new RegExp(`^${FLOW_NAME_CHARSET}$`);
1193
+ var FLOW_FILE_NAME_PATTERN = new RegExp(`^${FLOW_NAME_CHARSET}\\.yaml$`);
1194
+
1195
+ // ../registry/src/failure-codes.ts
1196
+ var FAILURE_CODES = {
1197
+ ARGENT_UNCLASSIFIED_FAILURE: "ARGENT_UNCLASSIFIED_FAILURE",
1198
+ REGISTRY_SERVICE_NOT_FOUND: "REGISTRY_SERVICE_NOT_FOUND",
1199
+ REGISTRY_SERVICE_INITIALIZATION_FAILED: "REGISTRY_SERVICE_INITIALIZATION_FAILED",
1200
+ REGISTRY_TOOL_NOT_FOUND: "REGISTRY_TOOL_NOT_FOUND",
1201
+ REGISTRY_TOOL_EXECUTION_FAILED: "REGISTRY_TOOL_EXECUTION_FAILED",
1202
+ REGISTRY_TOOL_FAILURE_UNCLASSIFIED: "REGISTRY_TOOL_FAILURE_UNCLASSIFIED",
1203
+ HTTP_TOOL_NOT_FOUND: "HTTP_TOOL_NOT_FOUND",
1204
+ HTTP_ZOD_VALIDATION_FAILED: "HTTP_ZOD_VALIDATION_FAILED",
1205
+ HTTP_CAPABILITY_UNSUPPORTED_OPERATION: "HTTP_CAPABILITY_UNSUPPORTED_OPERATION",
1206
+ HTTP_DEVICE_RESOLUTION_FAILED: "HTTP_DEVICE_RESOLUTION_FAILED",
1207
+ HTTP_DEPENDENCY_PREFLIGHT_MISSING: "HTTP_DEPENDENCY_PREFLIGHT_MISSING",
1208
+ CLI_RUN_TOOL_NOT_FOUND: "CLI_RUN_TOOL_NOT_FOUND",
1209
+ CLI_RUN_FLAG_PARSE_FAILED: "CLI_RUN_FLAG_PARSE_FAILED",
1210
+ CLI_RUN_ARGS_NOT_OBJECT: "CLI_RUN_ARGS_NOT_OBJECT",
1211
+ CLI_RUN_ARGS_JSON_INVALID: "CLI_RUN_ARGS_JSON_INVALID",
1212
+ CLI_RUN_INPUT_VALIDATION_FAILED: "CLI_RUN_INPUT_VALIDATION_FAILED",
1213
+ CLI_RUN_TOOL_CALL_FAILED: "CLI_RUN_TOOL_CALL_FAILED",
1214
+ CLI_RUN_SAVE_IMAGE_FAILED: "CLI_RUN_SAVE_IMAGE_FAILED",
1215
+ TOOL_CAPABILITY_UNSUPPORTED_OPERATION: "TOOL_CAPABILITY_UNSUPPORTED_OPERATION",
1216
+ TOOL_PLATFORM_NOT_IMPLEMENTED: "TOOL_PLATFORM_NOT_IMPLEMENTED",
1217
+ TOOL_DEPENDENCY_MISSING: "TOOL_DEPENDENCY_MISSING",
1218
+ TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
1219
+ TOOLSERVER_UNHANDLED_REJECTION: "TOOLSERVER_UNHANDLED_REJECTION",
1220
+ TOOLSERVER_UNCAUGHT_EXCEPTION: "TOOLSERVER_UNCAUGHT_EXCEPTION",
1221
+ INSTALL_GLOBAL_PACKAGE_FAILED: "INSTALL_GLOBAL_PACKAGE_FAILED",
1222
+ INSTALL_LOCAL_PACKAGE_FAILED: "INSTALL_LOCAL_PACKAGE_FAILED",
1223
+ INSTALL_LOCAL_PRECONDITION_FAILED: "INSTALL_LOCAL_PRECONDITION_FAILED",
1224
+ INSTALL_MODE_FLAG_CONFLICT: "INSTALL_MODE_FLAG_CONFLICT",
1225
+ INSTALL_FROM_TAR_PACKAGE_FAILED: "INSTALL_FROM_TAR_PACKAGE_FAILED",
1226
+ INSTALL_INIT_TRIGGERED_UPDATE_FAILED: "INSTALL_INIT_TRIGGERED_UPDATE_FAILED",
1227
+ INSTALL_SKILLS_REFRESH_FAILED: "INSTALL_SKILLS_REFRESH_FAILED",
1228
+ INSTALL_UNCLASSIFIED_FAILED: "INSTALL_UNCLASSIFIED_FAILED",
1229
+ UPDATE_INSTALLED_VERSION_DETECT_FAILED: "UPDATE_INSTALLED_VERSION_DETECT_FAILED",
1230
+ UPDATE_INVALID_TARGET_VERSION: "UPDATE_INVALID_TARGET_VERSION",
1231
+ UPDATE_REGISTRY_CHECK_FAILED: "UPDATE_REGISTRY_CHECK_FAILED",
1232
+ UPDATE_TOOLSERVER_STOP_FAILED: "UPDATE_TOOLSERVER_STOP_FAILED",
1233
+ UPDATE_PACKAGE_ACTION_FAILED: "UPDATE_PACKAGE_ACTION_FAILED",
1234
+ UPDATE_UNCLASSIFIED_FAILED: "UPDATE_UNCLASSIFIED_FAILED",
1235
+ UNINSTALL_TOOLSERVER_STOP_FAILED: "UNINSTALL_TOOLSERVER_STOP_FAILED",
1236
+ UNINSTALL_PACKAGE_ACTION_FAILED: "UNINSTALL_PACKAGE_ACTION_FAILED",
1237
+ UNINSTALL_UNCLASSIFIED_FAILED: "UNINSTALL_UNCLASSIFIED_FAILED",
1238
+ VEGA_CLI_COMMAND_FAILED: "VEGA_CLI_COMMAND_FAILED",
1239
+ VEGA_INPUT_UNAVAILABLE: "VEGA_INPUT_UNAVAILABLE",
1240
+ VEGA_DEVICE_NOT_FOUND: "VEGA_DEVICE_NOT_FOUND",
1241
+ VEGA_DEVICE_NOT_REGISTERED: "VEGA_DEVICE_NOT_REGISTERED",
1242
+ VEGA_MULTIPLE_DEVICES: "VEGA_MULTIPLE_DEVICES",
1243
+ VEGA_BOOT_TIMEOUT: "VEGA_BOOT_TIMEOUT",
1244
+ VEGA_IMAGE_NOT_FOUND: "VEGA_IMAGE_NOT_FOUND",
1245
+ VEGA_ALREADY_RUNNING: "VEGA_ALREADY_RUNNING",
1246
+ VEGA_SCREENSHOT_FAILED: "VEGA_SCREENSHOT_FAILED",
1247
+ VEGA_TEXT_INVALID: "VEGA_TEXT_INVALID",
1248
+ ANDROID_ADB_NOT_FOUND: "ANDROID_ADB_NOT_FOUND",
1249
+ ANDROID_EMULATOR_NOT_FOUND: "ANDROID_EMULATOR_NOT_FOUND",
1250
+ ANDROID_ADB_COMMAND_FAILED: "ANDROID_ADB_COMMAND_FAILED",
1251
+ ANDROID_ADB_BOOT_TERMINAL_STATE: "ANDROID_ADB_BOOT_TERMINAL_STATE",
1252
+ ANDROID_ADB_BOOT_TIMEOUT: "ANDROID_ADB_BOOT_TIMEOUT",
1253
+ SIMULATOR_NETWORK_TIMEOUT: "SIMULATOR_NETWORK_TIMEOUT",
1254
+ SIMULATOR_NETWORK_CONNECTION_REFUSED: "SIMULATOR_NETWORK_CONNECTION_REFUSED",
1255
+ SIMULATOR_NETWORK_CONNECTION_RESET: "SIMULATOR_NETWORK_CONNECTION_RESET",
1256
+ SIMULATOR_NETWORK_ERROR: "SIMULATOR_NETWORK_ERROR",
1257
+ SIMULATOR_NON_JSON_RESPONSE: "SIMULATOR_NON_JSON_RESPONSE",
1258
+ SIMULATOR_HTTP_ERROR_RESPONSE: "SIMULATOR_HTTP_ERROR_RESPONSE",
1259
+ SIMULATOR_MISSING_RESPONSE_FIELDS: "SIMULATOR_MISSING_RESPONSE_FIELDS",
1260
+ SIMULATOR_SCREENSHOT_FAILED: "SIMULATOR_SCREENSHOT_FAILED",
1261
+ SIMULATOR_SERVER_FACTORY_OPTIONS_MISSING: "SIMULATOR_SERVER_FACTORY_OPTIONS_MISSING",
1262
+ SIMULATOR_SERVER_DEVICE_ID_INVALID: "SIMULATOR_SERVER_DEVICE_ID_INVALID",
1263
+ SIMULATOR_SERVER_READY_EXITED: "SIMULATOR_SERVER_READY_EXITED",
1264
+ SIMULATOR_SERVER_READY_TIMEOUT: "SIMULATOR_SERVER_READY_TIMEOUT",
1265
+ SIMULATOR_SERVER_PROCESS_ERROR: "SIMULATOR_SERVER_PROCESS_ERROR",
1266
+ SIMULATOR_SERVER_TERMINATED: "SIMULATOR_SERVER_TERMINATED",
1267
+ AX_QUERY_TIMEOUT: "AX_QUERY_TIMEOUT",
1268
+ AX_DAEMON_READY_TIMEOUT: "AX_DAEMON_READY_TIMEOUT",
1269
+ AX_DAEMON_EXITED_BEFORE_READY: "AX_DAEMON_EXITED_BEFORE_READY",
1270
+ AX_DAEMON_PROCESS_ERROR: "AX_DAEMON_PROCESS_ERROR",
1271
+ AX_FACTORY_OPTIONS_MISSING: "AX_FACTORY_OPTIONS_MISSING",
1272
+ AX_WRONG_PLATFORM: "AX_WRONG_PLATFORM",
1273
+ AX_DEVICE_ID_INVALID: "AX_DEVICE_ID_INVALID",
1274
+ AX_DESCRIBE_ERROR: "AX_DESCRIBE_ERROR",
1275
+ AX_QUERY_FAILED: "AX_QUERY_FAILED",
1276
+ ANDROID_LAUNCH_ACTIVITY_RESOLVE_FAILED: "ANDROID_LAUNCH_ACTIVITY_RESOLVE_FAILED",
1277
+ ANDROID_LAUNCH_AM_START_FAILED: "ANDROID_LAUNCH_AM_START_FAILED",
1278
+ ANDROID_OPEN_URL_FAILED: "ANDROID_OPEN_URL_FAILED",
1279
+ ANDROID_REINSTALL_INSTALL_FAILED: "ANDROID_REINSTALL_INSTALL_FAILED",
1280
+ ANDROID_RESTART_FAILED: "ANDROID_RESTART_FAILED",
1281
+ ANDROID_SETTINGS_PERMISSION_FAILED: "ANDROID_SETTINGS_PERMISSION_FAILED",
1282
+ IOS_LAUNCH_SIMCTL_FAILED: "IOS_LAUNCH_SIMCTL_FAILED",
1283
+ IOS_OPEN_URL_FAILED: "IOS_OPEN_URL_FAILED",
1284
+ IOS_REINSTALL_INSTALL_FAILED: "IOS_REINSTALL_INSTALL_FAILED",
1285
+ IOS_RESTART_LAUNCH_FAILED: "IOS_RESTART_LAUNCH_FAILED",
1286
+ IOS_SETTINGS_PERMISSION_FAILED: "IOS_SETTINGS_PERMISSION_FAILED",
1287
+ SETTINGS_PERMISSION_UNSUPPORTED: "SETTINGS_PERMISSION_UNSUPPORTED",
1288
+ NATIVE_DEVTOOLS_DESCRIBE_ERROR: "NATIVE_DEVTOOLS_DESCRIBE_ERROR",
1289
+ NATIVE_DEVTOOLS_VIEW_AT_POINT_ERROR: "NATIVE_DEVTOOLS_VIEW_AT_POINT_ERROR",
1290
+ NATIVE_DEVTOOLS_USER_INTERACTABLE_VIEW_AT_POINT_ERROR: "NATIVE_DEVTOOLS_USER_INTERACTABLE_VIEW_AT_POINT_ERROR",
1291
+ NATIVE_DEVTOOLS_FIND_VIEWS_ERROR: "NATIVE_DEVTOOLS_FIND_VIEWS_ERROR",
1292
+ NATIVE_DEVTOOLS_FACTORY_OPTIONS_MISSING: "NATIVE_DEVTOOLS_FACTORY_OPTIONS_MISSING",
1293
+ NATIVE_DEVTOOLS_WRONG_PLATFORM: "NATIVE_DEVTOOLS_WRONG_PLATFORM",
1294
+ NATIVE_DEVTOOLS_NOT_INJECTABLE: "NATIVE_DEVTOOLS_NOT_INJECTABLE",
1295
+ NATIVE_DEVTOOLS_NOT_CONNECTED: "NATIVE_DEVTOOLS_NOT_CONNECTED",
1296
+ NATIVE_DEVTOOLS_RPC_TIMEOUT: "NATIVE_DEVTOOLS_RPC_TIMEOUT",
1297
+ NATIVE_DEVTOOLS_RPC_ERROR: "NATIVE_DEVTOOLS_RPC_ERROR",
1298
+ NATIVE_DEVTOOLS_SERVICE_DISPOSED: "NATIVE_DEVTOOLS_SERVICE_DISPOSED",
1299
+ NATIVE_DEVTOOLS_SOCKET_BIND_FAILED: "NATIVE_DEVTOOLS_SOCKET_BIND_FAILED",
1300
+ NATIVE_TARGET_NO_CONNECTED_APPS: "NATIVE_TARGET_NO_CONNECTED_APPS",
1301
+ NATIVE_TARGET_SINGLE_APP_NOT_FOREGROUND: "NATIVE_TARGET_SINGLE_APP_NOT_FOREGROUND",
1302
+ NATIVE_TARGET_MULTIPLE_APPS_AMBIGUOUS: "NATIVE_TARGET_MULTIPLE_APPS_AMBIGUOUS",
1303
+ ANDROID_DEVTOOLS_ADB_NOT_FOUND: "ANDROID_DEVTOOLS_ADB_NOT_FOUND",
1304
+ ANDROID_DEVTOOLS_ADB_FORWARD_UNEXPECTED: "ANDROID_DEVTOOLS_ADB_FORWARD_UNEXPECTED",
1305
+ ANDROID_DEVTOOLS_HELPER_EXITED_BEFORE_READY: "ANDROID_DEVTOOLS_HELPER_EXITED_BEFORE_READY",
1306
+ ANDROID_DEVTOOLS_HELPER_PROCESS_ERROR: "ANDROID_DEVTOOLS_HELPER_PROCESS_ERROR",
1307
+ ANDROID_DEVTOOLS_HELPER_READY_TIMEOUT: "ANDROID_DEVTOOLS_HELPER_READY_TIMEOUT",
1308
+ ANDROID_DEVTOOLS_FACTORY_OPTIONS_MISSING: "ANDROID_DEVTOOLS_FACTORY_OPTIONS_MISSING",
1309
+ ANDROID_DEVTOOLS_WRONG_PLATFORM: "ANDROID_DEVTOOLS_WRONG_PLATFORM",
1310
+ ANDROID_DEVTOOLS_DEVICE_ID_INVALID: "ANDROID_DEVTOOLS_DEVICE_ID_INVALID",
1311
+ ANDROID_DEVTOOLS_HELPER_TERMINATED: "ANDROID_DEVTOOLS_HELPER_TERMINATED",
1312
+ ANDROID_DEVTOOLS_RPC_CLIENT_CLOSED: "ANDROID_DEVTOOLS_RPC_CLIENT_CLOSED",
1313
+ ANDROID_DEVTOOLS_RPC_ERROR: "ANDROID_DEVTOOLS_RPC_ERROR",
1314
+ ANDROID_DEVTOOLS_RPC_TIMEOUT: "ANDROID_DEVTOOLS_RPC_TIMEOUT",
1315
+ ANDROID_DEVTOOLS_SOCKET_CLOSED: "ANDROID_DEVTOOLS_SOCKET_CLOSED",
1316
+ ANDROID_SCREEN_SIZE_PARSE_FAILED: "ANDROID_SCREEN_SIZE_PARSE_FAILED",
1317
+ ANDROID_SCREEN_SIZE_NON_POSITIVE: "ANDROID_SCREEN_SIZE_NON_POSITIVE",
1318
+ ANDROID_UIAUTOMATOR_PARSE_FAILED: "ANDROID_UIAUTOMATOR_PARSE_FAILED",
1319
+ ANDROID_UIAUTOMATOR_CAPTURE_FAILED: "ANDROID_UIAUTOMATOR_CAPTURE_FAILED",
1320
+ DEBUGGER_METRO_NOT_RUNNING: "DEBUGGER_METRO_NOT_RUNNING",
1321
+ DEBUGGER_METRO_NO_TARGETS: "DEBUGGER_METRO_NO_TARGETS",
1322
+ DEBUGGER_CDP_RUNTIME_EXCEPTION: "DEBUGGER_CDP_RUNTIME_EXCEPTION",
1323
+ DEBUGGER_CDP_BINDING_TIMEOUT: "DEBUGGER_CDP_BINDING_TIMEOUT",
1324
+ DEBUGGER_CDP_BINDING_UNAVAILABLE: "DEBUGGER_CDP_BINDING_UNAVAILABLE",
1325
+ DEBUGGER_CDP_PROTOCOL_ERROR: "DEBUGGER_CDP_PROTOCOL_ERROR",
1326
+ DEBUGGER_RELOAD_FAILED: "DEBUGGER_RELOAD_FAILED",
1327
+ JS_RUNTIME_CONSOLE_SERVER_BIND_FAILED: "JS_RUNTIME_CONSOLE_SERVER_BIND_FAILED",
1328
+ JS_RUNTIME_PAYLOAD_INVALID: "JS_RUNTIME_PAYLOAD_INVALID",
1329
+ JS_RUNTIME_PAYLOAD_DEVICE_MISSING: "JS_RUNTIME_PAYLOAD_DEVICE_MISSING",
1330
+ JS_RUNTIME_PAYLOAD_PORT_INVALID: "JS_RUNTIME_PAYLOAD_PORT_INVALID",
1331
+ JS_RUNTIME_CDP_DISCONNECTED: "JS_RUNTIME_CDP_DISCONNECTED",
1332
+ NETWORK_INSPECTOR_CDP_DISCONNECTED: "NETWORK_INSPECTOR_CDP_DISCONNECTED",
1333
+ REACT_PROFILER_NO_ACTIVE_SESSION: "REACT_PROFILER_NO_ACTIVE_SESSION",
1334
+ REACT_PROFILER_CDP_CONNECTION_LOST: "REACT_PROFILER_CDP_CONNECTION_LOST",
1335
+ REACT_PROFILER_NO_CPU_PROFILE: "REACT_PROFILER_NO_CPU_PROFILE",
1336
+ REACT_PROFILER_RUNTIME_EXCEPTION: "REACT_PROFILER_RUNTIME_EXCEPTION",
1337
+ REACT_PROFILER_NO_RUNTIME_DATA: "REACT_PROFILER_NO_RUNTIME_DATA",
1338
+ REACT_PROFILER_SESSION_PAYLOAD_INVALID: "REACT_PROFILER_SESSION_PAYLOAD_INVALID",
1339
+ REACT_PROFILER_SESSION_PAYLOAD_DEVICE_MISSING: "REACT_PROFILER_SESSION_PAYLOAD_DEVICE_MISSING",
1340
+ REACT_PROFILER_SESSION_CDP_DISCONNECTED: "REACT_PROFILER_SESSION_CDP_DISCONNECTED",
1341
+ REACT_PROFILER_CDP_NOT_CONNECTED: "REACT_PROFILER_CDP_NOT_CONNECTED",
1342
+ REACT_PROFILER_STATE_READ_FAILED: "REACT_PROFILER_STATE_READ_FAILED",
1343
+ REACT_PROFILER_DEVTOOLS_HOOK_MISSING: "REACT_PROFILER_DEVTOOLS_HOOK_MISSING",
1344
+ REACT_PROFILER_DEVTOOLS_BACKEND_ATTACH_FAILED: "REACT_PROFILER_DEVTOOLS_BACKEND_ATTACH_FAILED",
1345
+ REACT_PROFILER_DEVTOOLS_BACKEND_BOOTSTRAP_FAILED: "REACT_PROFILER_DEVTOOLS_BACKEND_BOOTSTRAP_FAILED",
1346
+ REACT_PROFILER_DEVTOOLS_RENDERER_MISSING: "REACT_PROFILER_DEVTOOLS_RENDERER_MISSING",
1347
+ REACT_PROFILER_START_FAILED: "REACT_PROFILER_START_FAILED",
1348
+ REACT_PROFILER_START_VERIFY_FAILED: "REACT_PROFILER_START_VERIFY_FAILED",
1349
+ REACT_PROFILER_HOOK_ERROR: "REACT_PROFILER_HOOK_ERROR",
1350
+ REACT_PROFILER_ANALYZE_NO_DATA: "REACT_PROFILER_ANALYZE_NO_DATA",
1351
+ NATIVE_PROFILER_FACTORY_OPTIONS_MISSING: "NATIVE_PROFILER_FACTORY_OPTIONS_MISSING",
1352
+ NATIVE_PROFILER_WRONG_PLATFORM: "NATIVE_PROFILER_WRONG_PLATFORM",
1353
+ NATIVE_PROFILER_APP_PROCESS_LIST_FAILED: "NATIVE_PROFILER_APP_PROCESS_LIST_FAILED",
1354
+ NATIVE_PROFILER_APP_LIST_FAILED: "NATIVE_PROFILER_APP_LIST_FAILED",
1355
+ NATIVE_PROFILER_NO_RUNNING_APPS: "NATIVE_PROFILER_NO_RUNNING_APPS",
1356
+ NATIVE_PROFILER_NO_RUNNING_USER_APPS: "NATIVE_PROFILER_NO_RUNNING_USER_APPS",
1357
+ NATIVE_PROFILER_MULTIPLE_RUNNING_USER_APPS: "NATIVE_PROFILER_MULTIPLE_RUNNING_USER_APPS",
1358
+ NATIVE_PROFILER_MALLOC_DEGRADED_XCODE: "NATIVE_PROFILER_MALLOC_DEGRADED_XCODE",
1359
+ NATIVE_PROFILER_MALLOC_STRATEGY_OVERRIDE: "NATIVE_PROFILER_MALLOC_STRATEGY_OVERRIDE",
1360
+ NATIVE_PROFILER_APP_BUNDLE_PATH_FAILED: "NATIVE_PROFILER_APP_BUNDLE_PATH_FAILED",
1361
+ NATIVE_PROFILER_LAUNCH_APP_NOT_FOUND: "NATIVE_PROFILER_LAUNCH_APP_NOT_FOUND",
1362
+ NATIVE_PROFILER_LAUNCH_APP_AMBIGUOUS: "NATIVE_PROFILER_LAUNCH_APP_AMBIGUOUS",
1363
+ NATIVE_PROFILER_SESSION_ALREADY_RUNNING: "NATIVE_PROFILER_SESSION_ALREADY_RUNNING",
1364
+ NATIVE_PROFILER_XCTRACE_NO_PID: "NATIVE_PROFILER_XCTRACE_NO_PID",
1365
+ NATIVE_PROFILER_XCTRACE_PROCESS_NOT_FOUND: "NATIVE_PROFILER_XCTRACE_PROCESS_NOT_FOUND",
1366
+ NATIVE_PROFILER_XCTRACE_READY_EXITED: "NATIVE_PROFILER_XCTRACE_READY_EXITED",
1367
+ NATIVE_PROFILER_XCTRACE_PROCESS_ERROR: "NATIVE_PROFILER_XCTRACE_PROCESS_ERROR",
1368
+ NATIVE_PROFILER_XCTRACE_READY_TIMEOUT: "NATIVE_PROFILER_XCTRACE_READY_TIMEOUT",
1369
+ NATIVE_PROFILER_TRACE_TEMPLATE_MISSING: "NATIVE_PROFILER_TRACE_TEMPLATE_MISSING",
1370
+ NATIVE_PROFILER_NO_ACTIVE_SESSION: "NATIVE_PROFILER_NO_ACTIVE_SESSION",
1371
+ NATIVE_PROFILER_APP_PROCESS_NOT_FOUND: "NATIVE_PROFILER_APP_PROCESS_NOT_FOUND",
1372
+ NATIVE_PROFILER_NO_EXPORTED_TRACE: "NATIVE_PROFILER_NO_EXPORTED_TRACE",
1373
+ // Android perfetto start-failure modes — mirror the iOS xctrace set so a
1374
+ // failed recording start is classified rather than falling through to the
1375
+ // generic tool-execution bucket.
1376
+ NATIVE_PROFILER_PERFETTO_PROCESS_ERROR: "NATIVE_PROFILER_PERFETTO_PROCESS_ERROR",
1377
+ NATIVE_PROFILER_PERFETTO_READY_TIMEOUT: "NATIVE_PROFILER_PERFETTO_READY_TIMEOUT",
1378
+ NATIVE_PROFILER_PERFETTO_READY_EXITED: "NATIVE_PROFILER_PERFETTO_READY_EXITED",
1379
+ // screen-recording-start / screen-recording-stop. One capture path for every
1380
+ // platform (simulator-server's frame stream into ffmpeg), so the stages name
1381
+ // the step that failed rather than the device family.
1382
+ SCREEN_RECORDING_FACTORY_OPTIONS_MISSING: "SCREEN_RECORDING_FACTORY_OPTIONS_MISSING",
1383
+ SCREEN_RECORDING_WRONG_PLATFORM: "SCREEN_RECORDING_WRONG_PLATFORM",
1384
+ SCREEN_RECORDING_ALREADY_ACTIVE: "SCREEN_RECORDING_ALREADY_ACTIVE",
1385
+ SCREEN_RECORDING_NO_ACTIVE_SESSION: "SCREEN_RECORDING_NO_ACTIVE_SESSION",
1386
+ SCREEN_RECORDING_STOP_IN_PROGRESS: "SCREEN_RECORDING_STOP_IN_PROGRESS",
1387
+ SCREEN_RECORDING_START_EXITED: "SCREEN_RECORDING_START_EXITED",
1388
+ SCREEN_RECORDING_START_TIMEOUT: "SCREEN_RECORDING_START_TIMEOUT",
1389
+ SCREEN_RECORDING_PROCESS_ERROR: "SCREEN_RECORDING_PROCESS_ERROR",
1390
+ SCREEN_RECORDING_OUTPUT_MISSING: "SCREEN_RECORDING_OUTPUT_MISSING",
1391
+ SCREEN_RECORDING_SERVER_SHUTTING_DOWN: "SCREEN_RECORDING_SERVER_SHUTTING_DOWN",
1392
+ SCREEN_RECORDING_STREAM_UNAVAILABLE: "SCREEN_RECORDING_STREAM_UNAVAILABLE",
1393
+ SCREEN_RECORDING_FFMPEG_NOT_FOUND: "SCREEN_RECORDING_FFMPEG_NOT_FOUND",
1394
+ FLOW_PROJECT_ROOT_REQUIRED: "FLOW_PROJECT_ROOT_REQUIRED",
1395
+ FLOW_PROJECT_ROOT_INVALID: "FLOW_PROJECT_ROOT_INVALID",
1396
+ FLOW_NAME_INVALID: "FLOW_NAME_INVALID",
1397
+ FLOW_NO_ACTIVE_RECORDING: "FLOW_NO_ACTIVE_RECORDING",
1398
+ FLOW_FILE_INVALID: "FLOW_FILE_INVALID",
1399
+ FLOW_ENTRY_UNRECOGNIZED: "FLOW_ENTRY_UNRECOGNIZED",
1400
+ FLOW_E2E_HAS_PREREQUISITE: "FLOW_E2E_HAS_PREREQUISITE",
1401
+ FLOW_DEVICE_RESOLUTION: "FLOW_DEVICE_RESOLUTION",
1402
+ PROFILER_QUERY_MODE_INVALID: "PROFILER_QUERY_MODE_INVALID",
1403
+ PROFILER_QUERY_REQUIRED_PARAM_MISSING: "PROFILER_QUERY_REQUIRED_PARAM_MISSING",
1404
+ PROFILER_DATA_NOT_LOADED: "PROFILER_DATA_NOT_LOADED",
1405
+ PROFILER_NATIVE_TRACE_MISSING: "PROFILER_NATIVE_TRACE_MISSING",
1406
+ PROFILER_NATIVE_METADATA_MISSING: "PROFILER_NATIVE_METADATA_MISSING",
1407
+ PROFILER_NATIVE_METADATA_INVALID: "PROFILER_NATIVE_METADATA_INVALID",
1408
+ CHROMIUM_CDP_UNREACHABLE: "CHROMIUM_CDP_UNREACHABLE",
1409
+ CHROMIUM_CDP_NO_PAGE_TARGET: "CHROMIUM_CDP_NO_PAGE_TARGET",
1410
+ CHROMIUM_CDP_INVALID_RESPONSE: "CHROMIUM_CDP_INVALID_RESPONSE",
1411
+ CHROMIUM_DEVICE_ID_INVALID: "CHROMIUM_DEVICE_ID_INVALID",
1412
+ CHROMIUM_PARAM_INVALID: "CHROMIUM_PARAM_INVALID",
1413
+ CHROMIUM_INPUT_INVALID: "CHROMIUM_INPUT_INVALID",
1414
+ CHROMIUM_WINDOW_HIDDEN: "CHROMIUM_WINDOW_HIDDEN",
1415
+ CHROMIUM_VIEWPORT_READ_FAILED: "CHROMIUM_VIEWPORT_READ_FAILED",
1416
+ CHROMIUM_SCREENSHOT_FAILED: "CHROMIUM_SCREENSHOT_FAILED",
1417
+ CHROMIUM_STORAGE_EVAL_FAILED: "CHROMIUM_STORAGE_EVAL_FAILED",
1418
+ CHROMIUM_TAB_NOT_FOUND: "CHROMIUM_TAB_NOT_FOUND",
1419
+ CHROMIUM_TAB_OPEN_FAILED: "CHROMIUM_TAB_OPEN_FAILED",
1420
+ CHROMIUM_DESCRIBE_FAILED: "CHROMIUM_DESCRIBE_FAILED",
1421
+ CHROMIUM_ELECTRON_APP_PATH_INVALID: "CHROMIUM_ELECTRON_APP_PATH_INVALID",
1422
+ CHROMIUM_ELECTRON_SPAWN_FAILED: "CHROMIUM_ELECTRON_SPAWN_FAILED",
1423
+ CHROMIUM_ELECTRON_CDP_TIMEOUT: "CHROMIUM_ELECTRON_CDP_TIMEOUT",
1424
+ CHROMIUM_ELECTRON_EXITED_BEFORE_READY: "CHROMIUM_ELECTRON_EXITED_BEFORE_READY",
1425
+ KEYBOARD_KEY_UNSUPPORTED: "KEYBOARD_KEY_UNSUPPORTED",
1426
+ KEYBOARD_CHARACTER_UNSUPPORTED: "KEYBOARD_CHARACTER_UNSUPPORTED",
1427
+ SECRET_PLACEHOLDER_UNKNOWN: "SECRET_PLACEHOLDER_UNKNOWN",
1428
+ SCREENSHOT_DIFF_INPUT_INVALID: "SCREENSHOT_DIFF_INPUT_INVALID",
1429
+ BOOT_DEVICE_TARGET_SELECTION_INVALID: "BOOT_DEVICE_TARGET_SELECTION_INVALID",
1430
+ BOOT_IOS_UNSUPPORTED_HOST: "BOOT_IOS_UNSUPPORTED_HOST",
1431
+ BOOT_ANDROID_NO_AVDS: "BOOT_ANDROID_NO_AVDS",
1432
+ BOOT_ANDROID_AVD_NOT_FOUND: "BOOT_ANDROID_AVD_NOT_FOUND",
1433
+ BOOT_ANDROID_ADB_UNAVAILABLE: "BOOT_ANDROID_ADB_UNAVAILABLE",
1434
+ BOOT_ANDROID_GPU_MODE_INVALID: "BOOT_ANDROID_GPU_MODE_INVALID",
1435
+ BOOT_ANDROID_ADB_REGISTER_TIMEOUT: "BOOT_ANDROID_ADB_REGISTER_TIMEOUT",
1436
+ BOOT_ANDROID_HOT_BOOT_FRAME_UNUSABLE: "BOOT_ANDROID_HOT_BOOT_FRAME_UNUSABLE",
1437
+ BOOT_ANDROID_FIRST_FRAME_TIMEOUT: "BOOT_ANDROID_FIRST_FRAME_TIMEOUT",
1438
+ BOOT_ANDROID_PACKAGE_MANAGER_UNAVAILABLE: "BOOT_ANDROID_PACKAGE_MANAGER_UNAVAILABLE",
1439
+ BOOT_ANDROID_COLD_BOOT_FAILED: "BOOT_ANDROID_COLD_BOOT_FAILED"
1440
+ };
1441
+
1442
+ // ../registry/src/errors.ts
1443
+ var FAILURE_AREAS = ["cli", "http", "registry", "tool_server", "installer"];
1444
+ var FAILURE_KINDS = [
1445
+ "validation",
1446
+ "not_found",
1447
+ "dependency_missing",
1448
+ "unsupported",
1449
+ "not_implemented",
1450
+ "timeout",
1451
+ "network",
1452
+ "subprocess",
1453
+ "crash",
1454
+ "unknown"
1455
+ ];
1456
+ var FAILURE_COMMANDS = [
1457
+ "adb",
1458
+ "emulator",
1459
+ "vega",
1460
+ "xcrun_simctl",
1461
+ "xctrace",
1462
+ "native_devtools",
1463
+ "android_devtools",
1464
+ "ax_service",
1465
+ "simulator_server",
1466
+ "ffmpeg",
1467
+ "cdp",
1468
+ "electron",
1469
+ "npm",
1470
+ "npx",
1471
+ "unknown"
1472
+ ];
1473
+ var FAILURE_SIGNAL_NAMES = [
1474
+ "SIGABRT",
1475
+ "SIGHUP",
1476
+ "SIGINT",
1477
+ "SIGKILL",
1478
+ "SIGQUIT",
1479
+ "SIGTERM"
1480
+ ];
1481
+ var FAILURE_SPAWN_CODES = ["EACCES", "ENOENT", "EPERM", "ETIMEDOUT"];
1482
+ var NETWORK_FAILURES = [
1483
+ "timeout",
1484
+ "connection_refused",
1485
+ "connection_reset",
1486
+ "invalid_response",
1487
+ "other"
1488
+ ];
1489
+ var FALLBACK_SIGNAL = {
1490
+ error_code: FAILURE_CODES.ARGENT_UNCLASSIFIED_FAILURE,
1491
+ failure_stage: "unclassified",
1492
+ failure_area: "registry",
1493
+ error_kind: "unknown"
1494
+ };
1495
+ var FAILURE_SIGNAL_NAME_SET = new Set(FAILURE_SIGNAL_NAMES);
1496
+ var FAILURE_SPAWN_CODE_SET = new Set(FAILURE_SPAWN_CODES);
1497
+
1498
+ // ../registry/src/registry.ts
1499
+ import { randomUUID as randomUUID2 } from "node:crypto";
1500
+
1501
+ // ../argent-tools-client/src/file-inputs.ts
1502
+ var FILE_INPUT_MARKER2 = "__argentFileInput";
1503
+ var CLIENT_FILE_MARKER2 = "__argentClientFile";
1504
+ var MAX_CONTENT_BYTES = 32 * 1024 * 1024;
1505
+ function interpolatePath(template, args) {
1506
+ let missing = false;
1507
+ const out = template.replace(/\$\{([A-Za-z0-9_]+)\}/g, (_m, name) => {
1508
+ const v = args[name];
1509
+ if (typeof v !== "string" || v.length === 0) {
1510
+ missing = true;
1511
+ return "";
1512
+ }
1513
+ return v;
1514
+ });
1515
+ return missing ? null : out;
1516
+ }
1517
+ async function tarball(sourcePath) {
1518
+ const tarPath = path3.join(tmpdir(), `argent-upload-${randomUUID3()}.tar.gz`);
1519
+ await createTarGzFile(sourcePath, tarPath);
1520
+ return tarPath;
1521
+ }
1522
+ function sha256File(filePath) {
1523
+ return new Promise((resolve10, reject) => {
1524
+ const hash = createHash2("sha256");
1525
+ createReadStream(filePath).on("data", (chunk) => hash.update(chunk)).on("end", () => resolve10(hash.digest("hex"))).on("error", reject);
1526
+ });
1527
+ }
1528
+ async function uploadTar(tarPath, endpoint) {
1529
+ const init2 = {
1530
+ method: "POST",
1531
+ headers: {
1532
+ "content-type": "application/gzip",
1533
+ ...endpoint.token ? { Authorization: `Bearer ${endpoint.token}` } : {}
1534
+ },
1535
+ body: createReadStream(tarPath),
1536
+ duplex: "half"
1537
+ };
1538
+ const res = await fetch(`${endpoint.url}/upload`, init2);
1539
+ if (!res.ok) {
1540
+ throw new Error(`Upload to ${endpoint.url}/upload failed: ${res.status} ${res.statusText}`);
1541
+ }
1542
+ const json = await res.json();
1543
+ return json.uploadId;
1544
+ }
1545
+ async function prepareFileInputs(specs, args, opts) {
1546
+ if (!specs || specs.length === 0 || typeof args !== "object" || args === null) {
1547
+ return args;
1548
+ }
1549
+ const record = args;
1550
+ let out = null;
1551
+ for (const spec of specs) {
1552
+ if (spec.skipWhenSet && record[spec.skipWhenSet] !== void 0) continue;
1553
+ if (spec.target in record && typeof record[spec.target] !== "string") continue;
1554
+ const filePath = interpolatePath(spec.path, record);
1555
+ if (filePath === null) continue;
1556
+ if (spec.target in record && record[spec.target] !== filePath) continue;
1557
+ const wire = { [FILE_INPUT_MARKER2]: true, path: filePath };
1558
+ if (spec.kind === "file") {
1559
+ try {
1560
+ const st = await stat2(filePath);
1561
+ if (st.isFile()) {
1562
+ wire.size = st.size;
1563
+ wire.mtimeMs = st.mtimeMs;
1564
+ if (opts.includeContent && st.size <= MAX_CONTENT_BYTES) {
1565
+ wire.content = (await readFile3(filePath)).toString("base64");
1566
+ } else if (opts.includeContent) {
1567
+ wire.contentOmitted = "size-limit";
1568
+ }
1569
+ }
1570
+ } catch {
1571
+ }
1572
+ }
1573
+ if (spec.kind === "tar-upload") {
1574
+ const st = await stat2(filePath).catch(() => null);
1575
+ if (st) {
1576
+ wire.size = st.size;
1577
+ wire.mtimeMs = st.mtimeMs;
1578
+ }
1579
+ if (opts.uploadEndpoint && st) {
1580
+ let tarPath = null;
1581
+ try {
1582
+ process.stderr.write(
1583
+ `Uploading ${path3.basename(filePath)} to the remote tool-server...
1584
+ `
1585
+ );
1586
+ tarPath = await tarball(filePath);
1587
+ wire.contentHash = await sha256File(tarPath);
1588
+ wire.uploadId = await uploadTar(tarPath, opts.uploadEndpoint);
1589
+ } finally {
1590
+ if (tarPath) await rm2(tarPath, { force: true }).catch(() => {
1591
+ });
1592
+ }
1593
+ }
1594
+ }
1595
+ out = out ?? { ...record };
1596
+ out[spec.target] = wire;
1597
+ }
1598
+ return out ?? args;
1599
+ }
1600
+ function isAllowedClientFilePath(p) {
1601
+ if (!path3.isAbsolute(p)) return false;
1602
+ const segments = p.split(/[\\/]+/);
1603
+ if (segments.includes("..")) return false;
1604
+ const file = segments[segments.length - 1] ?? "";
1605
+ if (!FLOW_FILE_NAME_PATTERN.test(file)) return false;
1606
+ return segments[segments.length - 3] === ".argent" && segments[segments.length - 2] === "flows";
1607
+ }
1608
+ function isClientFileDirective2(value) {
1609
+ return !!value && typeof value === "object" && value[CLIENT_FILE_MARKER2] === true && typeof value.path === "string" && typeof value.content === "string";
1610
+ }
1611
+ async function applyClientFileDirectives(result) {
1612
+ const written = [];
1613
+ async function walk(value) {
1614
+ if (isClientFileDirective2(value)) {
1615
+ if (!isAllowedClientFilePath(value.path)) return null;
1616
+ try {
1617
+ await mkdir3(path3.dirname(value.path), { recursive: true });
1618
+ await writeFile3(value.path, value.content, "utf8");
1619
+ written.push(value.path);
1620
+ return value.path;
1621
+ } catch {
1622
+ return null;
1623
+ }
1624
+ }
1625
+ if (Array.isArray(value)) {
1626
+ return Promise.all(value.map(walk));
1627
+ }
1628
+ if (value && typeof value === "object") {
1629
+ const out = {};
1630
+ for (const [k, v] of Object.entries(value)) {
1631
+ out[k] = await walk(v);
1632
+ }
1633
+ return out;
1634
+ }
1635
+ return value;
1636
+ }
1637
+ const rewritten = await walk(result);
1638
+ return { result: rewritten, written };
1639
+ }
1640
+
1641
+ // ../argent-tools-client/src/tools-client.ts
1642
+ var ToolInvocationError = class extends Error {
1643
+ errorCode;
1644
+ errorKind;
1645
+ constructor(message, signal) {
1646
+ super(message);
1647
+ this.name = "ToolInvocationError";
1648
+ this.errorCode = signal?.errorCode;
1649
+ this.errorKind = signal?.errorKind;
1650
+ }
1651
+ };
1652
+ function authHeaders2(token) {
1653
+ return token ? { Authorization: `Bearer ${token}` } : {};
1654
+ }
1655
+ async function consumeToolStream(body, onProgress) {
1656
+ let final;
1657
+ const handleLine = (line) => {
1658
+ if (!line.trim()) return;
1659
+ const msg = JSON.parse(line);
1660
+ if (msg.event === "progress") onProgress(msg.data);
1661
+ else if (msg.event === "result") final = { data: msg.data, note: msg.note };
1662
+ else if (msg.event === "error") {
1663
+ throw new ToolInvocationError(msg.error ?? "tool invocation failed", {
1664
+ errorCode: msg.error_code,
1665
+ errorKind: msg.error_kind
1666
+ });
1667
+ }
1668
+ };
1669
+ const reader = body.getReader();
1670
+ const decoder = new TextDecoder();
1671
+ let buffered = "";
1672
+ try {
1673
+ for (; ; ) {
1674
+ const { done, value } = await reader.read();
1675
+ if (done) break;
1676
+ buffered += decoder.decode(value, { stream: true });
1677
+ let newline;
1678
+ while ((newline = buffered.indexOf("\n")) !== -1) {
1679
+ const line = buffered.slice(0, newline);
1680
+ buffered = buffered.slice(newline + 1);
1681
+ handleLine(line);
1682
+ }
1683
+ }
1684
+ buffered += decoder.decode();
1685
+ if (buffered.trim()) handleLine(buffered);
1686
+ } catch (err) {
1687
+ void reader.cancel().catch(() => {
1688
+ });
1689
+ throw err;
1690
+ }
1691
+ if (!final) {
1692
+ throw new Error("tool stream ended without a result \u2014 connection lost mid-run?");
1693
+ }
1694
+ const { result: data } = await applyClientFileDirectives(final.data);
1695
+ return { data, note: final.note };
1696
+ }
1697
+ function createToolsClient(options = {}) {
1698
+ let cached2 = null;
1699
+ async function baseUrl() {
1700
+ const resolved = await getResolvedToolsUrl();
1701
+ if (resolved.url) {
1702
+ return { url: resolved.url, token: resolved.token ?? "" };
1703
+ }
1047
1704
  if (cached2) return cached2;
1048
1705
  if (!options.paths) {
1049
1706
  throw new Error(
@@ -1091,7 +1748,13 @@ function createToolsClient(options = {}) {
1091
1748
  }
1092
1749
  const json = await res.json().catch(() => ({}));
1093
1750
  if (!res.ok) {
1094
- throw new Error(json.error ?? json.message ?? `${res.status} ${res.statusText}`);
1751
+ throw new ToolInvocationError(
1752
+ json.error ?? json.message ?? `${res.status} ${res.statusText}`,
1753
+ {
1754
+ errorCode: json.error_code,
1755
+ errorKind: json.error_kind
1756
+ }
1757
+ );
1095
1758
  }
1096
1759
  const { result: data } = await applyClientFileDirectives(json.data);
1097
1760
  return { data, note: json.note };
@@ -1100,10 +1763,10 @@ function createToolsClient(options = {}) {
1100
1763
  }
1101
1764
 
1102
1765
  // ../argent-tools-client/src/artifacts.ts
1103
- import { copyFile, mkdir as mkdir4, readFile as readFile4, realpath, rm as rm3, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
1766
+ import { copyFile, mkdir as mkdir4, readFile as readFile4, realpath, rm as rm3, stat as stat3, writeFile as writeFile4 } from "node:fs/promises";
1104
1767
  import { constants as fsConstants } from "node:fs";
1105
1768
  import { tmpdir as tmpdir2 } from "node:os";
1106
- import { basename as basename3, dirname as dirname5, extname, isAbsolute as isAbsolute3, join as join8, normalize, resolve as resolve5, sep as sep2 } from "node:path";
1769
+ import { basename as basename4, dirname as dirname5, extname as extname2, isAbsolute as isAbsolute3, join as join9, normalize, resolve as resolve6, sep as sep2 } from "node:path";
1107
1770
  import { createHash as createHash3 } from "node:crypto";
1108
1771
 
1109
1772
  // ../configuration-core/src/flags.ts
@@ -1304,15 +1967,20 @@ function setAtPath(obj, dottedKey, value) {
1304
1967
  }
1305
1968
  function deleteAtPath(obj, dottedKey) {
1306
1969
  const parts = splitKey(dottedKey);
1307
- let cur = obj;
1970
+ const chain = [obj];
1308
1971
  for (let i2 = 0; i2 < parts.length - 1; i2++) {
1309
- const next = cur[parts[i2]];
1972
+ const next = chain[i2][parts[i2]];
1310
1973
  if (!isPlainObject(next)) return false;
1311
- cur = next;
1974
+ chain.push(next);
1312
1975
  }
1976
+ const parent = chain[parts.length - 1];
1313
1977
  const leaf = parts[parts.length - 1];
1314
- if (!Object.hasOwn(cur, leaf)) return false;
1315
- delete cur[leaf];
1978
+ if (!Object.hasOwn(parent, leaf)) return false;
1979
+ delete parent[leaf];
1980
+ for (let i2 = chain.length - 1; i2 >= 1; i2--) {
1981
+ if (Object.keys(chain[i2]).length > 0) break;
1982
+ delete chain[i2 - 1][parts[i2 - 1]];
1983
+ }
1316
1984
  return true;
1317
1985
  }
1318
1986
  var LOCK_STALE_MS2 = 1e4;
@@ -1387,6 +2055,97 @@ function updateConfig(mutate, scope = "global", options = {}) {
1387
2055
  }
1388
2056
  }
1389
2057
 
2058
+ // ../configuration-core/src/secrets.ts
2059
+ var import_dotenv = __toESM(require_main(), 1);
2060
+ import * as fs4 from "node:fs";
2061
+ import * as path7 from "node:path";
2062
+ var SECRET_ENV_PREFIX = "ARGENT_SECRET_";
2063
+ var SECRETS_FILE_NAME = "secrets.env";
2064
+ var SHARED_ENV_FILES = [".env.local", ".env"];
2065
+ var SECRET_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
2066
+ function envSource(env) {
2067
+ const values = /* @__PURE__ */ new Map();
2068
+ for (const [key, value] of Object.entries(env)) {
2069
+ if (value === void 0 || !key.startsWith(SECRET_ENV_PREFIX)) continue;
2070
+ const name = key.slice(SECRET_ENV_PREFIX.length);
2071
+ if (SECRET_NAME_RE.test(name)) values.set(name, value);
2072
+ }
2073
+ return {
2074
+ label: `environment (${SECRET_ENV_PREFIX}*)`,
2075
+ kind: "env",
2076
+ present: true,
2077
+ names: [...values.keys()].sort(),
2078
+ values
2079
+ };
2080
+ }
2081
+ function fileSource(filePath, exposure) {
2082
+ const label = filePath;
2083
+ const absent = {
2084
+ label,
2085
+ kind: "file",
2086
+ present: false,
2087
+ names: [],
2088
+ values: /* @__PURE__ */ new Map()
2089
+ };
2090
+ if (!fs4.statSync(filePath, { throwIfNoEntry: false })) return absent;
2091
+ let content;
2092
+ try {
2093
+ content = fs4.readFileSync(filePath, "utf8");
2094
+ } catch {
2095
+ return absent;
2096
+ }
2097
+ const values = /* @__PURE__ */ new Map();
2098
+ let skippedUnprefixed = false;
2099
+ for (const [key, value] of Object.entries((0, import_dotenv.parse)(content))) {
2100
+ const prefixed = key.startsWith(SECRET_ENV_PREFIX);
2101
+ if (exposure === "shared" && !prefixed) {
2102
+ skippedUnprefixed = true;
2103
+ continue;
2104
+ }
2105
+ const name = prefixed ? key.slice(SECRET_ENV_PREFIX.length) : key;
2106
+ if (SECRET_NAME_RE.test(name)) values.set(name, value);
2107
+ }
2108
+ return {
2109
+ label,
2110
+ kind: "file",
2111
+ present: true,
2112
+ names: [...values.keys()].sort(),
2113
+ values,
2114
+ ...values.size === 0 && skippedUnprefixed ? { needsPrefix: true } : {}
2115
+ };
2116
+ }
2117
+ function secretSources(options = {}) {
2118
+ const sources = [envSource(options.env ?? process.env)];
2119
+ const projectRoot = findProjectRoot(options.cwd ?? process.cwd());
2120
+ const filePaths = [];
2121
+ if (projectRoot) {
2122
+ filePaths.push({
2123
+ path: path7.join(projectRoot, ".argent", SECRETS_FILE_NAME),
2124
+ exposure: "dedicated"
2125
+ });
2126
+ for (const name of SHARED_ENV_FILES) {
2127
+ filePaths.push({ path: path7.join(projectRoot, name), exposure: "shared" });
2128
+ }
2129
+ }
2130
+ filePaths.push({
2131
+ path: path7.join(resolveHomeDir(options), ".argent", SECRETS_FILE_NAME),
2132
+ exposure: "dedicated"
2133
+ });
2134
+ const seen = /* @__PURE__ */ new Set();
2135
+ for (const entry of filePaths) {
2136
+ const resolved = path7.resolve(entry.path);
2137
+ if (seen.has(resolved)) continue;
2138
+ seen.add(resolved);
2139
+ sources.push(fileSource(resolved, entry.exposure));
2140
+ }
2141
+ return sources;
2142
+ }
2143
+ function secretNames(sources) {
2144
+ const names = /* @__PURE__ */ new Set();
2145
+ for (const source of sources) for (const name of source.names) names.add(name);
2146
+ return [...names].sort();
2147
+ }
2148
+
1390
2149
  // ../configuration-core/src/merge.ts
1391
2150
  function mergeRestrictive(local, global2) {
1392
2151
  if (local === void 0) return global2;
@@ -1447,6 +2206,9 @@ function asString(raw) {
1447
2206
  const trimmed = raw.trim();
1448
2207
  return trimmed === "" ? void 0 : trimmed;
1449
2208
  }
2209
+ function asNumber(raw) {
2210
+ return typeof raw === "number" && Number.isFinite(raw) ? raw : void 0;
2211
+ }
1450
2212
  function asStringArray(raw) {
1451
2213
  if (!Array.isArray(raw)) return void 0;
1452
2214
  const out = [];
@@ -1455,6 +2217,15 @@ function asStringArray(raw) {
1455
2217
  }
1456
2218
  return out;
1457
2219
  }
2220
+ var PARSER_EXPECTATIONS = /* @__PURE__ */ new Map([
2221
+ [asBoolean, "a boolean (true or false)"],
2222
+ [asString, "a non-empty string"],
2223
+ [asNumber, "a number"],
2224
+ [asStringArray, "an array of strings"]
2225
+ ]);
2226
+ function describeExpectedValue(def) {
2227
+ return def.expected ?? PARSER_EXPECTATIONS.get(def.parse);
2228
+ }
1458
2229
  var CONFIG_SCHEMA = [
1459
2230
  {
1460
2231
  key: "telemetry.enabled",
@@ -1512,7 +2283,7 @@ function getConfigDefinition(key, registry = CONFIG_SCHEMA) {
1512
2283
  }
1513
2284
 
1514
2285
  // ../configuration-core/src/config-access.ts
1515
- import * as path7 from "node:path";
2286
+ import * as path8 from "node:path";
1516
2287
  function readScopeValue(def, scope, options) {
1517
2288
  if (!def.scopes.includes(scope)) return void 0;
1518
2289
  const raw = getAtPath(readConfigObject(scope, options), def.key);
@@ -1560,12 +2331,18 @@ var ConfigScopeError = class extends Error {
1560
2331
  allowed;
1561
2332
  };
1562
2333
  var ConfigValidationError = class extends Error {
1563
- constructor(key) {
1564
- super(`Invalid value for config key "${key}".`);
2334
+ constructor(key, expected, example) {
2335
+ super(
2336
+ expected ? `Invalid value for config key "${key}": expected ${expected}.` : `Invalid value for config key "${key}".`
2337
+ );
1565
2338
  this.key = key;
2339
+ this.expected = expected;
2340
+ this.example = example;
1566
2341
  this.name = "ConfigValidationError";
1567
2342
  }
1568
2343
  key;
2344
+ expected;
2345
+ example;
1569
2346
  };
1570
2347
  var ConfigManagedElsewhereError = class extends Error {
1571
2348
  constructor(key, command) {
@@ -1582,7 +2359,8 @@ function setConfigValue(key, rawValue, scope = "global", options = {}, registry
1582
2359
  if (def.manageCommand) throw new ConfigManagedElsewhereError(key, def.manageCommand);
1583
2360
  if (!def.scopes.includes(scope)) throw new ConfigScopeError(key, scope, def.scopes);
1584
2361
  const parsed = def.parse(rawValue);
1585
- if (parsed === void 0) throw new ConfigValidationError(key);
2362
+ if (parsed === void 0)
2363
+ throw new ConfigValidationError(def.key, describeExpectedValue(def), def.example);
1586
2364
  updateConfig((config2) => setAtPath(config2, key, parsed), scope, options);
1587
2365
  return parsed;
1588
2366
  }
@@ -1607,6 +2385,8 @@ function listConfig(options = {}, registry = CONFIG_SCHEMA) {
1607
2385
  description: def.description,
1608
2386
  scopes: def.scopes,
1609
2387
  ...def.manageCommand ? { manageCommand: def.manageCommand } : {},
2388
+ ...describeExpectedValue(def) ? { expected: describeExpectedValue(def) } : {},
2389
+ ...def.example ? { example: def.example } : {},
1610
2390
  effective: getConfigValue(def, options),
1611
2391
  project: readScopeValue(def, "project", options),
1612
2392
  global: readScopeValue(def, "global", options)
@@ -1632,9 +2412,9 @@ function clearRememberedAgent(options = {}) {
1632
2412
  }
1633
2413
 
1634
2414
  // ../argent-tools-client/src/artifacts.ts
1635
- var ARTIFACT_MARKER = "__argentArtifact";
2415
+ var ARTIFACT_MARKER2 = "__argentArtifact";
1636
2416
  function isArtifactHandle(value) {
1637
- return !!value && typeof value === "object" && value[ARTIFACT_MARKER] === true && typeof value.id === "string" && typeof value.filename === "string";
2417
+ return !!value && typeof value === "object" && value[ARTIFACT_MARKER2] === true && typeof value.id === "string" && typeof value.filename === "string";
1638
2418
  }
1639
2419
  var SESSION_ID = null;
1640
2420
  function sessionId() {
@@ -1650,16 +2430,16 @@ function sanitizeSegment(segment) {
1650
2430
  function projectSlug() {
1651
2431
  const cwd = process.cwd();
1652
2432
  const hash = createHash3("sha1").update(cwd).digest("hex").slice(0, 6);
1653
- const name = sanitizeSegment(basename3(cwd)) || "root";
2433
+ const name = sanitizeSegment(basename4(cwd)) || "root";
1654
2434
  return `${name}-${hash}`;
1655
2435
  }
1656
2436
  function artifactsRoot() {
1657
- return process.env.ARGENT_ARTIFACTS_DIR ?? join8(tmpdir2(), "argent-artifacts");
2437
+ return process.env.ARGENT_ARTIFACTS_DIR ?? join9(tmpdir2(), "argent-artifacts");
1658
2438
  }
1659
2439
  function artifactDir(deviceId) {
1660
2440
  const parts = [artifactsRoot(), projectSlug(), sessionId()];
1661
2441
  if (deviceId) parts.push(sanitizeSegment(deviceId));
1662
- return join8(...parts);
2442
+ return join9(...parts);
1663
2443
  }
1664
2444
  function durableBaseDir() {
1665
2445
  const projectRoot = findProjectRoot(process.cwd());
@@ -1678,8 +2458,8 @@ function configuredRecordingsDir() {
1678
2458
  const trimmed = value.trim();
1679
2459
  if (trimmed === "") return null;
1680
2460
  const home = dirname5(argentHomeDir());
1681
- const expanded = trimmed === "~" ? home : trimmed.startsWith("~/") || trimmed.startsWith(`~${sep2}`) ? join8(home, trimmed.slice(2)) : trimmed;
1682
- return resolve5(durableBaseDir(), expanded);
2461
+ const expanded = trimmed === "~" ? home : trimmed.startsWith("~/") || trimmed.startsWith(`~${sep2}`) ? join9(home, trimmed.slice(2)) : trimmed;
2462
+ return resolve6(durableBaseDir(), expanded);
1683
2463
  }
1684
2464
  var MAX_DURABLE_BYTES = 2 * 1024 * 1024 * 1024;
1685
2465
  async function readCapped(res, cap) {
@@ -1708,14 +2488,14 @@ async function readCapped(res, cap) {
1708
2488
  return Buffer.concat(chunks);
1709
2489
  }
1710
2490
  async function writeDurableUnique(dir, filename, write) {
1711
- const ext = extname(filename);
2491
+ const ext = extname2(filename);
1712
2492
  const stem = filename.slice(0, filename.length - ext.length);
1713
2493
  for (let i2 = 1; i2 <= 1e3; i2++) {
1714
2494
  const candidate = i2 === 1 ? filename : `${stem} (${i2})${ext}`;
1715
- const path16 = join8(dir, candidate);
2495
+ const path17 = join9(dir, candidate);
1716
2496
  try {
1717
- await write(path16);
1718
- return path16;
2497
+ await write(path17);
2498
+ return path17;
1719
2499
  } catch (err) {
1720
2500
  if (err?.code === "EEXIST") continue;
1721
2501
  throw err;
@@ -1735,21 +2515,21 @@ function durableSaveTarget(handle) {
1735
2515
  if (configured) {
1736
2516
  return {
1737
2517
  dir: configured,
1738
- path: join8(configured, sanitizeSegment(handle.filename)),
2518
+ path: join9(configured, sanitizeSegment(handle.filename)),
1739
2519
  base: configured,
1740
2520
  rel: ""
1741
2521
  };
1742
2522
  }
1743
2523
  }
1744
2524
  const base = durableBaseDir();
1745
- const dir = join8(base, rel);
1746
- return { dir, path: join8(dir, sanitizeSegment(handle.filename)), base, rel };
2525
+ const dir = join9(base, rel);
2526
+ return { dir, path: join9(dir, sanitizeSegment(handle.filename)), base, rel };
1747
2527
  }
1748
2528
  async function confineToRealBase(dir, base, rel) {
1749
2529
  try {
1750
2530
  const realDir = await realpath(dir);
1751
2531
  const realBase = await realpath(base);
1752
- return realDir === join8(realBase, rel);
2532
+ return realDir === join9(realBase, rel);
1753
2533
  } catch {
1754
2534
  return false;
1755
2535
  }
@@ -1757,7 +2537,7 @@ async function confineToRealBase(dir, base, rel) {
1757
2537
  async function resolveLocalFile(handle) {
1758
2538
  if (!handle.hostPath) return null;
1759
2539
  try {
1760
- const st = await stat2(handle.hostPath);
2540
+ const st = await stat3(handle.hostPath);
1761
2541
  if (handle.archive) {
1762
2542
  return st.isDirectory() ? handle.hostPath : null;
1763
2543
  }
@@ -1772,7 +2552,7 @@ async function resolveLocalFile(handle) {
1772
2552
  }
1773
2553
  }
1774
2554
  async function downloadAndExtractArchive(handle, data, dir) {
1775
- const tarball2 = join8(dir, `${sanitizeSegment(handle.filename)}.tar.gz`);
2555
+ const tarball2 = join9(dir, `${sanitizeSegment(handle.filename)}.tar.gz`);
1776
2556
  try {
1777
2557
  await writeFile4(tarball2, data);
1778
2558
  return await safeExtractTarGz(tarball2, dir, handle.filename);
@@ -1800,7 +2580,7 @@ async function materializeArtifacts(result, ctx) {
1800
2580
  const localPath = await resolveLocalFile(value);
1801
2581
  const saveTarget = durableSaveTarget(value);
1802
2582
  if (saveTarget) {
1803
- const filename = basename3(saveTarget.path);
2583
+ const filename = basename4(saveTarget.path);
1804
2584
  try {
1805
2585
  await mkdir4(saveTarget.dir, { recursive: true });
1806
2586
  if (!await confineToRealBase(saveTarget.dir, saveTarget.base, saveTarget.rel)) {
@@ -1862,7 +2642,7 @@ async function materializeArtifacts(result, ctx) {
1862
2642
  return await downloadAndExtractArchive(value, data, dir);
1863
2643
  }
1864
2644
  if (value.size > 0 && data.length !== value.size) return null;
1865
- const downloadedPath = join8(dir, sanitizeSegment(value.filename));
2645
+ const downloadedPath = join9(dir, sanitizeSegment(value.filename));
1866
2646
  await writeFile4(downloadedPath, data);
1867
2647
  if (value.mimeType.startsWith("image/")) {
1868
2648
  images.push({ localPath: downloadedPath, data, mimeType: value.mimeType });
@@ -1922,8 +2702,8 @@ function createGetModuleFromFilename(basePath = process.argv[1] ? dirname6(proce
1922
2702
  return decodedFile;
1923
2703
  };
1924
2704
  }
1925
- function normalizeWindowsPath(path16) {
1926
- return path16.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
2705
+ function normalizeWindowsPath(path17) {
2706
+ return path17.replace(/^[A-Z]:/, "").replace(/\\/g, "/");
1927
2707
  }
1928
2708
 
1929
2709
  // ../../node_modules/@posthog/core/dist/featureFlagUtils.mjs
@@ -4475,15 +5255,15 @@ async function addSourceContext(frames) {
4475
5255
  LRU_FILE_CONTENTS_CACHE.reduce();
4476
5256
  return frames;
4477
5257
  }
4478
- function getContextLinesFromFile(path16, ranges, output) {
4479
- return new Promise((resolve9) => {
4480
- const stream = createReadStream2(path16);
5258
+ function getContextLinesFromFile(path17, ranges, output) {
5259
+ return new Promise((resolve10) => {
5260
+ const stream = createReadStream2(path17);
4481
5261
  const lineReaded = createInterface2({
4482
5262
  input: stream
4483
5263
  });
4484
5264
  function destroyStreamAndResolve() {
4485
5265
  stream.destroy();
4486
- resolve9();
5266
+ resolve10();
4487
5267
  }
4488
5268
  let lineNumber = 0;
4489
5269
  let currentRangeIndex = 0;
@@ -4492,7 +5272,7 @@ function getContextLinesFromFile(path16, ranges, output) {
4492
5272
  let rangeStart = range[0];
4493
5273
  let rangeEnd = range[1];
4494
5274
  function onStreamError() {
4495
- LRU_FILE_CONTENTS_FS_READ_FAILED.set(path16, 1);
5275
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(path17, 1);
4496
5276
  lineReaded.close();
4497
5277
  lineReaded.removeAllListeners();
4498
5278
  destroyStreamAndResolve();
@@ -4553,8 +5333,8 @@ function clearLineContext(frame) {
4553
5333
  delete frame.context_line;
4554
5334
  delete frame.post_context;
4555
5335
  }
4556
- function shouldSkipContextLinesForFile(path16) {
4557
- return path16.startsWith("node:") || path16.endsWith(".min.js") || path16.endsWith(".min.cjs") || path16.endsWith(".min.mjs") || path16.startsWith("data:");
5336
+ function shouldSkipContextLinesForFile(path17) {
5337
+ return path17.startsWith("node:") || path17.endsWith(".min.js") || path17.endsWith(".min.cjs") || path17.endsWith(".min.mjs") || path17.startsWith("data:");
4558
5338
  }
4559
5339
  function shouldSkipContextLinesForFrame(frame) {
4560
5340
  if (void 0 !== frame.lineno && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;
@@ -5780,9 +6560,9 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
5780
6560
  if (!waitUntil) return;
5781
6561
  if (this.disabled || this.optedOut) return;
5782
6562
  if (!this._waitUntilCycle) {
5783
- let resolve9;
6563
+ let resolve10;
5784
6564
  const promise = new Promise((r2) => {
5785
- resolve9 = r2;
6565
+ resolve10 = r2;
5786
6566
  });
5787
6567
  try {
5788
6568
  waitUntil(promise);
@@ -5790,7 +6570,7 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
5790
6570
  return;
5791
6571
  }
5792
6572
  this._waitUntilCycle = {
5793
- resolve: resolve9,
6573
+ resolve: resolve10,
5794
6574
  startedAt: Date.now(),
5795
6575
  timer: void 0
5796
6576
  };
@@ -5814,12 +6594,12 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
5814
6594
  return cycle?.resolve;
5815
6595
  }
5816
6596
  async resolveWaitUntilFlush() {
5817
- const resolve9 = this._consumeWaitUntilCycle();
6597
+ const resolve10 = this._consumeWaitUntilCycle();
5818
6598
  try {
5819
6599
  await super.flush();
5820
6600
  } catch {
5821
6601
  } finally {
5822
- resolve9?.();
6602
+ resolve10?.();
5823
6603
  }
5824
6604
  }
5825
6605
  getPersistedProperty(key) {
@@ -5940,15 +6720,15 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
5940
6720
  async waitForLocalEvaluationReady(timeoutMs = THIRTY_SECONDS) {
5941
6721
  if (this.isLocalEvaluationReady()) return true;
5942
6722
  if (void 0 === this.featureFlagsPoller) return false;
5943
- return new Promise((resolve9) => {
6723
+ return new Promise((resolve10) => {
5944
6724
  const timeout = setTimeout(() => {
5945
6725
  cleanup();
5946
- resolve9(false);
6726
+ resolve10(false);
5947
6727
  }, timeoutMs);
5948
6728
  const cleanup = this._events.on("localEvaluationFlagsLoaded", (count) => {
5949
6729
  clearTimeout(timeout);
5950
6730
  cleanup();
5951
- resolve9(count > 0);
6731
+ resolve10(count > 0);
5952
6732
  });
5953
6733
  });
5954
6734
  }
@@ -6403,14 +7183,14 @@ var PostHogBackendClient = class extends PostHogCoreStateless {
6403
7183
  this.context?.enter(data, options);
6404
7184
  }
6405
7185
  async _shutdown(shutdownTimeoutMs) {
6406
- const resolve9 = this._consumeWaitUntilCycle();
7186
+ const resolve10 = this._consumeWaitUntilCycle();
6407
7187
  await this.featureFlagsPoller?.stopPoller(shutdownTimeoutMs);
6408
7188
  this.errorTracking.shutdown();
6409
7189
  try {
6410
7190
  return await super._shutdown(shutdownTimeoutMs);
6411
7191
  } finally {
6412
7192
  this.distinctIdHasSentFlagCalls = {};
6413
- resolve9?.();
7193
+ resolve10?.();
6414
7194
  }
6415
7195
  }
6416
7196
  async _requestRemoteConfigPayload(flagKey) {
@@ -6649,452 +7429,142 @@ var PostHogContext = class {
6649
7429
  properties: {
6650
7430
  ...current.properties || {},
6651
7431
  ...context.properties || {}
6652
- }
6653
- };
6654
- }
6655
- };
6656
-
6657
- // ../../node_modules/posthog-node/dist/extensions/sentry-integration.mjs
6658
- var NAME = "posthog-node";
6659
- function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
6660
- "error"
6661
- ], sendExceptionsToPostHog = true } = {}) {
6662
- return (event) => {
6663
- const shouldProcessLevel = "*" === severityAllowList || severityAllowList.includes(event.level);
6664
- if (!shouldProcessLevel) return event;
6665
- if (!event.tags) event.tags = {};
6666
- const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
6667
- if (void 0 === userId) return event;
6668
- const uiHost = _posthog.options.host ?? "https://us.i.posthog.com";
6669
- const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
6670
- event.tags["PostHog Person URL"] = personUrl;
6671
- const exceptions = event.exception?.values || [];
6672
- const exceptionList = exceptions.map((exception) => ({
6673
- ...exception,
6674
- stacktrace: exception.stacktrace ? {
6675
- ...exception.stacktrace,
6676
- type: "raw",
6677
- frames: (exception.stacktrace.frames || []).map((frame) => ({
6678
- ...frame,
6679
- platform: "node:javascript"
6680
- }))
6681
- } : void 0
6682
- }));
6683
- const properties = {
6684
- $exception_message: exceptions[0]?.value || event.message,
6685
- $exception_type: exceptions[0]?.type,
6686
- $exception_level: event.level,
6687
- $exception_list: exceptionList,
6688
- $sentry_event_id: event.event_id,
6689
- $sentry_exception: event.exception,
6690
- $sentry_exception_message: exceptions[0]?.value || event.message,
6691
- $sentry_exception_type: exceptions[0]?.type,
6692
- $sentry_tags: event.tags
6693
- };
6694
- if (organization && projectId) properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
6695
- if (sendExceptionsToPostHog) _posthog.capture({
6696
- event: "$exception",
6697
- distinctId: userId,
6698
- properties
6699
- });
6700
- return event;
6701
- };
6702
- }
6703
- var PostHogSentryIntegration = class {
6704
- static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
6705
- constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
6706
- this.name = NAME;
6707
- this.name = NAME;
6708
- this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {
6709
- const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
6710
- addGlobalEventProcessor(createEventProcessor(_posthog, {
6711
- organization,
6712
- projectId,
6713
- prefix,
6714
- severityAllowList,
6715
- sendExceptionsToPostHog: sendExceptionsToPostHog ?? true
6716
- }));
6717
- };
6718
- }
6719
- };
6720
-
6721
- // ../../node_modules/posthog-node/dist/entrypoints/index.node.mjs
6722
- var PostHog = class extends PostHogBackendClient {
6723
- getLibraryId() {
6724
- return "posthog-node";
6725
- }
6726
- initializeContext() {
6727
- return new PostHogContext();
6728
- }
6729
- createErrorPropertiesBuilder() {
6730
- return new error_tracking_exports.ErrorPropertiesBuilder([
6731
- new error_tracking_exports.EventCoercer(),
6732
- new error_tracking_exports.ErrorCoercer(),
6733
- new error_tracking_exports.ObjectCoercer(),
6734
- new error_tracking_exports.StringCoercer(),
6735
- new error_tracking_exports.PrimitiveCoercer()
6736
- ], error_tracking_exports.createStackParser("node:javascript", error_tracking_exports.nodeStackLineParser), [
6737
- createModulerModifier(),
6738
- addSourceContext,
6739
- createRelativePathModifier()
6740
- ]);
6741
- }
6742
- };
6743
-
6744
- // ../telemetry/src/posthog.ts
6745
- var POSTHOG_HOST = "https://eu.i.posthog.com";
6746
- var POSTHOG_PROJECT_TOKEN = "phc_mebZhuUmASbeeXkdv7E2wqTZdtstPxQqHBhZfLSeQ5YL";
6747
- function readProjectToken() {
6748
- const g = globalThis;
6749
- const override = g.__ARGENT_POSTHOG_KEY_TEST;
6750
- if (typeof override === "string") return override;
6751
- return POSTHOG_PROJECT_TOKEN;
6752
- }
6753
- function resolveConfig() {
6754
- const key = readProjectToken();
6755
- const isUsable = key !== "" && key !== "phc_disabled" && key.startsWith("phc_");
6756
- return { key, isUsable };
6757
- }
6758
- var client;
6759
- function getClient() {
6760
- if (client !== void 0) return client;
6761
- const config2 = resolveConfig();
6762
- if (!config2.isUsable) {
6763
- client = null;
6764
- return null;
6765
- }
6766
- const opts = {
6767
- host: POSTHOG_HOST,
6768
- disableGeoip: true,
6769
- requestTimeout: 3e3,
6770
- flushAt: 20,
6771
- flushInterval: 1e4,
6772
- fetchRetryCount: 0
6773
- };
6774
- try {
6775
- client = new PostHog(config2.key, opts);
6776
- } catch {
6777
- client = null;
6778
- return null;
6779
- }
6780
- return client;
6781
- }
6782
- function getConstructedClient() {
6783
- return client ?? null;
6784
- }
6785
- function resetClient() {
6786
- client = void 0;
6787
- }
6788
-
6789
- // ../registry/src/artifacts.ts
6790
- import { stat as stat3 } from "node:fs/promises";
6791
- import { randomUUID as randomUUID3 } from "node:crypto";
6792
- import { basename as basename4, extname as extname2 } from "node:path";
7432
+ }
7433
+ };
7434
+ }
7435
+ };
6793
7436
 
6794
- // ../registry/src/failure-codes.ts
6795
- var FAILURE_CODES = {
6796
- ARGENT_UNCLASSIFIED_FAILURE: "ARGENT_UNCLASSIFIED_FAILURE",
6797
- REGISTRY_SERVICE_NOT_FOUND: "REGISTRY_SERVICE_NOT_FOUND",
6798
- REGISTRY_SERVICE_INITIALIZATION_FAILED: "REGISTRY_SERVICE_INITIALIZATION_FAILED",
6799
- REGISTRY_TOOL_NOT_FOUND: "REGISTRY_TOOL_NOT_FOUND",
6800
- REGISTRY_TOOL_EXECUTION_FAILED: "REGISTRY_TOOL_EXECUTION_FAILED",
6801
- REGISTRY_TOOL_FAILURE_UNCLASSIFIED: "REGISTRY_TOOL_FAILURE_UNCLASSIFIED",
6802
- HTTP_TOOL_NOT_FOUND: "HTTP_TOOL_NOT_FOUND",
6803
- HTTP_ZOD_VALIDATION_FAILED: "HTTP_ZOD_VALIDATION_FAILED",
6804
- HTTP_CAPABILITY_UNSUPPORTED_OPERATION: "HTTP_CAPABILITY_UNSUPPORTED_OPERATION",
6805
- HTTP_DEVICE_RESOLUTION_FAILED: "HTTP_DEVICE_RESOLUTION_FAILED",
6806
- HTTP_DEPENDENCY_PREFLIGHT_MISSING: "HTTP_DEPENDENCY_PREFLIGHT_MISSING",
6807
- CLI_RUN_TOOL_NOT_FOUND: "CLI_RUN_TOOL_NOT_FOUND",
6808
- CLI_RUN_FLAG_PARSE_FAILED: "CLI_RUN_FLAG_PARSE_FAILED",
6809
- CLI_RUN_ARGS_NOT_OBJECT: "CLI_RUN_ARGS_NOT_OBJECT",
6810
- CLI_RUN_ARGS_JSON_INVALID: "CLI_RUN_ARGS_JSON_INVALID",
6811
- CLI_RUN_TOOL_CALL_FAILED: "CLI_RUN_TOOL_CALL_FAILED",
6812
- CLI_RUN_SAVE_IMAGE_FAILED: "CLI_RUN_SAVE_IMAGE_FAILED",
6813
- TOOL_CAPABILITY_UNSUPPORTED_OPERATION: "TOOL_CAPABILITY_UNSUPPORTED_OPERATION",
6814
- TOOL_PLATFORM_NOT_IMPLEMENTED: "TOOL_PLATFORM_NOT_IMPLEMENTED",
6815
- TOOL_DEPENDENCY_MISSING: "TOOL_DEPENDENCY_MISSING",
6816
- TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
6817
- TOOLSERVER_UNHANDLED_REJECTION: "TOOLSERVER_UNHANDLED_REJECTION",
6818
- TOOLSERVER_UNCAUGHT_EXCEPTION: "TOOLSERVER_UNCAUGHT_EXCEPTION",
6819
- INSTALL_GLOBAL_PACKAGE_FAILED: "INSTALL_GLOBAL_PACKAGE_FAILED",
6820
- INSTALL_LOCAL_PACKAGE_FAILED: "INSTALL_LOCAL_PACKAGE_FAILED",
6821
- INSTALL_LOCAL_PRECONDITION_FAILED: "INSTALL_LOCAL_PRECONDITION_FAILED",
6822
- INSTALL_MODE_FLAG_CONFLICT: "INSTALL_MODE_FLAG_CONFLICT",
6823
- INSTALL_FROM_TAR_PACKAGE_FAILED: "INSTALL_FROM_TAR_PACKAGE_FAILED",
6824
- INSTALL_INIT_TRIGGERED_UPDATE_FAILED: "INSTALL_INIT_TRIGGERED_UPDATE_FAILED",
6825
- INSTALL_SKILLS_REFRESH_FAILED: "INSTALL_SKILLS_REFRESH_FAILED",
6826
- INSTALL_UNCLASSIFIED_FAILED: "INSTALL_UNCLASSIFIED_FAILED",
6827
- UPDATE_INSTALLED_VERSION_DETECT_FAILED: "UPDATE_INSTALLED_VERSION_DETECT_FAILED",
6828
- UPDATE_INVALID_TARGET_VERSION: "UPDATE_INVALID_TARGET_VERSION",
6829
- UPDATE_REGISTRY_CHECK_FAILED: "UPDATE_REGISTRY_CHECK_FAILED",
6830
- UPDATE_TOOLSERVER_STOP_FAILED: "UPDATE_TOOLSERVER_STOP_FAILED",
6831
- UPDATE_PACKAGE_ACTION_FAILED: "UPDATE_PACKAGE_ACTION_FAILED",
6832
- UPDATE_UNCLASSIFIED_FAILED: "UPDATE_UNCLASSIFIED_FAILED",
6833
- UNINSTALL_TOOLSERVER_STOP_FAILED: "UNINSTALL_TOOLSERVER_STOP_FAILED",
6834
- UNINSTALL_PACKAGE_ACTION_FAILED: "UNINSTALL_PACKAGE_ACTION_FAILED",
6835
- UNINSTALL_UNCLASSIFIED_FAILED: "UNINSTALL_UNCLASSIFIED_FAILED",
6836
- VEGA_CLI_COMMAND_FAILED: "VEGA_CLI_COMMAND_FAILED",
6837
- VEGA_INPUT_UNAVAILABLE: "VEGA_INPUT_UNAVAILABLE",
6838
- VEGA_DEVICE_NOT_FOUND: "VEGA_DEVICE_NOT_FOUND",
6839
- VEGA_DEVICE_NOT_REGISTERED: "VEGA_DEVICE_NOT_REGISTERED",
6840
- VEGA_MULTIPLE_DEVICES: "VEGA_MULTIPLE_DEVICES",
6841
- VEGA_BOOT_TIMEOUT: "VEGA_BOOT_TIMEOUT",
6842
- VEGA_IMAGE_NOT_FOUND: "VEGA_IMAGE_NOT_FOUND",
6843
- VEGA_ALREADY_RUNNING: "VEGA_ALREADY_RUNNING",
6844
- VEGA_SCREENSHOT_FAILED: "VEGA_SCREENSHOT_FAILED",
6845
- VEGA_TEXT_INVALID: "VEGA_TEXT_INVALID",
6846
- ANDROID_ADB_NOT_FOUND: "ANDROID_ADB_NOT_FOUND",
6847
- ANDROID_EMULATOR_NOT_FOUND: "ANDROID_EMULATOR_NOT_FOUND",
6848
- ANDROID_ADB_COMMAND_FAILED: "ANDROID_ADB_COMMAND_FAILED",
6849
- ANDROID_ADB_BOOT_TERMINAL_STATE: "ANDROID_ADB_BOOT_TERMINAL_STATE",
6850
- ANDROID_ADB_BOOT_TIMEOUT: "ANDROID_ADB_BOOT_TIMEOUT",
6851
- SIMULATOR_NETWORK_TIMEOUT: "SIMULATOR_NETWORK_TIMEOUT",
6852
- SIMULATOR_NETWORK_CONNECTION_REFUSED: "SIMULATOR_NETWORK_CONNECTION_REFUSED",
6853
- SIMULATOR_NETWORK_CONNECTION_RESET: "SIMULATOR_NETWORK_CONNECTION_RESET",
6854
- SIMULATOR_NETWORK_ERROR: "SIMULATOR_NETWORK_ERROR",
6855
- SIMULATOR_NON_JSON_RESPONSE: "SIMULATOR_NON_JSON_RESPONSE",
6856
- SIMULATOR_HTTP_ERROR_RESPONSE: "SIMULATOR_HTTP_ERROR_RESPONSE",
6857
- SIMULATOR_MISSING_RESPONSE_FIELDS: "SIMULATOR_MISSING_RESPONSE_FIELDS",
6858
- SIMULATOR_SCREENSHOT_FAILED: "SIMULATOR_SCREENSHOT_FAILED",
6859
- SIMULATOR_SERVER_FACTORY_OPTIONS_MISSING: "SIMULATOR_SERVER_FACTORY_OPTIONS_MISSING",
6860
- SIMULATOR_SERVER_DEVICE_ID_INVALID: "SIMULATOR_SERVER_DEVICE_ID_INVALID",
6861
- SIMULATOR_SERVER_READY_EXITED: "SIMULATOR_SERVER_READY_EXITED",
6862
- SIMULATOR_SERVER_READY_TIMEOUT: "SIMULATOR_SERVER_READY_TIMEOUT",
6863
- SIMULATOR_SERVER_PROCESS_ERROR: "SIMULATOR_SERVER_PROCESS_ERROR",
6864
- SIMULATOR_SERVER_TERMINATED: "SIMULATOR_SERVER_TERMINATED",
6865
- AX_QUERY_TIMEOUT: "AX_QUERY_TIMEOUT",
6866
- AX_DAEMON_READY_TIMEOUT: "AX_DAEMON_READY_TIMEOUT",
6867
- AX_DAEMON_EXITED_BEFORE_READY: "AX_DAEMON_EXITED_BEFORE_READY",
6868
- AX_DAEMON_PROCESS_ERROR: "AX_DAEMON_PROCESS_ERROR",
6869
- AX_FACTORY_OPTIONS_MISSING: "AX_FACTORY_OPTIONS_MISSING",
6870
- AX_WRONG_PLATFORM: "AX_WRONG_PLATFORM",
6871
- AX_DEVICE_ID_INVALID: "AX_DEVICE_ID_INVALID",
6872
- AX_DESCRIBE_ERROR: "AX_DESCRIBE_ERROR",
6873
- AX_QUERY_FAILED: "AX_QUERY_FAILED",
6874
- ANDROID_LAUNCH_ACTIVITY_RESOLVE_FAILED: "ANDROID_LAUNCH_ACTIVITY_RESOLVE_FAILED",
6875
- ANDROID_LAUNCH_AM_START_FAILED: "ANDROID_LAUNCH_AM_START_FAILED",
6876
- ANDROID_OPEN_URL_FAILED: "ANDROID_OPEN_URL_FAILED",
6877
- ANDROID_REINSTALL_INSTALL_FAILED: "ANDROID_REINSTALL_INSTALL_FAILED",
6878
- ANDROID_RESTART_FAILED: "ANDROID_RESTART_FAILED",
6879
- ANDROID_SETTINGS_PERMISSION_FAILED: "ANDROID_SETTINGS_PERMISSION_FAILED",
6880
- IOS_LAUNCH_SIMCTL_FAILED: "IOS_LAUNCH_SIMCTL_FAILED",
6881
- IOS_OPEN_URL_FAILED: "IOS_OPEN_URL_FAILED",
6882
- IOS_REINSTALL_INSTALL_FAILED: "IOS_REINSTALL_INSTALL_FAILED",
6883
- IOS_RESTART_LAUNCH_FAILED: "IOS_RESTART_LAUNCH_FAILED",
6884
- IOS_SETTINGS_PERMISSION_FAILED: "IOS_SETTINGS_PERMISSION_FAILED",
6885
- SETTINGS_PERMISSION_UNSUPPORTED: "SETTINGS_PERMISSION_UNSUPPORTED",
6886
- NATIVE_DEVTOOLS_DESCRIBE_ERROR: "NATIVE_DEVTOOLS_DESCRIBE_ERROR",
6887
- NATIVE_DEVTOOLS_VIEW_AT_POINT_ERROR: "NATIVE_DEVTOOLS_VIEW_AT_POINT_ERROR",
6888
- NATIVE_DEVTOOLS_USER_INTERACTABLE_VIEW_AT_POINT_ERROR: "NATIVE_DEVTOOLS_USER_INTERACTABLE_VIEW_AT_POINT_ERROR",
6889
- NATIVE_DEVTOOLS_FIND_VIEWS_ERROR: "NATIVE_DEVTOOLS_FIND_VIEWS_ERROR",
6890
- NATIVE_DEVTOOLS_FACTORY_OPTIONS_MISSING: "NATIVE_DEVTOOLS_FACTORY_OPTIONS_MISSING",
6891
- NATIVE_DEVTOOLS_WRONG_PLATFORM: "NATIVE_DEVTOOLS_WRONG_PLATFORM",
6892
- NATIVE_DEVTOOLS_NOT_INJECTABLE: "NATIVE_DEVTOOLS_NOT_INJECTABLE",
6893
- NATIVE_DEVTOOLS_NOT_CONNECTED: "NATIVE_DEVTOOLS_NOT_CONNECTED",
6894
- NATIVE_DEVTOOLS_RPC_TIMEOUT: "NATIVE_DEVTOOLS_RPC_TIMEOUT",
6895
- NATIVE_DEVTOOLS_RPC_ERROR: "NATIVE_DEVTOOLS_RPC_ERROR",
6896
- NATIVE_DEVTOOLS_SERVICE_DISPOSED: "NATIVE_DEVTOOLS_SERVICE_DISPOSED",
6897
- NATIVE_DEVTOOLS_SOCKET_BIND_FAILED: "NATIVE_DEVTOOLS_SOCKET_BIND_FAILED",
6898
- NATIVE_TARGET_NO_CONNECTED_APPS: "NATIVE_TARGET_NO_CONNECTED_APPS",
6899
- NATIVE_TARGET_SINGLE_APP_NOT_FOREGROUND: "NATIVE_TARGET_SINGLE_APP_NOT_FOREGROUND",
6900
- NATIVE_TARGET_MULTIPLE_APPS_AMBIGUOUS: "NATIVE_TARGET_MULTIPLE_APPS_AMBIGUOUS",
6901
- ANDROID_DEVTOOLS_ADB_NOT_FOUND: "ANDROID_DEVTOOLS_ADB_NOT_FOUND",
6902
- ANDROID_DEVTOOLS_ADB_FORWARD_UNEXPECTED: "ANDROID_DEVTOOLS_ADB_FORWARD_UNEXPECTED",
6903
- ANDROID_DEVTOOLS_HELPER_EXITED_BEFORE_READY: "ANDROID_DEVTOOLS_HELPER_EXITED_BEFORE_READY",
6904
- ANDROID_DEVTOOLS_HELPER_PROCESS_ERROR: "ANDROID_DEVTOOLS_HELPER_PROCESS_ERROR",
6905
- ANDROID_DEVTOOLS_HELPER_READY_TIMEOUT: "ANDROID_DEVTOOLS_HELPER_READY_TIMEOUT",
6906
- ANDROID_DEVTOOLS_FACTORY_OPTIONS_MISSING: "ANDROID_DEVTOOLS_FACTORY_OPTIONS_MISSING",
6907
- ANDROID_DEVTOOLS_WRONG_PLATFORM: "ANDROID_DEVTOOLS_WRONG_PLATFORM",
6908
- ANDROID_DEVTOOLS_DEVICE_ID_INVALID: "ANDROID_DEVTOOLS_DEVICE_ID_INVALID",
6909
- ANDROID_DEVTOOLS_HELPER_TERMINATED: "ANDROID_DEVTOOLS_HELPER_TERMINATED",
6910
- ANDROID_DEVTOOLS_RPC_CLIENT_CLOSED: "ANDROID_DEVTOOLS_RPC_CLIENT_CLOSED",
6911
- ANDROID_DEVTOOLS_RPC_ERROR: "ANDROID_DEVTOOLS_RPC_ERROR",
6912
- ANDROID_DEVTOOLS_RPC_TIMEOUT: "ANDROID_DEVTOOLS_RPC_TIMEOUT",
6913
- ANDROID_DEVTOOLS_SOCKET_CLOSED: "ANDROID_DEVTOOLS_SOCKET_CLOSED",
6914
- ANDROID_SCREEN_SIZE_PARSE_FAILED: "ANDROID_SCREEN_SIZE_PARSE_FAILED",
6915
- ANDROID_SCREEN_SIZE_NON_POSITIVE: "ANDROID_SCREEN_SIZE_NON_POSITIVE",
6916
- ANDROID_UIAUTOMATOR_PARSE_FAILED: "ANDROID_UIAUTOMATOR_PARSE_FAILED",
6917
- ANDROID_UIAUTOMATOR_CAPTURE_FAILED: "ANDROID_UIAUTOMATOR_CAPTURE_FAILED",
6918
- DEBUGGER_METRO_NOT_RUNNING: "DEBUGGER_METRO_NOT_RUNNING",
6919
- DEBUGGER_METRO_NO_TARGETS: "DEBUGGER_METRO_NO_TARGETS",
6920
- DEBUGGER_CDP_RUNTIME_EXCEPTION: "DEBUGGER_CDP_RUNTIME_EXCEPTION",
6921
- DEBUGGER_CDP_BINDING_TIMEOUT: "DEBUGGER_CDP_BINDING_TIMEOUT",
6922
- DEBUGGER_CDP_BINDING_UNAVAILABLE: "DEBUGGER_CDP_BINDING_UNAVAILABLE",
6923
- DEBUGGER_CDP_PROTOCOL_ERROR: "DEBUGGER_CDP_PROTOCOL_ERROR",
6924
- DEBUGGER_RELOAD_FAILED: "DEBUGGER_RELOAD_FAILED",
6925
- JS_RUNTIME_CONSOLE_SERVER_BIND_FAILED: "JS_RUNTIME_CONSOLE_SERVER_BIND_FAILED",
6926
- JS_RUNTIME_PAYLOAD_INVALID: "JS_RUNTIME_PAYLOAD_INVALID",
6927
- JS_RUNTIME_PAYLOAD_DEVICE_MISSING: "JS_RUNTIME_PAYLOAD_DEVICE_MISSING",
6928
- JS_RUNTIME_PAYLOAD_PORT_INVALID: "JS_RUNTIME_PAYLOAD_PORT_INVALID",
6929
- JS_RUNTIME_CDP_DISCONNECTED: "JS_RUNTIME_CDP_DISCONNECTED",
6930
- NETWORK_INSPECTOR_CDP_DISCONNECTED: "NETWORK_INSPECTOR_CDP_DISCONNECTED",
6931
- REACT_PROFILER_NO_ACTIVE_SESSION: "REACT_PROFILER_NO_ACTIVE_SESSION",
6932
- REACT_PROFILER_CDP_CONNECTION_LOST: "REACT_PROFILER_CDP_CONNECTION_LOST",
6933
- REACT_PROFILER_NO_CPU_PROFILE: "REACT_PROFILER_NO_CPU_PROFILE",
6934
- REACT_PROFILER_RUNTIME_EXCEPTION: "REACT_PROFILER_RUNTIME_EXCEPTION",
6935
- REACT_PROFILER_NO_RUNTIME_DATA: "REACT_PROFILER_NO_RUNTIME_DATA",
6936
- REACT_PROFILER_SESSION_PAYLOAD_INVALID: "REACT_PROFILER_SESSION_PAYLOAD_INVALID",
6937
- REACT_PROFILER_SESSION_PAYLOAD_DEVICE_MISSING: "REACT_PROFILER_SESSION_PAYLOAD_DEVICE_MISSING",
6938
- REACT_PROFILER_SESSION_CDP_DISCONNECTED: "REACT_PROFILER_SESSION_CDP_DISCONNECTED",
6939
- REACT_PROFILER_CDP_NOT_CONNECTED: "REACT_PROFILER_CDP_NOT_CONNECTED",
6940
- REACT_PROFILER_STATE_READ_FAILED: "REACT_PROFILER_STATE_READ_FAILED",
6941
- REACT_PROFILER_DEVTOOLS_HOOK_MISSING: "REACT_PROFILER_DEVTOOLS_HOOK_MISSING",
6942
- REACT_PROFILER_DEVTOOLS_BACKEND_ATTACH_FAILED: "REACT_PROFILER_DEVTOOLS_BACKEND_ATTACH_FAILED",
6943
- REACT_PROFILER_DEVTOOLS_BACKEND_BOOTSTRAP_FAILED: "REACT_PROFILER_DEVTOOLS_BACKEND_BOOTSTRAP_FAILED",
6944
- REACT_PROFILER_DEVTOOLS_RENDERER_MISSING: "REACT_PROFILER_DEVTOOLS_RENDERER_MISSING",
6945
- REACT_PROFILER_START_FAILED: "REACT_PROFILER_START_FAILED",
6946
- REACT_PROFILER_START_VERIFY_FAILED: "REACT_PROFILER_START_VERIFY_FAILED",
6947
- REACT_PROFILER_HOOK_ERROR: "REACT_PROFILER_HOOK_ERROR",
6948
- REACT_PROFILER_ANALYZE_NO_DATA: "REACT_PROFILER_ANALYZE_NO_DATA",
6949
- NATIVE_PROFILER_FACTORY_OPTIONS_MISSING: "NATIVE_PROFILER_FACTORY_OPTIONS_MISSING",
6950
- NATIVE_PROFILER_WRONG_PLATFORM: "NATIVE_PROFILER_WRONG_PLATFORM",
6951
- NATIVE_PROFILER_APP_PROCESS_LIST_FAILED: "NATIVE_PROFILER_APP_PROCESS_LIST_FAILED",
6952
- NATIVE_PROFILER_APP_LIST_FAILED: "NATIVE_PROFILER_APP_LIST_FAILED",
6953
- NATIVE_PROFILER_NO_RUNNING_APPS: "NATIVE_PROFILER_NO_RUNNING_APPS",
6954
- NATIVE_PROFILER_NO_RUNNING_USER_APPS: "NATIVE_PROFILER_NO_RUNNING_USER_APPS",
6955
- NATIVE_PROFILER_MULTIPLE_RUNNING_USER_APPS: "NATIVE_PROFILER_MULTIPLE_RUNNING_USER_APPS",
6956
- NATIVE_PROFILER_MALLOC_DEGRADED_XCODE: "NATIVE_PROFILER_MALLOC_DEGRADED_XCODE",
6957
- NATIVE_PROFILER_MALLOC_STRATEGY_OVERRIDE: "NATIVE_PROFILER_MALLOC_STRATEGY_OVERRIDE",
6958
- NATIVE_PROFILER_APP_BUNDLE_PATH_FAILED: "NATIVE_PROFILER_APP_BUNDLE_PATH_FAILED",
6959
- NATIVE_PROFILER_LAUNCH_APP_NOT_FOUND: "NATIVE_PROFILER_LAUNCH_APP_NOT_FOUND",
6960
- NATIVE_PROFILER_LAUNCH_APP_AMBIGUOUS: "NATIVE_PROFILER_LAUNCH_APP_AMBIGUOUS",
6961
- NATIVE_PROFILER_SESSION_ALREADY_RUNNING: "NATIVE_PROFILER_SESSION_ALREADY_RUNNING",
6962
- NATIVE_PROFILER_XCTRACE_NO_PID: "NATIVE_PROFILER_XCTRACE_NO_PID",
6963
- NATIVE_PROFILER_XCTRACE_PROCESS_NOT_FOUND: "NATIVE_PROFILER_XCTRACE_PROCESS_NOT_FOUND",
6964
- NATIVE_PROFILER_XCTRACE_READY_EXITED: "NATIVE_PROFILER_XCTRACE_READY_EXITED",
6965
- NATIVE_PROFILER_XCTRACE_PROCESS_ERROR: "NATIVE_PROFILER_XCTRACE_PROCESS_ERROR",
6966
- NATIVE_PROFILER_XCTRACE_READY_TIMEOUT: "NATIVE_PROFILER_XCTRACE_READY_TIMEOUT",
6967
- NATIVE_PROFILER_TRACE_TEMPLATE_MISSING: "NATIVE_PROFILER_TRACE_TEMPLATE_MISSING",
6968
- NATIVE_PROFILER_NO_ACTIVE_SESSION: "NATIVE_PROFILER_NO_ACTIVE_SESSION",
6969
- NATIVE_PROFILER_APP_PROCESS_NOT_FOUND: "NATIVE_PROFILER_APP_PROCESS_NOT_FOUND",
6970
- NATIVE_PROFILER_NO_EXPORTED_TRACE: "NATIVE_PROFILER_NO_EXPORTED_TRACE",
6971
- // Android perfetto start-failure modes — mirror the iOS xctrace set so a
6972
- // failed recording start is classified rather than falling through to the
6973
- // generic tool-execution bucket.
6974
- NATIVE_PROFILER_PERFETTO_PROCESS_ERROR: "NATIVE_PROFILER_PERFETTO_PROCESS_ERROR",
6975
- NATIVE_PROFILER_PERFETTO_READY_TIMEOUT: "NATIVE_PROFILER_PERFETTO_READY_TIMEOUT",
6976
- NATIVE_PROFILER_PERFETTO_READY_EXITED: "NATIVE_PROFILER_PERFETTO_READY_EXITED",
6977
- // screen-recording-start / screen-recording-stop. One capture path for every
6978
- // platform (simulator-server's frame stream into ffmpeg), so the stages name
6979
- // the step that failed rather than the device family.
6980
- SCREEN_RECORDING_FACTORY_OPTIONS_MISSING: "SCREEN_RECORDING_FACTORY_OPTIONS_MISSING",
6981
- SCREEN_RECORDING_WRONG_PLATFORM: "SCREEN_RECORDING_WRONG_PLATFORM",
6982
- SCREEN_RECORDING_ALREADY_ACTIVE: "SCREEN_RECORDING_ALREADY_ACTIVE",
6983
- SCREEN_RECORDING_NO_ACTIVE_SESSION: "SCREEN_RECORDING_NO_ACTIVE_SESSION",
6984
- SCREEN_RECORDING_STOP_IN_PROGRESS: "SCREEN_RECORDING_STOP_IN_PROGRESS",
6985
- SCREEN_RECORDING_START_EXITED: "SCREEN_RECORDING_START_EXITED",
6986
- SCREEN_RECORDING_START_TIMEOUT: "SCREEN_RECORDING_START_TIMEOUT",
6987
- SCREEN_RECORDING_PROCESS_ERROR: "SCREEN_RECORDING_PROCESS_ERROR",
6988
- SCREEN_RECORDING_OUTPUT_MISSING: "SCREEN_RECORDING_OUTPUT_MISSING",
6989
- SCREEN_RECORDING_SERVER_SHUTTING_DOWN: "SCREEN_RECORDING_SERVER_SHUTTING_DOWN",
6990
- SCREEN_RECORDING_STREAM_UNAVAILABLE: "SCREEN_RECORDING_STREAM_UNAVAILABLE",
6991
- SCREEN_RECORDING_FFMPEG_NOT_FOUND: "SCREEN_RECORDING_FFMPEG_NOT_FOUND",
6992
- FLOW_PROJECT_ROOT_REQUIRED: "FLOW_PROJECT_ROOT_REQUIRED",
6993
- FLOW_PROJECT_ROOT_INVALID: "FLOW_PROJECT_ROOT_INVALID",
6994
- FLOW_NAME_INVALID: "FLOW_NAME_INVALID",
6995
- FLOW_NO_ACTIVE_RECORDING: "FLOW_NO_ACTIVE_RECORDING",
6996
- FLOW_FILE_INVALID: "FLOW_FILE_INVALID",
6997
- FLOW_ENTRY_UNRECOGNIZED: "FLOW_ENTRY_UNRECOGNIZED",
6998
- FLOW_E2E_HAS_PREREQUISITE: "FLOW_E2E_HAS_PREREQUISITE",
6999
- FLOW_DEVICE_RESOLUTION: "FLOW_DEVICE_RESOLUTION",
7000
- PROFILER_QUERY_MODE_INVALID: "PROFILER_QUERY_MODE_INVALID",
7001
- PROFILER_QUERY_REQUIRED_PARAM_MISSING: "PROFILER_QUERY_REQUIRED_PARAM_MISSING",
7002
- PROFILER_DATA_NOT_LOADED: "PROFILER_DATA_NOT_LOADED",
7003
- PROFILER_NATIVE_TRACE_MISSING: "PROFILER_NATIVE_TRACE_MISSING",
7004
- PROFILER_NATIVE_METADATA_MISSING: "PROFILER_NATIVE_METADATA_MISSING",
7005
- PROFILER_NATIVE_METADATA_INVALID: "PROFILER_NATIVE_METADATA_INVALID",
7006
- CHROMIUM_CDP_UNREACHABLE: "CHROMIUM_CDP_UNREACHABLE",
7007
- CHROMIUM_CDP_NO_PAGE_TARGET: "CHROMIUM_CDP_NO_PAGE_TARGET",
7008
- CHROMIUM_CDP_INVALID_RESPONSE: "CHROMIUM_CDP_INVALID_RESPONSE",
7009
- CHROMIUM_DEVICE_ID_INVALID: "CHROMIUM_DEVICE_ID_INVALID",
7010
- CHROMIUM_PARAM_INVALID: "CHROMIUM_PARAM_INVALID",
7011
- CHROMIUM_INPUT_INVALID: "CHROMIUM_INPUT_INVALID",
7012
- CHROMIUM_WINDOW_HIDDEN: "CHROMIUM_WINDOW_HIDDEN",
7013
- CHROMIUM_VIEWPORT_READ_FAILED: "CHROMIUM_VIEWPORT_READ_FAILED",
7014
- CHROMIUM_SCREENSHOT_FAILED: "CHROMIUM_SCREENSHOT_FAILED",
7015
- CHROMIUM_STORAGE_EVAL_FAILED: "CHROMIUM_STORAGE_EVAL_FAILED",
7016
- CHROMIUM_TAB_NOT_FOUND: "CHROMIUM_TAB_NOT_FOUND",
7017
- CHROMIUM_TAB_OPEN_FAILED: "CHROMIUM_TAB_OPEN_FAILED",
7018
- CHROMIUM_DESCRIBE_FAILED: "CHROMIUM_DESCRIBE_FAILED",
7019
- CHROMIUM_ELECTRON_APP_PATH_INVALID: "CHROMIUM_ELECTRON_APP_PATH_INVALID",
7020
- CHROMIUM_ELECTRON_SPAWN_FAILED: "CHROMIUM_ELECTRON_SPAWN_FAILED",
7021
- CHROMIUM_ELECTRON_CDP_TIMEOUT: "CHROMIUM_ELECTRON_CDP_TIMEOUT",
7022
- CHROMIUM_ELECTRON_EXITED_BEFORE_READY: "CHROMIUM_ELECTRON_EXITED_BEFORE_READY",
7023
- KEYBOARD_KEY_UNSUPPORTED: "KEYBOARD_KEY_UNSUPPORTED",
7024
- KEYBOARD_CHARACTER_UNSUPPORTED: "KEYBOARD_CHARACTER_UNSUPPORTED",
7025
- SECRET_PLACEHOLDER_UNKNOWN: "SECRET_PLACEHOLDER_UNKNOWN",
7026
- SCREENSHOT_DIFF_INPUT_INVALID: "SCREENSHOT_DIFF_INPUT_INVALID",
7027
- BOOT_DEVICE_TARGET_SELECTION_INVALID: "BOOT_DEVICE_TARGET_SELECTION_INVALID",
7028
- BOOT_IOS_UNSUPPORTED_HOST: "BOOT_IOS_UNSUPPORTED_HOST",
7029
- BOOT_ANDROID_NO_AVDS: "BOOT_ANDROID_NO_AVDS",
7030
- BOOT_ANDROID_AVD_NOT_FOUND: "BOOT_ANDROID_AVD_NOT_FOUND",
7031
- BOOT_ANDROID_ADB_UNAVAILABLE: "BOOT_ANDROID_ADB_UNAVAILABLE",
7032
- BOOT_ANDROID_GPU_MODE_INVALID: "BOOT_ANDROID_GPU_MODE_INVALID",
7033
- BOOT_ANDROID_ADB_REGISTER_TIMEOUT: "BOOT_ANDROID_ADB_REGISTER_TIMEOUT",
7034
- BOOT_ANDROID_HOT_BOOT_FRAME_UNUSABLE: "BOOT_ANDROID_HOT_BOOT_FRAME_UNUSABLE",
7035
- BOOT_ANDROID_FIRST_FRAME_TIMEOUT: "BOOT_ANDROID_FIRST_FRAME_TIMEOUT",
7036
- BOOT_ANDROID_PACKAGE_MANAGER_UNAVAILABLE: "BOOT_ANDROID_PACKAGE_MANAGER_UNAVAILABLE",
7037
- BOOT_ANDROID_COLD_BOOT_FAILED: "BOOT_ANDROID_COLD_BOOT_FAILED"
7437
+ // ../../node_modules/posthog-node/dist/extensions/sentry-integration.mjs
7438
+ var NAME = "posthog-node";
7439
+ function createEventProcessor(_posthog, { organization, projectId, prefix, severityAllowList = [
7440
+ "error"
7441
+ ], sendExceptionsToPostHog = true } = {}) {
7442
+ return (event) => {
7443
+ const shouldProcessLevel = "*" === severityAllowList || severityAllowList.includes(event.level);
7444
+ if (!shouldProcessLevel) return event;
7445
+ if (!event.tags) event.tags = {};
7446
+ const userId = event.tags[PostHogSentryIntegration.POSTHOG_ID_TAG];
7447
+ if (void 0 === userId) return event;
7448
+ const uiHost = _posthog.options.host ?? "https://us.i.posthog.com";
7449
+ const personUrl = new URL(`/project/${_posthog.apiKey}/person/${userId}`, uiHost).toString();
7450
+ event.tags["PostHog Person URL"] = personUrl;
7451
+ const exceptions = event.exception?.values || [];
7452
+ const exceptionList = exceptions.map((exception) => ({
7453
+ ...exception,
7454
+ stacktrace: exception.stacktrace ? {
7455
+ ...exception.stacktrace,
7456
+ type: "raw",
7457
+ frames: (exception.stacktrace.frames || []).map((frame) => ({
7458
+ ...frame,
7459
+ platform: "node:javascript"
7460
+ }))
7461
+ } : void 0
7462
+ }));
7463
+ const properties = {
7464
+ $exception_message: exceptions[0]?.value || event.message,
7465
+ $exception_type: exceptions[0]?.type,
7466
+ $exception_level: event.level,
7467
+ $exception_list: exceptionList,
7468
+ $sentry_event_id: event.event_id,
7469
+ $sentry_exception: event.exception,
7470
+ $sentry_exception_message: exceptions[0]?.value || event.message,
7471
+ $sentry_exception_type: exceptions[0]?.type,
7472
+ $sentry_tags: event.tags
7473
+ };
7474
+ if (organization && projectId) properties["$sentry_url"] = (prefix || "https://sentry.io/organizations/") + organization + "/issues/?project=" + projectId + "&query=" + event.event_id;
7475
+ if (sendExceptionsToPostHog) _posthog.capture({
7476
+ event: "$exception",
7477
+ distinctId: userId,
7478
+ properties
7479
+ });
7480
+ return event;
7481
+ };
7482
+ }
7483
+ var PostHogSentryIntegration = class {
7484
+ static #_ = this.POSTHOG_ID_TAG = "posthog_distinct_id";
7485
+ constructor(_posthog, organization, prefix, severityAllowList, sendExceptionsToPostHog) {
7486
+ this.name = NAME;
7487
+ this.name = NAME;
7488
+ this.setupOnce = function(addGlobalEventProcessor, getCurrentHub) {
7489
+ const projectId = getCurrentHub()?.getClient()?.getDsn()?.projectId;
7490
+ addGlobalEventProcessor(createEventProcessor(_posthog, {
7491
+ organization,
7492
+ projectId,
7493
+ prefix,
7494
+ severityAllowList,
7495
+ sendExceptionsToPostHog: sendExceptionsToPostHog ?? true
7496
+ }));
7497
+ };
7498
+ }
7038
7499
  };
7039
7500
 
7040
- // ../registry/src/errors.ts
7041
- var FAILURE_AREAS = ["cli", "http", "registry", "tool_server", "installer"];
7042
- var FAILURE_KINDS = [
7043
- "validation",
7044
- "not_found",
7045
- "dependency_missing",
7046
- "unsupported",
7047
- "not_implemented",
7048
- "timeout",
7049
- "network",
7050
- "subprocess",
7051
- "crash",
7052
- "unknown"
7053
- ];
7054
- var FAILURE_COMMANDS = [
7055
- "adb",
7056
- "emulator",
7057
- "vega",
7058
- "xcrun_simctl",
7059
- "xctrace",
7060
- "native_devtools",
7061
- "android_devtools",
7062
- "ax_service",
7063
- "simulator_server",
7064
- "ffmpeg",
7065
- "cdp",
7066
- "electron",
7067
- "npm",
7068
- "npx",
7069
- "unknown"
7070
- ];
7071
- var FAILURE_SIGNAL_NAMES = [
7072
- "SIGABRT",
7073
- "SIGHUP",
7074
- "SIGINT",
7075
- "SIGKILL",
7076
- "SIGQUIT",
7077
- "SIGTERM"
7078
- ];
7079
- var FAILURE_SPAWN_CODES = ["EACCES", "ENOENT", "EPERM", "ETIMEDOUT"];
7080
- var NETWORK_FAILURES = [
7081
- "timeout",
7082
- "connection_refused",
7083
- "connection_reset",
7084
- "invalid_response",
7085
- "other"
7086
- ];
7087
- var FALLBACK_SIGNAL = {
7088
- error_code: FAILURE_CODES.ARGENT_UNCLASSIFIED_FAILURE,
7089
- failure_stage: "unclassified",
7090
- failure_area: "registry",
7091
- error_kind: "unknown"
7501
+ // ../../node_modules/posthog-node/dist/entrypoints/index.node.mjs
7502
+ var PostHog = class extends PostHogBackendClient {
7503
+ getLibraryId() {
7504
+ return "posthog-node";
7505
+ }
7506
+ initializeContext() {
7507
+ return new PostHogContext();
7508
+ }
7509
+ createErrorPropertiesBuilder() {
7510
+ return new error_tracking_exports.ErrorPropertiesBuilder([
7511
+ new error_tracking_exports.EventCoercer(),
7512
+ new error_tracking_exports.ErrorCoercer(),
7513
+ new error_tracking_exports.ObjectCoercer(),
7514
+ new error_tracking_exports.StringCoercer(),
7515
+ new error_tracking_exports.PrimitiveCoercer()
7516
+ ], error_tracking_exports.createStackParser("node:javascript", error_tracking_exports.nodeStackLineParser), [
7517
+ createModulerModifier(),
7518
+ addSourceContext,
7519
+ createRelativePathModifier()
7520
+ ]);
7521
+ }
7092
7522
  };
7093
- var FAILURE_SIGNAL_NAME_SET = new Set(FAILURE_SIGNAL_NAMES);
7094
- var FAILURE_SPAWN_CODE_SET = new Set(FAILURE_SPAWN_CODES);
7095
7523
 
7096
- // ../registry/src/registry.ts
7097
- import { randomUUID as randomUUID4 } from "node:crypto";
7524
+ // ../telemetry/src/posthog.ts
7525
+ var POSTHOG_HOST = "https://eu.i.posthog.com";
7526
+ var POSTHOG_PROJECT_TOKEN = "phc_mebZhuUmASbeeXkdv7E2wqTZdtstPxQqHBhZfLSeQ5YL";
7527
+ function readProjectToken() {
7528
+ const g = globalThis;
7529
+ const override = g.__ARGENT_POSTHOG_KEY_TEST;
7530
+ if (typeof override === "string") return override;
7531
+ return POSTHOG_PROJECT_TOKEN;
7532
+ }
7533
+ function resolveConfig() {
7534
+ const key = readProjectToken();
7535
+ const isUsable = key !== "" && key !== "phc_disabled" && key.startsWith("phc_");
7536
+ return { key, isUsable };
7537
+ }
7538
+ var client;
7539
+ function getClient() {
7540
+ if (client !== void 0) return client;
7541
+ const config2 = resolveConfig();
7542
+ if (!config2.isUsable) {
7543
+ client = null;
7544
+ return null;
7545
+ }
7546
+ const opts = {
7547
+ host: POSTHOG_HOST,
7548
+ disableGeoip: true,
7549
+ requestTimeout: 3e3,
7550
+ flushAt: 20,
7551
+ flushInterval: 1e4,
7552
+ fetchRetryCount: 0
7553
+ };
7554
+ try {
7555
+ client = new PostHog(config2.key, opts);
7556
+ } catch {
7557
+ client = null;
7558
+ return null;
7559
+ }
7560
+ return client;
7561
+ }
7562
+ function getConstructedClient() {
7563
+ return client ?? null;
7564
+ }
7565
+ function resetClient() {
7566
+ client = void 0;
7567
+ }
7098
7568
 
7099
7569
  // ../telemetry/src/events.ts
7100
7570
  var PLATFORMS = [
@@ -7396,9 +7866,9 @@ function isReplitAgent(env) {
7396
7866
  }
7397
7867
  var DEVIN_MARKER_PATH = "/opt/.devin";
7398
7868
  var JULES_MARKER_PATH = "/opt/environment_summary.sh";
7399
- function safeExists(fileExists, path16) {
7869
+ function safeExists(fileExists, path17) {
7400
7870
  try {
7401
- return fileExists(path16);
7871
+ return fileExists(path17);
7402
7872
  } catch {
7403
7873
  return false;
7404
7874
  }
@@ -7819,7 +8289,7 @@ var _CI_VENDOR_COUNT_FOR_TEST = vendors_default.length;
7819
8289
  var SESSION_ID2 = randomUUID5();
7820
8290
  function readCliVersion() {
7821
8291
  if (true) {
7822
- return "0.18.1";
8292
+ return "0.19.0";
7823
8293
  }
7824
8294
  return "0.0.0";
7825
8295
  }
@@ -7853,16 +8323,16 @@ function getBaseProps(runtime) {
7853
8323
 
7854
8324
  // ../telemetry/src/identity.ts
7855
8325
  import * as crypto2 from "node:crypto";
7856
- import * as fs4 from "node:fs";
7857
- import * as path9 from "node:path";
8326
+ import * as fs5 from "node:fs";
8327
+ import * as path10 from "node:path";
7858
8328
 
7859
8329
  // ../telemetry/src/paths.ts
7860
- import * as path8 from "node:path";
8330
+ import * as path9 from "node:path";
7861
8331
  function identityFilePath() {
7862
- return path8.join(argentHomeDir(), "telemetry-id");
8332
+ return path9.join(argentHomeDir(), "telemetry-id");
7863
8333
  }
7864
8334
  function debugLogPath() {
7865
- return path8.join(argentHomeDir(), "telemetry-debug.log");
8335
+ return path9.join(argentHomeDir(), "telemetry-debug.log");
7866
8336
  }
7867
8337
 
7868
8338
  // ../telemetry/src/identity.ts
@@ -7961,66 +8431,66 @@ function resolveFingerprintOnce(resolveFingerprint) {
7961
8431
  function isCorruptIdFile(filePath) {
7962
8432
  let isRegularFile;
7963
8433
  try {
7964
- isRegularFile = fs4.lstatSync(filePath).isFile();
8434
+ isRegularFile = fs5.lstatSync(filePath).isFile();
7965
8435
  } catch {
7966
8436
  return false;
7967
8437
  }
7968
8438
  return isRegularFile && tryReadId(filePath) === null;
7969
8439
  }
7970
8440
  function writeIdFileAtomic(finalPath, id) {
7971
- fs4.mkdirSync(argentHomeDir(), { recursive: true });
8441
+ fs5.mkdirSync(argentHomeDir(), { recursive: true });
7972
8442
  let occupant;
7973
8443
  try {
7974
- occupant = fs4.lstatSync(finalPath);
8444
+ occupant = fs5.lstatSync(finalPath);
7975
8445
  } catch (err) {
7976
8446
  if (err.code !== "ENOENT") throw err;
7977
8447
  }
7978
8448
  if (occupant && !occupant.isFile()) {
7979
8449
  throw new Error("telemetry: refusing to replace a non-regular file at the identity path");
7980
8450
  }
7981
- const tmpPath = path9.join(
8451
+ const tmpPath = path10.join(
7982
8452
  argentHomeDir(),
7983
8453
  `.telemetry-id.tmp.${process.pid}.${crypto2.randomUUID()}`
7984
8454
  );
7985
- const fd = fs4.openSync(tmpPath, "wx", 384);
8455
+ const fd = fs5.openSync(tmpPath, "wx", 384);
7986
8456
  try {
7987
8457
  try {
7988
- fs4.writeSync(fd, id);
7989
- fs4.fsyncSync(fd);
8458
+ fs5.writeSync(fd, id);
8459
+ fs5.fsyncSync(fd);
7990
8460
  } finally {
7991
- fs4.closeSync(fd);
8461
+ fs5.closeSync(fd);
7992
8462
  }
7993
- fs4.renameSync(tmpPath, finalPath);
8463
+ fs5.renameSync(tmpPath, finalPath);
7994
8464
  } finally {
7995
8465
  try {
7996
- fs4.unlinkSync(tmpPath);
8466
+ fs5.unlinkSync(tmpPath);
7997
8467
  } catch {
7998
8468
  }
7999
8469
  }
8000
8470
  }
8001
8471
  function mintRandomId(finalPath) {
8002
- fs4.mkdirSync(argentHomeDir(), { recursive: true });
8472
+ fs5.mkdirSync(argentHomeDir(), { recursive: true });
8003
8473
  let value = crypto2.randomUUID();
8004
8474
  for (let attempt = 0; attempt < 3; attempt++) {
8005
- const tmpPath = path9.join(
8475
+ const tmpPath = path10.join(
8006
8476
  argentHomeDir(),
8007
8477
  `.telemetry-id.tmp.${process.pid}.${crypto2.randomUUID()}`
8008
8478
  );
8009
8479
  let fd;
8010
8480
  try {
8011
- fd = fs4.openSync(tmpPath, "wx", 384);
8481
+ fd = fs5.openSync(tmpPath, "wx", 384);
8012
8482
  } catch (err) {
8013
8483
  if (err.code === "EEXIST") continue;
8014
8484
  throw err;
8015
8485
  }
8016
8486
  try {
8017
8487
  try {
8018
- fs4.writeSync(fd, value);
8019
- fs4.fsyncSync(fd);
8488
+ fs5.writeSync(fd, value);
8489
+ fs5.fsyncSync(fd);
8020
8490
  } finally {
8021
- fs4.closeSync(fd);
8491
+ fs5.closeSync(fd);
8022
8492
  }
8023
- fs4.linkSync(tmpPath, finalPath);
8493
+ fs5.linkSync(tmpPath, finalPath);
8024
8494
  cached = { path: finalPath, id: value };
8025
8495
  return value;
8026
8496
  } catch (err) {
@@ -8039,7 +8509,7 @@ function mintRandomId(finalPath) {
8039
8509
  throw err;
8040
8510
  } finally {
8041
8511
  try {
8042
- fs4.unlinkSync(tmpPath);
8512
+ fs5.unlinkSync(tmpPath);
8043
8513
  } catch {
8044
8514
  }
8045
8515
  }
@@ -8047,12 +8517,12 @@ function mintRandomId(finalPath) {
8047
8517
  throw new Error("telemetry: failed to create identity after retries");
8048
8518
  }
8049
8519
  function claimCorruptOccupant(finalPath) {
8050
- const claimed = path9.join(
8520
+ const claimed = path10.join(
8051
8521
  argentHomeDir(),
8052
8522
  `.telemetry-id.corrupt.${process.pid}.${crypto2.randomUUID()}`
8053
8523
  );
8054
8524
  try {
8055
- fs4.renameSync(finalPath, claimed);
8525
+ fs5.renameSync(finalPath, claimed);
8056
8526
  } catch {
8057
8527
  return null;
8058
8528
  }
@@ -8061,7 +8531,7 @@ function claimCorruptOccupant(finalPath) {
8061
8531
  grabbed = tryReadId(claimed);
8062
8532
  } finally {
8063
8533
  try {
8064
- fs4.unlinkSync(claimed);
8534
+ fs5.unlinkSync(claimed);
8065
8535
  } catch {
8066
8536
  }
8067
8537
  }
@@ -8073,9 +8543,9 @@ function peekAnonId() {
8073
8543
  function tryReadId(filePath) {
8074
8544
  let raw;
8075
8545
  try {
8076
- const stats = fs4.lstatSync(filePath);
8546
+ const stats = fs5.lstatSync(filePath);
8077
8547
  if (!stats.isFile()) return null;
8078
- raw = fs4.readFileSync(filePath, "utf8");
8548
+ raw = fs5.readFileSync(filePath, "utf8");
8079
8549
  } catch (err) {
8080
8550
  if (err.code === "ENOENT") return null;
8081
8551
  return null;
@@ -8089,12 +8559,12 @@ function tryReadId(filePath) {
8089
8559
  import { execFileSync as execFileSync2, spawn as spawn2 } from "node:child_process";
8090
8560
 
8091
8561
  // ../native-devtools-ios/src/index.ts
8092
- import * as path10 from "node:path";
8093
- import * as fs5 from "node:fs";
8094
- var DYLIB_DIR = process.env.ARGENT_NATIVE_DEVTOOLS_DIR ?? path10.join(__dirname, "..", "dylibs");
8095
- var BIN_DIR = process.env.ARGENT_SIMULATOR_SERVER_DIR ?? path10.join(__dirname, "..", "bin");
8096
- var DYLIB_TCP_DIR = process.env.ARGENT_NATIVE_DEVTOOLS_TCP_DIR ?? path10.join(DYLIB_DIR, "tcp");
8097
- var DYLIB_TVOS_DIR = path10.join(DYLIB_DIR, "tvos");
8562
+ import * as path11 from "node:path";
8563
+ import * as fs6 from "node:fs";
8564
+ var DYLIB_DIR = process.env.ARGENT_NATIVE_DEVTOOLS_DIR ?? path11.join(__dirname, "..", "dylibs");
8565
+ var BIN_DIR = process.env.ARGENT_SIMULATOR_SERVER_DIR ?? path11.join(__dirname, "..", "bin");
8566
+ var DYLIB_TCP_DIR = process.env.ARGENT_NATIVE_DEVTOOLS_TCP_DIR ?? path11.join(DYLIB_DIR, "tcp");
8567
+ var DYLIB_TVOS_DIR = path11.join(DYLIB_DIR, "tvos");
8098
8568
  function hostPlatformKey() {
8099
8569
  if (process.platform === "linux" && process.arch === "arm64") {
8100
8570
  return "linux-arm64";
@@ -8105,14 +8575,14 @@ function simulatorServerBinaryName() {
8105
8575
  return process.platform === "win32" ? "simulator-server.exe" : "simulator-server";
8106
8576
  }
8107
8577
  function platformBinDir() {
8108
- return path10.join(BIN_DIR, hostPlatformKey());
8578
+ return path11.join(BIN_DIR, hostPlatformKey());
8109
8579
  }
8110
8580
  function simulatorServerBinaryPath() {
8111
8581
  const binaryName = simulatorServerBinaryName();
8112
- const p = path10.join(platformBinDir(), binaryName);
8113
- if (!fs5.existsSync(p)) {
8114
- const flat = path10.join(BIN_DIR, binaryName);
8115
- const migrationHint = fs5.existsSync(flat) ? ` Found a binary at the old flat path ${flat}; move it to ${p} or update ARGENT_SIMULATOR_SERVER_DIR to point at the parent of the platform subdirectory.` : "";
8582
+ const p = path11.join(platformBinDir(), binaryName);
8583
+ if (!fs6.existsSync(p)) {
8584
+ const flat = path11.join(BIN_DIR, binaryName);
8585
+ const migrationHint = fs6.existsSync(flat) ? ` Found a binary at the old flat path ${flat}; move it to ${p} or update ARGENT_SIMULATOR_SERVER_DIR to point at the parent of the platform subdirectory.` : "";
8116
8586
  throw new Error(
8117
8587
  `simulator-server binary not found for platform "${hostPlatformKey()}" at ${p}. Supported hosts today: darwin, linux (x86_64 and arm64), win32.${migrationHint}`
8118
8588
  );
@@ -8145,12 +8615,12 @@ function resolveHostFingerprint() {
8145
8615
  }
8146
8616
  }
8147
8617
  function resolveHostFingerprintAsync() {
8148
- return new Promise((resolve9) => {
8618
+ return new Promise((resolve10) => {
8149
8619
  let binary;
8150
8620
  try {
8151
8621
  binary = simulatorServerBinaryPath();
8152
8622
  } catch {
8153
- resolve9(null);
8623
+ resolve10(null);
8154
8624
  return;
8155
8625
  }
8156
8626
  let settled = false;
@@ -8163,7 +8633,7 @@ function resolveHostFingerprintAsync() {
8163
8633
  child?.kill("SIGKILL");
8164
8634
  } catch {
8165
8635
  }
8166
- resolve9(value);
8636
+ resolve10(value);
8167
8637
  };
8168
8638
  const watchdog = setTimeout(() => finish(null), FINGERPRINT_TIMEOUT_MS);
8169
8639
  watchdog.unref?.();
@@ -8196,13 +8666,13 @@ function resolveHostFingerprintAsync() {
8196
8666
  }
8197
8667
 
8198
8668
  // ../telemetry/src/consent.ts
8199
- import * as fs6 from "node:fs";
8669
+ import * as fs7 from "node:fs";
8200
8670
  var cache = { current: null };
8201
8671
  var sessionOverride = null;
8202
8672
  function readConfigOverride() {
8203
8673
  let stats;
8204
8674
  try {
8205
- stats = fs6.lstatSync(configFilePath());
8675
+ stats = fs7.lstatSync(configFilePath());
8206
8676
  } catch (err) {
8207
8677
  if (err.code === "ENOENT") {
8208
8678
  cache.current = { mtimeMs: null, fingerprint: null, enabledOverride: null };
@@ -8222,7 +8692,7 @@ function readConfigOverride() {
8222
8692
  }
8223
8693
  let parsedEnabled = null;
8224
8694
  try {
8225
- const raw = fs6.readFileSync(configFilePath(), "utf8");
8695
+ const raw = fs7.readFileSync(configFilePath(), "utf8");
8226
8696
  const json = JSON.parse(raw);
8227
8697
  if (json && typeof json === "object") {
8228
8698
  const t2 = json.telemetry;
@@ -8283,7 +8753,7 @@ function writeConsentFlag(enabled) {
8283
8753
  }
8284
8754
 
8285
8755
  // ../telemetry/src/debug.ts
8286
- import * as fs7 from "node:fs";
8756
+ import * as fs8 from "node:fs";
8287
8757
  function isDebugEnabled(env = process.env) {
8288
8758
  const v = env.ARGENT_TELEMETRY_DEBUG;
8289
8759
  if (!v) return false;
@@ -8310,8 +8780,8 @@ function emitDebugPayload(payload) {
8310
8780
  } catch {
8311
8781
  }
8312
8782
  try {
8313
- fs7.mkdirSync(argentHomeDir(), { recursive: true });
8314
- fs7.appendFileSync(debugLogPath(), line + "\n");
8783
+ fs8.mkdirSync(argentHomeDir(), { recursive: true });
8784
+ fs8.appendFileSync(debugLogPath(), line + "\n");
8315
8785
  } catch {
8316
8786
  }
8317
8787
  }
@@ -8405,7 +8875,7 @@ async function shutdown(timeoutMs = SHORT_FLUSH_TIMEOUT_MS) {
8405
8875
  try {
8406
8876
  await Promise.race([
8407
8877
  client2.shutdown(timeoutMs),
8408
- new Promise((resolve9) => setTimeout(resolve9, timeoutMs + 250).unref())
8878
+ new Promise((resolve10) => setTimeout(resolve10, timeoutMs + 250).unref())
8409
8879
  ]);
8410
8880
  } catch (err) {
8411
8881
  emitDebugError("shutdown failed", err);
@@ -8425,7 +8895,7 @@ async function markDisabled() {
8425
8895
  try {
8426
8896
  await Promise.race([
8427
8897
  client2.shutdown(SHORT_FLUSH_TIMEOUT_MS),
8428
- new Promise((resolve9) => setTimeout(resolve9, SHORT_FLUSH_TIMEOUT_MS).unref())
8898
+ new Promise((resolve10) => setTimeout(resolve10, SHORT_FLUSH_TIMEOUT_MS).unref())
8429
8899
  ]);
8430
8900
  } catch {
8431
8901
  }
@@ -8458,6 +8928,18 @@ var FlagParseException = class extends Error {
8458
8928
  function isScalarType(type) {
8459
8929
  return type === "string" || type === "number" || type === "integer" || type === "boolean";
8460
8930
  }
8931
+ function isJsonField(prop) {
8932
+ return prop?.type === "object" || prop?.type === "array" && !isScalarType(prop.items?.type);
8933
+ }
8934
+ function flagNameFor(name, prop) {
8935
+ return isJsonField(prop) ? `--${name}-json` : `--${name}`;
8936
+ }
8937
+ function booleanLiteral(raw) {
8938
+ const value = raw.trim().toLowerCase();
8939
+ if (value === "true" || value === "1") return true;
8940
+ if (value === "false" || value === "0") return false;
8941
+ return void 0;
8942
+ }
8461
8943
  function coerceScalar(raw, type, field) {
8462
8944
  if (type === "number") {
8463
8945
  if (raw.trim() === "")
@@ -8475,9 +8957,9 @@ function coerceScalar(raw, type, field) {
8475
8957
  return n2;
8476
8958
  }
8477
8959
  if (type === "boolean") {
8478
- if (raw === "true" || raw === "1") return true;
8479
- if (raw === "false" || raw === "0") return false;
8480
- throw new FlagParseException(`--${field} expected true/false, got "${raw}"`);
8960
+ const value = booleanLiteral(raw);
8961
+ if (value !== void 0) return value;
8962
+ throw new FlagParseException(`--${field} expected true/false (or 1/0), got "${raw}"`);
8481
8963
  }
8482
8964
  return raw;
8483
8965
  }
@@ -8554,6 +9036,12 @@ function parseFlags(argv, schema) {
8554
9036
  if (inlineValue !== void 0) {
8555
9037
  throw new FlagParseException(`--no-${fieldName} does not take a value`);
8556
9038
  }
9039
+ const following = i2 + 1 < argv.length ? booleanLiteral(argv[i2 + 1]) : void 0;
9040
+ if (following !== void 0) {
9041
+ throw new FlagParseException(
9042
+ `--no-${fieldName} does not take a value; use --${fieldName} ${following}`
9043
+ );
9044
+ }
8557
9045
  args[fieldName] = false;
8558
9046
  continue;
8559
9047
  }
@@ -8562,6 +9050,12 @@ function parseFlags(argv, schema) {
8562
9050
  if (propSchema?.type === "boolean") {
8563
9051
  if (inlineValue !== void 0) {
8564
9052
  args[flag] = coerceScalar(inlineValue, "boolean", flag);
9053
+ continue;
9054
+ }
9055
+ const next = i2 + 1 < argv.length ? booleanLiteral(argv[i2 + 1]) : void 0;
9056
+ if (next !== void 0) {
9057
+ args[flag] = next;
9058
+ i2 += 1;
8565
9059
  } else {
8566
9060
  args[flag] = true;
8567
9061
  }
@@ -8619,14 +9113,19 @@ function formatSchemaUsage(schema) {
8619
9113
  const desc = prop.description ? ` ${prop.description}` : "";
8620
9114
  lines.push(` ${flag} ${typeLabel}${req}${desc}`);
8621
9115
  }
9116
+ if (entries.some(([, prop]) => prop.type === "boolean")) {
9117
+ lines.push(
9118
+ "",
9119
+ " Booleans: --flag, --flag true, or --flag 1 sets true; --flag false, --flag 0, --flag=false, or --no-flag sets false."
9120
+ );
9121
+ }
8622
9122
  return lines.join("\n");
8623
9123
  }
8624
9124
  function renderFlagName(name, prop) {
8625
- if (prop.type === "object" || prop.type === "array" && !isScalarType(prop.items?.type)) {
8626
- return `--${name}-json <json>`;
8627
- }
8628
- if (prop.type === "boolean") return `--${name}`;
8629
- return `--${name} <value>`;
9125
+ const flag = flagNameFor(name, prop);
9126
+ if (isJsonField(prop)) return `${flag} <json>`;
9127
+ if (prop.type === "boolean") return flag;
9128
+ return `${flag} <value>`;
8630
9129
  }
8631
9130
  function renderType(prop) {
8632
9131
  if (prop.enum && Array.isArray(prop.enum)) {
@@ -8640,6 +9139,93 @@ function renderType(prop) {
8640
9139
  return prop.type ?? "any";
8641
9140
  }
8642
9141
 
9142
+ // ../argent-cli/src/run-validation.ts
9143
+ function findMissingRequired(payload, schema) {
9144
+ const required = new Set(schema?.required ?? []);
9145
+ if (required.size === 0) return [];
9146
+ const declared = Object.keys(schema?.properties ?? {});
9147
+ const names = [...declared.filter((n2) => required.has(n2))];
9148
+ for (const name of required) {
9149
+ if (!names.includes(name)) names.push(name);
9150
+ }
9151
+ return names.filter((name) => !Object.hasOwn(payload, name));
9152
+ }
9153
+ function describeServerValidationFailure(err, payload, schema) {
9154
+ const message = err instanceof Error ? err.message : typeof err === "string" ? err : null;
9155
+ if (message === null) return null;
9156
+ let parsed;
9157
+ try {
9158
+ parsed = JSON.parse(message);
9159
+ } catch {
9160
+ return null;
9161
+ }
9162
+ if (!Array.isArray(parsed) || parsed.length === 0) return null;
9163
+ if (!parsed.every(isValidationIssue)) return null;
9164
+ const properties = schema?.properties ?? {};
9165
+ const addressesThisTool = (issue) => issue.path.length === 0 || typeof issue.path[0] === "string" && Object.hasOwn(properties, issue.path[0]);
9166
+ if (!parsed.every(addressesThisTool)) return null;
9167
+ const required = new Set(schema?.required ?? []);
9168
+ const missing = [];
9169
+ const invalid = [];
9170
+ for (const issue of parsed) {
9171
+ const head = issue.path[0];
9172
+ if (issue.path.length === 1 && typeof head === "string" && required.has(head) && !Object.hasOwn(payload, head)) {
9173
+ missing.push(head);
9174
+ } else {
9175
+ invalid.push({ path: issue.path, message: issue.message });
9176
+ }
9177
+ }
9178
+ return { missing: sortBySchemaOrder(missing, schema), invalid, rawIssues: parsed };
9179
+ }
9180
+ function formatValidationError(report, schema) {
9181
+ const properties = schema?.properties ?? {};
9182
+ const lines = [];
9183
+ if (report.missing.length > 0) {
9184
+ const flags2 = sortBySchemaOrder(report.missing, schema).map(
9185
+ (name) => flagNameFor(name, properties[name])
9186
+ );
9187
+ const noun = flags2.length === 1 ? "flag" : "flags";
9188
+ lines.push(`missing required ${noun} ${flags2.join(", ")}`);
9189
+ }
9190
+ for (const field of report.invalid) {
9191
+ lines.push(describeInvalidField(field, properties));
9192
+ }
9193
+ return lines.join("\n ");
9194
+ }
9195
+ function missingFlagNames(report, schema) {
9196
+ const properties = schema?.properties ?? {};
9197
+ return sortBySchemaOrder(report.missing, schema).map(
9198
+ (name) => flagNameFor(name, properties[name])
9199
+ );
9200
+ }
9201
+ function describeInvalidField(field, properties) {
9202
+ if (field.path.length === 0) return field.message;
9203
+ const [head, ...rest] = field.path;
9204
+ if (typeof head !== "string") return field.message;
9205
+ const flag = flagNameFor(head, properties[head]);
9206
+ const nested = rest.length > 0 ? ` ${head}${renderPathTail(rest)}` : "";
9207
+ return `${flag}${nested} ${field.message}`;
9208
+ }
9209
+ function renderPathTail(rest) {
9210
+ return rest.map((part) => typeof part === "number" ? `[${part}]` : `.${part}`).join("");
9211
+ }
9212
+ function sortBySchemaOrder(names, schema) {
9213
+ const order = Object.keys(schema?.properties ?? {});
9214
+ return [...names].sort((a2, b) => {
9215
+ const ia = order.indexOf(a2);
9216
+ const ib = order.indexOf(b);
9217
+ if (ia === -1 && ib === -1) return a2.localeCompare(b);
9218
+ if (ia === -1) return 1;
9219
+ if (ib === -1) return -1;
9220
+ return ia - ib;
9221
+ });
9222
+ }
9223
+ function isValidationIssue(value) {
9224
+ if (value === null || typeof value !== "object") return false;
9225
+ const issue = value;
9226
+ return typeof issue.code === "string" && Array.isArray(issue.path) && typeof issue.message === "string";
9227
+ }
9228
+
8643
9229
  // ../argent-cli/src/run.ts
8644
9230
  function splitOptions(argv) {
8645
9231
  let json = false;
@@ -8667,13 +9253,13 @@ function splitOptions(argv) {
8667
9253
  return { json, outPath, argvForFlags: rest };
8668
9254
  }
8669
9255
  async function readStdin() {
8670
- return new Promise((resolve9, reject) => {
9256
+ return new Promise((resolve10, reject) => {
8671
9257
  let data = "";
8672
9258
  process.stdin.setEncoding("utf8");
8673
9259
  process.stdin.on("data", (chunk) => {
8674
9260
  data += chunk;
8675
9261
  });
8676
- process.stdin.on("end", () => resolve9(data));
9262
+ process.stdin.on("end", () => resolve10(data));
8677
9263
  process.stdin.on("error", reject);
8678
9264
  });
8679
9265
  }
@@ -8705,8 +9291,8 @@ async function fetchImageToFile(result, outPath) {
8705
9291
  const res = await fetch(url);
8706
9292
  if (!res.ok) throw new Error(`Failed to download image: ${res.status} ${res.statusText}`);
8707
9293
  const buf = Buffer.from(await res.arrayBuffer());
8708
- fs8.mkdirSync(path11.dirname(path11.resolve(outPath)), { recursive: true });
8709
- fs8.writeFileSync(outPath, buf);
9294
+ fs9.mkdirSync(path12.dirname(path12.resolve(outPath)), { recursive: true });
9295
+ fs9.writeFileSync(outPath, buf);
8710
9296
  }
8711
9297
  function renderResult(result, outputHint, images, json) {
8712
9298
  if (json) return JSON.stringify(result, null, 2);
@@ -8751,7 +9337,25 @@ Examples:
8751
9337
  `);
8752
9338
  return;
8753
9339
  }
8754
- const { json, outPath, argvForFlags } = splitOptions(rest);
9340
+ let cliOptions;
9341
+ try {
9342
+ cliOptions = splitOptions(rest);
9343
+ } catch (err) {
9344
+ if (err instanceof FlagParseException) {
9345
+ console.error(`Error: ${err.message}
9346
+ `);
9347
+ console.error(`Run \`argent run ${toolName} --help\` to see this tool's flags.`);
9348
+ await trackRunFailure(toolName, startedAt, {
9349
+ error_code: FAILURE_CODES.CLI_RUN_FLAG_PARSE_FAILED,
9350
+ failure_stage: "cli_run_split_options",
9351
+ failure_area: "cli",
9352
+ error_kind: "validation"
9353
+ });
9354
+ process.exit(2);
9355
+ }
9356
+ throw err;
9357
+ }
9358
+ const { json, outPath, argvForFlags } = cliOptions;
8755
9359
  const meta = await fetchTool(toolName);
8756
9360
  if (!meta) {
8757
9361
  console.error(`Tool "${toolName}" not found. Run \`argent tools\` to list available tools.`);
@@ -8763,9 +9367,37 @@ Examples:
8763
9367
  });
8764
9368
  process.exit(1);
8765
9369
  }
9370
+ const schema = meta.inputSchema;
9371
+ const failValidation = async (report, stage) => {
9372
+ const summary = formatValidationError(report, schema);
9373
+ if (json) {
9374
+ console.error(
9375
+ JSON.stringify(
9376
+ {
9377
+ error: summary,
9378
+ missing: missingFlagNames(report, schema),
9379
+ issues: report.rawIssues ?? []
9380
+ },
9381
+ null,
9382
+ 2
9383
+ )
9384
+ );
9385
+ } else {
9386
+ console.error(`Error: ${summary}
9387
+ `);
9388
+ printToolHelp(meta);
9389
+ }
9390
+ await trackRunFailure(toolName, startedAt, {
9391
+ error_code: FAILURE_CODES.CLI_RUN_INPUT_VALIDATION_FAILED,
9392
+ failure_stage: stage,
9393
+ failure_area: "cli",
9394
+ error_kind: "validation"
9395
+ });
9396
+ process.exit(2);
9397
+ };
8766
9398
  let parsed;
8767
9399
  try {
8768
- parsed = parseFlags(argvForFlags, meta.inputSchema);
9400
+ parsed = parseFlags(argvForFlags, schema);
8769
9401
  } catch (err) {
8770
9402
  if (err instanceof FlagParseException) {
8771
9403
  console.error(`Error: ${err.message}
@@ -8785,6 +9417,11 @@ Examples:
8785
9417
  printToolHelp(meta);
8786
9418
  return;
8787
9419
  }
9420
+ if (parsed.positional.length > 0) {
9421
+ console.error(
9422
+ `Note: ignoring unused argument(s): ${parsed.positional.join(", ")}. Pass values as --flag <value> or --flag=<value>.`
9423
+ );
9424
+ }
8788
9425
  let payload = {};
8789
9426
  if (parsed.rawArgs !== null) {
8790
9427
  let rawJson = parsed.rawArgs;
@@ -8818,6 +9455,10 @@ Examples:
8818
9455
  for (const [k, v] of Object.entries(parsed.args)) {
8819
9456
  payload[k] = v;
8820
9457
  }
9458
+ const missing = findMissingRequired(payload, schema);
9459
+ if (missing.length > 0) {
9460
+ await failValidation({ missing, invalid: [], rawIssues: null }, "cli_run_required_flags");
9461
+ }
8821
9462
  let result;
8822
9463
  let note;
8823
9464
  let images = [];
@@ -8833,6 +9474,10 @@ Examples:
8833
9474
  images = materialized.images;
8834
9475
  note = resp.note;
8835
9476
  } catch (err) {
9477
+ const report = describeServerValidationFailure(err, payload, schema);
9478
+ if (report) {
9479
+ await failValidation(report, "cli_run_server_validation");
9480
+ }
8836
9481
  console.error(err instanceof Error ? err.message : String(err));
8837
9482
  await trackRunFailure(toolName, startedAt, {
8838
9483
  error_code: FAILURE_CODES.CLI_RUN_TOOL_CALL_FAILED,
@@ -8845,8 +9490,8 @@ Examples:
8845
9490
  if (outPath && meta.outputHint === "image") {
8846
9491
  try {
8847
9492
  if (images.length > 0) {
8848
- fs8.mkdirSync(path11.dirname(path11.resolve(outPath)), { recursive: true });
8849
- fs8.writeFileSync(outPath, images[0].data);
9493
+ fs9.mkdirSync(path12.dirname(path12.resolve(outPath)), { recursive: true });
9494
+ fs9.writeFileSync(outPath, images[0].data);
8850
9495
  } else if (result && typeof result === "object") {
8851
9496
  await fetchImageToFile(result, outPath);
8852
9497
  }
@@ -8870,7 +9515,9 @@ Examples:
8870
9515
 
8871
9516
  // ../argent-cli/src/flow.ts
8872
9517
  import * as fsp from "node:fs/promises";
8873
- import * as path12 from "node:path";
9518
+ import { constants as fsConstants2 } from "node:fs";
9519
+ import { createHash as createHash5 } from "node:crypto";
9520
+ import * as path13 from "node:path";
8874
9521
  var STATUS_GLYPH = {
8875
9522
  pass: "\u2713",
8876
9523
  fail: "\u2717",
@@ -8885,36 +9532,83 @@ function stepIndent(depth) {
8885
9532
  function printHelp() {
8886
9533
  console.log(`Usage: argent flow <subcommand> [options]
8887
9534
 
8888
- Run a saved flow without an LLM in the loop. Flows live in
8889
- \`.argent/flows/<name>.yaml\` under the current working directory. A flow that
8890
- begins with a \`launch\` step runs its app from scratch; any other flow (a
8891
- fragment) runs against the device's current state \u2014 handy while authoring one.
9535
+ Run a YAML flow without an LLM in the loop. \`run\` takes any of these forms:
9536
+
9537
+ a name A flow saved under .argent/flows \u2014 "checkout" runs
9538
+ .argent/flows/checkout.yaml, resolved from the current directory
9539
+ a path Any .yaml file on the local filesystem, resolved from the current
9540
+ directory. It must not contain ".." segments (pass the resolved
9541
+ path instead); a path is what reaches flows kept elsewhere, and
9542
+ what \`argent flow list\` prints for nested ones
9543
+ a dir Every flow in that directory, run sequentially
9544
+
9545
+ For a name and for a file path alike, the
9546
+ filename (minus .yaml) names the run's report and artifacts, so it must
9547
+ contain only letters, numbers, "_", or "-" \u2014 the same charset a name must
9548
+ match. A flow that begins with a \`launch\` step runs its app from scratch; any
9549
+ other flow (a fragment) runs against the device's current state \u2014 handy while
9550
+ authoring one.
9551
+
9552
+ A directory run prints only failing steps plus a final flow summary;
9553
+ --recursive walks subdirectories too (dot-directories and node_modules are
9554
+ skipped). An invalid flow file fails alone and the batch continues; an infra
9555
+ error stops the batch and counts the remaining flows skipped.
9556
+
9557
+ Runs require the auto-started local tool server;
9558
+ ARGENT_TOOLS_URL and \`argent link\` routing are not supported.
8892
9559
 
8893
9560
  Subcommands:
8894
- run <name> Run a flow and report pass/fail (exit code reflects result)
8895
- list List flows in .argent/flows
9561
+ run <flow|flow.yaml|dir> Run a saved flow by name, a YAML file by path, or
9562
+ every flow in a directory, and report pass/fail
9563
+ (exit reflects result)
9564
+ list List runnable YAML paths in .argent/flows
8896
9565
 
8897
9566
  Options (run):
8898
9567
  --device <id> Device id to run against (auto-detected when omitted)
8899
9568
  --platform <p> ios | android | chromium | vega \u2014 narrow auto-detection
8900
9569
  --update-baselines Write/refresh screenshot baselines instead of diffing
8901
9570
  --output <dir> Also write failed snapshot images (baseline/current/diff)
8902
- under <dir>/<flow>/ \u2014 a stable path for CI artifact upload
9571
+ under <dir>/<flow>/ \u2014 a stable path for CI artifact
9572
+ upload; a directory run keys nested flows as
9573
+ <dir>/<subdir>/<flow>/. A different flow file with the
9574
+ same filename sharing <dir> exports to <flow>-<pathhash>/
9575
+ instead (with a warning), so no flow's evidence is
9576
+ overwritten
9577
+ -r, --recursive With a directory path, also run flows in subdirectories
8903
9578
  --json Print the raw JSON report
8904
9579
  --help, -h Show this help
9580
+ -- End of options \u2014 only needed for a flow whose name
9581
+ starts with "-" (\`argent flow run -- -nightly\`)
8905
9582
 
8906
9583
  Examples:
8907
9584
  argent flow run checkout --platform ios
8908
- argent flow run checkout --device <UDID> --update-baselines
8909
- argent flow run checkout --output flow-artifacts --json
9585
+ argent flow run .argent/flows/checkout.yaml --output flow-artifacts --json
9586
+ argent flow run ~/shared-flows/checkout.yaml --device <UDID> --update-baselines
9587
+ argent flow run .argent/flows --recursive
8910
9588
  `);
8911
9589
  }
8912
9590
  function parseRunArgs(argv) {
8913
- const out = { updateBaselines: false, json: false };
9591
+ const out = {
9592
+ updateBaselines: false,
9593
+ recursive: false,
9594
+ json: false
9595
+ };
9596
+ const takePositional = (tok) => {
9597
+ if (out.flowRef !== void 0) {
9598
+ throw new FlagParseException(
9599
+ `unexpected argument ${JSON.stringify(tok)}; flow run accepts one flow name, YAML file path, or directory path`
9600
+ );
9601
+ }
9602
+ out.flowRef = tok;
9603
+ };
8914
9604
  for (let i2 = 0; i2 < argv.length; i2++) {
8915
9605
  const tok = argv[i2];
9606
+ if (tok === "--") {
9607
+ for (const rest of argv.slice(i2 + 1)) takePositional(rest);
9608
+ break;
9609
+ }
8916
9610
  if (!tok.startsWith("-")) {
8917
- if (!out.name) out.name = tok;
9611
+ takePositional(tok);
8918
9612
  continue;
8919
9613
  }
8920
9614
  const eq = tok.startsWith("--") ? tok.indexOf("=") : -1;
@@ -8934,6 +9628,12 @@ function parseRunArgs(argv) {
8934
9628
  };
8935
9629
  const noValue = (name) => {
8936
9630
  if (inline !== void 0) throw new FlagParseException(`${name} does not take a value`);
9631
+ const next = argv[i2 + 1]?.trim().toLowerCase();
9632
+ if (next === "true" || next === "false") {
9633
+ throw new FlagParseException(
9634
+ `${name} does not take a value \u2014 it is a switch; omit it to leave the option off`
9635
+ );
9636
+ }
8937
9637
  };
8938
9638
  if (flag === "--update-baselines") {
8939
9639
  noValue("--update-baselines");
@@ -8941,6 +9641,9 @@ function parseRunArgs(argv) {
8941
9641
  } else if (flag === "--json") {
8942
9642
  noValue("--json");
8943
9643
  out.json = true;
9644
+ } else if (flag === "--recursive" || flag === "-r") {
9645
+ noValue("--recursive");
9646
+ out.recursive = true;
8944
9647
  } else if (flag === "--device") out.device = takeValue("--device");
8945
9648
  else if (flag === "--platform") out.platform = takeValue("--platform");
8946
9649
  else if (flag === "--output") out.output = takeValue("--output");
@@ -8971,8 +9674,10 @@ function renderUnderStepLine(s, n2, text2) {
8971
9674
  function renderSummary(report, opts = {}) {
8972
9675
  const warnings = report.steps.filter((s) => s.warning).length;
8973
9676
  const warningsNote = warnings ? `, ${warnings} warning${warnings === 1 ? "" : "s"}` : "";
8974
- const where = opts.withDevice ? ` on ${report.device}` : "";
8975
- return `${report.ok ? "PASS" : "FAIL"}${where} \u2014 ${report.passed} passed, ${report.failed} failed, ${report.errored} errored, ${report.skipped} skipped${warningsNote}`;
9677
+ const where = opts.withDevice && report.device ? ` on ${report.device}` : "";
9678
+ const nothingCounted = report.ok && report.passed + report.failed + report.errored + report.skipped === 0;
9679
+ const note = nothingCounted ? " (no test steps)" : "";
9680
+ return `${report.ok ? "PASS" : "FAIL"}${where} \u2014 ${report.passed} passed, ${report.failed} failed, ${report.errored} errored, ${report.skipped} skipped${warningsNote}${note}`;
8976
9681
  }
8977
9682
  function renderArtifactLines(report) {
8978
9683
  const lines = [];
@@ -8988,28 +9693,137 @@ function renderArtifactLines(report) {
8988
9693
  }
8989
9694
  return lines;
8990
9695
  }
8991
- var SAFE_ARTIFACT_NAME = /^[A-Za-z0-9_-]+$/;
8992
- async function exportFailureArtifacts(report, outputDir, ctx) {
8993
- if (!SAFE_ARTIFACT_NAME.test(report.flow)) {
9696
+ function renderFailedSteps(report) {
9697
+ const lines = [];
9698
+ let n2 = 0;
9699
+ for (const s of report.steps) {
9700
+ if (s.kind === "echo") continue;
9701
+ n2++;
9702
+ if (s.status !== "fail" && s.status !== "error") continue;
9703
+ lines.push(renderStepLine(s, n2, report.flow));
9704
+ if (s.warning) lines.push(renderUnderStepLine(s, n2, `\u26A0 ${s.warning}`));
9705
+ if (s.artifacts && typeof s.artifacts === "object") {
9706
+ for (const [k, v] of Object.entries(s.artifacts)) {
9707
+ if (typeof v === "string") lines.push(renderUnderStepLine(s, n2, `${k}: ${v}`));
9708
+ }
9709
+ }
9710
+ }
9711
+ return lines;
9712
+ }
9713
+ function renderBatchSummary(counts) {
9714
+ return `${counts.failed === 0 ? "PASS" : "FAIL"} \u2014 ${counts.total} flow${counts.total === 1 ? "" : "s"}: ${counts.passed} passed, ${counts.failed} failed, ${counts.skipped} skipped`;
9715
+ }
9716
+ var SAFE_ARTIFACT_NAME = FLOW_NAME_PATTERN;
9717
+ var SAFE_FLOW_NAME = FLOW_NAME_PATTERN;
9718
+ var FLOWS_DIR = path13.join(".argent", "flows");
9719
+ var SHELL_SAFE_ARG = /^[A-Za-z0-9_@%+=:,./-]+$/;
9720
+ function shellQuoteArg(arg) {
9721
+ if (SHELL_SAFE_ARG.test(arg)) return arg;
9722
+ return `'${arg.replaceAll("'", "'\\''")}'`;
9723
+ }
9724
+ var EXPORT_SOURCE_MARKER = ".argent-flow-source";
9725
+ var MARKER_READ_RETRIES = 4;
9726
+ var MARKER_READ_DELAY_MS = 5;
9727
+ async function readExportMarker(dir) {
9728
+ const marker = path13.join(dir, EXPORT_SOURCE_MARKER);
9729
+ for (let attempt = 0; ; attempt++) {
9730
+ let owner;
9731
+ try {
9732
+ owner = (await fsp.readFile(marker, "utf8")).trim();
9733
+ } catch {
9734
+ return void 0;
9735
+ }
9736
+ if (owner) return owner;
9737
+ if (attempt === MARKER_READ_RETRIES) return null;
9738
+ await new Promise((resolve10) => setTimeout(resolve10, MARKER_READ_DELAY_MS));
9739
+ }
9740
+ }
9741
+ async function classifyExportDir(dir, flowPath) {
9742
+ let owner = await readExportMarker(dir);
9743
+ if (owner === void 0) {
9744
+ try {
9745
+ if ((await fsp.readdir(dir)).length === 0) {
9746
+ return { state: "free" };
9747
+ }
9748
+ } catch (err) {
9749
+ if (err.code === "ENOENT") {
9750
+ return { state: "free" };
9751
+ }
9752
+ }
9753
+ owner = null;
9754
+ }
9755
+ return owner === flowPath ? { state: "mine" } : { state: "foreign", owner };
9756
+ }
9757
+ function occupiedBy(owner) {
9758
+ return owner === null ? "already holds files from an unknown source" : `already holds artifacts from ${owner}`;
9759
+ }
9760
+ async function takeExportDir(dir, flowPath) {
9761
+ try {
9762
+ await fsp.mkdir(dir, { recursive: true });
9763
+ await fsp.writeFile(path13.join(dir, EXPORT_SOURCE_MARKER), `${flowPath}
9764
+ `, { flag: "wx" });
9765
+ return null;
9766
+ } catch (err) {
9767
+ if (err.code !== "EEXIST") {
9768
+ return `could not be claimed (${err instanceof Error ? err.message : String(err)})`;
9769
+ }
9770
+ }
9771
+ const owner = await readExportMarker(dir);
9772
+ return owner === flowPath ? null : occupiedBy(owner ?? null);
9773
+ }
9774
+ async function claimExportDirName(outputDir, flowPath, stem) {
9775
+ const hash = createHash5("sha256").update(flowPath).digest("hex");
9776
+ const candidates = [stem];
9777
+ for (let len = 8; len <= hash.length; len += 8) {
9778
+ candidates.push(`${stem}-${hash.slice(0, len)}`);
9779
+ }
9780
+ const avoided = [];
9781
+ for (const name of candidates) {
9782
+ const dir = path13.join(outputDir, name);
9783
+ const claim = await classifyExportDir(dir, flowPath);
9784
+ const reason = claim.state === "foreign" ? occupiedBy(claim.owner) : await takeExportDir(dir, flowPath);
9785
+ if (reason !== null) {
9786
+ avoided.push({ dir, reason });
9787
+ continue;
9788
+ }
9789
+ for (const entry of avoided) {
9790
+ console.error(
9791
+ `warning: ${entry.dir} ${entry.reason}; writing this flow's artifacts to ${dir} so neither set is overwritten`
9792
+ );
9793
+ }
9794
+ return name;
9795
+ }
9796
+ console.error(
9797
+ `warning: not exporting artifacts for ${flowPath}: no candidate directory from ${avoided[0].dir} through ${avoided[avoided.length - 1].dir} could be claimed without overwriting other files; leaving this run's artifact paths in place so nothing is overwritten`
9798
+ );
9799
+ return null;
9800
+ }
9801
+ async function exportFailureArtifacts(report, outputDir, flowPath, ctx) {
9802
+ const stem = path13.basename(flowPath, ".yaml");
9803
+ if (!SAFE_ARTIFACT_NAME.test(stem)) {
8994
9804
  console.error(
8995
- `warning: skipping artifact export for unsafe flow name ${JSON.stringify(report.flow)}`
9805
+ `warning: skipping artifact export for unsafe flow filename ${JSON.stringify(stem)}`
8996
9806
  );
8997
9807
  return;
8998
9808
  }
9809
+ let dir = null;
8999
9810
  for (const s of report.steps) {
9000
9811
  if (s.kind !== "snapshot" || s.status !== "fail" || !s.artifacts) continue;
9001
9812
  const key = s.snapshotKey ?? keyFromBaselinePath(s.artifacts);
9002
9813
  if (!key || !SAFE_ARTIFACT_NAME.test(key)) continue;
9003
9814
  const { result } = await materializeArtifacts(s.artifacts, ctx);
9004
9815
  s.artifacts = result;
9005
- const dir = path12.join(outputDir, report.flow);
9006
9816
  for (const [role, value] of Object.entries(s.artifacts)) {
9007
9817
  if (typeof value !== "string") continue;
9008
- const dest = path12.join(dir, `${key}-${role}.png`);
9009
- const rel = path12.relative(outputDir, dest);
9010
- if (rel.startsWith("..") || path12.isAbsolute(rel)) continue;
9818
+ if (dir === null) {
9819
+ const dirName = await claimExportDirName(outputDir, flowPath, stem);
9820
+ if (dirName === null) return;
9821
+ dir = path13.join(outputDir, dirName);
9822
+ }
9823
+ const dest = path13.join(dir, `${key}-${role}.png`);
9824
+ const rel = path13.relative(outputDir, dest);
9825
+ if (rel.startsWith("..") || path13.isAbsolute(rel)) continue;
9011
9826
  try {
9012
- await fsp.mkdir(dir, { recursive: true });
9013
9827
  await fsp.copyFile(value, dest);
9014
9828
  s.artifacts[role] = dest;
9015
9829
  } catch (err) {
@@ -9023,7 +9837,7 @@ async function exportFailureArtifacts(report, outputDir, ctx) {
9023
9837
  function keyFromBaselinePath(artifacts) {
9024
9838
  const baseline = artifacts.baseline;
9025
9839
  if (typeof baseline !== "string") return null;
9026
- return path12.basename(baseline).replace(/\.png$/, "");
9840
+ return path13.basename(baseline).replace(/\.png$/, "");
9027
9841
  }
9028
9842
  function resolveArtifactDisplayPaths(report) {
9029
9843
  for (const s of report.steps) {
@@ -9035,12 +9849,12 @@ function resolveArtifactDisplayPaths(report) {
9035
9849
  }
9036
9850
  function exitAfterFlush(code, streams = [process.stdout, process.stderr]) {
9037
9851
  return Promise.all(
9038
- streams.map((s) => new Promise((resolve9) => s.write("", () => resolve9())))
9852
+ streams.map((s) => new Promise((resolve10) => s.write("", () => resolve10())))
9039
9853
  ).then(() => process.exit(code));
9040
9854
  }
9041
9855
  function renderReport(report) {
9042
9856
  const lines = [];
9043
- lines.push(`Flow "${report.flow}" on ${report.device}`);
9857
+ lines.push(`Flow "${report.flow}"${report.device ? ` on ${report.device}` : ""}`);
9044
9858
  if (report.executionPrerequisite) {
9045
9859
  lines.push(` assumes: ${report.executionPrerequisite}`);
9046
9860
  }
@@ -9064,20 +9878,188 @@ function renderReport(report) {
9064
9878
  ${renderSummary(report)}`);
9065
9879
  return lines.join("\n");
9066
9880
  }
9881
+ async function isRunnableFlowFile(filePath) {
9882
+ try {
9883
+ const stat5 = await fsp.stat(filePath);
9884
+ if (!stat5.isFile()) return false;
9885
+ await fsp.access(filePath, fsConstants2.R_OK);
9886
+ return true;
9887
+ } catch {
9888
+ return false;
9889
+ }
9890
+ }
9891
+ async function collectRunnableFlowPaths(dir, relDir = "") {
9892
+ const found = [];
9893
+ const entries = await fsp.readdir(dir, { withFileTypes: true });
9894
+ for (const entry of entries) {
9895
+ const rel = relDir ? path13.join(relDir, entry.name) : entry.name;
9896
+ if (entry.isDirectory()) {
9897
+ if (entry.name === "__baselines__") continue;
9898
+ found.push(
9899
+ ...await collectRunnableFlowPaths(path13.join(dir, entry.name), rel).catch(() => [])
9900
+ );
9901
+ continue;
9902
+ }
9903
+ if (!entry.name.endsWith(".yaml")) continue;
9904
+ if (!SAFE_FLOW_NAME.test(path13.basename(entry.name, ".yaml"))) continue;
9905
+ if (await isRunnableFlowFile(path13.join(dir, entry.name))) found.push(rel);
9906
+ }
9907
+ return found;
9908
+ }
9909
+ function resolveFlowRef(ref) {
9910
+ if (!SAFE_FLOW_NAME.test(ref)) return { suppliedPath: ref, fromName: false };
9911
+ return { suppliedPath: path13.join(FLOWS_DIR, `${ref}.yaml`), fromName: true };
9912
+ }
9913
+ async function savedFlowHint(projectRoot, missingPath) {
9914
+ const dir = path13.resolve(projectRoot, FLOWS_DIR);
9915
+ const within = path13.relative(dir, missingPath);
9916
+ if (!within.startsWith("..") && !path13.isAbsolute(within)) return "";
9917
+ const wanted = `${path13.basename(missingPath, ".yaml")}.yaml`;
9918
+ const entries = await fsp.readdir(dir).catch(() => null);
9919
+ if (entries === null) return "";
9920
+ const actual = entries.includes(wanted) ? wanted : entries.find((name2) => name2.toLowerCase() === wanted.toLowerCase());
9921
+ if (actual === void 0) return "";
9922
+ const name = path13.basename(actual, ".yaml");
9923
+ if (!SAFE_FLOW_NAME.test(name)) return "";
9924
+ if (!await isRunnableFlowFile(path13.join(dir, actual))) return "";
9925
+ return `
9926
+ A flow named "${name}" is saved under ${FLOWS_DIR} \u2014 did you mean: argent flow run ${name}`;
9927
+ }
9928
+ async function collectFlowFiles(dir, recursive) {
9929
+ const found = [];
9930
+ const walk = async (current, rel) => {
9931
+ for (const entry of await fsp.readdir(current, { withFileTypes: true })) {
9932
+ const entryRel = rel ? path13.join(rel, entry.name) : entry.name;
9933
+ if (entry.isDirectory()) {
9934
+ if (recursive && !entry.name.startsWith(".") && entry.name !== "node_modules") {
9935
+ await walk(path13.join(current, entry.name), entryRel).catch(() => {
9936
+ });
9937
+ }
9938
+ continue;
9939
+ }
9940
+ if (!entry.name.endsWith(".yaml")) continue;
9941
+ if (!SAFE_FLOW_NAME.test(path13.basename(entry.name, ".yaml"))) continue;
9942
+ if (await isRunnableFlowFile(path13.join(current, entry.name))) found.push(entryRel);
9943
+ }
9944
+ };
9945
+ await walk(dir, "");
9946
+ return found.sort();
9947
+ }
9948
+ async function requireLocalToolServer() {
9949
+ const routing = await getResolvedToolsUrl();
9950
+ if (routing.source === "none") return true;
9951
+ const recovery = routing.source === "env" ? routing.shadowedLink ? `Unset ARGENT_TOOLS_URL and run \`argent unlink\`, then try again \u2014 a link to ${routing.shadowedLink.url} is also configured and takes over once the env var is unset.` : "Unset ARGENT_TOOLS_URL and try again." : "Run `argent unlink` and try again.";
9952
+ console.error(
9953
+ `argent flow run requires the auto-started local tool server; ${routing.source} routing is configured.
9954
+ ${recovery}`
9955
+ );
9956
+ return false;
9957
+ }
9958
+ function buildRunPayload(flowPath, projectRoot, args) {
9959
+ const payload = {
9960
+ flow_path: flowPath,
9961
+ project_root: projectRoot,
9962
+ // Headless runs never block on the LLM prerequisite handshake.
9963
+ prerequisiteAcknowledged: true
9964
+ };
9965
+ if (args.device) payload.device = args.device;
9966
+ if (args.platform) payload.platform = args.platform;
9967
+ if (args.updateBaselines) payload.updateBaselines = true;
9968
+ return payload;
9969
+ }
9970
+ async function exportAndResolveArtifacts(report, outputDir, flowPath, baseUrl) {
9971
+ if (outputDir) {
9972
+ const { url, token } = await baseUrl();
9973
+ await exportFailureArtifacts(report, outputDir, flowPath, { toolsUrl: url, authToken: token });
9974
+ }
9975
+ resolveArtifactDisplayPaths(report);
9976
+ }
9977
+ async function runFlowDirectory(dir, args, projectRoot, options) {
9978
+ let flows;
9979
+ try {
9980
+ flows = await collectFlowFiles(dir, args.recursive);
9981
+ } catch {
9982
+ console.error(`Could not read flow directory: ${dir}`);
9983
+ return exitAfterFlush(2);
9984
+ }
9985
+ if (flows.length === 0) {
9986
+ console.error(`No flows found in ${dir}`);
9987
+ if (!args.recursive) console.error("Pass -r/--recursive to include subdirectories.");
9988
+ return exitAfterFlush(2);
9989
+ }
9990
+ if (!await requireLocalToolServer()) return exitAfterFlush(2);
9991
+ const { callTool, baseUrl } = createToolsClient({ paths: options.paths });
9992
+ const outputBase = args.output ? path13.resolve(args.output) : void 0;
9993
+ const results = [];
9994
+ let stopped = false;
9995
+ for (const [i2, rel] of flows.entries()) {
9996
+ if (!args.json) console.log(`[${i2 + 1}/${flows.length}] ${rel}`);
9997
+ if (stopped) {
9998
+ results.push({ path: rel, status: "skip" });
9999
+ if (!args.json) console.log(` ${STATUS_GLYPH.skip} not run (batch stopped)`);
10000
+ continue;
10001
+ }
10002
+ let report;
10003
+ try {
10004
+ const resp = await callTool(
10005
+ "flow-execute",
10006
+ buildRunPayload(path13.join(dir, rel), projectRoot, args)
10007
+ );
10008
+ const data = resp.data;
10009
+ if (data && typeof data === "object" && "steps" in data) report = data;
10010
+ } catch (err) {
10011
+ const message = err instanceof Error ? err.message : String(err);
10012
+ console.error(message);
10013
+ results.push({ path: rel, status: "fail", error: message });
10014
+ const rejectedThisFlowOnly = err instanceof ToolInvocationError && err.errorKind === "validation";
10015
+ if (!rejectedThisFlowOnly) stopped = true;
10016
+ continue;
10017
+ }
10018
+ if (!report) {
10019
+ const message = `"${rel}" did not produce a run report.`;
10020
+ console.error(message);
10021
+ results.push({ path: rel, status: "fail", error: message });
10022
+ stopped = true;
10023
+ continue;
10024
+ }
10025
+ await exportAndResolveArtifacts(
10026
+ report,
10027
+ outputBase ? path13.join(outputBase, path13.dirname(rel)) : void 0,
10028
+ path13.join(dir, rel),
10029
+ baseUrl
10030
+ );
10031
+ results.push({ path: rel, status: report.ok ? "pass" : "fail", report });
10032
+ if (!args.json) {
10033
+ for (const line of renderFailedSteps(report)) console.log(line);
10034
+ console.log(` ${renderSummary(report, { withDevice: true })}`);
10035
+ }
10036
+ }
10037
+ const counts = {
10038
+ total: results.length,
10039
+ passed: results.filter((r2) => r2.status === "pass").length,
10040
+ failed: results.filter((r2) => r2.status === "fail").length,
10041
+ skipped: results.filter((r2) => r2.status === "skip").length
10042
+ };
10043
+ if (args.json) {
10044
+ console.log(JSON.stringify({ ok: counts.failed === 0, ...counts, flows: results }, null, 2));
10045
+ } else {
10046
+ console.log(`
10047
+ ${renderBatchSummary(counts)}`);
10048
+ }
10049
+ return exitAfterFlush(counts.failed === 0 ? 0 : 1);
10050
+ }
9067
10051
  async function flow(argv, options) {
9068
10052
  const [sub, ...rest] = argv;
9069
10053
  if (!sub || sub === "--help" || sub === "-h") {
9070
10054
  printHelp();
9071
10055
  return;
9072
10056
  }
9073
- const { callTool, baseUrl } = createToolsClient({ paths: options.paths });
9074
10057
  if (sub === "list") {
9075
- const dir = path12.join(process.cwd(), ".argent", "flows");
10058
+ const dir = path13.join(process.cwd(), FLOWS_DIR);
9076
10059
  try {
9077
- const entries = await fsp.readdir(dir);
9078
- const names = entries.filter((f) => f.endsWith(".yaml")).map((f) => f.replace(/\.yaml$/, ""));
9079
- if (names.length === 0) console.log("No flows found in .argent/flows");
9080
- else console.log(names.join("\n"));
10060
+ const paths = (await collectRunnableFlowPaths(dir)).sort().map((rel) => path13.join(FLOWS_DIR, rel));
10061
+ if (paths.length === 0) console.log("No flows found in .argent/flows");
10062
+ else console.log(paths.join("\n"));
9081
10063
  } catch {
9082
10064
  console.log("No .argent/flows directory in the current working directory.");
9083
10065
  }
@@ -9103,21 +10085,121 @@ async function flow(argv, options) {
9103
10085
  }
9104
10086
  throw err;
9105
10087
  }
9106
- if (!args.name) {
9107
- console.error("argent flow run <name> requires a flow name.");
10088
+ if (!args.flowRef) {
10089
+ console.error(
10090
+ "argent flow run <flow|flow.yaml|dir> requires a flow name, a YAML file path, or a directory path."
10091
+ );
9108
10092
  printHelp();
9109
10093
  return exitAfterFlush(2);
9110
10094
  }
9111
- const flowName = args.name;
9112
- const payload = {
9113
- name: flowName,
9114
- project_root: process.cwd(),
9115
- // Headless runs never block on the LLM prerequisite handshake.
9116
- prerequisiteAcknowledged: true
9117
- };
9118
- if (args.device) payload.device = args.device;
9119
- if (args.platform) payload.platform = args.platform;
9120
- if (args.updateBaselines) payload.updateBaselines = true;
10095
+ const projectRoot = process.cwd();
10096
+ const { suppliedPath, fromName } = resolveFlowRef(args.flowRef);
10097
+ if (suppliedPath.split(/[\\/]+/).includes("..")) {
10098
+ let recovery = "Pass the fully resolved path to the flow's YAML.";
10099
+ const suppliedBase2 = path13.basename(suppliedPath);
10100
+ if (suppliedBase2 !== ".." && suppliedBase2 !== ".") {
10101
+ try {
10102
+ const resolved = path13.join(await fsp.realpath(path13.dirname(suppliedPath)), suppliedBase2);
10103
+ await fsp.stat(resolved);
10104
+ recovery = `Did you mean: argent flow run ${shellQuoteArg(resolved)}`;
10105
+ } catch {
10106
+ }
10107
+ }
10108
+ console.error(
10109
+ `Flow path must not contain ".." segments \u2014 they are collapsed without following symlinks, so the path can name a different file than the one your shell opens: ${suppliedPath}
10110
+ ` + recovery
10111
+ );
10112
+ return exitAfterFlush(2);
10113
+ }
10114
+ const resolvedPath = path13.resolve(projectRoot, suppliedPath);
10115
+ let isDirectory = false;
10116
+ try {
10117
+ isDirectory = (await fsp.stat(resolvedPath)).isDirectory();
10118
+ } catch {
10119
+ if (args.recursive && !fromName) {
10120
+ console.error(`Flow directory not found: ${resolvedPath}`);
10121
+ return exitAfterFlush(2);
10122
+ }
10123
+ }
10124
+ if (isDirectory) {
10125
+ return runFlowDirectory(resolvedPath, args, projectRoot, options);
10126
+ }
10127
+ if (args.recursive) {
10128
+ console.error(
10129
+ fromName ? `flow run --recursive requires a directory path; "${args.flowRef}" is a saved-flow name, which always addresses the single file ${suppliedPath}.` : `flow run --recursive requires a directory path: ${suppliedPath}`
10130
+ );
10131
+ return exitAfterFlush(2);
10132
+ }
10133
+ const separatorTrimmedPath = suppliedPath.replace(/[\\/]+$/, "");
10134
+ if (separatorTrimmedPath !== suppliedPath && separatorTrimmedPath !== "") {
10135
+ const hint = SAFE_FLOW_NAME.test(separatorTrimmedPath) ? `.${path13.sep}${separatorTrimmedPath}` : separatorTrimmedPath;
10136
+ console.error(
10137
+ `Flow path must not end in a path separator \u2014 the separator claims a directory, which the kernel would refuse to open as a file, so the CLI would run a file this string does not name: ${suppliedPath}
10138
+ Did you mean: argent flow run ${shellQuoteArg(hint)}`
10139
+ );
10140
+ return exitAfterFlush(2);
10141
+ }
10142
+ if (path13.extname(suppliedPath) !== ".yaml") {
10143
+ const looksLikeName = !suppliedPath.includes("/") && !suppliedPath.includes("\\") && path13.extname(suppliedPath) === "";
10144
+ if (path13.basename(suppliedPath).toLowerCase() === ".yaml") {
10145
+ console.error(
10146
+ `Flow filename must have a non-empty name containing only letters, numbers, "_", or "-": ${suppliedPath}`
10147
+ );
10148
+ } else if (looksLikeName) {
10149
+ console.error(
10150
+ `Flow name must contain only letters, numbers, "_", or "-": ${suppliedPath}
10151
+ Names run \`${FLOWS_DIR}/<name>.yaml\`; pass a path ending in .yaml to run a flow file kept elsewhere.`
10152
+ );
10153
+ } else if (path13.extname(suppliedPath).toLowerCase() === ".yaml") {
10154
+ console.error(
10155
+ `Flow extension must be lowercase .yaml, not ${path13.extname(suppliedPath)}: ${suppliedPath}`
10156
+ );
10157
+ } else {
10158
+ console.error(`Flow path must end in .yaml: ${suppliedPath}`);
10159
+ }
10160
+ return exitAfterFlush(2);
10161
+ }
10162
+ const flowName = path13.basename(suppliedPath, ".yaml");
10163
+ if (!SAFE_FLOW_NAME.test(flowName)) {
10164
+ console.error(
10165
+ `Flow filename must have a non-empty name containing only letters, numbers, "_", or "-": ${suppliedPath}`
10166
+ );
10167
+ return exitAfterFlush(2);
10168
+ }
10169
+ const flowPath = resolvedPath;
10170
+ try {
10171
+ const stat5 = await fsp.stat(flowPath);
10172
+ if (!stat5.isFile()) {
10173
+ console.error(`Flow path is not a file: ${flowPath}`);
10174
+ return exitAfterFlush(2);
10175
+ }
10176
+ await fsp.access(flowPath, fsConstants2.R_OK);
10177
+ } catch (err) {
10178
+ const code = err.code;
10179
+ const detail = code === "ENOENT" ? "Flow file not found" : "Could not read flow file";
10180
+ let recovery = "";
10181
+ if (code === "ENOENT") {
10182
+ recovery = fromName ? `
10183
+ No flow named "${args.flowRef}" is saved there \u2014 run \`argent flow list\` to see the saved flows.` : await savedFlowHint(projectRoot, flowPath);
10184
+ }
10185
+ console.error(`${detail}: ${flowPath}${recovery}`);
10186
+ return exitAfterFlush(2);
10187
+ }
10188
+ const suppliedBase = path13.basename(flowPath);
10189
+ const siblings = await fsp.readdir(path13.dirname(flowPath)).catch(() => null);
10190
+ if (siblings !== null && !siblings.includes(suppliedBase)) {
10191
+ const actual = siblings.find((name) => name.toLowerCase() === suppliedBase.toLowerCase());
10192
+ const actualRunnable = actual !== void 0 && path13.extname(actual) === ".yaml" && SAFE_FLOW_NAME.test(path13.basename(actual, ".yaml"));
10193
+ const recovery = actualRunnable ? fromName ? `Did you mean: argent flow run ${path13.basename(actual, ".yaml")}` : `Did you mean: argent flow run ${shellQuoteArg(path13.join(path13.dirname(suppliedPath), actual))}` : actual !== void 0 ? `Rename ${actual} to ${suppliedBase} to run it \u2014 flow files must be lowercase .yaml.` : "Pass the flow file's name exactly as it appears on disk.";
10194
+ console.error(
10195
+ `Flow path must name the file as it appears on disk \u2014 this filesystem matched ${JSON.stringify(suppliedBase)} case-insensitively${actual !== void 0 ? ` to ${JSON.stringify(actual)}` : ""}, so the flow name (which keys the report, __baselines__/, and --output) would be one no file carries: ${suppliedPath}
10196
+ ${recovery}`
10197
+ );
10198
+ return exitAfterFlush(2);
10199
+ }
10200
+ if (!await requireLocalToolServer()) return exitAfterFlush(2);
10201
+ const { callTool, baseUrl } = createToolsClient({ paths: options.paths });
10202
+ const payload = buildRunPayload(flowPath, projectRoot, args);
9121
10203
  let liveSteps = 0;
9122
10204
  let liveIndex = 0;
9123
10205
  const onStepReport = (event) => {
@@ -9149,14 +10231,12 @@ async function flow(argv, options) {
9149
10231
  console.error(`"${flowName}" did not produce a run report.`);
9150
10232
  return exitAfterFlush(2);
9151
10233
  }
9152
- if (args.output) {
9153
- const { url, token } = await baseUrl();
9154
- await exportFailureArtifacts(report, path12.resolve(args.output), {
9155
- toolsUrl: url,
9156
- authToken: token
9157
- });
9158
- }
9159
- resolveArtifactDisplayPaths(report);
10234
+ await exportAndResolveArtifacts(
10235
+ report,
10236
+ args.output ? path13.resolve(args.output) : void 0,
10237
+ flowPath,
10238
+ baseUrl
10239
+ );
9160
10240
  if (args.json) {
9161
10241
  console.log(JSON.stringify(report, null, 2));
9162
10242
  } else if (liveSteps > 0) {
@@ -9216,10 +10296,27 @@ ${sorted.length} tools. Run \`argent tools describe <name>\` for details.`);
9216
10296
  console.log(formatSchemaUsage(meta.inputSchema));
9217
10297
  if (meta.outputHint) console.log(`
9218
10298
  Output hint: ${meta.outputHint}`);
10299
+ }
10300
+ function printUsage4() {
10301
+ console.log(`Usage:
10302
+ argent tools List available tools
10303
+ argent tools describe <name> Show one tool's flags and description
10304
+
10305
+ Options:
10306
+ --json Print machine-readable JSON
10307
+ --help, -h Show this help
10308
+
10309
+ Listing tools contacts the argent tool-server, starting one if none is running.
10310
+ `);
9219
10311
  }
9220
10312
  const json = argv.includes("--json");
9221
- const positional = argv.filter((a2) => !a2.startsWith("--"));
10313
+ const isHelpFlag = (a2) => a2 === "--help" || a2 === "-h";
10314
+ const positional = argv.filter((a2) => !a2.startsWith("--") || isHelpFlag(a2));
9222
10315
  const sub = positional[0];
10316
+ if (sub !== void 0 && isHelpFlag(sub)) {
10317
+ printUsage4();
10318
+ return;
10319
+ }
9223
10320
  if (!sub) {
9224
10321
  await listTools(json);
9225
10322
  return;
@@ -9233,27 +10330,17 @@ Output hint: ${meta.outputHint}`);
9233
10330
  await describeTool(name, json);
9234
10331
  return;
9235
10332
  }
9236
- if (sub === "--help" || sub === "-h") {
9237
- console.log(`Usage:
9238
- argent tools List available tools
9239
- argent tools describe <name> Show one tool's flags and description
9240
-
9241
- Options:
9242
- --json Print machine-readable JSON
9243
- `);
9244
- return;
9245
- }
9246
10333
  console.error(`Unknown subcommand: tools ${sub}`);
9247
10334
  process.exit(1);
9248
10335
  }
9249
10336
 
9250
10337
  // ../argent-cli/src/server.ts
9251
- import * as fs9 from "node:fs";
9252
- import * as path13 from "node:path";
10338
+ import * as fs10 from "node:fs";
10339
+ import * as path14 from "node:path";
9253
10340
  import { homedir as homedir5, networkInterfaces } from "node:os";
9254
10341
  import { spawn as spawn3 } from "node:child_process";
9255
- var STATE_DIR2 = path13.join(homedir5(), ".argent");
9256
- var LOG_FILE2 = path13.join(STATE_DIR2, "tool-server.log");
10342
+ var STATE_DIR2 = path14.join(homedir5(), ".argent");
10343
+ var LOG_FILE2 = path14.join(STATE_DIR2, "tool-server.log");
9257
10344
  async function describeForeignServers(ownBundlePath) {
9258
10345
  const others = (await readAllToolsServerStates()).filter(
9259
10346
  ({ state: state2 }) => state2.bundlePath !== ownBundlePath && isToolsServerProcessAlive(state2.pid)
@@ -9312,12 +10399,12 @@ Stop one with: kill <pid>`);
9312
10399
  console.log(`tool-server stopped (pid ${state2.pid}).`);
9313
10400
  }
9314
10401
  function logsCmd(follow) {
9315
- if (!fs9.existsSync(LOG_FILE2)) {
10402
+ if (!fs10.existsSync(LOG_FILE2)) {
9316
10403
  console.log(`No log file at ${LOG_FILE2}`);
9317
10404
  return;
9318
10405
  }
9319
10406
  if (!follow) {
9320
- process.stdout.write(fs9.readFileSync(LOG_FILE2, "utf8"));
10407
+ process.stdout.write(fs10.readFileSync(LOG_FILE2, "utf8"));
9321
10408
  return;
9322
10409
  }
9323
10410
  const child = spawn3("tail", ["-f", LOG_FILE2], { stdio: "inherit" });
@@ -9660,9 +10747,9 @@ async function server(argv, options) {
9660
10747
  }
9661
10748
 
9662
10749
  // ../argent-cli/src/lens.ts
9663
- import * as fs10 from "node:fs";
10750
+ import * as fs11 from "node:fs";
9664
10751
  import * as os2 from "node:os";
9665
- import * as path14 from "node:path";
10752
+ import * as path15 from "node:path";
9666
10753
 
9667
10754
  // ../argent-cli/src/lens-terminal.ts
9668
10755
  import { execFileSync as execFileSync3 } from "node:child_process";
@@ -9880,15 +10967,15 @@ function isSessionAlive(session) {
9880
10967
  // ../argent-cli/src/lens-pty.ts
9881
10968
  import { chmodSync as chmodSync2, readdirSync as readdirSync2 } from "node:fs";
9882
10969
  import { createRequire } from "node:module";
9883
- import { dirname as dirname8, join as join14 } from "node:path";
10970
+ import { dirname as dirname9, join as join15 } from "node:path";
9884
10971
  var nodeRequire = createRequire(import.meta.url);
9885
10972
  function ensureSpawnHelperExecutable(req = nodeRequire) {
9886
10973
  if (process.platform !== "darwin") return;
9887
10974
  try {
9888
- const prebuilds = join14(dirname8(req.resolve("node-pty/package.json")), "prebuilds");
10975
+ const prebuilds = join15(dirname9(req.resolve("node-pty/package.json")), "prebuilds");
9889
10976
  for (const entry of readdirSync2(prebuilds)) {
9890
10977
  try {
9891
- chmodSync2(join14(prebuilds, entry, "spawn-helper"), 493);
10978
+ chmodSync2(join15(prebuilds, entry, "spawn-helper"), 493);
9892
10979
  } catch {
9893
10980
  }
9894
10981
  }
@@ -9920,7 +11007,7 @@ function ptyInjectBeats(text2) {
9920
11007
  ];
9921
11008
  }
9922
11009
  function sleep(ms) {
9923
- return new Promise((resolve9) => setTimeout(resolve9, ms));
11010
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
9924
11011
  }
9925
11012
  var DEFAULT_COLS = 80;
9926
11013
  var DEFAULT_ROWS = 24;
@@ -10030,10 +11117,10 @@ function parseSseBuffer(buffer) {
10030
11117
  const events = [];
10031
11118
  let rest = normalised;
10032
11119
  for (; ; ) {
10033
- const sep5 = rest.indexOf("\n\n");
10034
- if (sep5 === -1) break;
10035
- const rawFrame = rest.slice(0, sep5);
10036
- rest = rest.slice(sep5 + 2);
11120
+ const sep6 = rest.indexOf("\n\n");
11121
+ if (sep6 === -1) break;
11122
+ const rawFrame = rest.slice(0, sep6);
11123
+ rest = rest.slice(sep6 + 2);
10037
11124
  let event = "message";
10038
11125
  const dataLines = [];
10039
11126
  for (const line of rawFrame.split("\n")) {
@@ -10141,7 +11228,7 @@ var SPAWN_GRACE_MS = 8e3;
10141
11228
  var DEATH_CONFIRMATIONS = 3;
10142
11229
  var SSE_RECONNECT_MS = 1e3;
10143
11230
  function sleep2(ms) {
10144
- return new Promise((resolve9) => setTimeout(resolve9, ms));
11231
+ return new Promise((resolve10) => setTimeout(resolve10, ms));
10145
11232
  }
10146
11233
  var TRUST_PROMPT_RE = /trust this folder|do you trust|yes,? i trust|trust the files in this/i;
10147
11234
  async function dismissTrustPrompt(session) {
@@ -10297,8 +11384,15 @@ function parseArgs(argv) {
10297
11384
  for (let i2 = 0; i2 < argv.length; i2++) {
10298
11385
  const tok = argv[i2];
10299
11386
  if (tok === "--help" || tok === "-h") help = true;
10300
- else if (tok === "--forget") forget = true;
10301
- else if (tok === "--terminal" || tok === "-t") {
11387
+ else if (tok === "--forget") {
11388
+ forget = true;
11389
+ const next = argv[i2 + 1]?.trim().toLowerCase();
11390
+ if (next === "true" || next === "false") {
11391
+ process.stderr.write(`lens: --forget does not take a value; omit it to keep the state
11392
+ `);
11393
+ process.exit(2);
11394
+ }
11395
+ } else if (tok === "--terminal" || tok === "-t") {
10302
11396
  const v = argv[++i2];
10303
11397
  if (v === "iterm" || v === "terminal") terminal = v;
10304
11398
  else {
@@ -10414,12 +11508,12 @@ async function lens(argv, options) {
10414
11508
  await endSession(baseUrl);
10415
11509
  process.exit(1);
10416
11510
  }
10417
- const seedFile = path14.join(os2.tmpdir(), `argent-lens-seed-${process.pid}-${Date.now()}.txt`);
10418
- fs10.writeFileSync(seedFile, buildSeedPrompt(), "utf8");
11511
+ const seedFile = path15.join(os2.tmpdir(), `argent-lens-seed-${process.pid}-${Date.now()}.txt`);
11512
+ fs11.writeFileSync(seedFile, buildSeedPrompt(), "utf8");
10419
11513
  const launchCmd = agent.launch(shellQuote(process.cwd()), shellQuote(seedFile));
10420
11514
  const removeSeedFile = () => {
10421
11515
  try {
10422
- fs10.rmSync(seedFile, { force: true });
11516
+ fs11.rmSync(seedFile, { force: true });
10423
11517
  } catch {
10424
11518
  }
10425
11519
  };
@@ -10809,7 +11903,7 @@ Options:
10809
11903
 
10810
11904
  // ../argent-cli/src/config.ts
10811
11905
  var import_picocolors2 = __toESM(require_picocolors(), 1);
10812
- import * as path15 from "node:path";
11906
+ import * as path16 from "node:path";
10813
11907
  function config(argv) {
10814
11908
  if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
10815
11909
  printUsage();
@@ -10859,6 +11953,7 @@ the raw value stored at each scope.`);
10859
11953
  }
10860
11954
  function scopeDetail(e) {
10861
11955
  const parts = [`scopes: ${e.scopes.join(", ")}`];
11956
+ if (e.expected) parts.push(`value: ${e.expected}${e.example ? `, e.g. ${e.example}` : ""}`);
10862
11957
  if (e.project !== void 0) parts.push(`project=${formatValuePlain(e.project)}`);
10863
11958
  if (e.global !== void 0) parts.push(`global=${formatValuePlain(e.global)}`);
10864
11959
  return parts.join(" \xB7 ");
@@ -10923,7 +12018,7 @@ parsed (e.g. \`true\`, \`42\`, \`["a","b"]\`); anything else is stored as a stri
10923
12018
  if (warning) console.error(import_picocolors2.default.yellow(warning));
10924
12019
  console.log(`Set ${import_picocolors2.default.bold(key)} = ${formatValuePlain(stored)} (${scopeLabel(targetScope)}).`);
10925
12020
  } catch (err) {
10926
- reportError(err);
12021
+ reportError(err, () => suggestCorrectedSet(err, key, rawValue, scope));
10927
12022
  }
10928
12023
  }
10929
12024
  function cmdUnset(argv) {
@@ -10992,16 +12087,16 @@ function wantsHelp(argv) {
10992
12087
  }
10993
12088
  function scopeLabel(scope) {
10994
12089
  if (scope === "global") return "global";
10995
- return `project: ${path15.dirname(configDir("project"))}`;
12090
+ return `project: ${path16.dirname(configDir("project"))}`;
10996
12091
  }
10997
12092
  function degenerateProjectScopeWarning(scope) {
10998
12093
  if (scope !== "project") return null;
10999
12094
  const projDir = configDir("project");
11000
- if (path15.resolve(projDir) === path15.resolve(configDir("global"))) {
11001
- return `WARNING: no project found between ${process.cwd()} and your home directory \u2014 "project" scope resolved to the home directory, so this writes the GLOBAL config file (${path15.join(projDir, "config.json")}).`;
12095
+ if (path16.resolve(projDir) === path16.resolve(configDir("global"))) {
12096
+ return `WARNING: no project found between ${process.cwd()} and your home directory \u2014 "project" scope resolved to the home directory, so this writes the GLOBAL config file (${path16.join(projDir, "config.json")}).`;
11002
12097
  }
11003
12098
  if (findProjectRoot(process.cwd()) === null) {
11004
- return `WARNING: no project markers (.argent, .git, package.json) found above ${process.cwd()} \u2014 treating it as the project root and creating ${path15.join(projDir, "config.json")}.`;
12099
+ return `WARNING: no project markers (.argent, .git, package.json) found above ${process.cwd()} \u2014 treating it as the project root and creating ${path16.join(projDir, "config.json")}.`;
11005
12100
  }
11006
12101
  return null;
11007
12102
  }
@@ -11016,7 +12111,20 @@ function formatValue(value) {
11016
12111
  }
11017
12112
  return formatValuePlain(value);
11018
12113
  }
11019
- function reportError(err) {
12114
+ function quoteForShell(value) {
12115
+ if (/^[A-Za-z0-9._/@:+-]+$/.test(value)) return value;
12116
+ return `'${value.replace(/'/g, `'\\''`)}'`;
12117
+ }
12118
+ function suggestCorrectedSet(err, key, rawValue, scope) {
12119
+ if (!(err instanceof ConfigValidationError)) return null;
12120
+ const def = getConfigDefinition(key);
12121
+ if (!def) return null;
12122
+ const wrapped = def.parse([rawValue]);
12123
+ if (wrapped === void 0) return null;
12124
+ const scopeFlag = scope ? ` --scope ${scope}` : "";
12125
+ return `argent config set ${key} ${quoteForShell(JSON.stringify([rawValue]))}${scopeFlag}`;
12126
+ }
12127
+ function reportError(err, suggest) {
11020
12128
  if (err instanceof ConfigManagedElsewhereError) {
11021
12129
  console.error(`Error: ${err.message} Use \`${err.command}\` instead.`);
11022
12130
  } else if (err instanceof UnknownConfigKeyError || err instanceof ConfigScopeError || err instanceof ConfigValidationError) {
@@ -11024,6 +12132,15 @@ function reportError(err) {
11024
12132
  if (err instanceof UnknownConfigKeyError) {
11025
12133
  console.error(`Run \`argent config list\` to see available keys.`);
11026
12134
  }
12135
+ if (err instanceof ConfigValidationError) {
12136
+ const corrected = suggest?.() ?? null;
12137
+ if (corrected) {
12138
+ console.error(`Did you mean: ${corrected}`);
12139
+ } else if (err.example) {
12140
+ console.error(`Example: argent config set ${err.key} ${quoteForShell(err.example)}`);
12141
+ }
12142
+ console.error(`Run \`argent config list\` to see each key's expected value.`);
12143
+ }
11027
12144
  } else {
11028
12145
  console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
11029
12146
  }
@@ -11055,6 +12172,99 @@ ${keyLines.join("\n")}
11055
12172
  Run \`argent config <command> --help\` for command-specific help.`);
11056
12173
  }
11057
12174
 
12175
+ // ../argent-cli/src/secrets.ts
12176
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
12177
+ async function secrets(argv) {
12178
+ const [sub, ...rest] = argv;
12179
+ if (sub === void 0 || sub === "list") return cmdList2(rest);
12180
+ if (sub === "--help" || sub === "-h") return printUsage2();
12181
+ if (sub === "--json") return cmdList2([sub, ...rest]);
12182
+ console.error(`Error: unknown subcommand "secrets ${sub}". Try \`argent secrets --help\`.`);
12183
+ process.exit(2);
12184
+ }
12185
+ function printUsage2() {
12186
+ console.log(`Usage: argent secrets [list] [--json]
12187
+
12188
+ List the secrets a \`{{secret:<NAME>}}\` placeholder can resolve, and the sources
12189
+ they come from. Names only \u2014 a value is never printed.
12190
+
12191
+ A name is resolved by the machine running the tool-server, taking the first
12192
+ source that defines it:
12193
+
12194
+ 1. ${SECRET_ENV_PREFIX}<NAME> in the environment prefixed variables only
12195
+ 2. <project>/.argent/secrets.env every key (gitignore this file)
12196
+ 3. <project>/.env.local, then <project>/.env only ${SECRET_ENV_PREFIX}-prefixed keys
12197
+ 4. ~/.argent/secrets.env every key, any project
12198
+
12199
+ A secrets file applies to the next tool call \u2014 no restart. An environment
12200
+ variable only reaches a tool-server started after it was exported.
12201
+
12202
+ Examples:
12203
+ echo 'APP_PASSWORD=\u2026' >> ~/.argent/secrets.env # available in every project
12204
+ argent secrets # check it is picked up`);
12205
+ }
12206
+ async function cmdList2(argv) {
12207
+ if (argv.includes("--help") || argv.includes("-h")) return printUsage2();
12208
+ const json = argv.includes("--json");
12209
+ const sources = secretSources();
12210
+ const all = secretNames(sources);
12211
+ if (json) {
12212
+ console.log(
12213
+ JSON.stringify(
12214
+ {
12215
+ secrets: all,
12216
+ sources: sources.map((s) => ({
12217
+ source: s.label,
12218
+ present: s.present,
12219
+ names: s.names,
12220
+ ...s.needsPrefix ? { needsPrefix: true } : {}
12221
+ }))
12222
+ },
12223
+ null,
12224
+ 2
12225
+ )
12226
+ );
12227
+ return;
12228
+ }
12229
+ console.log(`Secrets available to \`{{secret:<NAME>}}\` on this machine:
12230
+ `);
12231
+ const claimed = /* @__PURE__ */ new Set();
12232
+ for (const source of sources) {
12233
+ console.log(` ${source.label}`);
12234
+ if (!source.present) {
12235
+ console.log(` ${import_picocolors3.default.dim("not found")}`);
12236
+ } else if (source.needsPrefix) {
12237
+ console.log(
12238
+ ` ${import_picocolors3.default.dim(`no ${SECRET_ENV_PREFIX}* keys \u2014 only prefixed keys are exposed from a file the app shares`)}`
12239
+ );
12240
+ } else if (source.names.length === 0) {
12241
+ console.log(` ${import_picocolors3.default.dim("no secrets")}`);
12242
+ } else {
12243
+ const rendered = source.names.map(
12244
+ (name) => claimed.has(name) ? import_picocolors3.default.dim(`${name} (shadowed above)`) : name
12245
+ );
12246
+ for (const name of source.names) claimed.add(name);
12247
+ console.log(` ${rendered.join(", ")}`);
12248
+ }
12249
+ }
12250
+ console.log(
12251
+ `
12252
+ ${all.length === 0 ? "No secrets are defined." : `${all.length} name${all.length === 1 ? "" : "s"} in effect: ${all.join(", ")}`}`
12253
+ );
12254
+ console.log(
12255
+ import_picocolors3.default.dim("Values are never printed. Run `argent secrets --help` to see where to add one.")
12256
+ );
12257
+ const routed = await getResolvedToolsUrl().catch(() => ({ url: null }));
12258
+ if (routed.url) {
12259
+ console.log(
12260
+ import_picocolors3.default.yellow(
12261
+ `
12262
+ Note: a remote tool-server is linked (${routed.url}). Placeholders resolve there, against that machine's environment and secrets files \u2014 not the ones listed above.`
12263
+ )
12264
+ );
12265
+ }
12266
+ }
12267
+
11058
12268
  // ../../node_modules/@clack/core/dist/index.mjs
11059
12269
  import { styleText } from "node:util";
11060
12270
  import { stdout, stdin } from "node:process";
@@ -11775,7 +12985,7 @@ import { styleText as styleText2, stripVTControlCharacters } from "node:util";
11775
12985
  import process$1 from "node:process";
11776
12986
  var import_sisteransi2 = __toESM(require_src(), 1);
11777
12987
  import { existsSync as existsSync7, lstatSync as lstatSync3, readdirSync as readdirSync3 } from "node:fs";
11778
- import { dirname as dirname10, join as join17 } from "node:path";
12988
+ import { dirname as dirname11, join as join18 } from "node:path";
11779
12989
  function isUnicodeSupported() {
11780
12990
  if (process$1.platform !== "win32") {
11781
12991
  return process$1.env.TERM !== "linux";
@@ -12212,7 +13422,7 @@ ${r2}
12212
13422
  }).prompt();
12213
13423
 
12214
13424
  // ../argent-cli/src/link.ts
12215
- var import_picocolors3 = __toESM(require_picocolors(), 1);
13425
+ var import_picocolors4 = __toESM(require_picocolors(), 1);
12216
13426
  var WILDCARD_HOSTS = /* @__PURE__ */ new Set(["0.0.0.0", "::", "::0", ""]);
12217
13427
  function isLoopback2(host) {
12218
13428
  return host === "127.0.0.1" || host === "localhost" || host === "::1";
@@ -12470,7 +13680,7 @@ async function preflightHealth(url, token) {
12470
13680
  }
12471
13681
  function printRestartHint() {
12472
13682
  console.log(
12473
- import_picocolors3.default.dim("Restart your editor to apply the change to any running `argent mcp` session.")
13683
+ import_picocolors4.default.dim("Restart your editor to apply the change to any running `argent mcp` session.")
12474
13684
  );
12475
13685
  }
12476
13686
  function printSecurityCaveat(host, token, url) {
@@ -12479,7 +13689,7 @@ function printSecurityCaveat(host, token, url) {
12479
13689
  if (tls) {
12480
13690
  if (!token) {
12481
13691
  process.stderr.write(
12482
- import_picocolors3.default.yellow(
13692
+ import_picocolors4.default.yellow(
12483
13693
  `WARNING: ${host} is reached over HTTPS but with NO token \u2014 anyone who can reach the URL can drive the server. Pair with a token.
12484
13694
  `
12485
13695
  )
@@ -12489,7 +13699,7 @@ function printSecurityCaveat(host, token, url) {
12489
13699
  }
12490
13700
  if (token) {
12491
13701
  process.stderr.write(
12492
- import_picocolors3.default.dim(
13702
+ import_picocolors4.default.dim(
12493
13703
  `Note: ${host} is reached over plain HTTP (bearer-token auth, no TLS). Keep this link to a trusted network or VPN, or front it with an https:// tunnel.
12494
13704
  `
12495
13705
  )
@@ -12497,7 +13707,7 @@ function printSecurityCaveat(host, token, url) {
12497
13707
  return;
12498
13708
  }
12499
13709
  process.stderr.write(
12500
- import_picocolors3.default.yellow(
13710
+ import_picocolors4.default.yellow(
12501
13711
  `WARNING: linked target ${host} is non-loopback and has NO token \u2014 tool calls travel over plain HTTP with no auth. Treat this link as trusted-network-only, or pair with a token (start the server without --no-auth).
12502
13712
  `
12503
13713
  )
@@ -12530,9 +13740,9 @@ async function link(argv) {
12530
13740
  if (flags2.host !== null) {
12531
13741
  host = flags2.host;
12532
13742
  } else {
12533
- intro(import_picocolors3.default.bgCyan(import_picocolors3.default.black(" argent link ")));
13743
+ intro(import_picocolors4.default.bgCyan(import_picocolors4.default.black(" argent link ")));
12534
13744
  if (existing) {
12535
- log.info(`Current link: ${import_picocolors3.default.cyan(existing.url)} (${existing.createdAt})`);
13745
+ log.info(`Current link: ${import_picocolors4.default.cyan(existing.url)} (${existing.createdAt})`);
12536
13746
  }
12537
13747
  host = await promptHost(existing);
12538
13748
  }
@@ -12548,12 +13758,12 @@ async function link(argv) {
12548
13758
  let url = flags2.url ?? formatUrl(host, port);
12549
13759
  if (!flags2.yes && existing) {
12550
13760
  if (existing.url === url) {
12551
- log.info(`Already linked to ${import_picocolors3.default.cyan(url)}.`);
13761
+ log.info(`Already linked to ${import_picocolors4.default.cyan(url)}.`);
12552
13762
  outro("No changes.");
12553
13763
  return;
12554
13764
  }
12555
13765
  const overwrite = await confirm({
12556
- message: `Replace existing link ${import_picocolors3.default.dim(existing.url)} with ${import_picocolors3.default.cyan(url)}?`,
13766
+ message: `Replace existing link ${import_picocolors4.default.dim(existing.url)} with ${import_picocolors4.default.cyan(url)}?`,
12557
13767
  initialValue: true
12558
13768
  });
12559
13769
  if (isCancel(overwrite) || !overwrite) {
@@ -12571,10 +13781,10 @@ async function link(argv) {
12571
13781
  }
12572
13782
  const result = await preflightHealth(url, token);
12573
13783
  if (result.ok) {
12574
- if (spinner2) spinner2.stop(import_picocolors3.default.green("Tool-server reachable."));
13784
+ if (spinner2) spinner2.stop(import_picocolors4.default.green("Tool-server reachable."));
12575
13785
  break;
12576
13786
  }
12577
- if (spinner2) spinner2.stop(import_picocolors3.default.red("Verification failed."));
13787
+ if (spinner2) spinner2.stop(import_picocolors4.default.red("Verification failed."));
12578
13788
  const detail = result.error ? ` (${result.error})` : "";
12579
13789
  if (flags2.yes) {
12580
13790
  console.error(
@@ -12614,15 +13824,15 @@ async function link(argv) {
12614
13824
  };
12615
13825
  await writeLinkConfig(cfg);
12616
13826
  if (existing && existing.url !== url) {
12617
- console.log(`${import_picocolors3.default.green("\u2713")} Link updated: ${import_picocolors3.default.dim(existing.url)} \u2192 ${import_picocolors3.default.cyan(url)}`);
13827
+ console.log(`${import_picocolors4.default.green("\u2713")} Link updated: ${import_picocolors4.default.dim(existing.url)} \u2192 ${import_picocolors4.default.cyan(url)}`);
12618
13828
  } else {
12619
- console.log(`${import_picocolors3.default.green("\u2713")} Linked: ${import_picocolors3.default.cyan(url)}`);
13829
+ console.log(`${import_picocolors4.default.green("\u2713")} Linked: ${import_picocolors4.default.cyan(url)}`);
12620
13830
  }
12621
- if (token) console.log(import_picocolors3.default.dim(" auth: token stored in ~/.argent/link.json (0600)"));
13831
+ if (token) console.log(import_picocolors4.default.dim(" auth: token stored in ~/.argent/link.json (0600)"));
12622
13832
  printSecurityCaveat(host, token, url);
12623
13833
  if (process.env.ARGENT_TOOLS_URL) {
12624
13834
  console.log(
12625
- import_picocolors3.default.yellow(
13835
+ import_picocolors4.default.yellow(
12626
13836
  `Note: ARGENT_TOOLS_URL=${process.env.ARGENT_TOOLS_URL} is set in your environment and takes precedence over the link.`
12627
13837
  )
12628
13838
  );
@@ -12653,7 +13863,7 @@ async function unlink3(argv) {
12653
13863
  }
12654
13864
  if (!flags2.yes) {
12655
13865
  const confirmed = await confirm({
12656
- message: `Remove link to ${import_picocolors3.default.cyan(existing.url)}?`,
13866
+ message: `Remove link to ${import_picocolors4.default.cyan(existing.url)}?`,
12657
13867
  initialValue: true
12658
13868
  });
12659
13869
  if (isCancel(confirmed) || !confirmed) {
@@ -12662,10 +13872,10 @@ async function unlink3(argv) {
12662
13872
  }
12663
13873
  }
12664
13874
  await clearLinkConfig();
12665
- console.log(`${import_picocolors3.default.green("\u2713")} Unlinked from ${import_picocolors3.default.dim(existing.url)}.`);
13875
+ console.log(`${import_picocolors4.default.green("\u2713")} Unlinked from ${import_picocolors4.default.dim(existing.url)}.`);
12666
13876
  if (process.env.ARGENT_TOOLS_URL) {
12667
13877
  console.log(
12668
- import_picocolors3.default.yellow(
13878
+ import_picocolors4.default.yellow(
12669
13879
  `The env var ARGENT_TOOLS_URL is also set in your shell (=${process.env.ARGENT_TOOLS_URL}) and takes precedence \u2014 unset it manually if you want fully local behaviour.`
12670
13880
  )
12671
13881
  );
@@ -12674,13 +13884,13 @@ async function unlink3(argv) {
12674
13884
  }
12675
13885
 
12676
13886
  // ../argent-cli/src/telemetry.ts
12677
- var import_picocolors4 = __toESM(require_picocolors(), 1);
13887
+ var import_picocolors5 = __toESM(require_picocolors(), 1);
12678
13888
  async function telemetry(args) {
12679
13889
  const sub = args[0];
12680
13890
  init("cli");
12681
13891
  switch (sub) {
12682
13892
  case void 0:
12683
- printUsage2();
13893
+ printUsage3();
12684
13894
  await shutdown();
12685
13895
  return;
12686
13896
  case "status":
@@ -12695,7 +13905,7 @@ async function telemetry(args) {
12695
13905
  return;
12696
13906
  case "--help":
12697
13907
  case "-h":
12698
- printUsage2();
13908
+ printUsage3();
12699
13909
  await shutdown();
12700
13910
  return;
12701
13911
  default:
@@ -12704,7 +13914,7 @@ async function telemetry(args) {
12704
13914
  process.exit(1);
12705
13915
  }
12706
13916
  }
12707
- function printUsage2() {
13917
+ function printUsage3() {
12708
13918
  console.log(`Usage:
12709
13919
  argent telemetry status Show telemetry state and device id
12710
13920
  argent telemetry enable Enable telemetry
@@ -12722,21 +13932,21 @@ async function cmdEnable() {
12722
13932
  const wasEnabled = isEnabled();
12723
13933
  markEnabled();
12724
13934
  if (wasEnabled) {
12725
- console.log(import_picocolors4.default.dim("Telemetry was already enabled."));
13935
+ console.log(import_picocolors5.default.dim("Telemetry was already enabled."));
12726
13936
  } else {
12727
- console.log(import_picocolors4.default.green("Telemetry enabled."));
13937
+ console.log(import_picocolors5.default.green("Telemetry enabled."));
12728
13938
  }
12729
13939
  await shutdown();
12730
13940
  }
12731
13941
  async function cmdDisable() {
12732
13942
  const wasEnabled = isEnabled();
12733
13943
  if (!wasEnabled) {
12734
- console.log(import_picocolors4.default.dim("Telemetry was already disabled."));
13944
+ console.log(import_picocolors5.default.dim("Telemetry was already disabled."));
12735
13945
  await shutdown();
12736
13946
  return;
12737
13947
  }
12738
13948
  await markDisabled();
12739
- console.log(import_picocolors4.default.red("Telemetry disabled."));
13949
+ console.log(import_picocolors5.default.red("Telemetry disabled."));
12740
13950
  await shutdown();
12741
13951
  }
12742
13952
  export {
@@ -12751,6 +13961,7 @@ export {
12751
13961
  lens,
12752
13962
  link,
12753
13963
  run,
13964
+ secrets,
12754
13965
  server,
12755
13966
  telemetry,
12756
13967
  tools,