oc-flight-deck 0.12.0 → 0.19.2

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/src/tui/go.ts CHANGED
@@ -8,34 +8,107 @@
8
8
  // * Guard is per-session, so it waits for `follow(sessionID)` before fetching.
9
9
  // Go usage is account-wide: one API key, one shared quota, no session to
10
10
  // target — so the timer starts at construction and there is no `follow`.
11
- // * The key is read on every poll through the same env accessor the Zen Go
12
- // client uses, so a key loaded or rotated after startup is picked up
13
- // without a restart.
11
+ // * The key is resolved on every poll - from the host's credential store
12
+ // (direct or wrapped), then the provider catalog's resolved `settings.apiKey`
13
+ // - so a key loaded, rotated, or activated after startup is picked up
14
+ // without a restart. Every source is guarded and bounded, so a hung read
15
+ // becomes a named reason, not a stall.
14
16
  //
15
17
  // Why the store bridge at all is documented in ./guard.ts and ./ticker.ts: the
16
18
  // host's Solid and the plugin's are separate module instances, so only the
17
19
  // host-owned `context.storage.memory` store can wake the host render.
18
20
  //
19
- // The bridge never throws. Any failure — no store, no key, refused request,
20
- // non-OK status, malformed JSON — stores `null`, which the getter reads as
21
+ // The bridge never throws. Any failure - no store, no key, refused request,
22
+ // non-OK status, malformed JSON - stores `null`, which the getter reads as
21
23
  // `undefined` so the persist layer renders the placeholder. A missing key is
22
24
  // explicitly not an error: it is the row's documented "no key" dash path.
25
+ //
26
+ // A blank panel must never be silent about WHY it is blank, so the store also
27
+ // carries a {@link GoNoDataReason} beside the null value: the bridge records
28
+ // which stage failed (see the type) and exposes it as `reason`. The two are
29
+ // written together, so a reader can never see a null value with a stale reason.
30
+
31
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
32
+ import { tmpdir } from "node:os";
33
+ import { join } from "node:path";
34
+
35
+ import { normalizeGoUsage, type GoUsage, type GoWindow } from "./go-usage.js";
23
36
 
24
- import { normalizeGoUsage, type GoUsage } from "./go-usage.js";
37
+ /**
38
+ * Why the bridge has no usage to show.
39
+ *
40
+ * Additive to `value`: a reader that only wants the usage is unchanged, while
41
+ * a surface that has to explain a blank panel reads this alongside it. The set
42
+ * is closed so a renderer can trust it, and each value names the failed stage,
43
+ * not a symptom:
44
+ *
45
+ * * `"no-client"` - none of the host's credential sources could be asked at
46
+ * all: the client was absent, its `list` was not a function, or it answered
47
+ * with something that was not a usable list. The key lookup never had a
48
+ * chance to run.
49
+ * * `"no-key"` - a source answered, but held no usable `opencode-go`
50
+ * credential.
51
+ * * `"http"` - a key was resolved and the usage request threw or came
52
+ * back non-OK.
53
+ * * `"parse"` - the request succeeded but the body did not normalize into
54
+ * any known window shape.
55
+ * * `"timeout"` - a credential source never settled inside its hard bound,
56
+ * so the poll stopped waiting rather than stalling forever.
57
+ * * `"pending"` - a bridge exists but has produced neither a value nor a
58
+ * reason yet (its first poll is still in flight).
59
+ */
60
+ export type GoNoDataReason = "no-client" | "no-key" | "http" | "parse" | "timeout" | "pending";
25
61
 
26
62
  /** The value kept in the host's memory store. Null means "no data". */
27
63
  interface GoStoreState {
28
64
  value: GoUsage | null;
65
+ /**
66
+ * Why `value` is null, or null when there is a value (or the reason is not
67
+ * yet known). Written atomically with `value` so the two never disagree.
68
+ */
69
+ reason: GoNoDataReason | null;
29
70
  }
30
71
 
31
72
  /** The store the host hands back: read-only to us, reactive to the host. */
32
73
  interface GoStore {
33
74
  readonly value?: unknown;
75
+ readonly reason?: unknown;
34
76
  }
35
77
 
36
78
  /** The mutation function the host hands back. */
37
79
  type GoUpdate = (mutation: (draft: GoStoreState) => void) => void;
38
80
 
81
+ /**
82
+ * The credential store as the bridge reads it.
83
+ *
84
+ * Minimal on purpose, like `storage` above: the bridge needs one capability, so
85
+ * it names one capability and stays trivially stubbable. It is no longer a
86
+ * stand-in for a declaration the pin lacked - the pinned `@opencode/plugin`
87
+ * client (`@opencode/client` 2.0.26) declares `credential.list()`, so the call
88
+ * below is direct and type-checked. The runtime `typeof list === "function"`
89
+ * check stays because the host binary is what actually answers: a host whose
90
+ * client predates the method yields no key instead of throwing.
91
+ */
92
+ interface GoCredentialClient {
93
+ readonly credential?: GoCredentialStore;
94
+ /**
95
+ * Some contexts wrap the client one level deeper. Reached only through
96
+ * `credential.list` again, and only when the direct store yielded nothing.
97
+ */
98
+ readonly api?: { readonly credential?: GoCredentialStore };
99
+ }
100
+
101
+ /**
102
+ * The one method the bridge calls on the credential group.
103
+ *
104
+ * The return stays `unknown` deliberately: the payload arrives over the wire
105
+ * and is validated entry by entry at runtime, so trusting a declared element
106
+ * type here would only move the failure into the loop.
107
+ */
108
+ interface GoCredentialStore {
109
+ readonly list: () => Promise<unknown>;
110
+ }
111
+
39
112
  /** The one host capability the bridge needs, so it stays trivially stubbable. */
40
113
  export interface GoHost {
41
114
  readonly storage?: {
@@ -46,12 +119,29 @@ export interface GoHost {
46
119
  */
47
120
  memory(key: string, options: { readonly initial: GoStoreState }): unknown;
48
121
  };
122
+ /** The host's HTTP client, reached only for its credential store. */
123
+ readonly client?: GoCredentialClient;
124
+ /**
125
+ * The host's data collections, reached only for the provider catalog: the
126
+ * provider RPC does not redact, so the resolved `settings.apiKey` may be
127
+ * there when the credential store is not.
128
+ */
129
+ readonly data?: {
130
+ readonly location?: {
131
+ readonly provider?: unknown;
132
+ };
133
+ };
49
134
  }
50
135
 
51
- /** Injectable key accessor and fetch, so tests never touch the network or env. */
136
+ /** Injectable key accessor and fetch, so tests never touch the network. */
52
137
  export interface GoDeps {
138
+ /** Synchronous key override; short-circuits the store. */
53
139
  readonly key?: () => string | undefined;
140
+ /** Async key override; used when `key` is absent, ahead of the store. */
141
+ readonly resolveKey?: () => Promise<string | undefined>;
54
142
  readonly fetchJson?: (url: string, init: RequestInit) => Promise<unknown>;
143
+ /** Overrides the credential-source hard bound, so a hung store is testable fast. */
144
+ readonly credentialTimeoutMs?: number;
55
145
  }
56
146
 
57
147
  interface GoBridge {
@@ -63,6 +153,12 @@ interface GoBridge {
63
153
  * `undefined` means no data, so the persist layer renders the placeholder.
64
154
  */
65
155
  readonly usage: GoUsage | undefined;
156
+ /**
157
+ * Why {@link usage} is `undefined`, or `undefined` when there IS a value (or
158
+ * the reason is not yet known). Read it inside the same render as `usage` so
159
+ * the host registers the dependency and a blank panel can name its cause.
160
+ */
161
+ readonly reason: GoNoDataReason | undefined;
66
162
  /** Stops the timer. Safe to call more than once. */
67
163
  dispose(): void;
68
164
  }
@@ -82,11 +178,46 @@ export const GO_POLL_MS = 60_000;
82
178
  /** The Zen Go usage endpoint. Fixed: usage is account-wide, not per-session. */
83
179
  export const GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
84
180
 
85
- /** The env var the Zen Go client reads its key from, matched by name only. */
86
- export const GO_KEY_ENV = "OPENCODE_GO_API_KEY";
181
+ /**
182
+ * The integration id the Zen Go provider stores its credential under. The
183
+ * provider id and the integration id are the same string, so this is the one
184
+ * value that selects the right entry out of `credential.list()`. It is NOT a
185
+ * key, a label, or a value: which entry is the right one is decided by its
186
+ * `active` flag, which differs per user.
187
+ */
188
+ const GO_INTEGRATION_ID = "opencode-go";
87
189
 
88
190
  const GO_TIMEOUT_MS = 10_000;
89
191
 
192
+ /**
193
+ * The hard bound on any single credential source.
194
+ *
195
+ * A credential read that never settles must not stall the poll forever, so it
196
+ * races this bound and resolves to the `"timeout"` reason instead.
197
+ */
198
+ export const GO_CREDENTIAL_TIMEOUT_MS = 6_000;
199
+
200
+ /** Where the poll's observation log lives, under the OS temp directory. */
201
+ const GO_LOG_DIR = "opencode";
202
+ const GO_LOG_FILE = "flight-deck-go.log";
203
+
204
+ /**
205
+ * Opt-in switch for the observation log: the log is written only when this
206
+ * environment variable is `"1"`, so the default is quiet (no disk write).
207
+ */
208
+ export const GO_LOG_ENV = "FLIGHT_DECK_GO_LOG";
209
+
210
+ function goLogEnabled(): boolean {
211
+ try {
212
+ return process.env[GO_LOG_ENV] === "1";
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+
218
+ /** The log is overwritten once it holds this many lines, so it stays small. */
219
+ export const GO_LOG_MAX_LINES = 200;
220
+
90
221
  /**
91
222
  * Fetch and parse a usage payload. A non-OK response throws so the poll's one
92
223
  * catch handles both transport and status failures; the body is only parsed
@@ -94,7 +225,11 @@ const GO_TIMEOUT_MS = 10_000;
94
225
  */
95
226
  async function defaultFetchJson(url: string, init: RequestInit): Promise<unknown> {
96
227
  const response = await fetch(url, init);
97
- if (!response.ok) throw new Error(`go usage: HTTP ${response.status}`);
228
+ if (!response.ok) {
229
+ const error = new Error(`go usage: HTTP ${response.status}`) as Error & { status?: number };
230
+ error.status = response.status;
231
+ throw error;
232
+ }
98
233
  return response.json();
99
234
  }
100
235
 
@@ -104,7 +239,7 @@ async function defaultFetchJson(url: string, init: RequestInit): Promise<unknown
104
239
  function openStore(storage: NonNullable<GoHost["storage"]>): { store: GoStore; update: GoUpdate } | undefined {
105
240
  let opened: unknown;
106
241
  try {
107
- opened = storage.memory(GO_KEY, { initial: { value: null } });
242
+ opened = storage.memory(GO_KEY, { initial: { value: null, reason: null } });
108
243
  } catch {
109
244
  return undefined;
110
245
  }
@@ -117,20 +252,160 @@ function openStore(storage: NonNullable<GoHost["storage"]>): { store: GoStore; u
117
252
  return { store: store as GoStore, update: update as GoUpdate };
118
253
  }
119
254
 
255
+ /**
256
+ * Canonical window order, matching ./go-usage.ts, so a stored value reads back
257
+ * in the same order the fetch path wrote it.
258
+ */
259
+ const GO_WINDOW_ORDER: readonly GoWindow["id"][] = ["5h", "1w", "1m"];
260
+
261
+ /** A finite number, or `undefined` when the value is not one. Never throws. */
262
+ function asStoredNumber(value: unknown): number | undefined {
263
+ try {
264
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
265
+ } catch {
266
+ return undefined;
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Validate one stored window AS a {@link GoUsage} entry, not a raw payload.
272
+ *
273
+ * The store already holds normalised windows (`{ id, ratio, ... }`), so the
274
+ * raw-payload normaliser must not run here: it only understands `percent` /
275
+ * `used` / `limit`, and a window carrying only `ratio` would fall through
276
+ * `buildWindow` and be dropped, leaving the panel on `pending` despite a good
277
+ * poll. Only the `5h`/`1w`/`1m` ids survive; a present `ratio` must be finite
278
+ * (clamped to `[0, 1]`); `resetAtMs`/`status`/`used`/`limit` are preserved when
279
+ * readable. Never throws.
280
+ */
281
+ function asStoredWindow(entry: unknown, seen: Set<GoWindow["id"]>): GoWindow | undefined {
282
+ try {
283
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return undefined;
284
+ const record = entry as Record<string, unknown>;
285
+ let id: unknown;
286
+ let ratioRaw: unknown;
287
+ let usedRaw: unknown;
288
+ let limitRaw: unknown;
289
+ let resetRaw: unknown;
290
+ let statusRaw: unknown;
291
+ try {
292
+ id = record["id"];
293
+ } catch {
294
+ return undefined;
295
+ }
296
+ if (id !== "5h" && id !== "1w" && id !== "1m") return undefined;
297
+ if (seen.has(id)) return undefined;
298
+ try {
299
+ ratioRaw = record["ratio"];
300
+ } catch {
301
+ return undefined;
302
+ }
303
+ let ratio: number | undefined;
304
+ if (ratioRaw !== undefined) {
305
+ const finite = asStoredNumber(ratioRaw);
306
+ if (finite === undefined) return undefined;
307
+ ratio = Math.min(1, Math.max(0, finite));
308
+ }
309
+ let used: number | undefined;
310
+ let limit: number | undefined;
311
+ let resetAtMs: number | undefined;
312
+ let status: string | undefined;
313
+ try {
314
+ usedRaw = record["used"];
315
+ limitRaw = record["limit"];
316
+ resetRaw = record["resetAtMs"];
317
+ statusRaw = record["status"];
318
+ } catch {
319
+ return undefined;
320
+ }
321
+ used = asStoredNumber(usedRaw);
322
+ limit = asStoredNumber(limitRaw);
323
+ resetAtMs = asStoredNumber(resetRaw);
324
+ try {
325
+ if (typeof statusRaw === "string" && statusRaw.trim().length > 0) status = statusRaw.trim();
326
+ } catch {
327
+ status = undefined;
328
+ }
329
+ if (used === undefined && limit === undefined && ratio === undefined) return undefined;
330
+ seen.add(id);
331
+ const result: { -readonly [K in keyof GoWindow]: GoWindow[K] } = { id };
332
+ if (used !== undefined) result.used = used;
333
+ if (limit !== undefined) result.limit = limit;
334
+ if (ratio !== undefined) result.ratio = ratio;
335
+ if (resetAtMs !== undefined) result.resetAtMs = resetAtMs;
336
+ if (status !== undefined) result.status = status;
337
+ return result;
338
+ } catch {
339
+ return undefined;
340
+ }
341
+ }
342
+
120
343
  function readUsage(store: GoStore | undefined): GoUsage | undefined {
121
344
  try {
122
345
  const value = store?.value;
123
346
  if (value === null || value === undefined) return undefined;
124
- return normalizeGoUsage(value);
347
+ if (typeof value !== "object" || Array.isArray(value)) return undefined;
348
+ let windowsRaw: unknown;
349
+ try {
350
+ windowsRaw = (value as Record<string, unknown>)["windows"];
351
+ } catch {
352
+ return undefined;
353
+ }
354
+ if (!Array.isArray(windowsRaw)) return undefined;
355
+ const windows: GoWindow[] = [];
356
+ const seen = new Set<GoWindow["id"]>();
357
+ for (const entry of windowsRaw) {
358
+ const window = asStoredWindow(entry, seen);
359
+ if (window !== undefined) windows.push(window);
360
+ }
361
+ if (windows.length === 0) return undefined;
362
+ windows.sort((a, b) => GO_WINDOW_ORDER.indexOf(a.id) - GO_WINDOW_ORDER.indexOf(b.id));
363
+ return { windows };
125
364
  } catch {
126
365
  return undefined;
127
366
  }
128
367
  }
129
368
 
130
- function writeValue(opened: { store: GoStore; update: GoUpdate }, value: GoUsage | null): boolean {
369
+ /** The closed set of reasons, so a corrupt store value can never leak through. */
370
+ export const GO_NO_DATA_REASONS: readonly GoNoDataReason[] = [
371
+ "no-client",
372
+ "no-key",
373
+ "http",
374
+ "parse",
375
+ "timeout",
376
+ "pending",
377
+ ];
378
+
379
+ /**
380
+ * Why the store has no value, or `undefined` when it has one or the reason is
381
+ * unreadable. Validated against the closed set for the same reason the frame
382
+ * and usage are: the store is reached across a version boundary and may be
383
+ * written by a hot-reloaded sibling.
384
+ */
385
+ function readReason(store: GoStore | undefined): GoNoDataReason | undefined {
386
+ try {
387
+ const reason = store?.reason;
388
+ if (typeof reason !== "string") return undefined;
389
+ return (GO_NO_DATA_REASONS as readonly string[]).includes(reason) ? (reason as GoNoDataReason) : undefined;
390
+ } catch {
391
+ return undefined;
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Write the value and its reason as one mutation, so a reader can never observe
397
+ * a null value paired with a stale reason. A non-null value always clears the
398
+ * reason; a null value carries the reason that produced it.
399
+ */
400
+ function writeValue(
401
+ opened: { store: GoStore; update: GoUpdate },
402
+ value: GoUsage | null,
403
+ reason: GoNoDataReason,
404
+ ): boolean {
131
405
  try {
132
406
  opened.update((draft) => {
133
407
  draft.value = value;
408
+ draft.reason = value === null ? reason : null;
134
409
  });
135
410
  return true;
136
411
  } catch {
@@ -138,15 +413,237 @@ function writeValue(opened: { store: GoStore; update: GoUpdate }, value: GoUsage
138
413
  }
139
414
  }
140
415
 
141
- function resolveKeyFn(deps: GoDeps | undefined): () => string | undefined {
416
+ function resolveKeyFn(deps: GoDeps | undefined): (() => string | undefined) | undefined {
142
417
  if (deps !== undefined) {
143
418
  try {
144
419
  if (typeof deps.key === "function") return deps.key;
145
420
  } catch {
146
- // fall through to the env accessor
421
+ // fall through to the async override, then the store
422
+ }
423
+ }
424
+ return undefined;
425
+ }
426
+
427
+ function resolveAsyncKeyFn(deps: GoDeps | undefined): (() => Promise<string | undefined>) | undefined {
428
+ if (deps !== undefined) {
429
+ try {
430
+ if (typeof deps.resolveKey === "function") return deps.resolveKey;
431
+ } catch {
432
+ // fall through to the store
433
+ }
434
+ }
435
+ return undefined;
436
+ }
437
+
438
+ /** A credential entry's key, or undefined unless it is a usable `key` value. */
439
+ function keyOfValue(value: unknown): string | undefined {
440
+ if (value === null || typeof value !== "object") return undefined;
441
+ const record = value as Record<string, unknown>;
442
+ if (record["type"] !== "key") return undefined;
443
+ const key = record["key"];
444
+ return typeof key === "string" && key.length > 0 ? key : undefined;
445
+ }
446
+
447
+ /** Read a property without letting a hostile getter or proxy throw. */
448
+ function safeGet(target: unknown, key: string): unknown {
449
+ try {
450
+ if (target === null || (typeof target !== "object" && typeof target !== "function")) return undefined;
451
+ return (target as Record<string, unknown>)[key];
452
+ } catch {
453
+ return undefined;
454
+ }
455
+ }
456
+
457
+ /** The credential-source bound, overridable for tests, defaulting to 6s. */
458
+ function resolveCredentialTimeout(deps: GoDeps | undefined): number {
459
+ if (deps !== undefined) {
460
+ try {
461
+ const value = deps.credentialTimeoutMs;
462
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
463
+ } catch {
464
+ // fall through to the default bound
147
465
  }
148
466
  }
149
- return () => process.env[GO_KEY_ENV];
467
+ return GO_CREDENTIAL_TIMEOUT_MS;
468
+ }
469
+
470
+ /** Where a resolved key came from, for the observation log only. */
471
+ export type GoKeySource = "credential" | "provider" | "none";
472
+
473
+ /** One source's outcome: a key, or why it had none, plus whether it answered. */
474
+ interface KeyAttempt {
475
+ readonly key?: string;
476
+ readonly reason?: GoNoDataReason;
477
+ /** True when the source answered with a readable collection, key or not. */
478
+ readonly answered: boolean;
479
+ }
480
+
481
+ /** The settled-or-not result of one guarded, timed source call. */
482
+ type Settled =
483
+ | { readonly ok: true; readonly value: unknown }
484
+ | { readonly ok: false; readonly timedOut: boolean };
485
+
486
+ /**
487
+ * Await `call()` under a hard bound.
488
+ *
489
+ * A promise that never settles resolves to `timedOut: true` instead of stalling
490
+ * the poll forever; a synchronous throw or a rejection is an error, not a
491
+ * timeout. Never rejects.
492
+ */
493
+ function settleCall(call: () => unknown, ms: number): Promise<Settled> {
494
+ let produced: unknown;
495
+ try {
496
+ produced = call();
497
+ } catch {
498
+ return Promise.resolve({ ok: false, timedOut: false });
499
+ }
500
+
501
+ const thenable =
502
+ produced !== null && (typeof produced === "object" || typeof produced === "function")
503
+ ? (produced as { then?: unknown }).then
504
+ : undefined;
505
+ if (typeof thenable !== "function") return Promise.resolve({ ok: true, value: produced });
506
+
507
+ return new Promise<Settled>((resolve) => {
508
+ const timer = setTimeout(() => resolve({ ok: false, timedOut: true }), ms);
509
+ (produced as Promise<unknown>).then(
510
+ (value) => {
511
+ clearTimeout(timer);
512
+ resolve({ ok: true, value });
513
+ },
514
+ () => {
515
+ clearTimeout(timer);
516
+ resolve({ ok: false, timedOut: false });
517
+ },
518
+ );
519
+ });
520
+ }
521
+
522
+ /**
523
+ * The list inside a credential response.
524
+ *
525
+ * The RPC may hand back a bare array or wrap it in an envelope (`{ data: [...] }`,
526
+ * `{ output: [...] }`); every one of those is accepted. Only a value that yields
527
+ * no array at all is not a usable list.
528
+ */
529
+ function asList(value: unknown): unknown[] | undefined {
530
+ if (Array.isArray(value)) return value;
531
+ if (value === null || typeof value !== "object") return undefined;
532
+ const record = value as Record<string, unknown>;
533
+ const data = record["data"];
534
+ if (Array.isArray(data)) return data;
535
+ const output = record["output"];
536
+ if (Array.isArray(output)) return output;
537
+ return undefined;
538
+ }
539
+
540
+ /**
541
+ * Whether a credential entry is the active one.
542
+ *
543
+ * Robust on purpose: the API may serialise `active` as a boolean `true` or a
544
+ * numeric `1`, so any truthy value counts. The active entry is the credential
545
+ * the user selected, and it differs per user - it is never hard-coded.
546
+ */
547
+ function isActive(value: unknown): boolean {
548
+ return Boolean(value);
549
+ }
550
+
551
+ /**
552
+ * The Zen Go key among credential entries.
553
+ *
554
+ * The ACTIVE entry for the `opencode-go` integration always wins. A non-active
555
+ * entry is a fallback ONLY when no entry is marked active. Among equally-active
556
+ * entries the first usable one wins.
557
+ */
558
+ function goKeyFromEntries(entries: readonly unknown[]): string | undefined {
559
+ let fallback: string | undefined;
560
+ for (const entry of entries) {
561
+ if (entry === null || typeof entry !== "object") continue;
562
+ const record = entry as Record<string, unknown>;
563
+ if (record["integrationID"] !== GO_INTEGRATION_ID) continue;
564
+ const key = keyOfValue(record["value"]);
565
+ if (key === undefined) continue;
566
+ if (isActive(record["active"])) return key;
567
+ if (fallback === undefined) fallback = key;
568
+ }
569
+ return fallback;
570
+ }
571
+
572
+ /**
573
+ * Ask one credential store for the Zen Go key.
574
+ *
575
+ * Guarded and timed: a store that is absent, whose `list` is not a function,
576
+ * that throws, times out, or answers with a non-list yields `"no-client"` or
577
+ * `"timeout"` with no key; a store that answers without a usable entry yields
578
+ * `"no-key"`. Never throws.
579
+ */
580
+ async function credentialAttempt(store: unknown, ms: number): Promise<KeyAttempt> {
581
+ const list = safeGet(store, "list");
582
+ if (typeof list !== "function") return { reason: "no-client", answered: false };
583
+ const settled = await settleCall(() => (list as () => unknown).call(store), ms);
584
+ if (!settled.ok) return { reason: settled.timedOut ? "timeout" : "no-client", answered: false };
585
+ const entries = asList(settled.value);
586
+ if (entries === undefined) return { reason: "no-client", answered: false };
587
+ const key = goKeyFromEntries(entries);
588
+ return key === undefined ? { reason: "no-key", answered: true } : { key, answered: true };
589
+ }
590
+
591
+ /** The `opencode-go` provider's own `settings.apiKey`, if it is there. */
592
+ function providerKeyOf(info: unknown): string | undefined {
593
+ if (info === null || typeof info !== "object") return undefined;
594
+ const record = info as Record<string, unknown>;
595
+ if (record["id"] !== GO_INTEGRATION_ID && record["integrationID"] !== GO_INTEGRATION_ID) return undefined;
596
+ const settings = record["settings"];
597
+ if (settings === null || typeof settings !== "object") return undefined;
598
+ const apiKey = (settings as Record<string, unknown>)["apiKey"];
599
+ return typeof apiKey === "string" && apiKey.length > 0 ? apiKey : undefined;
600
+ }
601
+
602
+ /** Unwrap a one-item envelope (`{ data: ProviderInfo }`) before reading it. */
603
+ function unwrapOne(value: unknown): unknown {
604
+ if (value === null || typeof value !== "object") return value;
605
+ const data = (value as Record<string, unknown>)["data"];
606
+ return data !== null && typeof data === "object" && !Array.isArray(data) ? data : value;
607
+ }
608
+
609
+ /**
610
+ * Ask the provider catalog for the `opencode-go` provider's resolved credential.
611
+ *
612
+ * The provider RPC does not redact, so the key may sit in `settings.apiKey`.
613
+ * Either collection shape - `get(id)` or `list()` - is handled defensively, and
614
+ * the call is guarded and timed like every other source. Never throws.
615
+ */
616
+ async function providerAttempt(provider: unknown, ms: number): Promise<KeyAttempt> {
617
+ if (provider === null || typeof provider !== "object") return { reason: "no-client", answered: false };
618
+ const collection = provider as Record<string, unknown>;
619
+ const get = collection["get"];
620
+ const list = collection["list"];
621
+
622
+ if (typeof get === "function") {
623
+ const settled = await settleCall(() => (get as (id: string) => unknown).call(collection, GO_INTEGRATION_ID), ms);
624
+ if (!settled.ok) return { reason: settled.timedOut ? "timeout" : "no-client", answered: false };
625
+ if (settled.value === undefined || settled.value === null) return { reason: "no-key", answered: true };
626
+ const key = providerKeyOf(unwrapOne(settled.value));
627
+ return key === undefined ? { reason: "no-key", answered: true } : { key, answered: true };
628
+ }
629
+
630
+ if (typeof list === "function") {
631
+ const settled = await settleCall(() => (list as () => unknown).call(collection), ms);
632
+ if (!settled.ok) return { reason: settled.timedOut ? "timeout" : "no-client", answered: false };
633
+ const entries = asList(settled.value);
634
+ if (entries === undefined) return { reason: "no-client", answered: false };
635
+ let key: string | undefined;
636
+ for (const entry of entries) {
637
+ const candidate = providerKeyOf(entry);
638
+ if (candidate !== undefined) {
639
+ key = candidate;
640
+ break;
641
+ }
642
+ }
643
+ return key === undefined ? { reason: "no-key", answered: true } : { key, answered: true };
644
+ }
645
+
646
+ return { reason: "no-client", answered: false };
150
647
  }
151
648
 
152
649
  function resolveFetchJson(deps: GoDeps | undefined): (url: string, init: RequestInit) => Promise<unknown> {
@@ -160,6 +657,51 @@ function resolveFetchJson(deps: GoDeps | undefined): (url: string, init: Request
160
657
  return defaultFetchJson;
161
658
  }
162
659
 
660
+ /** The HTTP status a failure carried, or `"n/a"` when it carried none. */
661
+ function httpOf(error: unknown): string {
662
+ const status = error !== null && typeof error === "object" ? (error as { status?: unknown }).status : undefined;
663
+ return typeof status === "number" && Number.isFinite(status) ? String(status) : "n/a";
664
+ }
665
+
666
+ /**
667
+ * The observation boundary: ONE bounded line per poll outcome, so a failure is
668
+ * readable next time.
669
+ *
670
+ * Written under the OS temp directory, resolved via `os.tmpdir()`, and only
671
+ * when `FLIGHT_DECK_GO_LOG=1` (see {@link GO_LOG_ENV}): the default is quiet.
672
+ * It records which source was consulted, whether it produced a key, the HTTP
673
+ * status, the parse result, and the reason - and NEVER the key or any part of
674
+ * it. Best effort: a log that cannot be written must never affect the poll.
675
+ * Rotated by overwriting once the file holds {@link GO_LOG_MAX_LINES} lines.
676
+ */
677
+ function logPoll(entry: {
678
+ readonly src: GoKeySource;
679
+ readonly key: boolean;
680
+ readonly http: string;
681
+ readonly parse: string;
682
+ readonly reason: string;
683
+ }): void {
684
+ if (!goLogEnabled()) return;
685
+ try {
686
+ const directory = join(tmpdir(), GO_LOG_DIR);
687
+ const path = join(directory, GO_LOG_FILE);
688
+ const line = `ts=${new Date().toISOString()} src=${entry.src} key=${entry.key ? "yes" : "no"} http=${entry.http} parse=${entry.parse} reason=${entry.reason}\n`;
689
+
690
+ let prior = "";
691
+ try {
692
+ if (existsSync(path)) prior = readFileSync(path, "utf8");
693
+ } catch {
694
+ prior = "";
695
+ }
696
+ const lines = prior.length === 0 ? 0 : prior.split("\n").filter((row) => row.length > 0).length;
697
+ mkdirSync(directory, { recursive: true });
698
+ if (lines >= GO_LOG_MAX_LINES) writeFileSync(path, line);
699
+ else appendFileSync(path, line);
700
+ } catch {
701
+ // Observation must never break the observed.
702
+ }
703
+ }
704
+
163
705
  /**
164
706
  * Start polling Go usage into the host's memory store, or return `undefined`
165
707
  * when there is no usable store.
@@ -168,9 +710,11 @@ function resolveFetchJson(deps: GoDeps | undefined): (url: string, init: Request
168
710
  * starts here and reads the key afresh on every poll. The first poll fires
169
711
  * immediately so the row populates without waiting a full interval.
170
712
  *
171
- * Assumption: `deps` is a test-only override. Production omits it, so the
172
- * accessor is `process.env[GO_KEY_ENV]` on each poll (late keys recover) and
173
- * the request is the real `fetch` with a bounded timeout.
713
+ * Assumption: `deps` is a test-only override. Production omits it, so on each
714
+ * poll the key is resolved from the host's credential sources - the credential
715
+ * store, then the provider catalog's `settings.apiKey` (late or rotated keys
716
+ * recover) - each under a hard bound, and the request is the real `fetch` with
717
+ * a bounded timeout.
174
718
  */
175
719
  export function startGoBridge(
176
720
  host: GoHost | undefined,
@@ -185,7 +729,82 @@ export function startGoBridge(
185
729
 
186
730
  const cadence = Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : GO_POLL_MS;
187
731
  const keyFn = resolveKeyFn(deps);
732
+ const asyncKeyFn = resolveAsyncKeyFn(deps);
188
733
  const fetchJson = resolveFetchJson(deps);
734
+ const credentialTimeoutMs = resolveCredentialTimeout(deps);
735
+ const client = host.client;
736
+ // Read the nested sources once, through `safeGet`, so a hostile getter or a
737
+ // wrapped client cannot throw out of the setup.
738
+ const directStore = safeGet(client, "credential");
739
+ const wrappedStore = safeGet(safeGet(client, "api"), "credential");
740
+ const providerSource = safeGet(safeGet(safeGet(host, "data"), "location"), "provider");
741
+
742
+ // The key source, in order: an injected override (`key`, then `resolveKey`),
743
+ // then the real sources - the host's own credential store (direct, then a
744
+ // context that wraps the client) and the provider catalog's unredacted
745
+ // `settings.apiKey`. Every source is guarded and timed, and the result names
746
+ // WHICH source produced the key (or why none did), so the blank panel is
747
+ // never silent and never lies. There is deliberately no environment fallback:
748
+ // the key comes only from OpenCode's own credential store.
749
+ // Deliberately renderer-side, not server-side: the TUI/CLI plugin page
750
+ // documents `context.client` as "the generated OpenCode client" but gives
751
+ // no credential-read example or credential-specific authorization; the
752
+ // documented server-side secret channel is `integration.connection.active`
753
+ // + `resolve`, exposed to the renderer through an RPC contract. The move
754
+ // stays unmade because one fact is unestablished: whether
755
+ // `resolve(active("opencode-go"))` yields the SAME key the Zen Go usage
756
+ // endpoint accepts. OpenCode's own provider plugin
757
+ // (`packages/core/src/plugin/provider/opencode.ts`, upstream) resolves only
758
+ // the `opencode` (Console OAuth) integration; the endpoint's accepted
759
+ // credential is undocumented, and the `settings.apiKey` source below has
760
+ // no documented server-side equivalent, so the move could silently lose
761
+ // the feature for installs whose key lives outside that connection.
762
+ const readKey = async (): Promise<{ key?: string; src: GoKeySource; reason?: GoNoDataReason }> => {
763
+ if (keyFn !== undefined) {
764
+ try {
765
+ const key = keyFn();
766
+ return typeof key === "string" && key.length > 0
767
+ ? { key, src: "credential" }
768
+ : { src: "none", reason: "no-key" };
769
+ } catch {
770
+ return { src: "none", reason: "no-key" };
771
+ }
772
+ }
773
+ if (asyncKeyFn !== undefined) {
774
+ try {
775
+ const key = await asyncKeyFn();
776
+ return typeof key === "string" && key.length > 0
777
+ ? { key, src: "credential" }
778
+ : { src: "none", reason: "no-key" };
779
+ } catch {
780
+ return { src: "none", reason: "no-key" };
781
+ }
782
+ }
783
+
784
+ let answered = false;
785
+ let timedOut = false;
786
+
787
+ // a. the host's own credential store.
788
+ const direct = await credentialAttempt(directStore, credentialTimeoutMs);
789
+ if (direct.key !== undefined) return { key: direct.key, src: "credential" };
790
+ answered = answered || direct.answered;
791
+ timedOut = timedOut || direct.reason === "timeout";
792
+
793
+ // b. a context that wraps the client one level deeper.
794
+ const wrapped = await credentialAttempt(wrappedStore, credentialTimeoutMs);
795
+ if (wrapped.key !== undefined) return { key: wrapped.key, src: "credential" };
796
+ answered = answered || wrapped.answered;
797
+ timedOut = timedOut || wrapped.reason === "timeout";
798
+
799
+ // c. the provider catalog's resolved credential.
800
+ const provider = await providerAttempt(providerSource, credentialTimeoutMs);
801
+ if (provider.key !== undefined) return { key: provider.key, src: "provider" };
802
+ answered = answered || provider.answered;
803
+ timedOut = timedOut || provider.reason === "timeout";
804
+
805
+ if (answered) return { src: "none", reason: "no-key" };
806
+ return { src: "none", reason: timedOut ? "timeout" : "no-client" };
807
+ };
189
808
 
190
809
  let timer: ReturnType<typeof setInterval> | undefined;
191
810
  // Generation invalidated on dispose, so a poll that outlives its bridge —
@@ -211,16 +830,21 @@ export function startGoBridge(
211
830
  const stillCurrent = () => myGeneration === generation && mySeq === latestSeq && !disposed;
212
831
 
213
832
  let key: string | undefined;
833
+ let keySrc: GoKeySource = "none";
834
+ let keyReason: GoNoDataReason = "no-key";
214
835
  try {
215
- key = keyFn();
836
+ const resolved = await readKey();
837
+ key = resolved.key;
838
+ keySrc = resolved.src;
839
+ if (resolved.reason !== undefined) keyReason = resolved.reason;
216
840
  } catch {
217
841
  key = undefined;
218
842
  }
219
843
  // No key is the row's "no key" dash path, not an error: store null and
220
844
  // make no request, so a keyless install never touches the endpoint.
221
845
  if (typeof key !== "string" || key.length === 0) {
222
- if (!stillCurrent()) return;
223
- if (!writeValue(opened, null)) stopTimer();
846
+ if (stillCurrent() && !writeValue(opened, null, keyReason)) stopTimer();
847
+ logPoll({ src: keySrc, key: false, http: "n/a", parse: "n/a", reason: keyReason });
224
848
  return;
225
849
  }
226
850
 
@@ -230,21 +854,30 @@ export function startGoBridge(
230
854
  headers: { Authorization: `Bearer ${key}` },
231
855
  signal: AbortSignal.timeout(GO_TIMEOUT_MS),
232
856
  });
233
- } catch {
857
+ } catch (error) {
234
858
  // Refused, timed out, non-OK status, or a transport failure: no data,
235
859
  // not an error.
236
- if (!stillCurrent()) return;
237
- if (!writeValue(opened, null)) stopTimer();
860
+ if (stillCurrent() && !writeValue(opened, null, "http")) stopTimer();
861
+ logPoll({ src: keySrc, key: true, http: httpOf(error), parse: "n/a", reason: "http" });
238
862
  return;
239
863
  }
240
- if (!stillCurrent()) return;
864
+
241
865
  let normalized: GoUsage | null;
242
866
  try {
243
867
  normalized = normalizeGoUsage(raw) ?? null;
244
868
  } catch {
245
869
  normalized = null;
246
870
  }
247
- if (!writeValue(opened, normalized)) stopTimer();
871
+ // A body that normalized to nothing is the `"parse"` reason; a real value
872
+ // clears the reason inside `writeValue`.
873
+ if (stillCurrent() && !writeValue(opened, normalized, "parse")) stopTimer();
874
+ logPoll({
875
+ src: keySrc,
876
+ key: true,
877
+ http: "ok",
878
+ parse: normalized === null ? "no" : "ok",
879
+ reason: normalized === null ? "parse" : "none",
880
+ });
248
881
  };
249
882
 
250
883
  timer = setInterval(() => {
@@ -257,6 +890,9 @@ export function startGoBridge(
257
890
  get usage() {
258
891
  return readUsage(opened.store);
259
892
  },
893
+ get reason() {
894
+ return readReason(opened.store);
895
+ },
260
896
  dispose() {
261
897
  disposed = true;
262
898
  generation += 1;