@yugimob/pi-opencode-go-rotation 1.7.2 → 1.7.4

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
@@ -24,7 +24,9 @@ The first key added becomes active immediately.
24
24
 
25
25
  If `OPENCODE_API_KEY` is set in the environment and no keys are configured, the extension recognizes it as an unmanaged `env` key: it reports that key's usage and keeps the footer working, but never writes it to the config file. Pi already uses that variable for its own requests, so nothing changes about how the model is called. `/opencode add` stores a managed copy that participates in rotation.
26
26
 
27
- The extension never imports keys from `auth.json` automatically. When no keys are configured, `/opencode` offers to import the auth.json key once; declining is remembered and it is not asked again.
27
+ The extension never imports keys from `auth.json` automatically. When no keys are configured, it observes the credential pi resolves from `auth.json` as an unmanaged `auth` key, so status, usage, and the footer work without writing it to the config file. It does not participate in rotation until imported.
28
+
29
+ `/opencode` offers to import the `auth.json` key once. Declining is remembered, and the observed `auth` key keeps working. Run `/opencode import` to import it later without the prompt.
28
30
 
29
31
  ## Interactive key manager
30
32
 
@@ -42,7 +44,7 @@ Changes are saved as soon as they are confirmed. Outside interactive mode the co
42
44
 
43
45
  ## How it works
44
46
 
45
- The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials. When no keys are configured, the environment key is only observed (as `env`) and never overridden or persisted.
47
+ The extension sets the active key as a runtime override, which takes priority over `OPENCODE_API_KEY` environment variables and `auth.json` credentials. When no keys are configured, the environment key and an `auth.json` credential are only observed (as `env` and `auth`) and never overridden or persisted.
46
48
 
47
49
  Automatic rotation is governed by `rotationPolicy`:
48
50
 
@@ -58,13 +60,13 @@ The extension has three recovery paths:
58
60
 
59
61
  1. **Usage-verified Go quota exhaustion**: when OpenCode Go returns HTTP 429, the extension sends the active key only to `https://opencode.ai/zen/go/v1/usage`. A key with a `rate-limited` window or a window at 100% is blocked until the latest reported reset, and the next candidate is activated. With `verifyCandidates` enabled, candidate keys are checked the same way before they are selected, so an exhausted key is blocked and skipped instead of being tried. Rotation prefers keys outside transient cooldown, but can clear a cooldown rather than keep using an exhausted key. When every key is quota-blocked, rotation stops and reports the earliest reset instead of cycling.
60
62
  2. **Transient limit errors** (`full` only): when the usage endpoint is unavailable, does not report an exhausted window, or does not finish within 10 seconds, the extension aborts a timed-out usage request, marks the current key as on cooldown, and switches to the next key that is not quota-blocked. Under `quota-only` and `off` the key stays active and the extension reports the limit instead of rotating.
61
- 3. **Silent stalls**: when an `opencode-go` provider request has no response or stream activity for the watchdog window, the extension aborts the hung turn and rewrites the abort as a retryable timeout error. It rotates only under `full`; otherwise pi retries the same key.
63
+ 3. **Silent stalls**: when an `opencode-go` provider request has no response or stream activity for the watchdog window, the extension aborts the hung turn and, after the run settles, automatically restarts the request through a hidden continuation message. There is no retry cap: every stall schedules another continuation. It rotates under `full`; otherwise the continuation uses the same key. Setting `retry.enabled: false` in pi's settings also disables the continuation.
62
64
 
63
65
  Checks happen at decision points only: a candidate is verified when `verifyCandidates` is enabled and it is about to be selected, and a key with a recorded block is left alone until its stored reset passes. Normal requests are not pre-checked. With the interactive footer active, the periodic footer refresh also re-checks the active key and, unless `rotationPolicy` is `off`, records a block if a window is full, so the next request can rotate before it fails.
64
66
 
65
67
  Fixed-window Go plan quota errors reported at message end follow the same policy: a parseable reset timestamp is authoritative; without one, `quota-only` and `off` record the cooldown-length block without rotating, and `full` rotates. A response-hook rotation is deduplicated so the matching message-end error cannot rotate twice.
66
68
 
67
- Pi's built-in auto-retry picks up the new key on the next request.
69
+ Rotations driven by a 429 or a response hook rely on pi's built-in auto-retry and its `retry.maxRetries`. A watchdog abort cannot use that retry because pi skips aborted runs, so the extension schedules its own continuation, with no cap.
68
70
 
69
71
  Cooldowns default to 60 minutes. Quota blocks expire at their persisted deadline. Manual `/opencode use <n>` and `/opencode next` clear both restrictions on the selected key.
70
72
 
@@ -79,18 +81,19 @@ personal: wk 40% · mo 55% | ↻ Nov 12
79
81
  ```
80
82
  The rolling 5-hour window is omitted from the footer.
81
83
 
82
- It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. Under `quota-only` and `full`, a window at 100% or rate-limited blocks the active key until the window's reset and the next request moves to another key; under `off` the footer reports the window without changing keys. The active key's name leads the line, and switching to another provider clears it.
84
+ It refreshes on session start, model changes, turns, key rotations, manual key commands, and every 5 minutes. Under `quota-only` and `full`, a window at 100% or rate-limited blocks the active key until the window's reset and the next request moves to another key; under `off` the footer reports the window without changing keys. The key name — or `env`/`auth` for an unmanaged key — leads the line, and switching to another provider clears it.
83
85
 
84
86
  ## Commands
85
87
 
86
88
  | Command | Description |
87
89
  |---------|-------------|
88
90
  | `/opencode` or `/opencode config` | Open the interactive key manager |
89
- | `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status, or the `env` key when only `OPENCODE_API_KEY` is set |
91
+ | `/opencode status` | Show all keys, active key marker, cooldown and quota-blocked status, or the unmanaged `env`/`auth` key when no managed keys are configured |
90
92
  | `/opencode usage` or `/opencode quota` | Fetch OpenCode Go usage for the active key without showing key material |
91
93
  | `/opencode use <n>` | Switch to key number `n` (1-based) and clear its cooldown and quota block |
92
94
  | `/opencode next` | Advance to the next configured key and clear its cooldown and quota block before activating it |
93
95
  | `/opencode add <name> <key>` | Add a new key |
96
+ | `/opencode import` | Import the `auth.json` key into the config even after a declined prompt |
94
97
  | `/opencode rm <n>` | Remove key number `n` |
95
98
  | `/opencode reset` | Clear all cooldowns and quota blocks |
96
99
  | `/opencode cooldown <min>` | Set or view cooldown duration in minutes |
@@ -112,7 +115,7 @@ Keys are stored in `~/.pi/agent/opencode-keys.json` with file permissions `0600`
112
115
  "activeKeyIndex": 0,
113
116
  "cooldownMinutes": 60,
114
117
  "watchdogEnabled": true,
115
- "watchdogIdleMs": 90000,
118
+ "watchdogIdleMs": 300000,
116
119
  "rotationPolicy": "quota-only",
117
120
  "verifyCandidates": false,
118
121
  "cooldowns": {},
@@ -134,19 +137,19 @@ Pair with pi's auto-retry for best results. In `~/.pi/agent/settings.json`:
134
137
  }
135
138
  ```
136
139
 
137
- Set `maxRetries` to at least the number of keys so all keys get a chance before pi gives up.
140
+ Set `maxRetries` to at least the number of keys so all keys get a chance before pi gives up. This applies to 429 and response-hook rotations. The watchdog continuation ignores `maxRetries` and has no cap, so it keeps restarting a silent stall; `retry.enabled: false` turns it off.
138
141
 
139
142
  ## Limitations
140
143
 
141
144
  - The watchdog is scoped to the `opencode-go` provider only. Other providers are not aborted, and the watchdog rotates only under `rotationPolicy` `full`.
142
- - A legitimate long-running request with no stream activity can be treated as stalled and aborted; tune with `/opencode watchdog <seconds>` or disable with `/opencode watchdog off`.
145
+ - The watchdog defaults to a 5-minute idle window. A legitimate long-running request with no stream activity can be treated as stalled and aborted; tune with `/opencode watchdog <seconds>` or disable with `/opencode watchdog off`.
143
146
  - Under `quota-only`, a bare 429, an HTTP 401, an unconfirmed usage result, and a watchdog stall never switch keys; the extension reports them and leaves the active key in place. `full` restores the earlier behavior.
144
147
  - When all non-quota-blocked keys are transiently cooling down (`full` only), the extension may clear the next eligible key's cooldown. It never automatically clears or force-selects a quota-blocked key.
145
148
  - When all keys are quota-blocked, automatic rotation stops on the current runtime key; each key becomes eligible again automatically when its stored reset deadline passes, or immediately after `/opencode reset`.
146
149
  - Recorded blocks are never re-probed before their stored reset, so there is no plan-top-up recovery; use `/opencode reset` or `/opencode use <n>` to clear a block early.
147
150
  - Go plan usage limits are tied to the subscription workspace; multiple keys from one workspace should not be assumed to provide independent quota. See the [OpenCode Go documentation](https://opencode.ai/docs/go/).
148
151
  - Keys added via `/opencode add` are stored in plaintext. The config file is created and maintained with `0600` permissions.
149
- - An `OPENCODE_API_KEY` environment key is never stored, so it cannot rotate and is not remembered across sessions; `/opencode add` creates a managed copy. A stored `auth.json` credential takes precedence over the environment variable, and the extension follows the credential pi resolves.
152
+ - An unmanaged `env` or `auth` key is never stored, so it cannot rotate and is not remembered as a managed key; `/opencode add` stores a managed copy, and `/opencode import` stores the `auth.json` credential. A stored `auth.json` credential takes precedence over the environment variable, and the extension follows the credential pi resolves.
150
153
 
151
154
  ## License
152
155
 
@@ -1,6 +1,6 @@
1
1
  export declare const CONFIG_PATH_ENV = "PI_OPENCODE_ROTATION_CONFIG";
2
2
  export declare const DEFAULT_COOLDOWN_MINUTES = 60;
3
- export declare const DEFAULT_WATCHDOG_IDLE_MS = 90000;
3
+ export declare const DEFAULT_WATCHDOG_IDLE_MS = 300000;
4
4
  export type RotationPolicy = "off" | "quota-only" | "full";
5
5
  export interface KeyEntry {
6
6
  name: string;
@@ -4,7 +4,7 @@ import { dirname, join } from "node:path";
4
4
  import { randomUUID } from "node:crypto";
5
5
  export const CONFIG_PATH_ENV = "PI_OPENCODE_ROTATION_CONFIG";
6
6
  export const DEFAULT_COOLDOWN_MINUTES = 60;
7
- export const DEFAULT_WATCHDOG_IDLE_MS = 90_000;
7
+ export const DEFAULT_WATCHDOG_IDLE_MS = 300_000;
8
8
  const DEFAULT_ROTATION_POLICY = "quota-only";
9
9
  const DEFAULT_VERIFY_CANDIDATES = false;
10
10
  const CONFIG_FILE_MODE = 0o600;
package/dist/index.js CHANGED
@@ -4,7 +4,8 @@ import { formatDuration, formatResetIn } from "./format-time.js";
4
4
  export { formatResetIn };
5
5
  const PROVIDER = "opencode-go";
6
6
  const OPENCODE_KEY_ENV = "OPENCODE_API_KEY";
7
- const AMBIENT_KEY_NAME = "env";
7
+ const AMBIENT_ENV_KEY_NAME = "env";
8
+ const AMBIENT_AUTH_KEY_NAME = "auth";
8
9
  const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
9
10
  const OPENCODE_GO_USAGE_TIMEOUT_MS = 10_000;
10
11
  const FIXED_WINDOW_QUOTA_RE = /\b(?:5[- ]hour|weekly|monthly)\b[\s\S]*\b(?:usage\s+)?(?:quota|limit)\b|\b(?:usage|plan)\s+allocated\s+quota\s+exceeded\b|\b(?:quota|limit)\b[\s\S]*\b(?:will\s+reset|resets?\s+at|fixed[- ]window)\b/i;
@@ -13,12 +14,34 @@ const USAGE_STATUS_KEY = "opencode-go-usage";
13
14
  const USAGE_STATUS_REFRESH_MS = 60_000;
14
15
  const USAGE_STATUS_STALE_MS = 300_000;
15
16
  const USAGE_STATUS_DEBOUNCE_MS = 2_000;
17
+ const WATCHDOG_RETRY_MESSAGE_TYPE = "opencode-go-timeout-retry";
18
+ const WATCHDOG_RETRY_PROMPT = "Continue.";
16
19
  function getCooldownMs(config) {
17
20
  return (config.cooldownMinutes || DEFAULT_COOLDOWN_MINUTES) * 60_000;
18
21
  }
19
22
  function getWatchdogIdleMs(config) {
20
23
  return config.watchdogIdleMs > 0 ? config.watchdogIdleMs : DEFAULT_WATCHDOG_IDLE_MS;
21
24
  }
25
+ function retryEnabled(ctx) {
26
+ try {
27
+ const getSettings = ctx.getSettings;
28
+ if (typeof getSettings !== "function")
29
+ return true;
30
+ const enabled = getSettings.call(ctx).retry?.enabled;
31
+ return enabled !== false;
32
+ }
33
+ catch {
34
+ return true;
35
+ }
36
+ }
37
+ function hasUsableKey(config, currentTime) {
38
+ if (config.keys.length === 0)
39
+ return true;
40
+ const keyIndex = pickAvailableKeyIndex(config, currentTime);
41
+ if (keyIndex === undefined)
42
+ return false;
43
+ return getQuotaBlockedUntil(config, keyIndex, currentTime) === undefined;
44
+ }
22
45
  export function shouldWatchProvider(provider) {
23
46
  return provider === PROVIDER;
24
47
  }
@@ -613,13 +636,15 @@ function usageWindowPercent(window) {
613
636
  return (window.used / window.limit) * 100;
614
637
  return undefined;
615
638
  }
616
- function formatStatus(config, now = Date.now(), ambientKeyApplied = false) {
639
+ function formatStatus(config, now = Date.now(), ambientKeyName) {
617
640
  const watchdogStatus = `Watchdog: ${config.watchdogEnabled ? "on" : "off"} (${Math.ceil(getWatchdogIdleMs(config) / 1000)}s idle)`;
618
641
  const policyStatus = `Rotation: ${config.rotationPolicy} (candidate verification ${config.verifyCandidates ? "on" : "off"})`;
619
642
  if (config.keys.length === 0) {
620
- const keyStatus = ambientKeyApplied
621
- ? `Using ${AMBIENT_KEY_NAME} key from ${OPENCODE_KEY_ENV}.`
622
- : "No keys configured. Use /opencode add <name> <key>.";
643
+ const keyStatus = ambientKeyName === AMBIENT_ENV_KEY_NAME
644
+ ? `Using ${AMBIENT_ENV_KEY_NAME} key from ${OPENCODE_KEY_ENV}.`
645
+ : ambientKeyName === AMBIENT_AUTH_KEY_NAME
646
+ ? "Using auth key from auth.json."
647
+ : "No keys configured. Use /opencode add <name> <key>.";
623
648
  return `${keyStatus}\n${policyStatus}\n${watchdogStatus}`;
624
649
  }
625
650
  const cdMs = getCooldownMs(config);
@@ -667,6 +692,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
667
692
  let watchdogAbortMessage;
668
693
  let watchdogTimeoutInfo;
669
694
  let watchdogRequestTimedOut = false;
695
+ let watchdogRetryPending = false;
670
696
  let usageDecisionEpoch = 0;
671
697
  let requestRateLimitState;
672
698
  const watchdogEvents = [];
@@ -674,6 +700,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
674
700
  let usageStatusTimer;
675
701
  let usageStatusDebounce;
676
702
  let usageStatusKeyIndex;
703
+ let usageStatusBearerToken;
677
704
  let usageStatusFetchedAt = 0;
678
705
  let usageStatusInFlight;
679
706
  let ambientKey;
@@ -701,16 +728,19 @@ export function createOpencodeGoRotationExtension(options = {}) {
701
728
  return false;
702
729
  }
703
730
  }
704
- async function resolveEnvKey(ctx) {
705
- const envKey = process.env[OPENCODE_KEY_ENV]?.trim();
706
- if (!envKey)
731
+ async function resolveAmbientKey(ctx, current) {
732
+ if (current.keys.length > 0)
707
733
  return undefined;
708
734
  const resolved = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
709
- return resolved === undefined || resolved === envKey ? envKey : undefined;
735
+ const envKey = process.env[OPENCODE_KEY_ENV]?.trim();
736
+ if (envKey && (resolved === undefined || resolved === envKey)) {
737
+ return { name: AMBIENT_ENV_KEY_NAME, key: envKey };
738
+ }
739
+ return resolved ? { name: AMBIENT_AUTH_KEY_NAME, key: resolved } : undefined;
710
740
  }
711
741
  function getAmbientUsageTarget() {
712
742
  return ambientKey
713
- ? { keyIndex: -1, keyName: AMBIENT_KEY_NAME, bearerToken: ambientKey }
743
+ ? { keyIndex: -1, keyName: ambientKey.name, bearerToken: ambientKey.key }
714
744
  : undefined;
715
745
  }
716
746
  function getStatusUsageTarget(current) {
@@ -802,13 +832,14 @@ export function createOpencodeGoRotationExtension(options = {}) {
802
832
  return;
803
833
  if (!refreshConfig())
804
834
  return;
835
+ ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
805
836
  const target = getStatusUsageTarget(config);
806
837
  if (!target) {
807
838
  setUsageStatus("opencode-go: no keys configured");
808
839
  return;
809
840
  }
810
841
  const currentTime = now();
811
- const keyChanged = target.keyIndex !== usageStatusKeyIndex;
842
+ const keyChanged = target.keyIndex !== usageStatusKeyIndex || target.bearerToken !== usageStatusBearerToken;
812
843
  if (!force && !keyChanged && currentTime - usageStatusFetchedAt < USAGE_STATUS_REFRESH_MS)
813
844
  return;
814
845
  if (usageStatusInFlight)
@@ -817,6 +848,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
817
848
  const usage = await fetchOpenCodeGoUsage(target, fetchApi, options.timers);
818
849
  const receivedAt = now();
819
850
  usageStatusKeyIndex = target.keyIndex;
851
+ usageStatusBearerToken = target.bearerToken;
820
852
  usageStatusFetchedAt = receivedAt;
821
853
  if (usageStatusCtx !== ctx)
822
854
  return;
@@ -994,7 +1026,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
994
1026
  return { rotated: false };
995
1027
  const currentTime = now();
996
1028
  if (config.keys.length <= 1 || !allowsWatchdogRotation(config)) {
997
- return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime), rotated: false };
1029
+ return { keyName: applyActiveKey(config, ctx.modelRegistry, currentTime) ?? ambientKey?.name, rotated: false };
998
1030
  }
999
1031
  if (shouldRotateAfterWatchdogTimeout(timeoutInfo, rateLimitAlreadyRotated)) {
1000
1032
  const previousIndex = config.activeKeyIndex;
@@ -1040,11 +1072,16 @@ export function createOpencodeGoRotationExtension(options = {}) {
1040
1072
  activeKey: rotation.keyName,
1041
1073
  ...timeoutInfo,
1042
1074
  });
1075
+ const currentTime = now();
1076
+ const willRetry = rotation.keyName !== undefined && hasUsableKey(config, currentTime) && retryEnabled(ctx);
1077
+ watchdogRetryPending = willRetry;
1043
1078
  watchdogAbortPending = true;
1044
- watchdogAbortMessage = rotation.keyName
1079
+ watchdogAbortMessage = willRetry
1045
1080
  ? `OpenCode Go timeout: ${formatTimeoutInfo(timeoutInfo)}; ${rotation.rotated ? "rotated to" : "using"} ${rotation.keyName}; retrying.`
1046
- : `OpenCode Go timeout: ${formatTimeoutInfo(timeoutInfo)}; no other key available.`;
1047
- ctx.ui.notify(watchdogAbortMessage, rotation.keyName ? "info" : "warning");
1081
+ : rotation.keyName
1082
+ ? `OpenCode Go timeout: ${formatTimeoutInfo(timeoutInfo)}; using ${rotation.keyName}.`
1083
+ : `OpenCode Go timeout: ${formatTimeoutInfo(timeoutInfo)}; no other key available.`;
1084
+ ctx.ui.notify(watchdogAbortMessage, willRetry ? "info" : "warning");
1048
1085
  ctx.abort();
1049
1086
  },
1050
1087
  timers: options.timers,
@@ -1064,15 +1101,19 @@ export function createOpencodeGoRotationExtension(options = {}) {
1064
1101
  async function promptAuthImport(ctx) {
1065
1102
  if (!ctx.hasUI || config.keys.length > 0 || config.authImportDeclined)
1066
1103
  return false;
1067
- ambientKey ??= await resolveEnvKey(ctx);
1068
- if (ambientKey)
1104
+ ambientKey = await resolveAmbientKey(ctx, config);
1105
+ if (ambientKey?.name === AMBIENT_ENV_KEY_NAME)
1069
1106
  return false;
1070
1107
  const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
1071
1108
  if (!authKey)
1072
1109
  return false;
1073
1110
  const confirmed = await ctx.ui.confirm("OpenCode Go key found", "An OpenCode Go API key exists in auth.json. Import it into the rotation config?");
1074
- if (confirmed === true)
1075
- return await importAuthKey(authKey);
1111
+ if (confirmed === true) {
1112
+ const imported = await importAuthKey(authKey);
1113
+ if (imported)
1114
+ ambientKey = undefined;
1115
+ return imported;
1116
+ }
1076
1117
  const persisted = mutateSharedConfig((freshConfig) => {
1077
1118
  freshConfig.authImportDeclined = true;
1078
1119
  return true;
@@ -1088,12 +1129,13 @@ export function createOpencodeGoRotationExtension(options = {}) {
1088
1129
  invalidateAutomaticDecisions();
1089
1130
  requestRateLimitState = undefined;
1090
1131
  clearWatchdogTimeoutGuard();
1132
+ watchdogRetryPending = false;
1091
1133
  setUsageStatus(undefined);
1092
1134
  stopUsageStatusTimer();
1093
1135
  usageStatusCtx = ctx;
1094
1136
  if (!ensureConfig(ctx))
1095
1137
  return;
1096
- ambientKey = config.keys.length === 0 ? await resolveEnvKey(ctx) : undefined;
1138
+ ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
1097
1139
  if (event.reason === "reload") {
1098
1140
  applySynchronizedActiveKey(ctx);
1099
1141
  syncUsageStatus(ctx, true);
@@ -1101,7 +1143,10 @@ export function createOpencodeGoRotationExtension(options = {}) {
1101
1143
  }
1102
1144
  if (config.keys.length === 0) {
1103
1145
  if (ambientKey) {
1104
- ctx.ui.notify(`OpenCode: Using ${AMBIENT_KEY_NAME} key from ${OPENCODE_KEY_ENV}. Run /opencode add to store a managed copy.`, "info");
1146
+ const message = ambientKey.name === AMBIENT_ENV_KEY_NAME
1147
+ ? `OpenCode: Using ${AMBIENT_ENV_KEY_NAME} key from ${OPENCODE_KEY_ENV}. Run /opencode add to store a managed copy.`
1148
+ : "OpenCode: Using auth key from auth.json. Run /opencode to import it into rotation.";
1149
+ ctx.ui.notify(message, "info");
1105
1150
  syncUsageStatus(ctx, true);
1106
1151
  return;
1107
1152
  }
@@ -1383,7 +1428,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1383
1428
  handler: async (args, ctx) => {
1384
1429
  if (!ensureConfig(ctx))
1385
1430
  return;
1386
- ambientKey = config.keys.length === 0 ? ambientKey ?? await resolveEnvKey(ctx) : undefined;
1431
+ ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
1387
1432
  const parts = args.trim().split(/\s+/);
1388
1433
  const subcommand = parts[0] || "";
1389
1434
  const indexArg = parseInt(parts[1] ?? "", 10);
@@ -1397,7 +1442,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1397
1442
  ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
1398
1443
  }
1399
1444
  if (ctx.mode !== "tui") {
1400
- ctx.ui.notify(formatStatus(config, now(), ambientKey !== undefined), "info");
1445
+ ctx.ui.notify(formatStatus(config, now(), ambientKey?.name), "info");
1401
1446
  break;
1402
1447
  }
1403
1448
  const result = await openOpencodeConfig(ctx);
@@ -1415,7 +1460,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1415
1460
  case "status":
1416
1461
  case "list":
1417
1462
  case "ls": {
1418
- const status = formatStatus(config, now(), ambientKey !== undefined);
1463
+ const status = formatStatus(config, now(), ambientKey?.name);
1419
1464
  ctx.ui.notify(status, "info");
1420
1465
  break;
1421
1466
  }
@@ -1427,6 +1472,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1427
1472
  case "usage":
1428
1473
  case "quota": {
1429
1474
  applySynchronizedActiveKey(ctx);
1475
+ ambientKey = config.keys.length === 0 ? await resolveAmbientKey(ctx, config) : undefined;
1430
1476
  const usage = await fetchOpenCodeGoUsage(getStatusUsageTarget(config), fetchApi, options.timers);
1431
1477
  ctx.ui.notify(formatUsageStatus(usage), usage.ok ? "info" : "warning");
1432
1478
  break;
@@ -1506,6 +1552,27 @@ export function createOpencodeGoRotationExtension(options = {}) {
1506
1552
  syncUsageStatus(ctx, true);
1507
1553
  break;
1508
1554
  }
1555
+ case "import": {
1556
+ const authKey = await ctx.modelRegistry.getApiKeyForProvider(PROVIDER);
1557
+ if (!authKey) {
1558
+ ctx.ui.notify("OpenCode: no auth.json key found for opencode-go.", "warning");
1559
+ return;
1560
+ }
1561
+ invalidateAutomaticDecisions();
1562
+ const imported = await importAuthKey(authKey);
1563
+ if (!imported) {
1564
+ if (configError)
1565
+ ctx.ui.notify(`OpenCode: ${configError}.`, "error");
1566
+ else
1567
+ ctx.ui.notify("OpenCode: that auth.json key is already configured.", "info");
1568
+ return;
1569
+ }
1570
+ ambientKey = undefined;
1571
+ const importedName = applyActiveKey(config, ctx.modelRegistry, now()) ?? "auth";
1572
+ ctx.ui.notify(`OpenCode: Imported key from auth.json → ${importedName}`, "info");
1573
+ syncUsageStatus(ctx, true);
1574
+ break;
1575
+ }
1509
1576
  case "remove":
1510
1577
  case "rm": {
1511
1578
  const removeIndex = indexArg - 1;
@@ -1658,7 +1725,7 @@ export function createOpencodeGoRotationExtension(options = {}) {
1658
1725
  break;
1659
1726
  }
1660
1727
  default:
1661
- ctx.ui.notify("Usage: /opencode [config|status|usage|quota|events|use <n>|next|add <name> <key>|rm <n>|reset|cooldown <min>|policy [off|quota-only|full]|verify <on|off>|watchdog [status|on|off|<seconds>]]", "info");
1728
+ ctx.ui.notify("Usage: /opencode [config|status|usage|quota|events|use <n>|next|add <name> <key>|import|rm <n>|reset|cooldown <min>|policy [off|quota-only|full]|verify <on|off>|watchdog [status|on|off|<seconds>]]", "info");
1662
1729
  }
1663
1730
  },
1664
1731
  });
@@ -1673,11 +1740,28 @@ export function createOpencodeGoRotationExtension(options = {}) {
1673
1740
  cleanupLifecycleState();
1674
1741
  scheduleUsageStatusRefresh(ctx);
1675
1742
  });
1743
+ pi.on("agent_settled", (event, ctx) => {
1744
+ if (!watchdogRetryPending)
1745
+ return;
1746
+ watchdogRetryPending = false;
1747
+ if (!event.aborted || ctx.model?.provider !== PROVIDER || !ctx.isIdle())
1748
+ return;
1749
+ if (!refreshConfig())
1750
+ return;
1751
+ if (!hasUsableKey(config, now()))
1752
+ return;
1753
+ pi.sendMessage({
1754
+ customType: WATCHDOG_RETRY_MESSAGE_TYPE,
1755
+ content: [{ type: "text", text: WATCHDOG_RETRY_PROMPT }],
1756
+ display: false,
1757
+ }, { triggerTurn: true });
1758
+ });
1676
1759
  pi.on("session_shutdown", () => {
1677
1760
  stopUsageStatusTimer();
1678
1761
  setUsageStatus(undefined);
1679
1762
  usageStatusCtx = undefined;
1680
1763
  ambientKey = undefined;
1764
+ watchdogRetryPending = false;
1681
1765
  cleanupLifecycleState();
1682
1766
  });
1683
1767
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yugimob/pi-opencode-go-rotation",
3
- "version": "1.7.2",
3
+ "version": "1.7.4",
4
4
  "description": "Rotate between multiple OpenCode Go API keys with reactive 429, rate-limit, and watchdog stall detection, plus live footer usage for the active key",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",