@evident-ai/cli 3.1.1-dev.7568241 → 3.1.1-dev.7972495

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
@@ -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
@@ -455,9 +468,22 @@ async function login(options) {
455
468
  }
456
469
 
457
470
  // src/commands/logout.ts
471
+ function describeFailure(failure) {
472
+ if (failure.type === "enumerate") {
473
+ return `could not list stored keychain entries (${failure.error.message})`;
474
+ }
475
+ return `${failure.account} (${failure.error.message})`;
476
+ }
458
477
  async function logout(options = {}) {
459
478
  if (options.all) {
460
- await deleteToken({ all: true });
479
+ const result = await deleteToken({ all: true });
480
+ if (result.failures.length > 0) {
481
+ printError(
482
+ `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.`
483
+ );
484
+ process.exitCode = 1;
485
+ return;
486
+ }
461
487
  printSuccess("Logged out of all endpoints.");
462
488
  return;
463
489
  }
@@ -510,7 +536,10 @@ var TelemetryEventTypes = {
510
536
  AGENT_DISCONNECTED: "agent.disconnected",
511
537
  AGENT_MESSAGE_PROCESSING: "agent.message_processing",
512
538
  AGENT_MESSAGE_DONE: "agent.message_done",
513
- AGENT_MESSAGE_FAILED: "agent.message_failed"
539
+ AGENT_MESSAGE_FAILED: "agent.message_failed",
540
+ // A `warn`/`error` runner-side log line forwarded server-side for
541
+ // observability (issue #916) — see `apps/cli/src/lib/runner-activity-telemetry.ts`.
542
+ RUNNER_ACTIVITY: "runner.activity"
514
543
  };
515
544
 
516
545
  // ../../packages/types/src/tunnel/index.ts
@@ -565,6 +594,13 @@ var isShuttingDown = false;
565
594
  var FLUSH_INTERVAL_MS = 5e3;
566
595
  var MAX_BUFFER_SIZE = 50;
567
596
  var FLUSH_TIMEOUT_MS = 3e3;
597
+ var authProvider = null;
598
+ function setTelemetryAuthProvider(provider) {
599
+ authProvider = provider;
600
+ }
601
+ var FLUSH_FAILURE_LOG_INTERVAL_MS = 6e4;
602
+ var lastFlushFailureLoggedAt = 0;
603
+ var suppressedFlushFailureCount = 0;
568
604
  function logEvent(eventType, options = {}) {
569
605
  const event = {
570
606
  event_type: eventType,
@@ -599,9 +635,16 @@ async function flushEvents() {
599
635
  flushTimeout = null;
600
636
  }
601
637
  try {
602
- const credentials2 = await getToken();
603
- if (!credentials2) {
604
- return;
638
+ const providerContext = authProvider?.();
639
+ let authHeader;
640
+ if (providerContext?.authHeader) {
641
+ authHeader = providerContext.authHeader;
642
+ } else {
643
+ const credentials2 = await getToken();
644
+ if (!credentials2) {
645
+ return;
646
+ }
647
+ authHeader = `Bearer ${credentials2.token}`;
605
648
  }
606
649
  const apiUrl = getApiUrlConfig();
607
650
  const controller = new AbortController();
@@ -616,7 +659,7 @@ async function flushEvents() {
616
659
  method: "POST",
617
660
  headers: {
618
661
  "Content-Type": "application/json",
619
- Authorization: `Bearer ${credentials2.token}`
662
+ Authorization: authHeader
620
663
  },
621
664
  body: JSON.stringify(request),
622
665
  signal: controller.signal
@@ -628,8 +671,15 @@ async function flushEvents() {
628
671
  clearTimeout(timeout);
629
672
  }
630
673
  } catch (error2) {
631
- if (process.env.DEBUG) {
632
- console.error("Telemetry error:", error2);
674
+ const now = Date.now();
675
+ if (now - lastFlushFailureLoggedAt >= FLUSH_FAILURE_LOG_INTERVAL_MS) {
676
+ const message = error2 instanceof Error ? error2.message : String(error2);
677
+ const suffix = suppressedFlushFailureCount > 0 ? ` (${suppressedFlushFailureCount} more suppressed in the last ${FLUSH_FAILURE_LOG_INTERVAL_MS / 1e3}s)` : "";
678
+ console.error(`Telemetry flush error: ${message}${suffix}`);
679
+ lastFlushFailureLoggedAt = now;
680
+ suppressedFlushFailureCount = 0;
681
+ } else {
682
+ suppressedFlushFailureCount++;
633
683
  }
634
684
  }
635
685
  }
@@ -698,6 +748,69 @@ var EventTypes = {
698
748
  DEPRECATED_AGENT_KEY_ENV_USED: "cli.deprecated_agent_key_env_used"
699
749
  };
700
750
 
751
+ // src/lib/runner-activity-telemetry.ts
752
+ var FORWARDED_LEVELS = /* @__PURE__ */ new Set(["warn", "error"]);
753
+ var SEVERITY_BY_LEVEL = {
754
+ warn: "warning",
755
+ error: "error"
756
+ };
757
+ var MAX_MESSAGE_LENGTH = 500;
758
+ var TRUNCATION_MARKER = "\u2026";
759
+ function redact(message) {
760
+ return message.replace(/esk_[A-Za-z0-9_-]+/g, "esk_***").replace(/ct_[A-Za-z0-9_-]+/g, "ct_***").replace(/https?:\/\/\S+/g, "<url>");
761
+ }
762
+ function truncate(message) {
763
+ if (message.length <= MAX_MESSAGE_LENGTH) return message;
764
+ return message.slice(0, MAX_MESSAGE_LENGTH - TRUNCATION_MARKER.length) + TRUNCATION_MARKER;
765
+ }
766
+ var RATE_LIMIT_WINDOW_MS = 6e4;
767
+ var RATE_LIMIT_MAX_EVENTS = 30;
768
+ var windowStartedAt = 0;
769
+ var windowCount = 0;
770
+ var windowDroppedCount = 0;
771
+ function admitUnderRateLimit(now) {
772
+ if (now - windowStartedAt >= RATE_LIMIT_WINDOW_MS) {
773
+ if (windowDroppedCount > 0) {
774
+ console.error(
775
+ `[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)`
776
+ );
777
+ }
778
+ windowStartedAt = now;
779
+ windowCount = 0;
780
+ windowDroppedCount = 0;
781
+ }
782
+ if (windowCount >= RATE_LIMIT_MAX_EVENTS) {
783
+ windowDroppedCount++;
784
+ if (windowDroppedCount === 1) {
785
+ console.error(
786
+ `[runner-activity-telemetry] rate cap reached (${RATE_LIMIT_MAX_EVENTS} per ${RATE_LIMIT_WINDOW_MS / 1e3}s) \u2014 dropping further entries this window`
787
+ );
788
+ }
789
+ return false;
790
+ }
791
+ windowCount++;
792
+ return true;
793
+ }
794
+ function forwardRunnerActivity(entry, context) {
795
+ try {
796
+ if (!FORWARDED_LEVELS.has(entry.level)) return;
797
+ if (!context.agentId || !context.authHeader) return;
798
+ if (!admitUnderRateLimit(Date.now())) return;
799
+ const rawMessage = entry.error ?? entry.message ?? "";
800
+ const message = truncate(redact(rawMessage));
801
+ logEvent(TelemetryEventTypes.RUNNER_ACTIVITY, {
802
+ severity: SEVERITY_BY_LEVEL[entry.level],
803
+ message,
804
+ metadata: { source: "cli.run" },
805
+ agentId: context.agentId
806
+ });
807
+ } catch (err) {
808
+ console.error(
809
+ `[runner-activity-telemetry] failed to forward runner activity: ${err instanceof Error ? err.message : String(err)}`
810
+ );
811
+ }
812
+ }
813
+
701
814
  // src/lib/auth.ts
702
815
  async function getAuthCredentials() {
703
816
  const runnerKey = process.env.EVIDENT_RUNNER_KEY;
@@ -1548,6 +1661,42 @@ function messageError(messages, userMessageId) {
1548
1661
  }
1549
1662
  return "The agent run failed.";
1550
1663
  }
1664
+ function messageFailure(messages, userMessageId) {
1665
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
1666
+ const error2 = errorOf(reply);
1667
+ if (error2 == null || typeof error2 !== "object") return null;
1668
+ const e = error2;
1669
+ const replyProviderId = reply?.info?.providerID ?? null;
1670
+ const replyModelId = reply?.info?.modelID ?? null;
1671
+ if (e.name === "ProviderAuthError") {
1672
+ const data = e.data;
1673
+ const providerId = typeof data?.providerID === "string" && data.providerID || replyProviderId;
1674
+ return { kind: "model_auth", providerId, modelId: replyModelId, reason: "missing" };
1675
+ }
1676
+ if (e.name === "APIError") {
1677
+ const data = e.data;
1678
+ const statusCode = data?.statusCode;
1679
+ if (statusCode === 401 || statusCode === 403) {
1680
+ return {
1681
+ kind: "model_auth",
1682
+ providerId: replyProviderId,
1683
+ modelId: replyModelId,
1684
+ reason: "rejected"
1685
+ };
1686
+ }
1687
+ }
1688
+ return null;
1689
+ }
1690
+ function applyZeroProviderFallback(classified, hasConfiguredProvider, replyProviderId, replyModelId = null) {
1691
+ if (classified != null) return classified;
1692
+ if (hasConfiguredProvider !== false) return null;
1693
+ return {
1694
+ kind: "model_auth",
1695
+ providerId: replyProviderId,
1696
+ modelId: replyModelId,
1697
+ reason: "missing"
1698
+ };
1699
+ }
1551
1700
  function hasRunningAssistantExcept(messages, exceptUserMessageId) {
1552
1701
  if (!messages || messages.length === 0) return false;
1553
1702
  return messages.some(
@@ -2076,6 +2225,18 @@ var RunnerConnection = class {
2076
2225
  }
2077
2226
  };
2078
2227
 
2228
+ // src/lib/tunnel/ready-marker.ts
2229
+ import { writeFileSync } from "fs";
2230
+ function writeTunnelReadyMarker(path, agentId) {
2231
+ try {
2232
+ writeFileSync(path, `${agentId}
2233
+ `);
2234
+ return { ok: true };
2235
+ } catch (error2) {
2236
+ return { ok: false, error: error2 instanceof Error ? error2.message : String(error2) };
2237
+ }
2238
+ }
2239
+
2079
2240
  // src/lib/channels/driver.ts
2080
2241
  import { homedir } from "os";
2081
2242
 
@@ -3586,8 +3747,16 @@ var ChannelDriver = class _ChannelDriver {
3586
3747
  message_id: inFlight.evidentMessageId
3587
3748
  });
3588
3749
  const usage = messageUsage(messages, inFlight.opencodeMessageId);
3750
+ const failure = await this.classifyModelAuthFailure(messages, inFlight.opencodeMessageId);
3589
3751
  try {
3590
- await this.markFailed(conv.id, inFlight.evidentMessageId, sessionId, error2, usage);
3752
+ await this.markFailed(
3753
+ conv.id,
3754
+ inFlight.evidentMessageId,
3755
+ sessionId,
3756
+ error2,
3757
+ usage,
3758
+ failure
3759
+ );
3591
3760
  } catch (err) {
3592
3761
  if (err instanceof ChannelAuthError) throw err;
3593
3762
  if (err instanceof ChannelTerminalError) {
@@ -3968,6 +4137,7 @@ var ChannelDriver = class _ChannelDriver {
3968
4137
  if (state === "failed") {
3969
4138
  const error2 = messageError(messages, ocId ?? "") ?? void 0;
3970
4139
  const usage = messageUsage(messages, ocId ?? "");
4140
+ const failure = await this.classifyModelAuthFailure(messages, ocId ?? "");
3971
4141
  this.log({
3972
4142
  level: "error",
3973
4143
  message: `Re-adopt: message ${row.id.slice(0, 8)} errored while unwatched \u2014 marking failed: ${error2 ?? "(no error text)"}`,
@@ -3975,7 +4145,7 @@ var ChannelDriver = class _ChannelDriver {
3975
4145
  message_id: row.id
3976
4146
  });
3977
4147
  try {
3978
- await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage);
4148
+ await this.markFailed(row.conversation_id, row.id, sessionId, error2, usage, failure);
3979
4149
  } catch (err) {
3980
4150
  if (err instanceof ChannelAuthError) throw err;
3981
4151
  if (err instanceof ChannelTerminalError) {
@@ -4953,7 +5123,7 @@ var ChannelDriver = class _ChannelDriver {
4953
5123
  * exists but is wedged, so the next attempt must get a fresh one
4954
5124
  * instead of reusing it — see WI-1's server-side null-clearing PATCH).
4955
5125
  */
4956
- async markFailed(conversationId, messageId, sessionId, error2, usage) {
5126
+ async markFailed(conversationId, messageId, sessionId, error2, usage, failure) {
4957
5127
  const body = { status: "failed" };
4958
5128
  if (sessionId === null) {
4959
5129
  body.opencode_session_id = null;
@@ -4962,6 +5132,12 @@ var ChannelDriver = class _ChannelDriver {
4962
5132
  }
4963
5133
  if (error2 !== void 0) body.error = error2;
4964
5134
  if (usage) Object.assign(body, usage);
5135
+ if (failure) {
5136
+ body.failure_kind = failure.kind;
5137
+ body.failure_provider_id = failure.providerId;
5138
+ body.failure_model_id = failure.modelId;
5139
+ body.failure_reason = failure.reason;
5140
+ }
4965
5141
  await this.callWithRetry(
4966
5142
  "marking message as failed",
4967
5143
  () => this.fetchImpl(
@@ -4974,6 +5150,29 @@ var ChannelDriver = class _ChannelDriver {
4974
5150
  )
4975
5151
  );
4976
5152
  }
5153
+ /**
5154
+ * Classify an errored turn as a model-auth failure (#736 P1-4), for `markFailed`.
5155
+ *
5156
+ * `messageFailure` alone (structured OpenCode error → `model_auth`) covers
5157
+ * most cases; when it returns `null` on this ALREADY-FAILED turn, fall back
5158
+ * to the P1-2b zero-provider check — one extra loopback call to
5159
+ * `hasAnyConfiguredProvider`, only reached when the structured classifier
5160
+ * couldn't place it. Fails open (never throws): a fallback probe failure
5161
+ * (`null`/indeterminate) leaves the classification `null`, which produces
5162
+ * today's byte-identical PATCH body via `markFailed`'s `if (failure)` guard.
5163
+ */
5164
+ async classifyModelAuthFailure(messages, userMessageId) {
5165
+ const classified = messageFailure(messages, userMessageId);
5166
+ if (classified != null) return classified;
5167
+ const reply = findLastAssistantReplyFor(messages, userMessageId);
5168
+ const hasProvider = await hasAnyConfiguredProvider(this.port);
5169
+ return applyZeroProviderFallback(
5170
+ classified,
5171
+ hasProvider,
5172
+ reply?.info?.providerID ?? null,
5173
+ reply?.info?.modelID ?? null
5174
+ );
5175
+ }
4977
5176
  /**
4978
5177
  * Best-effort, SINGLE-ATTEMPT runner→server telemetry ping
4979
5178
  * (queued-followup-redrive). `POST .../messages/:id/signal {signal, ...extra}`
@@ -5456,6 +5655,10 @@ function log2(state, message, level = "info") {
5456
5655
  function logActivity(state, entry) {
5457
5656
  const level = entry.level ?? (entry.type === "error" ? "error" : "info");
5458
5657
  if (!meetsThreshold(state, level)) return;
5658
+ forwardRunnerActivity(
5659
+ { level, message: entry.message, error: entry.error },
5660
+ { agentId: state.agentId, authHeader: state.authHeader }
5661
+ );
5459
5662
  const fullEntry = {
5460
5663
  ...entry,
5461
5664
  level,
@@ -5810,6 +6013,7 @@ async function run(options) {
5810
6013
  sessionCleanupTimers: [],
5811
6014
  authHeader: ""
5812
6015
  };
6016
+ setTelemetryAuthProvider(() => ({ authHeader: state.authHeader, agentId: state.agentId }));
5813
6017
  if (fileSyncDirectories.length > 0) {
5814
6018
  log2(state, `File sync enabled for: ${fileSyncDirectories.join(", ")}`);
5815
6019
  } else {
@@ -6076,6 +6280,18 @@ async function run(options) {
6076
6280
  type: "info",
6077
6281
  message: `Tunnel ${isReconnect ? "reconnected" : "connected"} (runner: ${agentId})`
6078
6282
  });
6283
+ if (options.tunnelReadyFile) {
6284
+ const marker = writeTunnelReadyMarker(options.tunnelReadyFile, agentId);
6285
+ if (marker.ok) {
6286
+ log2(state, `Wrote tunnel readiness marker to ${options.tunnelReadyFile}`, "debug");
6287
+ } else {
6288
+ log2(
6289
+ state,
6290
+ `Failed to write tunnel readiness marker to ${options.tunnelReadyFile}: ${marker.error}`,
6291
+ "error"
6292
+ );
6293
+ }
6294
+ }
6079
6295
  emitAgentConnected(state.agentId, {
6080
6296
  port: state.port,
6081
6297
  cli_version: getCliVersion(),
@@ -6240,6 +6456,9 @@ program.command("run").description("Connect to Evident and process messages").op
6240
6456
  "Allow Evident to write files into this directory (repeatable). Omit to disable file sync entirely.",
6241
6457
  (value, previous) => previous.concat([value]),
6242
6458
  []
6459
+ ).option(
6460
+ "--tunnel-ready-file <path>",
6461
+ "Path to write once the tunnel is connected (set by the MicroVM hooks; unused on a developer machine)"
6243
6462
  ).action(
6244
6463
  (options) => {
6245
6464
  run({
@@ -6259,7 +6478,8 @@ program.command("run").description("Connect to Evident and process messages").op
6259
6478
  sessionCleanupInterval: options.sessionCleanupInterval,
6260
6479
  // Raw values — expansion/validation is single-sourced in run.ts's
6261
6480
  // resolveFileSyncDirectories.
6262
- enableFileSyncTo: options.enableFileSyncTo
6481
+ enableFileSyncTo: options.enableFileSyncTo,
6482
+ tunnelReadyFile: options.tunnelReadyFile
6263
6483
  });
6264
6484
  }
6265
6485
  );