@evident-ai/cli 3.1.1-dev.c65cbfc → 3.1.1-dev.caa3277

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
@@ -267,16 +267,28 @@ async function getToken() {
267
267
  }
268
268
  return null;
269
269
  }
270
+ function toError(err) {
271
+ return err instanceof Error ? err : new Error(String(err));
272
+ }
270
273
  async function deleteToken(options = {}) {
271
274
  const keytar = await getKeytar();
275
+ const failures = [];
272
276
  if (keytar) {
273
277
  if (options.all) {
274
- const all = await keytar.findCredentials(SERVICE_NAME).catch(() => []);
278
+ let accounts = [];
279
+ try {
280
+ accounts = await keytar.findCredentials(SERVICE_NAME);
281
+ } catch (err) {
282
+ failures.push({ type: "enumerate", error: toError(err) });
283
+ }
275
284
  await Promise.all(
276
- all.map(
277
- (entry) => keytar.deletePassword(SERVICE_NAME, entry.account).catch(() => {
278
- })
279
- )
285
+ accounts.map(async (entry) => {
286
+ try {
287
+ await keytar.deletePassword(SERVICE_NAME, entry.account);
288
+ } catch (err) {
289
+ failures.push({ type: "delete", account: entry.account, error: toError(err) });
290
+ }
291
+ })
280
292
  );
281
293
  } else {
282
294
  await keytar.deletePassword(SERVICE_NAME, keychainAccount());
@@ -287,6 +299,7 @@ async function deleteToken(options = {}) {
287
299
  } else {
288
300
  clearCredentials();
289
301
  }
302
+ return { failures };
290
303
  }
291
304
 
292
305
  // src/utils/ui.ts
@@ -404,8 +417,10 @@ async function deviceFlowLogin(options) {
404
417
  }
405
418
  async function tokenLogin() {
406
419
  console.log("Token login mode.");
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.");
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
+ );
409
424
  blank();
410
425
  process.stdout.write("Paste token: ");
411
426
  const token = await new Promise((resolve3) => {
@@ -429,13 +444,22 @@ async function tokenLogin() {
429
444
  printError("No token provided.");
430
445
  process.exit(1);
431
446
  }
447
+ await validateAndStoreToken(token);
448
+ }
449
+ async function validateAndStoreToken(token) {
432
450
  const spinner = ora("Validating token...").start();
433
451
  try {
434
- 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
+ }
435
460
  await storeToken({
436
461
  token,
437
- user: result.user,
438
- expiresAt: result.expires_at
462
+ user: { email: result.user.email }
439
463
  });
440
464
  spinner.stop();
441
465
  printSuccess(`Logged in as ${chalk2.bold(result.user.email)}`);
@@ -455,9 +479,22 @@ async function login(options) {
455
479
  }
456
480
 
457
481
  // src/commands/logout.ts
482
+ function describeFailure(failure) {
483
+ if (failure.type === "enumerate") {
484
+ return `could not list stored keychain entries (${failure.error.message})`;
485
+ }
486
+ return `${failure.account} (${failure.error.message})`;
487
+ }
458
488
  async function logout(options = {}) {
459
489
  if (options.all) {
460
- await deleteToken({ all: true });
490
+ const result = await deleteToken({ all: true });
491
+ if (result.failures.length > 0) {
492
+ printError(
493
+ `Failed to fully clear your keychain: ${result.failures.map(describeFailure).join("; ")}. Your local credentials file was cleared, but stale keychain entries may remain \u2014 run \`evident logout --all\` again, or remove them manually from your OS keychain / credential manager.`
494
+ );
495
+ process.exitCode = 1;
496
+ return;
497
+ }
461
498
  printSuccess("Logged out of all endpoints.");
462
499
  return;
463
500
  }
@@ -482,7 +519,9 @@ async function whoami() {
482
519
  blank();
483
520
  console.log(keyValue("Endpoint", apiUrl));
484
521
  console.log(keyValue("User", chalk3.bold(credentials2.user.email)));
485
- console.log(keyValue("User ID", credentials2.user.id));
522
+ if (credentials2.user.id) {
523
+ console.log(keyValue("User ID", credentials2.user.id));
524
+ }
486
525
  if (credentials2.expiresAt) {
487
526
  const expiresAt = new Date(credentials2.expiresAt);
488
527
  const now = /* @__PURE__ */ new Date();
@@ -510,7 +549,10 @@ var TelemetryEventTypes = {
510
549
  AGENT_DISCONNECTED: "agent.disconnected",
511
550
  AGENT_MESSAGE_PROCESSING: "agent.message_processing",
512
551
  AGENT_MESSAGE_DONE: "agent.message_done",
513
- 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"
514
556
  };
515
557
 
516
558
  // ../../packages/types/src/tunnel/index.ts
@@ -565,6 +607,13 @@ var isShuttingDown = false;
565
607
  var FLUSH_INTERVAL_MS = 5e3;
566
608
  var MAX_BUFFER_SIZE = 50;
567
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;
568
617
  function logEvent(eventType, options = {}) {
569
618
  const event = {
570
619
  event_type: eventType,
@@ -599,9 +648,16 @@ async function flushEvents() {
599
648
  flushTimeout = null;
600
649
  }
601
650
  try {
602
- const credentials2 = await getToken();
603
- if (!credentials2) {
604
- 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}`;
605
661
  }
606
662
  const apiUrl = getApiUrlConfig();
607
663
  const controller = new AbortController();
@@ -616,7 +672,7 @@ async function flushEvents() {
616
672
  method: "POST",
617
673
  headers: {
618
674
  "Content-Type": "application/json",
619
- Authorization: `Bearer ${credentials2.token}`
675
+ Authorization: authHeader
620
676
  },
621
677
  body: JSON.stringify(request),
622
678
  signal: controller.signal
@@ -628,8 +684,15 @@ async function flushEvents() {
628
684
  clearTimeout(timeout);
629
685
  }
630
686
  } catch (error2) {
631
- if (process.env.DEBUG) {
632
- 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++;
633
696
  }
634
697
  }
635
698
  }
@@ -698,6 +761,69 @@ var EventTypes = {
698
761
  DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
699
762
  };
700
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
+
701
827
  // src/lib/auth.ts
702
828
  async function getAuthCredentials() {
703
829
  const runnerKey = process.env.EVIDENT_RUNNER_KEY;
@@ -1548,6 +1674,42 @@ function messageError(messages, userMessageId) {
1548
1674
  }
1549
1675
  return "The agent run failed.";
1550
1676
  }
1677
+ function messageFailure(messages, userMessageId) {
1678
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1679
+ const error2 = errorOf(reply);
1680
+ if (error2 == null || typeof error2 !== "object") return null;
1681
+ const e = error2;
1682
+ const replyProviderId = reply?.info?.providerID ?? null;
1683
+ const replyModelId = reply?.info?.modelID ?? null;
1684
+ if (e.name === "ProviderAuthError") {
1685
+ const data = e.data;
1686
+ const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
1687
+ return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
1688
+ }
1689
+ if (e.name === "APIError") {
1690
+ const data = e.data;
1691
+ const statusCode = data?.statusCode;
1692
+ if (statusCode === 401 || statusCode === 403) {
1693
+ return {
1694
+ kind: "model_auth",
1695
+ providerId: replyProviderId,
1696
+ modelId: replyModelId,
1697
+ reason: "rejected"
1698
+ };
1699
+ }
1700
+ }
1701
+ return null;
1702
+ }
1703
+ function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
1704
+ if (classified != null) return classified;
1705
+ if (hasConfiguredProvider !== false) return null;
1706
+ return {
1707
+ kind: "model_auth",
1708
+ providerId: replyProviderId,
1709
+ modelId: replyModelId,
1710
+ reason: "missing"
1711
+ };
1712
+ }
1551
1713
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1552
1714
  if (!messages || messages.length === 0) return false;
1553
1715
  return messages.some(
@@ -2076,6 +2238,18 @@ var RunnerConnection = class {
2076
2238
  }
2077
2239
  };
2078
2240
 
2241
+ // src/lib/tunnel/ready-marker.ts
2242
+ import { writeFileSync } from "fs";
2243
+ function writeTunnelReadyMarker(path, agentId) {
2244
+ try {
2245
+ writeFileSync(path, `${agentId}
2246
+ `);
2247
+ return { ok: true };
2248
+ } catch (error2) {
2249
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
2250
+ }
2251
+ }
2252
+
2079
2253
  // src/lib/channels/driver.ts
2080
2254
  import { homedir } from "os";
2081
2255
 
@@ -3586,8 +3760,16 @@ var ChannelDriver = class _ChannelDriver {
3586
3760
  message_id: inFlight.evidentMessageId
3587
3761
  });
3588
3762
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
3763
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
3589
3764
  try {
3590
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
3765
+ await this.markFailed(
3766
+ conv.id,
3767
+ inFlight.evidentMessageId,
3768
+ sessionId,
3769
+ error2,
3770
+ usage,
3771
+ failure
3772
+ );
3591
3773
  } catch (err) {
3592
3774
  if (err instanceof ChannelAuthError) throw err;
3593
3775
  if (err instanceof ChannelTerminalError) {
@@ -3968,6 +4150,7 @@ var ChannelDriver = class _ChannelDriver {
3968
4150
  if (state === "failed") {
3969
4151
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3970
4152
  const usage = messageUsage(messages, ocId ?? "");
4153
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3971
4154
  this.log({
3972
4155
  level: "error",
3973
4156
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3975,7 +4158,7 @@ var ChannelDriver = class _ChannelDriver {
3975
4158
  message_id: row.id
3976
4159
  });
3977
4160
  try {
3978
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4161
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3979
4162
  } catch (err) {
3980
4163
  if (err instanceof ChannelAuthError) throw err;
3981
4164
  if (err instanceof ChannelTerminalError) {
@@ -4953,7 +5136,7 @@ var ChannelDriver = class _ChannelDriver {
4953
5136
  * exists but is wedged, so the next attempt must get a fresh one
4954
5137
  * instead of reusing it — see WI-1's server-side null-clearing PATCH).
4955
5138
  */
4956
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5139
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
4957
5140
  const body = { status: "failed" };
4958
5141
  if (sessionId === null) {
4959
5142
  body.opencode_session_id = null;
@@ -4962,6 +5145,12 @@ var ChannelDriver = class _ChannelDriver {
4962
5145
  }
4963
5146
  if (error2 !== void 0) body.error = error2;
4964
5147
  if (usage) Object.assign(body, usage);
5148
+ if (failure) {
5149
+ body.failure_kind = failure.kind;
5150
+ body.failure_provider_id = failure.providerId;
5151
+ body.failure_model_id = failure.modelId;
5152
+ body.failure_reason = failure.reason;
5153
+ }
4965
5154
  await this.callWithRetry(
4966
5155
  "marking message as failed",
4967
5156
  () => this.fetchImpl(
@@ -4974,6 +5163,29 @@ var ChannelDriver = class _ChannelDriver {
4974
5163
  )
4975
5164
  );
4976
5165
  }
5166
+ /**
5167
+ * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
5168
+ *
5169
+ * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
5170
+ * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
5171
+ * to the P1-2b zero-provider check — one extra loopback call to
5172
+ * `hasAnyConfiguredProvider`, only reached when the structured classifier
5173
+ * couldn't place it. Fails open (never throws): a fallback probe failure
5174
+ * (`null`/indeterminate) leaves the classification `null`, which produces
5175
+ * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
5176
+ */
5177
+ async classifyModelAuthFailure(messages, userMessageId) {
5178
+ const classified = messageFailure(messages, userMessageId);
5179
+ if (classified != null) return classified;
5180
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
5181
+ const hasProvider = await hasAnyConfiguredProvider(this.port);
5182
+ return applyZeroProviderFallback(
5183
+ classified,
5184
+ hasProvider,
5185
+ reply?.info?.providerID ?? null,
5186
+ reply?.info?.modelID ?? null
5187
+ );
5188
+ }
4977
5189
  /**
4978
5190
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
4979
5191
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -5126,10 +5338,16 @@ var ChannelDriver = class _ChannelDriver {
5126
5338
  import chalk5 from "chalk";
5127
5339
  import ora2 from "ora";
5128
5340
  import { select as select2 } from "@inquirer/prompts";
5341
+ var INTERACTIVE_START_TIMEOUT_MS = 3e4;
5129
5342
  async function ensureOpenCodeRunning(ctx) {
5130
5343
  const healthCheck = await checkOpenCodeHealth(ctx.port);
5131
5344
  if (healthCheck.healthy) {
5132
- return { port: ctx.port, process: null, version: healthCheck.version ?? null };
5345
+ return {
5346
+ port: ctx.port,
5347
+ process: null,
5348
+ version: healthCheck.version ?? null,
5349
+ notReadyReason: null
5350
+ };
5133
5351
  }
5134
5352
  const runningInstances = await findHealthyOpenCodeInstances();
5135
5353
  if (runningInstances.length > 0) {
@@ -5170,14 +5388,22 @@ async function ensureOpenCodeRunning(ctx) {
5170
5388
  if (!ctx.interactive) {
5171
5389
  ctx.log(`OpenCode is not running on port ${ctx.port}. Starting it automatically...`);
5172
5390
  const proc = await startOpenCode(ctx.port);
5173
- const health = await waitForOpenCodeHealth(ctx.port, 3e4);
5391
+ const health = await waitForOpenCodeHealth(ctx.port, ctx.startTimeoutMs);
5174
5392
  if (!health.healthy) {
5175
- throw new Error(
5176
- `OpenCode failed to start on port ${ctx.port}. Install with: npm install -g opencode-ai`
5177
- );
5393
+ return {
5394
+ port: ctx.port,
5395
+ process: proc,
5396
+ version: null,
5397
+ notReadyReason: `it did not become healthy within ${Math.round(ctx.startTimeoutMs / 1e3)}s`
5398
+ };
5178
5399
  }
5179
5400
  ctx.log(`OpenCode started on port ${ctx.port}${health.version ? ` (v${health.version})` : ""}`);
5180
- return { port: ctx.port, process: proc, version: health.version ?? null };
5401
+ return {
5402
+ port: ctx.port,
5403
+ process: proc,
5404
+ version: health.version ?? null,
5405
+ notReadyReason: null
5406
+ };
5181
5407
  }
5182
5408
  let port = ctx.port;
5183
5409
  if (isPortInUse(port)) {
@@ -5230,15 +5456,15 @@ Port ${port} is already in use.`));
5230
5456
  if (action === "start") {
5231
5457
  const spinner = ora2("Starting OpenCode...").start();
5232
5458
  const proc = await startOpenCode(port);
5233
- const health = await waitForOpenCodeHealth(port, 3e4);
5459
+ const health = await waitForOpenCodeHealth(port, INTERACTIVE_START_TIMEOUT_MS);
5234
5460
  if (!health.healthy) {
5235
5461
  spinner.fail("Failed to start OpenCode");
5236
5462
  throw new Error("OpenCode failed to start");
5237
5463
  }
5238
5464
  spinner.stop();
5239
- return { port, process: proc, version: health.version ?? null };
5465
+ return { port, process: proc, version: health.version ?? null, notReadyReason: null };
5240
5466
  }
5241
- return { port, process: null, version: null };
5467
+ return { port, process: null, version: null, notReadyReason: "you chose to continue without it" };
5242
5468
  }
5243
5469
 
5244
5470
  // src/commands/agent-lookup.ts
@@ -5435,6 +5661,35 @@ function resolveFileSyncDirectories(raw, homeDir) {
5435
5661
  }
5436
5662
  return directories;
5437
5663
  }
5664
+ var DEFAULT_OPENCODE_START_TIMEOUT_SECONDS = 180;
5665
+ var MAX_OPENCODE_START_TIMEOUT_SECONDS = 3600;
5666
+ var OPENCODE_START_TIMEOUT_ENV = "EVIDENT_OPENCODE_START_TIMEOUT";
5667
+ function resolveOpenCodeStartTimeoutMs(options, env = process.env) {
5668
+ const defaultMs = DEFAULT_OPENCODE_START_TIMEOUT_SECONDS * 1e3;
5669
+ let raw;
5670
+ let source;
5671
+ if (options.opencodeStartTimeout !== void 0) {
5672
+ raw = options.opencodeStartTimeout;
5673
+ source = "--opencode-start-timeout";
5674
+ } else if (env[OPENCODE_START_TIMEOUT_ENV] !== void 0 && env[OPENCODE_START_TIMEOUT_ENV] !== "") {
5675
+ raw = env[OPENCODE_START_TIMEOUT_ENV];
5676
+ source = OPENCODE_START_TIMEOUT_ENV;
5677
+ } else {
5678
+ return { timeoutMs: defaultMs, warnings: [] };
5679
+ }
5680
+ const trimmed = raw.trim();
5681
+ const seconds = Number(trimmed);
5682
+ const isPositiveInteger = /^\d+$/.test(trimmed) && Number.isInteger(seconds) && seconds > 0;
5683
+ if (!isPositiveInteger || seconds > MAX_OPENCODE_START_TIMEOUT_SECONDS) {
5684
+ return {
5685
+ timeoutMs: defaultMs,
5686
+ warnings: [
5687
+ `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`
5688
+ ]
5689
+ };
5690
+ }
5691
+ return { timeoutMs: seconds * 1e3, warnings: [] };
5692
+ }
5438
5693
  function meetsThreshold(state, level) {
5439
5694
  return LOG_LEVELS[level] >= LOG_LEVELS[state.logLevel];
5440
5695
  }
@@ -5456,6 +5711,10 @@ function log2(state, message, level = "info") {
5456
5711
  function logActivity(state, entry) {
5457
5712
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5458
5713
  if (!meetsThreshold(state, level)) return;
5714
+ forwardRunnerActivity(
5715
+ { level, message: entry.message, error: entry.error },
5716
+ { agentId: state.agentId, authHeader: state.authHeader }
5717
+ );
5459
5718
  const fullEntry = {
5460
5719
  ...entry,
5461
5720
  level,
@@ -5810,6 +6069,7 @@ async function run(options) {
5810
6069
  sessionCleanupTimers: [],
5811
6070
  authHeader: ""
5812
6071
  };
6072
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5813
6073
  if (fileSyncDirectories.length > 0) {
5814
6074
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5815
6075
  } else {
@@ -5998,40 +6258,52 @@ async function run(options) {
5998
6258
  } else {
5999
6259
  log2(state, "Not running in a MicroVM (MICROVM_ID unset) \u2014 nothing to report", "debug");
6000
6260
  }
6261
+ const { timeoutMs: opencodeStartTimeoutMs, warnings: opencodeStartTimeoutWarnings } = resolveOpenCodeStartTimeoutMs(options, process.env);
6262
+ for (const warning2 of opencodeStartTimeoutWarnings) {
6263
+ logActivity(state, { type: "info", level: "warn", message: warning2 });
6264
+ }
6001
6265
  const ocSpinner = interactive && !state.json ? ora3("Checking OpenCode...").start() : null;
6002
6266
  try {
6003
6267
  const oc = await ensureOpenCodeRunning({
6004
6268
  port: state.port,
6005
6269
  interactive: state.interactive,
6006
6270
  agentId: state.agentId,
6007
- log: (message) => log2(state, message)
6271
+ log: (message) => log2(state, message),
6272
+ startTimeoutMs: opencodeStartTimeoutMs
6008
6273
  });
6009
6274
  state.port = oc.port;
6010
6275
  state.opencodeProcess = oc.process;
6011
6276
  state.opencodeVersion = oc.version;
6012
- state.opencodeConnected = oc.process !== null || oc.version !== null;
6277
+ state.opencodeConnected = oc.notReadyReason === null;
6013
6278
  const version2 = state.opencodeVersion ? ` (v${state.opencodeVersion})` : "";
6014
6279
  ocSpinner?.succeed(`OpenCode running on port ${state.port}${version2}`);
6015
- const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6016
- if (versionWarning) {
6017
- log2(state, versionWarning, "warn");
6018
- if (state.interactive && !state.json) {
6019
- logActivity(state, { type: "info", level: "warn", message: versionWarning });
6280
+ if (!state.interactive && oc.notReadyReason !== null) {
6281
+ 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}).`;
6282
+ logActivity(state, { type: "info", level: "warn", message });
6283
+ } else {
6284
+ const versionWarning = buildOpenCodeVersionWarning(state.opencodeVersion);
6285
+ if (versionWarning) {
6286
+ log2(state, versionWarning, "warn");
6287
+ if (state.interactive && !state.json) {
6288
+ logActivity(state, { type: "info", level: "warn", message: versionWarning });
6289
+ }
6020
6290
  }
6021
- }
6022
- const noProviderWarning = buildNoProviderWarning(await hasAnyConfiguredProvider(state.port));
6023
- if (noProviderWarning) {
6024
- log2(state, noProviderWarning, "warn");
6025
- if (state.interactive && !state.json) {
6026
- logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6027
- blank();
6028
- console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6029
- console.log(
6030
- chalk6.dim(
6031
- `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6032
- )
6033
- );
6034
- blank();
6291
+ const noProviderWarning = buildNoProviderWarning(
6292
+ await hasAnyConfiguredProvider(state.port)
6293
+ );
6294
+ if (noProviderWarning) {
6295
+ log2(state, noProviderWarning, "warn");
6296
+ if (state.interactive && !state.json) {
6297
+ logActivity(state, { type: "info", level: "warn", message: noProviderWarning });
6298
+ blank();
6299
+ console.log(chalk6.yellow("\u26A0 No OpenCode model provider is configured."));
6300
+ console.log(
6301
+ chalk6.dim(
6302
+ `Run ${chalk6.cyan("opencode auth login")} to set one up \u2014 messages will fail until then.`
6303
+ )
6304
+ );
6305
+ blank();
6306
+ }
6035
6307
  }
6036
6308
  }
6037
6309
  } catch (error2) {
@@ -6076,6 +6348,18 @@ async function run(options) {
6076
6348
  type: "info",
6077
6349
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
6078
6350
  });
6351
+ if (options.tunnelReadyFile) {
6352
+ const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
6353
+ if (marker.ok) {
6354
+ log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
6355
+ } else {
6356
+ log2(
6357
+ state,
6358
+ `Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
6359
+ "error"
6360
+ );
6361
+ }
6362
+ }
6079
6363
  emitAgentConnected(state.agentId, {
6080
6364
  port: state.port,
6081
6365
  cli_version: getCliVersion(),
@@ -6226,7 +6510,10 @@ program.command("run").description("Connect to Evident and process messages").op
6226
6510
  ).option("-p, --port <port>", "OpenCode port (default: 4096)", "4096").option(
6227
6511
  "--log-level <level>",
6228
6512
  "Log verbosity: debug | info | warn | error (default: info). Env: EVIDENT_LOG_LEVEL"
6229
- ).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(
6513
+ ).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(
6514
+ "--opencode-start-timeout <seconds>",
6515
+ "Seconds to wait for OpenCode to become healthy when the runner starts it (default: 180). Env: EVIDENT_OPENCODE_START_TIMEOUT"
6516
+ ).option("--json", "Output in JSON format").option(
6230
6517
  "--session-cleanup-max-age <duration>",
6231
6518
  "Delete OpenCode sessions idle longer than this (e.g. 7d, 24h). Enables cleanup. Env: EVIDENT_SESSION_CLEANUP_MAX_AGE"
6232
6519
  ).option(
@@ -6240,6 +6527,9 @@ program.command("run").description("Connect to Evident and process messages").op
6240
6527
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6241
6528
  (value, previous) => previous.concat([value]),
6242
6529
  []
6530
+ ).option(
6531
+ "--tunnel-ready-file <path>",
6532
+ "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
6243
6533
  ).action(
6244
6534
  (options) => {
6245
6535
  run({
@@ -6252,6 +6542,9 @@ program.command("run").description("Connect to Evident and process messages").op
6252
6542
  verbose: options.verbose,
6253
6543
  conversation: options.conversation,
6254
6544
  idleTimeout: options.idleTimeout ? parseInt(options.idleTimeout, 10) : void 0,
6545
+ // Raw string — validation/precedence is single-sourced in run.ts's
6546
+ // resolveOpenCodeStartTimeoutMs (flag > EVIDENT_OPENCODE_START_TIMEOUT > 180s default).
6547
+ opencodeStartTimeout: options.opencodeStartTimeout,
6255
6548
  json: options.json,
6256
6549
  // Raw strings — the resolver in run.ts single-sources parsing (M1).
6257
6550
  sessionCleanupMaxAge: options.sessionCleanupMaxAge,
@@ -6259,7 +6552,8 @@ program.command("run").description("Connect to Evident and process messages").op
6259
6552
  sessionCleanupInterval: options.sessionCleanupInterval,
6260
6553
  // Raw values — expansion/validation is single-sourced in run.ts's
6261
6554
  // resolveFileSyncDirectories.
6262
- enableFileSyncTo: options.enableFileSyncTo
6555
+ enableFileSyncTo: options.enableFileSyncTo,
6556
+ tunnelReadyFile: options.tunnelReadyFile
6263
6557
  });
6264
6558
  }
6265
6559
  );