@evident-ai/cli 3.1.1-dev.691c8d0 → 3.1.1-dev.6a74c3d

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/index.js CHANGED
@@ -11,8 +11,8 @@ import chalk2 from "chalk";
11
11
 
12
12
  // src/lib/config.ts
13
13
  import Conf from "conf";
14
- import { homedir } from "os";
15
- import { join } from "path";
14
+ import { chmodSync, existsSync, statSync } from "fs";
15
+ import { dirname } from "path";
16
16
  var PRODUCTION_API_URL = "https://api.production.evident.run/v1";
17
17
  var PRODUCTION_TUNNEL_URL = "wss://tunnel.production.evident.run";
18
18
  var defaults = {
@@ -47,8 +47,35 @@ var credentials = new Conf({
47
47
  projectName: "evident",
48
48
  projectSuffix: "",
49
49
  configName: "credentials",
50
- defaults: {}
50
+ defaults: {},
51
+ configFileMode: 384
51
52
  });
53
+ var CREDENTIALS_FILE_MODE = 384;
54
+ var CREDENTIALS_DIR_MODE = 448;
55
+ var permissionWarningEmitted = false;
56
+ function hardenCredentialsPermissions() {
57
+ if (process.platform === "win32") {
58
+ return;
59
+ }
60
+ const file = credentials.path;
61
+ for (const [path, mode] of [
62
+ [file, CREDENTIALS_FILE_MODE],
63
+ [dirname(file), CREDENTIALS_DIR_MODE]
64
+ ]) {
65
+ try {
66
+ if (existsSync(path) && (statSync(path).mode & 511) !== mode) {
67
+ chmodSync(path, mode);
68
+ }
69
+ } catch (err) {
70
+ if (!permissionWarningEmitted) {
71
+ permissionWarningEmitted = true;
72
+ console.error(
73
+ `[config] could not restrict permissions on ${path}; the credentials file may be readable by other users on this machine: ${err instanceof Error ? err.message : String(err)}`
74
+ );
75
+ }
76
+ }
77
+ }
78
+ }
52
79
  function getApiUrlConfig() {
53
80
  return getApiUrl();
54
81
  }
@@ -59,6 +86,7 @@ function credentialsKey() {
59
86
  return getApiUrl();
60
87
  }
61
88
  function getCredentials() {
89
+ hardenCredentialsPermissions();
62
90
  const byEndpoint = credentials.get("byEndpoint") ?? {};
63
91
  return byEndpoint[credentialsKey()] ?? {};
64
92
  }
@@ -70,14 +98,17 @@ function setCredentials(creds) {
70
98
  expiresAt: creds.expiresAt
71
99
  };
72
100
  credentials.set("byEndpoint", byEndpoint);
101
+ hardenCredentialsPermissions();
73
102
  }
74
103
  function clearCredentials() {
75
104
  const byEndpoint = credentials.get("byEndpoint") ?? {};
76
105
  delete byEndpoint[credentialsKey()];
77
106
  credentials.set("byEndpoint", byEndpoint);
107
+ hardenCredentialsPermissions();
78
108
  }
79
109
  function clearAllCredentials() {
80
110
  credentials.clear();
111
+ hardenCredentialsPermissions();
81
112
  }
82
113
  function getCliName() {
83
114
  const argv1 = process.argv[1] || "";
@@ -285,14 +316,14 @@ function blank() {
285
316
  console.log();
286
317
  }
287
318
  function waitForEnter(prompt = "Press Enter to continue...") {
288
- return new Promise((resolve2) => {
319
+ return new Promise((resolve3) => {
289
320
  process.stdout.write(chalk.dim(prompt));
290
321
  const handler = () => {
291
322
  process.stdin.removeListener("data", handler);
292
323
  process.stdin.setRawMode?.(false);
293
324
  process.stdin.pause();
294
325
  console.log();
295
- resolve2();
326
+ resolve3();
296
327
  };
297
328
  if (process.stdin.isTTY) {
298
329
  process.stdin.setRawMode?.(true);
@@ -302,7 +333,7 @@ function waitForEnter(prompt = "Press Enter to continue...") {
302
333
  });
303
334
  }
304
335
  function sleep(ms) {
305
- return new Promise((resolve2) => setTimeout(resolve2, ms));
336
+ return new Promise((resolve3) => setTimeout(resolve3, ms));
306
337
  }
307
338
 
308
339
  // src/commands/login.ts
@@ -373,22 +404,23 @@ async function deviceFlowLogin(options) {
373
404
  }
374
405
  async function tokenLogin() {
375
406
  console.log("Token login mode.");
376
- console.log("Visit your Evident dashboard to generate a CLI token.");
407
+ console.log("Run `evident login` on a machine with a browser to get a token.");
408
+ console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
377
409
  blank();
378
410
  process.stdout.write("Paste token: ");
379
- const token = await new Promise((resolve2) => {
411
+ const token = await new Promise((resolve3) => {
380
412
  let data = "";
381
413
  process.stdin.setEncoding("utf8");
382
414
  process.stdin.on("data", (chunk) => {
383
415
  data += chunk;
384
416
  });
385
417
  process.stdin.on("end", () => {
386
- resolve2(data.trim());
418
+ resolve3(data.trim());
387
419
  });
388
420
  if (process.stdin.isTTY) {
389
421
  process.stdin.once("data", (chunk) => {
390
422
  process.stdin.pause();
391
- resolve2(chunk.toString().trim());
423
+ resolve3(chunk.toString().trim());
392
424
  });
393
425
  process.stdin.resume();
394
426
  }
@@ -467,9 +499,9 @@ async function whoami() {
467
499
  }
468
500
 
469
501
  // src/commands/run.ts
502
+ import { homedir as homedir2 } from "os";
503
+ import { isAbsolute as isAbsolute2, join as join2, parse, resolve as resolvePath } from "path";
470
504
  import chalk6 from "chalk";
471
- import ora3 from "ora";
472
- import { select as select3 } from "@inquirer/prompts";
473
505
 
474
506
  // ../../packages/types/src/telemetry/index.ts
475
507
  var TelemetryEventTypes = {
@@ -485,6 +517,10 @@ var TelemetryEventTypes = {
485
517
  var MAX_FRAME_BYTES = 256 * 1024;
486
518
  var TUNNEL_DRAIN_PING_PATH = "/__evident/drain";
487
519
 
520
+ // ../../packages/types/src/runner-files.ts
521
+ var MAX_FILE_PUSH_BYTES = 64 * 1024;
522
+ var MAX_FILE_SYNC_DIRECTORIES = 16;
523
+
488
524
  // ../../packages/types/src/logging/index.ts
489
525
  var CORRELATION_ID_HEADER = "x-evident-correlation-id";
490
526
  function log(level, event, fields) {
@@ -514,6 +550,10 @@ function stripQuery(url) {
514
550
  }
515
551
  }
516
552
 
553
+ // src/commands/run.ts
554
+ import ora3 from "ora";
555
+ import { select as select3 } from "@inquirer/prompts";
556
+
517
557
  // src/lib/telemetry.ts
518
558
  var CLI_VERSION = (true ? "3.0.0" : void 0) ?? process.env.npm_package_version ?? "unknown";
519
559
  function getCliVersion() {
@@ -725,7 +765,7 @@ async function waitForOpenCodeHealth(port, timeoutMs = 3e4) {
725
765
  if (health.healthy) {
726
766
  return health;
727
767
  }
728
- await new Promise((resolve2) => setTimeout(resolve2, 1e3));
768
+ await new Promise((resolve3) => setTimeout(resolve3, 1e3));
729
769
  }
730
770
  return { healthy: false, error: "Timeout waiting for OpenCode to be healthy" };
731
771
  }
@@ -1364,7 +1404,7 @@ async function sendPromptAsync(port, sessionId, content, options, attachments) {
1364
1404
  }
1365
1405
  }
1366
1406
  if (attempt < READ_BACK_ATTEMPTS - 1) {
1367
- await new Promise((resolve2) => setTimeout(resolve2, READ_BACK_DELAY_MS));
1407
+ await new Promise((resolve3) => setTimeout(resolve3, READ_BACK_DELAY_MS));
1368
1408
  }
1369
1409
  }
1370
1410
  return null;
@@ -1738,12 +1778,12 @@ var StreamForwarder = class {
1738
1778
  let endBody;
1739
1779
  if (has_body) {
1740
1780
  const chunks = [];
1741
- bodyPromise = new Promise((resolve2) => {
1781
+ bodyPromise = new Promise((resolve3) => {
1742
1782
  pushBody = (buf) => {
1743
1783
  chunks.push(buf);
1744
1784
  };
1745
1785
  endBody = () => {
1746
- resolve2(Buffer.concat(chunks));
1786
+ resolve3(Buffer.concat(chunks));
1747
1787
  };
1748
1788
  });
1749
1789
  }
@@ -1860,7 +1900,7 @@ function connectTunnel(options) {
1860
1900
  } = options;
1861
1901
  const tunnelUrl = getTunnelUrlConfig();
1862
1902
  const url = `${tunnelUrl}/tunnel/${agentId}/connect`;
1863
- return new Promise((resolve2, reject) => {
1903
+ return new Promise((resolve3, reject) => {
1864
1904
  const ws = new WebSocket2(url, {
1865
1905
  headers: {
1866
1906
  Authorization: authHeader
@@ -1915,7 +1955,7 @@ function connectTunnel(options) {
1915
1955
  clearTimeout(connectionTimeout);
1916
1956
  const connectedAgentId = message.agent_id ?? agentId;
1917
1957
  onConnected?.(connectedAgentId);
1918
- resolve2({
1958
+ resolve3({
1919
1959
  ws,
1920
1960
  close: () => ws.close(1e3, "CLI shutdown")
1921
1961
  });
@@ -2033,6 +2073,404 @@ var RunnerConnection = class {
2033
2073
  }
2034
2074
  };
2035
2075
 
2076
+ // src/lib/channels/driver.ts
2077
+ import { homedir } from "os";
2078
+
2079
+ // src/lib/file-push.ts
2080
+ import { randomUUID } from "crypto";
2081
+ import { chmod, mkdir, open as open2, realpath, rename, unlink } from "fs/promises";
2082
+ import { basename, dirname as dirname2, isAbsolute, join, relative, resolve as resolve2, sep } from "path";
2083
+ var FILE_MODE = 384;
2084
+ var DIRECTORY_MODE = 448;
2085
+ async function writePushedFile(request) {
2086
+ const { requestedPath, content, allowedDirectories, homeDir } = request;
2087
+ const bytes = content.byteLength;
2088
+ if (allowedDirectories.length === 0) {
2089
+ return refuse("file_sync_disabled", "File sync is not enabled on this runner.", {
2090
+ path: requestedPath,
2091
+ bytes
2092
+ });
2093
+ }
2094
+ if (bytes > MAX_FILE_PUSH_BYTES) {
2095
+ return refuse(
2096
+ "file_too_large",
2097
+ `File is ${bytes} bytes; the limit is ${MAX_FILE_PUSH_BYTES}.`,
2098
+ {
2099
+ path: requestedPath,
2100
+ bytes
2101
+ }
2102
+ );
2103
+ }
2104
+ const candidate = expandAndValidate(requestedPath, homeDir);
2105
+ if (candidate === null) {
2106
+ return refuse("invalid_path", "The requested path is not a valid absolute file path.", {
2107
+ path: requestedPath,
2108
+ bytes
2109
+ });
2110
+ }
2111
+ try {
2112
+ const { existingAncestor, missingSegments } = await resolveNearestExistingAncestor(
2113
+ dirname2(candidate)
2114
+ );
2115
+ const realTarget = join(existingAncestor, ...missingSegments, basename(candidate));
2116
+ const allowedDirectory = await findContainingAllowedDirectory(allowedDirectories, realTarget);
2117
+ if (allowedDirectory === null) {
2118
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2119
+ path: realTarget,
2120
+ bytes
2121
+ });
2122
+ }
2123
+ if (missingSegments.length > 0) {
2124
+ await createMissingDirectories(existingAncestor, missingSegments);
2125
+ const realParent = await realpath(dirname2(realTarget));
2126
+ if (realParent !== dirname2(realTarget) || !contains(allowedDirectory, realTarget)) {
2127
+ return refuse("path_not_allowed", "The runner does not allow writing to that location.", {
2128
+ path: realTarget,
2129
+ bytes,
2130
+ reason: "parent_changed_after_create"
2131
+ });
2132
+ }
2133
+ }
2134
+ await writeAtomically(realTarget, content);
2135
+ log("info", "file_push_written", { path: realTarget, bytes });
2136
+ return { ok: true, path: realTarget };
2137
+ } catch (err) {
2138
+ const errno = err.code ?? "UNKNOWN";
2139
+ return refuse("write_failed", `The runner could not write the file (${errno}).`, {
2140
+ path: candidate,
2141
+ bytes,
2142
+ errno,
2143
+ ...errorFields(err)
2144
+ });
2145
+ }
2146
+ }
2147
+ function expandAndValidate(requestedPath, homeDir) {
2148
+ if (requestedPath.trim() === "" || requestedPath.includes("\0")) {
2149
+ return null;
2150
+ }
2151
+ const expanded = requestedPath === "~" ? homeDir : requestedPath.startsWith("~/") ? join(homeDir, requestedPath.slice(2)) : requestedPath;
2152
+ if (expanded.split(/[/\\]/).includes("..")) {
2153
+ return null;
2154
+ }
2155
+ if (!isAbsolute(expanded)) {
2156
+ return null;
2157
+ }
2158
+ const candidate = resolve2(expanded);
2159
+ const name = basename(candidate);
2160
+ return name === "" || name === "." || name === ".." ? null : candidate;
2161
+ }
2162
+ async function resolveNearestExistingAncestor(directory) {
2163
+ const missingSegments = [];
2164
+ let current = directory;
2165
+ for (; ; ) {
2166
+ try {
2167
+ return { existingAncestor: await realpath(current), missingSegments };
2168
+ } catch (err) {
2169
+ const parent = dirname2(current);
2170
+ if (err.code !== "ENOENT" || parent === current) {
2171
+ throw err;
2172
+ }
2173
+ missingSegments.unshift(basename(current));
2174
+ current = parent;
2175
+ }
2176
+ }
2177
+ }
2178
+ async function findContainingAllowedDirectory(allowedDirectories, realTarget) {
2179
+ for (const directory of allowedDirectories) {
2180
+ if (!isAbsolute(directory)) {
2181
+ log("warn", "file_push_allowed_directory_skipped", { directory, reason: "not_absolute" });
2182
+ continue;
2183
+ }
2184
+ const realDirectory = await realpathCreatingIfMissing(directory);
2185
+ if (realDirectory !== null && contains(realDirectory, realTarget)) {
2186
+ return realDirectory;
2187
+ }
2188
+ }
2189
+ return null;
2190
+ }
2191
+ async function realpathCreatingIfMissing(directory) {
2192
+ try {
2193
+ return await realpath(directory);
2194
+ } catch (err) {
2195
+ if (err.code !== "ENOENT") {
2196
+ log("warn", "file_push_allowed_directory_skipped", {
2197
+ directory,
2198
+ reason: "unresolvable",
2199
+ ...errorFields(err)
2200
+ });
2201
+ return null;
2202
+ }
2203
+ }
2204
+ try {
2205
+ await mkdir(directory, { recursive: true, mode: DIRECTORY_MODE });
2206
+ await chmod(directory, DIRECTORY_MODE);
2207
+ return await realpath(directory);
2208
+ } catch (err) {
2209
+ log("warn", "file_push_allowed_directory_skipped", {
2210
+ directory,
2211
+ reason: "create_failed",
2212
+ ...errorFields(err)
2213
+ });
2214
+ return null;
2215
+ }
2216
+ }
2217
+ function contains(realDirectory, realTarget) {
2218
+ const rel = relative(realDirectory, realTarget);
2219
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
2220
+ }
2221
+ async function createMissingDirectories(existingAncestor, missingSegments) {
2222
+ let current = existingAncestor;
2223
+ for (const segment of missingSegments) {
2224
+ current = join(current, segment);
2225
+ await mkdir(current, { recursive: true, mode: DIRECTORY_MODE });
2226
+ await chmod(current, DIRECTORY_MODE);
2227
+ }
2228
+ }
2229
+ async function writeAtomically(realTarget, content) {
2230
+ const temporaryPath = join(dirname2(realTarget), `.evident-push-${randomUUID()}.tmp`);
2231
+ let handle;
2232
+ try {
2233
+ handle = await open2(temporaryPath, "wx", FILE_MODE);
2234
+ await handle.writeFile(content);
2235
+ await handle.chmod(FILE_MODE);
2236
+ await handle.close();
2237
+ handle = void 0;
2238
+ await rename(temporaryPath, realTarget);
2239
+ } catch (err) {
2240
+ await discardTemporaryFile(temporaryPath, handle);
2241
+ throw err;
2242
+ }
2243
+ }
2244
+ async function discardTemporaryFile(temporaryPath, handle) {
2245
+ try {
2246
+ await handle?.close();
2247
+ } catch (err) {
2248
+ log("warn", "file_push_temp_close_failed", { path: temporaryPath, ...errorFields(err) });
2249
+ }
2250
+ try {
2251
+ await unlink(temporaryPath);
2252
+ } catch (err) {
2253
+ const errno = err.code;
2254
+ if (errno !== "ENOENT" && errno !== "ENOTDIR") {
2255
+ log("warn", "file_push_temp_cleanup_failed", { path: temporaryPath, ...errorFields(err) });
2256
+ }
2257
+ }
2258
+ }
2259
+ function refuse(code, message, fields) {
2260
+ log(code === "write_failed" ? "error" : "warn", "file_push_refused", { code, ...fields });
2261
+ return { ok: false, code, message };
2262
+ }
2263
+
2264
+ // src/lib/runner-file-sync.ts
2265
+ var MAX_ACK_ATTEMPTS = 5;
2266
+ async function syncPendingRunnerFiles(options) {
2267
+ const pending = await listPendingFiles(options);
2268
+ const pendingIds = new Set(pending.map((file) => file.id));
2269
+ for (const id of options.ackFailures.keys()) {
2270
+ if (!pendingIds.has(id)) options.ackFailures.delete(id);
2271
+ }
2272
+ if (pending.length === 0) return 0;
2273
+ options.log({
2274
+ level: "info",
2275
+ message: `Runner file sync: ${pending.length} file(s) queued for this runner`
2276
+ });
2277
+ let applied = 0;
2278
+ for (const file of pending) {
2279
+ if ((options.ackFailures.get(file.id) ?? 0) >= MAX_ACK_ATTEMPTS) continue;
2280
+ if (await applyOne(options, file)) applied += 1;
2281
+ }
2282
+ return applied;
2283
+ }
2284
+ async function listPendingFiles(options) {
2285
+ let res;
2286
+ try {
2287
+ res = await options.fetchImpl(`${options.apiUrl}/runners/${options.agentId}/files/pending`, {
2288
+ headers: { Authorization: options.getAuthHeader() }
2289
+ });
2290
+ } catch (err) {
2291
+ options.log({
2292
+ level: "warn",
2293
+ message: `Could not list pending runner files \u2014 retrying on the next drain: ${describe(err)}`
2294
+ });
2295
+ return [];
2296
+ }
2297
+ if (!res.ok) {
2298
+ options.log({
2299
+ level: res.status === 404 ? "debug" : "warn",
2300
+ message: `Listing pending runner files returned HTTP ${res.status} \u2014 retrying on the next drain`
2301
+ });
2302
+ return [];
2303
+ }
2304
+ let body;
2305
+ try {
2306
+ body = await res.json();
2307
+ } catch (err) {
2308
+ options.log({
2309
+ level: "warn",
2310
+ message: `Pending runner file list was not readable JSON \u2014 retrying on the next drain: ${describe(err)}`
2311
+ });
2312
+ return [];
2313
+ }
2314
+ if (!Array.isArray(body)) {
2315
+ options.log({
2316
+ level: "warn",
2317
+ message: "Pending runner file list was not an array \u2014 ignoring it for this drain"
2318
+ });
2319
+ return [];
2320
+ }
2321
+ const files = [];
2322
+ for (const entry of body) {
2323
+ const file = asPendingFile(entry);
2324
+ if (file === null) {
2325
+ options.log({
2326
+ level: "warn",
2327
+ message: "Ignoring a malformed pending runner file entry (expected id, path and size)"
2328
+ });
2329
+ continue;
2330
+ }
2331
+ files.push(file);
2332
+ }
2333
+ return files;
2334
+ }
2335
+ function asPendingFile(entry) {
2336
+ if (entry === null || typeof entry !== "object") return null;
2337
+ const { id, path, size } = entry;
2338
+ if (typeof id !== "string" || id === "") return null;
2339
+ if (typeof path !== "string" || path === "") return null;
2340
+ if (typeof size !== "number" || !Number.isFinite(size) || size < 0) return null;
2341
+ return { id, path, size };
2342
+ }
2343
+ async function applyOne(options, file) {
2344
+ const label = `${file.id.slice(0, 8)} (${file.path})`;
2345
+ if (options.allowedDirectories.length === 0) {
2346
+ options.log({
2347
+ level: "warn",
2348
+ message: `Runner file ${label} rejected: file sync is not enabled on this runner (start it with --enable-file-sync-to)`
2349
+ });
2350
+ await ack(options, file, "rejected", "file_sync_disabled");
2351
+ return false;
2352
+ }
2353
+ if (file.size > MAX_FILE_PUSH_BYTES) {
2354
+ options.log({
2355
+ level: "warn",
2356
+ message: `Runner file ${label} rejected: declared ${file.size} bytes, the limit is ${MAX_FILE_PUSH_BYTES}`
2357
+ });
2358
+ await ack(options, file, "rejected", "file_too_large");
2359
+ return false;
2360
+ }
2361
+ const download = await downloadContent(options, file, label);
2362
+ if (!download.ok) {
2363
+ if (download.terminal) await ack(options, file, "rejected", download.code);
2364
+ return false;
2365
+ }
2366
+ let outcome;
2367
+ try {
2368
+ outcome = await writePushedFile({
2369
+ requestedPath: file.path,
2370
+ content: download.content,
2371
+ allowedDirectories: options.allowedDirectories,
2372
+ homeDir: options.homeDir
2373
+ });
2374
+ } catch (err) {
2375
+ options.log({
2376
+ level: "error",
2377
+ message: `Runner file ${label} could not be written: ${describe(err)}`
2378
+ });
2379
+ await ack(options, file, "rejected", "write_failed");
2380
+ return false;
2381
+ }
2382
+ if (!outcome.ok) {
2383
+ options.log({
2384
+ level: "warn",
2385
+ message: `Runner file ${label} rejected (${outcome.code}): ${outcome.message}`
2386
+ });
2387
+ await ack(options, file, "rejected", outcome.code);
2388
+ return false;
2389
+ }
2390
+ options.log({
2391
+ level: "info",
2392
+ message: `Runner file ${label} applied (${download.content.byteLength} bytes)`
2393
+ });
2394
+ await ack(options, file, "applied");
2395
+ return true;
2396
+ }
2397
+ function durableDownloadCode(status) {
2398
+ return status === 413 ? "file_too_large" : "write_failed";
2399
+ }
2400
+ async function downloadContent(options, file, label) {
2401
+ try {
2402
+ const res = await options.fetchImpl(
2403
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/content`,
2404
+ { headers: { Authorization: options.getAuthHeader() } }
2405
+ );
2406
+ if (!res.ok) {
2407
+ const terminal = res.status >= 400 && res.status < 500 && res.status !== 401 && res.status !== 403 && res.status !== 408 && res.status !== 429;
2408
+ if (!terminal) {
2409
+ options.log({
2410
+ level: "warn",
2411
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 retrying on the next drain`
2412
+ });
2413
+ return { ok: false, terminal: false };
2414
+ }
2415
+ const code = durableDownloadCode(res.status);
2416
+ options.log({
2417
+ level: "error",
2418
+ message: `Downloading runner file ${label} returned HTTP ${res.status} \u2014 rejecting it as ${code} (the bytes never reached the writer)`
2419
+ });
2420
+ return { ok: false, terminal: true, code };
2421
+ }
2422
+ return { ok: true, content: Buffer.from(await res.arrayBuffer()) };
2423
+ } catch (err) {
2424
+ options.log({
2425
+ level: "warn",
2426
+ message: `Downloading runner file ${label} failed \u2014 retrying on the next drain: ${describe(err)}`
2427
+ });
2428
+ return { ok: false, terminal: false };
2429
+ }
2430
+ }
2431
+ async function ack(options, file, status, reason) {
2432
+ const outcome = `${status}${reason ? ` (${reason})` : ""}`;
2433
+ try {
2434
+ const res = await options.fetchImpl(
2435
+ `${options.apiUrl}/runners/${options.agentId}/files/${file.id}/ack`,
2436
+ {
2437
+ method: "POST",
2438
+ headers: {
2439
+ Authorization: options.getAuthHeader(),
2440
+ "Content-Type": "application/json"
2441
+ },
2442
+ body: JSON.stringify(reason ? { status, reason } : { status })
2443
+ }
2444
+ );
2445
+ if (!res.ok) {
2446
+ recordAckFailure(
2447
+ options,
2448
+ file,
2449
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} returned HTTP ${res.status}`
2450
+ );
2451
+ return;
2452
+ }
2453
+ options.ackFailures.delete(file.id);
2454
+ } catch (err) {
2455
+ recordAckFailure(
2456
+ options,
2457
+ file,
2458
+ `Acking runner file ${file.id.slice(0, 8)} as ${outcome} failed: ${describe(err)}`
2459
+ );
2460
+ }
2461
+ }
2462
+ function recordAckFailure(options, file, what) {
2463
+ const attempts = (options.ackFailures.get(file.id) ?? 0) + 1;
2464
+ options.ackFailures.set(file.id, attempts);
2465
+ options.log({
2466
+ level: "error",
2467
+ message: attempts >= MAX_ACK_ATTEMPTS ? `${what} \u2014 giving up after ${attempts} attempts. It stays pending until the server expires it; restart the runner to retry.` : `${what} \u2014 it stays pending until a later drain re-acks it (attempt ${attempts} of ${MAX_ACK_ATTEMPTS})`
2468
+ });
2469
+ }
2470
+ function describe(err) {
2471
+ return err instanceof Error ? err.message : String(err);
2472
+ }
2473
+
2036
2474
  // src/lib/channels/driver.ts
2037
2475
  function messageIdOf(m) {
2038
2476
  if (!m || typeof m !== "object") return void 0;
@@ -2099,6 +2537,8 @@ var ChannelDriver = class _ChannelDriver {
2099
2537
  pausedMaxWaitMs;
2100
2538
  stuckQueuedMs;
2101
2539
  now;
2540
+ fileSyncDirectories;
2541
+ homeDir;
2102
2542
  /** Cache of conversationId → opencode sessionId. */
2103
2543
  sessions = /* @__PURE__ */ new Map();
2104
2544
  /**
@@ -2251,6 +2691,24 @@ var ChannelDriver = class _ChannelDriver {
2251
2691
  sessionTitles = /* @__PURE__ */ new Map();
2252
2692
  /** Serialises drains so a reconnect during a drain doesn't double-process. */
2253
2693
  draining = false;
2694
+ /**
2695
+ * Serialises runner-file syncs (#559) so the ~2s poll tick and a concurrent
2696
+ * drain ping don't download, write and ack the same file twice.
2697
+ */
2698
+ syncingFiles = false;
2699
+ /**
2700
+ * Consecutive failed acks per pending file (#559). Lives on the driver so it
2701
+ * survives across drains — without it, a file whose ack keeps failing is
2702
+ * re-downloaded and re-written every ~2s until the server expires it.
2703
+ */
2704
+ fileAckFailures = /* @__PURE__ */ new Map();
2705
+ /**
2706
+ * Monotonic count of files this runner has pulled and written (#559). Only
2707
+ * ever increases, so `run.ts` detects work by comparing it against the value
2708
+ * it saw on the previous cycle — including work that landed mid-sleep, the
2709
+ * same trick `lastProxiedActivityAt` uses.
2710
+ */
2711
+ appliedFileCount = 0;
2254
2712
  /**
2255
2713
  * The currently-executing `drainPending()` promise, or null when idle. Lets a
2256
2714
  * graceful shutdown (`waitForInFlight`) await an in-progress drain so a turn it
@@ -2281,6 +2739,8 @@ var ChannelDriver = class _ChannelDriver {
2281
2739
  this.pausedMaxWaitMs = config2.pausedMaxWaitMs ?? DEFAULT_PAUSED_MAX_WAIT_MS;
2282
2740
  this.stuckQueuedMs = config2.stuckQueuedMs ?? DEFAULT_STUCK_QUEUED_MS;
2283
2741
  this.now = config2.now ?? (() => Date.now());
2742
+ this.fileSyncDirectories = config2.fileSyncDirectories ?? [];
2743
+ this.homeDir = config2.homeDir ?? homedir();
2284
2744
  }
2285
2745
  /** The IPv4-loopback base URL for the local `opencode serve`. */
2286
2746
  get opencodeBase() {
@@ -2308,6 +2768,47 @@ var ChannelDriver = class _ChannelDriver {
2308
2768
  );
2309
2769
  return run2;
2310
2770
  }
2771
+ /**
2772
+ * Pull-and-apply any files Evident has queued for this runner (#559), riding
2773
+ * the EXISTING drain cycle — `run.ts` calls it from the same ~2s channel poll
2774
+ * and drain ping that call `drainPending()`. There is deliberately no channel,
2775
+ * control frame or poll loop of its own: worst-case latency is one poll tick.
2776
+ *
2777
+ * NEVER throws and never surfaces a `ChannelAuthError`: a file failure must not
2778
+ * cost a conversation turn. Failures are logged and either acked as a terminal
2779
+ * outcome or left pending for the next drain (see `runner-file-sync.ts`).
2780
+ *
2781
+ * Re-entrant calls are skipped (the poll tick and a drain ping can overlap).
2782
+ *
2783
+ * @returns the number of files written to disk.
2784
+ */
2785
+ async syncPendingFiles() {
2786
+ if (this.stopped) return 0;
2787
+ if (this.syncingFiles) return 0;
2788
+ this.syncingFiles = true;
2789
+ try {
2790
+ const applied = await syncPendingRunnerFiles({
2791
+ agentId: this.agentId,
2792
+ apiUrl: this.apiUrl,
2793
+ getAuthHeader: this.getAuthHeader,
2794
+ fetchImpl: this.fetchImpl,
2795
+ allowedDirectories: this.fileSyncDirectories,
2796
+ homeDir: this.homeDir,
2797
+ ackFailures: this.fileAckFailures,
2798
+ log: this.log
2799
+ });
2800
+ this.appliedFileCount += applied;
2801
+ return applied;
2802
+ } catch (err) {
2803
+ this.log({
2804
+ level: "error",
2805
+ message: `Runner file sync failed unexpectedly (message processing is unaffected): ${err instanceof Error ? err.message : String(err)}`
2806
+ });
2807
+ return 0;
2808
+ } finally {
2809
+ this.syncingFiles = false;
2810
+ }
2811
+ }
2311
2812
  async runDrain() {
2312
2813
  let dispatched = 0;
2313
2814
  try {
@@ -2341,6 +2842,28 @@ var ChannelDriver = class _ChannelDriver {
2341
2842
  }
2342
2843
  return false;
2343
2844
  }
2845
+ /**
2846
+ * File-pull work, for `run.ts`'s idle accounting (#559).
2847
+ *
2848
+ * Pulling a file is real work that `drainPending()` knows nothing about, so
2849
+ * without this a near-idle runner counts a credential pull as an empty tick
2850
+ * and `--idle-timeout` can `process.exit` mid-pull — leaving a
2851
+ * `.evident-push-*.tmp` behind — or immediately after the write, before the
2852
+ * browser has run the authorize/callback that activates it (the user then sees
2853
+ * `saved_not_activated` for a runner that was fine).
2854
+ *
2855
+ * Two signals because one cannot cover both cases: `inFlight` is the pull
2856
+ * happening RIGHT NOW (it may outlive the tick that started it), and
2857
+ * `appliedFiles` is monotonic so a pull that started AND finished between two
2858
+ * idle checks still shows up as an advance.
2859
+ *
2860
+ * CALLER CONTRACT: sample `inFlight` BEFORE calling `syncPendingFiles()` for
2861
+ * the cycle. `syncPendingFiles` sets the flag synchronously, so a caller that
2862
+ * samples afterwards reads `true` every single cycle and can never idle out.
2863
+ */
2864
+ fileSyncActivity() {
2865
+ return { appliedFiles: this.appliedFileCount, inFlight: this.syncingFiles };
2866
+ }
2344
2867
  /**
2345
2868
  * OpenCode session ids the session-cleanup sweep (issue #190) must NOT delete:
2346
2869
  * exactly those with a live (dispatched-but-not-done / paused) turn, i.e. a
@@ -2402,7 +2925,7 @@ var ChannelDriver = class _ChannelDriver {
2402
2925
  await this.sleep(step);
2403
2926
  }
2404
2927
  }
2405
- while (this.hasInFlightWatchers()) {
2928
+ while (this.hasInFlightWatchers() || this.syncingFiles) {
2406
2929
  if (this.now() >= deadline) return false;
2407
2930
  await this.sleep(step);
2408
2931
  }
@@ -4608,6 +5131,34 @@ function resolveLogLevel(options) {
4608
5131
  }
4609
5132
  return "info";
4610
5133
  }
5134
+ function resolveFileSyncDirectories(raw, homeDir) {
5135
+ const directories = [];
5136
+ for (const entry of raw ?? []) {
5137
+ const trimmed = entry.trim();
5138
+ if (trimmed === "") {
5139
+ throw new Error("--enable-file-sync-to requires a directory path (got an empty value)");
5140
+ }
5141
+ const expanded = trimmed === "~" ? homeDir : trimmed.startsWith("~/") ? join2(homeDir, trimmed.slice(2)) : trimmed;
5142
+ if (!isAbsolute2(expanded)) {
5143
+ throw new Error(`--enable-file-sync-to requires an absolute directory path; got "${entry}"`);
5144
+ }
5145
+ const normalized = resolvePath(expanded);
5146
+ if (parse(normalized).root === normalized) {
5147
+ throw new Error(
5148
+ `--enable-file-sync-to will not allow-list the filesystem root ("${entry}"); name the specific directory the credentials belong in (for example ~/.claude)`
5149
+ );
5150
+ }
5151
+ if (!directories.includes(normalized)) {
5152
+ directories.push(normalized);
5153
+ }
5154
+ }
5155
+ if (directories.length > MAX_FILE_SYNC_DIRECTORIES) {
5156
+ throw new Error(
5157
+ `--enable-file-sync-to accepts at most ${MAX_FILE_SYNC_DIRECTORIES} directories; got ${directories.length}`
5158
+ );
5159
+ }
5160
+ return directories;
5161
+ }
4611
5162
  function meetsThreshold(state, level) {
4612
5163
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
4613
5164
  }
@@ -4729,18 +5280,29 @@ async function handleAuthError(state, error2) {
4729
5280
  async function driveChannels(state, driver) {
4730
5281
  let idlePolls = 0;
4731
5282
  let lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
5283
+ let lastSeenAppliedFiles = driver.fileSyncActivity().appliedFiles;
4732
5284
  while (state.running) {
4733
5285
  if (state.connection?.reconnecting && state.connection.reconnectPromise) {
4734
5286
  logActivity(state, { type: "info", message: "Waiting for tunnel reconnection..." });
4735
5287
  if (state.interactive) displayStatus(state);
4736
5288
  await state.connection.reconnectPromise;
4737
5289
  }
5290
+ const carriedOverFileSync = driver.fileSyncActivity().inFlight;
5291
+ void driver.syncPendingFiles().catch(
5292
+ (error2) => logActivity(state, {
5293
+ type: "error",
5294
+ error: `Runner file sync failed: ${error2 instanceof Error ? error2.message : String(error2)}`
5295
+ })
5296
+ );
4738
5297
  try {
4739
5298
  const processed = await driver.drainPending();
4740
5299
  state.messageCount += processed;
4741
5300
  const proxiedActivity = state.lastProxiedActivityAt !== lastSeenProxiedActivityAt;
4742
5301
  lastSeenProxiedActivityAt = state.lastProxiedActivityAt;
4743
- if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity) {
5302
+ const appliedFiles = driver.fileSyncActivity().appliedFiles;
5303
+ const fileActivity = carriedOverFileSync || appliedFiles !== lastSeenAppliedFiles;
5304
+ lastSeenAppliedFiles = appliedFiles;
5305
+ if (processed > 0 || driver.hasInFlightWatchers() || proxiedActivity || fileActivity) {
4744
5306
  idlePolls = 0;
4745
5307
  if (processed > 0 && state.interactive) displayStatus(state);
4746
5308
  } else if (state.idleTimeout !== null) {
@@ -4769,7 +5331,7 @@ async function driveChannels(state, driver) {
4769
5331
  logActivity(state, { type: "error", error: `Channel processing error: ${errorMessage}` });
4770
5332
  if (state.interactive) displayStatus(state);
4771
5333
  }
4772
- await new Promise((resolve2) => setTimeout(resolve2, CHANNEL_POLL_INTERVAL_MS));
5334
+ await new Promise((resolve3) => setTimeout(resolve3, CHANNEL_POLL_INTERVAL_MS));
4773
5335
  if (state.idleTimeout !== null && idlePolls >= 2) {
4774
5336
  const idleMs = idlePolls * CHANNEL_POLL_INTERVAL_MS;
4775
5337
  if (idleMs > state.idleTimeout * 1e3) {
@@ -4914,8 +5476,10 @@ async function cleanup(state, opts = {}) {
4914
5476
  async function run(options) {
4915
5477
  const interactive = isInteractive(options.json);
4916
5478
  let logLevel;
5479
+ let fileSyncDirectories;
4917
5480
  try {
4918
5481
  logLevel = resolveLogLevel(options);
5482
+ fileSyncDirectories = resolveFileSyncDirectories(options.enableFileSyncTo, homedir2());
4919
5483
  } catch (error2) {
4920
5484
  const message = error2 instanceof Error ? error2.message : String(error2);
4921
5485
  if (options.json) {
@@ -4950,6 +5514,11 @@ async function run(options) {
4950
5514
  sessionCleanupTimers: [],
4951
5515
  authHeader: ""
4952
5516
  };
5517
+ if (fileSyncDirectories.length > 0) {
5518
+ log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5519
+ } else {
5520
+ log2(state, "File sync is disabled (no --enable-file-sync-to given)", "debug");
5521
+ }
4953
5522
  if (!options.runner && options.agent) {
4954
5523
  telemetry.info(
4955
5524
  EventTypes.DEPRECATED_AGENT_FLAG_USED,
@@ -5142,6 +5711,10 @@ async function run(options) {
5142
5711
  getAuthHeader: () => state.authHeader,
5143
5712
  conversationFilter: state.conversationFilter,
5144
5713
  stuckQueuedMs: CHANNEL_STUCK_QUEUED_MS,
5714
+ // #559: the `--enable-file-sync-to` allow-list. Empty ⇒ pending files are
5715
+ // REJECTED with `file_sync_disabled` on the ack, not silently ignored.
5716
+ fileSyncDirectories,
5717
+ homeDir: homedir2(),
5145
5718
  log: (entry) => (
5146
5719
  // Thread the driver's real level straight through so `debug`/`warn`
5147
5720
  // survive the sink filter (they no longer collapse to info). `type`
@@ -5223,6 +5796,12 @@ async function run(options) {
5223
5796
  onDrainPing: () => {
5224
5797
  if (!state.running) return;
5225
5798
  logActivity(state, { type: "info", message: "Drain ping received \u2014 draining" });
5799
+ void channelDriver.syncPendingFiles().catch(
5800
+ (error2) => logActivity(state, {
5801
+ type: "error",
5802
+ error: `Runner file sync failed on ping: ${error2 instanceof Error ? error2.message : String(error2)}`
5803
+ })
5804
+ );
5226
5805
  channelDriver.drainPending().then((processed) => {
5227
5806
  if (processed > 0) {
5228
5807
  state.messageCount += processed;
@@ -5321,6 +5900,11 @@ program.command("run").description("Connect to Evident and process messages").op
5321
5900
  ).option(
5322
5901
  "--session-cleanup-interval <duration>",
5323
5902
  "How often the cleanup sweep runs (default: 1h). Env: EVIDENT_SESSION_CLEANUP_INTERVAL"
5903
+ ).option(
5904
+ "--enable-file-sync-to <dir>",
5905
+ "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
5906
+ (value, previous) => previous.concat([value]),
5907
+ []
5324
5908
  ).action(
5325
5909
  (options) => {
5326
5910
  run({
@@ -5337,7 +5921,10 @@ program.command("run").description("Connect to Evident and process messages").op
5337
5921
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
5338
5922
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
5339
5923
  sessionCleanupMaxCount: options.sessionCleanupMaxCount,
5340
- sessionCleanupInterval: options.sessionCleanupInterval
5924
+ sessionCleanupInterval: options.sessionCleanupInterval,
5925
+ // Raw values — expansion/validation is single-sourced in run.ts's
5926
+ // resolveFileSyncDirectories.
5927
+ enableFileSyncTo: options.enableFileSyncTo
5341
5928
  });
5342
5929
  }
5343
5930
  );