@evident-ai/cli 3.1.1-dev.2b250ad → 3.1.1-dev.2f79773

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/README.md CHANGED
@@ -94,6 +94,10 @@ Options:
94
94
  - `-c, --conversation <id>` — Process only this specific conversation.
95
95
  - `--idle-timeout <seconds>` — Exit after N seconds with no pending work (useful
96
96
  in CI to avoid polling indefinitely).
97
+ - `--opencode-start-timeout <seconds>` — How long to wait for OpenCode to become
98
+ healthy when the runner starts it itself (default: `180`). On expiry the runner
99
+ warns and comes online anyway rather than failing. Env:
100
+ `EVIDENT_OPENCODE_START_TIMEOUT` (seconds).
97
101
  - `--json` — Output in JSON format (forces non-interactive mode).
98
102
 
99
103
  ## Global flags
package/dist/index.js CHANGED
@@ -417,8 +417,10 @@ async function deviceFlowLogin(options) {
417
417
  }
418
418
  async function tokenLogin() {
419
419
  console.log("Token login mode.");
420
- console.log("Run `evident login` on a machine with a browser to get a token.");
421
- console.log("Manage or revoke existing tokens under Settings \u2192 CLI tokens.");
420
+ console.log("Create a token under Settings \u2192 CLI tokens in the dashboard, then paste it below.");
421
+ console.log(
422
+ "(Alternatively, run `evident login` on a machine with a browser, or set EVIDENT_TOKEN for CI.)"
423
+ );
422
424
  blank();
423
425
  process.stdout.write("Paste token: ");
424
426
  const token = await new Promise((resolve3) => {
@@ -442,13 +444,22 @@ async function tokenLogin() {
442
444
  printError("No token provided.");
443
445
  process.exit(1);
444
446
  }
447
+ await validateAndStoreToken(token);
448
+ }
449
+ async function validateAndStoreToken(token) {
445
450
  const spinner = ora("Validating token...").start();
446
451
  try {
447
- const result = await api.post("/auth/token/validate", { token });
452
+ const result = await api.get("/me", {
453
+ headers: { Authorization: `Bearer ${token}` }
454
+ });
455
+ if (!result.user) {
456
+ throw new Error(
457
+ "This token is not a user login (e.g. a runner key). Paste a CLI token instead."
458
+ );
459
+ }
448
460
  await storeToken({
449
461
  token,
450
- user: result.user,
451
- expiresAt: result.expires_at
462
+ user: { email: result.user.email }
452
463
  });
453
464
  spinner.stop();
454
465
  printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
@@ -508,7 +519,9 @@ async function whoami() {
508
519
  blank();
509
520
  console.log(keyValue("Endpoint", apiUrl));
510
521
  console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
511
- console.log(keyValue("User ID", credentials2.user.id));
522
+ if (credentials2.user.id) {
523
+ console.log(keyValue("User ID", credentials2.user.id));
524
+ }
512
525
  if (credentials2.expiresAt) {
513
526
  const expiresAt = new Date(credentials2.expiresAt);
514
527
  const now = /* @__PURE__ */ new Date();
@@ -536,7 +549,10 @@ var TelemetryEventTypes = {
536
549
  AGENT_DISCONNECTED: "agent.disconnected",
537
550
  AGENT_MESSAGE_PROCESSING: "agent.message_processing",
538
551
  AGENT_MESSAGE_DONE: "agent.message_done",
539
- AGENT_MESSAGE_FAILED: "agent.message_failed"
552
+ AGENT_MESSAGE_FAILED: "agent.message_failed",
553
+ // A `warn`/`error` runner-side log line forwarded server-side for
554
+ // observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
555
+ RUNNER_ACTIVITY: "runner.activity"
540
556
  };
541
557
 
542
558
  // ../../packages/types/src/tunnel/index.ts
@@ -591,6 +607,13 @@ var isShuttingDown = false;
591
607
  var FLUSH_INTERVAL_MS = 5e3;
592
608
  var MAX_BUFFER_SIZE = 50;
593
609
  var FLUSH_TIMEOUT_MS = 3e3;
610
+ var authProvider = null;
611
+ function setTelemetryAuthProvider(provider) {
612
+ authProvider = provider;
613
+ }
614
+ var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
615
+ var lastFlushFailureLoggedAt = 0;
616
+ var suppressedFlushFailureCount = 0;
594
617
  function logEvent(eventType, options = {}) {
595
618
  const event = {
596
619
  event_type: eventType,
@@ -625,9 +648,16 @@ async function flushEvents() {
625
648
  flushTimeout = null;
626
649
  }
627
650
  try {
628
- const credentials2 = await getToken();
629
- if (!credentials2) {
630
- return;
651
+ const providerContext = authProvider?.();
652
+ let authHeader;
653
+ if (providerContext?.authHeader) {
654
+ authHeader = providerContext.authHeader;
655
+ } else {
656
+ const credentials2 = await getToken();
657
+ if (!credentials2) {
658
+ return;
659
+ }
660
+ authHeader = `Bearer ${credentials2.token}`;
631
661
  }
632
662
  const apiUrl = getApiUrlConfig();
633
663
  const controller = new AbortController();
@@ -642,7 +672,7 @@ async function flushEvents() {
642
672
  method: "POST",
643
673
  headers: {
644
674
  "Content-Type": "application/json",
645
- Authorization: `Bearer ${credentials2.token}`
675
+ Authorization: authHeader
646
676
  },
647
677
  body: JSON.stringify(request),
648
678
  signal: controller.signal
@@ -654,8 +684,15 @@ async function flushEvents() {
654
684
  clearTimeout(timeout);
655
685
  }
656
686
  } catch (error2) {
657
- if (process.env.DEBUG) {
658
- console.error("Telemetry error:", error2);
687
+ const now = Date.now();
688
+ if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
689
+ const message = error2 instanceof Error ? error2.message : String(error2);
690
+ const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
691
+ console.error(`Telemetry flush error: ${message}${suffix}`);
692
+ lastFlushFailureLoggedAt = now;
693
+ suppressedFlushFailureCount = 0;
694
+ } else {
695
+ suppressedFlushFailureCount++;
659
696
  }
660
697
  }
661
698
  }
@@ -724,6 +761,69 @@ var EventTypes = {
724
761
  DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
725
762
  };
726
763
 
764
+ // src/lib/runner-activity-telemetry.ts
765
+ var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
766
+ var SEVERITY_BY_LEVEL = {
767
+ warn: "warning",
768
+ error: "error"
769
+ };
770
+ var MAX_MESSAGE_LENGTH = 500;
771
+ var TRUNCATION_MARKER = "\u2026";
772
+ function redact(message) {
773
+ return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
774
+ }
775
+ function truncate(message) {
776
+ if (message.length <= MAX_MESSAGE_LENGTH) return message;
777
+ return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
778
+ }
779
+ var RATE_LIMIT_WINDOW_MS = 6e4;
780
+ var RATE_LIMIT_MAX_EVENTS = 30;
781
+ var windowStartedAt = 0;
782
+ var windowCount = 0;
783
+ var windowDroppedCount = 0;
784
+ function admitUnderRateLimit(now) {
785
+ if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
786
+ if (windowDroppedCount > 0) {
787
+ console.error(
788
+ `[runner-activity-telemetry] rate cap reached: dropped ${windowDroppedCount} ${windowDroppedCount === 1 ? "entry" : "entries"} in the last ${RATE_LIMIT_WINDOW_MS / 1e3}s (cap ${RATE_LIMIT_MAX_EVENTS}/min)`
789
+ );
790
+ }
791
+ windowStartedAt = now;
792
+ windowCount = 0;
793
+ windowDroppedCount = 0;
794
+ }
795
+ if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
796
+ windowDroppedCount++;
797
+ if (windowDroppedCount === 1) {
798
+ console.error(
799
+ `[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
800
+ );
801
+ }
802
+ return false;
803
+ }
804
+ windowCount++;
805
+ return true;
806
+ }
807
+ function forwardRunnerActivity(entry, context) {
808
+ try {
809
+ if (!FORWARDED_LEVELS.has(entry.level)) return;
810
+ if (!context.agentId || !context.authHeader) return;
811
+ if (!admitUnderRateLimit(Date.now())) return;
812
+ const rawMessage = entry.error ?? entry.message ?? "";
813
+ const message = truncate(redact(rawMessage));
814
+ logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
815
+ severity: SEVERITY_BY_LEVEL[entry.level],
816
+ message,
817
+ metadata: { source: "cli.run" },
818
+ agentId: context.agentId
819
+ });
820
+ } catch (err) {
821
+ console.error(
822
+ `[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
823
+ );
824
+ }
825
+ }
826
+
727
827
  // src/lib/auth.ts
728
828
  async function getAuthCredentials() {
729
829
  const runnerKey = process.env.EVIDENT_RUNNER_KEY;
@@ -3204,7 +3304,12 @@ var ChannelDriver = class _ChannelDriver {
3204
3304
  const directory = await this.resolveOpenCodeDirectory();
3205
3305
  const sessionId = await createOpenCodeSession(this.port, directory);
3206
3306
  this.sessions.set(conversationId, sessionId);
3207
- await this.persistSession(conversationId, sessionId).catch(() => {
3307
+ await this.persistSession(conversationId, sessionId).catch((err) => {
3308
+ this.log({
3309
+ level: "warn",
3310
+ message: `Persisting the OpenCode session binding ${sessionId.slice(0, 8)} for conversation ${conversationId.slice(0, 8)} failed (best-effort, not retried) \u2014 the completion PATCH also carries opencode_session_id, so the binding is repaired when the turn finishes: ${err instanceof Error ? err.message : String(err)}`,
3311
+ conversation_id: conversationId
3312
+ });
3208
3313
  });
3209
3314
  return sessionId;
3210
3315
  }
@@ -5238,10 +5343,16 @@ var ChannelDriver = class _ChannelDriver {
5238
5343
  import chalk5 from "chalk";
5239
5344
  import ora2 from "ora";
5240
5345
  import { select as select2 } from "@inquirer/prompts";
5346
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
5241
5347
  async function ensureOpenCodeRunning(ctx) {
5242
5348
  const healthCheck = await checkOpenCodeHealth(ctx.port);
5243
5349
  if (healthCheck.healthy) {
5244
- return { port: ctx.port, process: null, version: healthCheck.version ?? null };
5350
+ return {
5351
+ port: ctx.port,
5352
+ process: null,
5353
+ version: healthCheck.version ?? null,
5354
+ notReadyReason: null
5355
+ };
5245
5356
  }
5246
5357
  const runningInstances = await findHealthyOpenCodeInstances();
5247
5358
  if (runningInstances.length > 0) {
@@ -5282,14 +5393,22 @@ async function ensureOpenCodeRunning(ctx) {
5282
5393
  if (!ctx.interactive) {
5283
5394
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
5284
5395
  const proc = await startOpenCode(ctx.port);
5285
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5396
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
5286
5397
  if (!health.healthy) {
5287
- throw new Error(
5288
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
5289
- );
5398
+ return {
5399
+ port: ctx.port,
5400
+ process: proc,
5401
+ version: null,
5402
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
5403
+ };
5290
5404
  }
5291
5405
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
5292
- return { port: ctx.port, process: proc, version: health.version ?? null };
5406
+ return {
5407
+ port: ctx.port,
5408
+ process: proc,
5409
+ version: health.version ?? null,
5410
+ notReadyReason: null
5411
+ };
5293
5412
  }
5294
5413
  let port = ctx.port;
5295
5414
  if (isPortInUse(port)) {
@@ -5342,15 +5461,15 @@ Port ${port} is already in use.`));
5342
5461
  if (action === "start") {
5343
5462
  const spinner = ora2("Starting OpenCode...").start();
5344
5463
  const proc = await startOpenCode(port);
5345
- const health = await waitForOpenCodeHealth(port, 3e4);
5464
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
5346
5465
  if (!health.healthy) {
5347
5466
  spinner.fail("Failed to start OpenCode");
5348
5467
  throw new Error("OpenCode failed to start");
5349
5468
  }
5350
5469
  spinner.stop();
5351
- return { port, process: proc, version: health.version ?? null };
5470
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
5352
5471
  }
5353
- return { port, process: null, version: null };
5472
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
5354
5473
  }
5355
5474
 
5356
5475
  // src/commands/agent-lookup.ts
@@ -5547,6 +5666,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
5547
5666
  }
5548
5667
  return directories;
5549
5668
  }
5669
+ var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
5670
+ var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
5671
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
5672
+ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
5673
+ const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
5674
+ let raw;
5675
+ let source;
5676
+ if (options.opencodeStartTimeout !== void 0) {
5677
+ raw = options.opencodeStartTimeout;
5678
+ source = "--opencode-start-timeout";
5679
+ } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
5680
+ raw = env[OPENCODE_START_TIMEOUT_ENV];
5681
+ source = OPENCODE_START_TIMEOUT_ENV;
5682
+ } else {
5683
+ return { timeoutMs: defaultMs, warnings: [] };
5684
+ }
5685
+ const trimmed = raw.trim();
5686
+ const seconds = Number(trimmed);
5687
+ const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
5688
+ if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
5689
+ return {
5690
+ timeoutMs: defaultMs,
5691
+ warnings: [
5692
+ `Ignoring invalid ${source} "${raw}": expected a positive integer number of seconds (at most ${MAX_OPENCODE_START_TIMEOUT_SECONDS}); using the default ${DEFAULT_OPENCODE_START_TIMEOUT_SECONDS}s`
5693
+ ]
5694
+ };
5695
+ }
5696
+ return { timeoutMs: seconds * 1e3, warnings: [] };
5697
+ }
5550
5698
  function meetsThreshold(state, level) {
5551
5699
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5552
5700
  }
@@ -5568,6 +5716,10 @@ function log2(state, message, level = "info") {
5568
5716
  function logActivity(state, entry) {
5569
5717
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5570
5718
  if (!meetsThreshold(state, level)) return;
5719
+ forwardRunnerActivity(
5720
+ { level, message: entry.message, error: entry.error },
5721
+ { agentId: state.agentId, authHeader: state.authHeader }
5722
+ );
5571
5723
  const fullEntry = {
5572
5724
  ...entry,
5573
5725
  level,
@@ -5922,6 +6074,7 @@ async function run(options) {
5922
6074
  sessionCleanupTimers: [],
5923
6075
  authHeader: ""
5924
6076
  };
6077
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5925
6078
  if (fileSyncDirectories.length > 0) {
5926
6079
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5927
6080
  } else {
@@ -6110,40 +6263,52 @@ async function run(options) {
6110
6263
  } else {
6111
6264
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6112
6265
  }
6266
+ const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
6267
+ for (const warning2 of opencodeStartTimeoutWarnings) {
6268
+ logActivity(state, { type: "info", level: "warn", message: warning2 });
6269
+ }
6113
6270
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
6114
6271
  try {
6115
6272
  const oc = await ensureOpenCodeRunning({
6116
6273
  port: state.port,
6117
6274
  interactive: state.interactive,
6118
6275
  agentId: state.agentId,
6119
- log: (message) => log2(state, message)
6276
+ log: (message) => log2(state, message),
6277
+ startTimeoutMs: opencodeStartTimeoutMs
6120
6278
  });
6121
6279
  state.port = oc.port;
6122
6280
  state.opencodeProcess = oc.process;
6123
6281
  state.opencodeVersion = oc.version;
6124
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6282
+ state.opencodeConnected = oc.notReadyReason === null;
6125
6283
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
6126
6284
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
6127
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6128
- if (versionWarning) {
6129
- log2(state, versionWarning, "warn");
6130
- if (state.interactive && !state.json) {
6131
- logActivity(state, { type: "info", level: "warn", message: versionWarning });
6285
+ if (!state.interactive && oc.notReadyReason !== null) {
6286
+ const message = `OpenCode is not ready on port ${state.port}: ${oc.notReadyReason}. The runner will still come online, but messages will fail until opencode answers \u2014 raise the wait with --opencode-start-timeout <seconds> (env ${OPENCODE_START_TIMEOUT_ENV}).`;
6287
+ logActivity(state, { type: "info", level: "warn", message });
6288
+ } else {
6289
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6290
+ if (versionWarning) {
6291
+ log2(state, versionWarning, "warn");
6292
+ if (state.interactive && !state.json) {
6293
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
6294
+ }
6132
6295
  }
6133
- }
6134
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
6135
- if (noProviderWarning) {
6136
- log2(state, noProviderWarning, "warn");
6137
- if (state.interactive && !state.json) {
6138
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6139
- blank();
6140
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6141
- console.log(
6142
- chalk6.dim(
6143
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6144
- )
6145
- );
6146
- blank();
6296
+ const noProviderWarning = buildNoProviderWarning(
6297
+ await hasAnyConfiguredProvider(state.port)
6298
+ );
6299
+ if (noProviderWarning) {
6300
+ log2(state, noProviderWarning, "warn");
6301
+ if (state.interactive && !state.json) {
6302
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6303
+ blank();
6304
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6305
+ console.log(
6306
+ chalk6.dim(
6307
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6308
+ )
6309
+ );
6310
+ blank();
6311
+ }
6147
6312
  }
6148
6313
  }
6149
6314
  } catch (error2) {
@@ -6350,7 +6515,10 @@ program.command("run").description("Connect to Evident and process messages").op
6350
6515
  ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6351
6516
  "--log-level <level>",
6352
6517
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
6353
- ).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option("--json", "Output in JSON format").option(
6518
+ ).option("-v, --verbose", "Alias for --log-level debug (ignored if --log-level is set)").option("-c, --conversation <id>", "Process only this specific conversation").option("--idle-timeout <seconds>", "Exit after N seconds idle").option(
6519
+ "--opencode-start-timeout <seconds>",
6520
+ "Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
6521
+ ).option("--json", "Output in JSON format").option(
6354
6522
  "--session-cleanup-max-age <duration>",
6355
6523
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
6356
6524
  ).option(
@@ -6379,6 +6547,9 @@ program.command("run").description("Connect to Evident and process messages").op
6379
6547
  verbose: options.verbose,
6380
6548
  conversation: options.conversation,
6381
6549
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
6550
+ // Raw string — validation/precedence is single-sourced in run.ts's
6551
+ // resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
6552
+ opencodeStartTimeout: options.opencodeStartTimeout,
6382
6553
  json: options.json,
6383
6554
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
6384
6555
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,