-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplugin.ts
More file actions
345 lines (298 loc) · 10.4 KB
/
plugin.ts
File metadata and controls
345 lines (298 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import type { Hooks, Plugin } from "@opencode-ai/plugin";
import type { Event } from "@opencode-ai/sdk";
import { mkdirSync, writeFileSync } from "fs";
import { homedir } from "os";
import { dirname, join } from "path";
import { resolveAgentFile, toRelativeAgentPath } from "./config/agent-loader.js";
import { loadConfig } from "./config/loader.js";
import { classifyError } from "./detection/classifier.js";
import { matchesAnyPattern } from "./detection/patterns.js";
import { notifyFallback, notifyFallbackActive, notifyRecovery } from "./display/notifier.js";
import { Logger } from "./logging/logger.js";
import { tryPreemptiveRedirect } from "./preemptive.js";
import { attemptFallback } from "./replay/orchestrator.js";
import { FallbackStore } from "./state/store.js";
import { createFallbackStatusTool } from "./tools/fallback-status.js";
import type { ModelKey } from "./types.js";
function resolveFallbackStatusCommandPath(): string {
return join(homedir(), ".config", "opencode", "commands", "fallback-status.md");
}
export function ensureFallbackStatusCommand(logger: Logger, cmdPath: string): void {
try {
mkdirSync(dirname(cmdPath), { recursive: true, mode: 0o700 });
writeFileSync(cmdPath, "Call the fallback-status tool and display the full output.\n", {
flag: "wx",
});
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "EEXIST") {
logger.warn("fallback-status.command.write.failed", { cmdPath, err });
}
}
}
export const createPlugin: Plugin = async ({ client, directory }) => {
const { config, path: configPath, warnings, migrated } = loadConfig(directory);
const logger = new Logger(client, config.logPath, config.logging, config.logLevel);
logger.info("plugin.init", {
configPath,
enabled: config.enabled,
migrated,
agentCount: Object.keys(config.agents).length,
});
for (const w of warnings) {
logger.warn("config.warning", { warning: w });
}
if (migrated) {
logger.info("config.migrated", {
note: "Auto-migrated from old rate-limit-fallback.json format",
});
}
if (!config.enabled) {
logger.info("plugin.disabled");
return {};
}
const cmdPath = resolveFallbackStatusCommandPath();
ensureFallbackStatusCommand(logger, cmdPath);
const store = new FallbackStore(config, logger);
const hooks: Hooks = {
async event({ event }) {
await handleEvent(event, client, store, config, logger, directory);
},
"chat.message": async (input, output) => {
if (!input.model) return;
const modelKey: ModelKey = `${input.model.providerID}/${input.model.modelID}`;
const sessionState = store.sessions.get(input.sessionID);
if (input.agent) {
store.sessions.setAgentName(input.sessionID, input.agent);
if (!sessionState.agentFile) {
const absPath = resolveAgentFile(
input.agent,
directory,
config.agentDirs?.length ? config.agentDirs : undefined
);
if (absPath) {
store.sessions.setAgentFile(input.sessionID, toRelativeAgentPath(absPath, directory));
}
}
}
const result = tryPreemptiveRedirect(
input.sessionID,
modelKey,
sessionState.agentName,
store,
config,
logger
);
if (result.redirected && result.fallbackModel) {
const [providerID, ...rest] = result.fallbackModel.split("/");
const modelID = rest.join("/");
output.message.model = { providerID, modelID };
logger.debug("chat.message.redirected", {
sessionID: input.sessionID,
from: modelKey,
to: result.fallbackModel,
});
}
const activeFallback = store.sessions.consumeFallbackActiveNotification(input.sessionID);
if (activeFallback) {
notifyFallbackActive(
client,
activeFallback.originalModel,
activeFallback.currentModel
).catch(() => {});
}
},
tool: {
"fallback-status": createFallbackStatusTool(store, config, client, directory),
},
};
return hooks;
};
export async function handleEvent(
event: Event,
client: Parameters<Plugin>[0]["client"],
store: FallbackStore,
config: ReturnType<typeof loadConfig>["config"],
logger: Logger,
directory: string
): Promise<void> {
logger.debug("event.received", { type: event.type });
if (event.type === "session.status") {
const { sessionID, status } = event.properties;
if (status.type === "retry") {
await handleRetry(sessionID, status.message, client, store, config, logger, directory);
} else if (status.type === "idle") {
await handleIdle(sessionID, client, store, config, logger);
}
return;
}
if (event.type === "session.error") {
const { sessionID, error } = event.properties;
if (!sessionID || !error) return;
if (error.name === "APIError") {
const apiMessage = typeof error.data?.message === "string" ? error.data.message : "";
const apiStatusCode =
typeof error.data?.statusCode === "number" ? error.data.statusCode : undefined;
const category = classifyError(apiMessage, apiStatusCode);
if (config.defaults.fallbackOn.includes(category)) {
const result = await attemptFallback(
sessionID,
category,
client,
store,
config,
logger,
directory
);
if (result.success && result.fallbackModel) {
await notifyFallback(client, result.fromModel ?? null, result.fallbackModel, category);
}
}
}
return;
}
if (event.type === "session.deleted") {
const sessionID = event.properties.info.id;
store.sessions.delete(sessionID);
return;
}
// omf-owh.3: On compaction, message IDs shift so fallbackHistory is stale,
// but originalModel/currentModel/agentName/fallbackDepth remain valid.
if (event.type === "session.compacted") {
const sessionID = event.properties.sessionID;
store.sessions.partialReset(sessionID);
logger.info("session.compacted.reset", { sessionID });
return;
}
}
async function handleRetry(
sessionId: string,
message: string,
client: Parameters<Plugin>[0]["client"],
store: FallbackStore,
config: ReturnType<typeof loadConfig>["config"],
logger: Logger,
directory: string
): Promise<void> {
if (!matchesAnyPattern(message, config.patterns)) {
logger.debug("retry.nomatch", { sessionId, messageLength: message.length });
return;
}
const category = classifyError(message);
if (!config.defaults.fallbackOn.includes(category)) {
logger.debug("retry.ignored", {
sessionId,
category,
messageLength: message.length,
});
return;
}
// Seed session state with current model if unknown
const sessionState = store.sessions.get(sessionId);
if (!sessionState.currentModel) {
try {
const msgs = await client.session.messages({ path: { id: sessionId } });
const latestUserMessage = getLastUserModelAndAgent(msgs.data);
if (latestUserMessage?.modelKey) {
store.sessions.setOriginalModel(sessionId, latestUserMessage.modelKey);
if (latestUserMessage.agentName) {
store.sessions.setAgentName(sessionId, latestUserMessage.agentName);
const absPath = resolveAgentFile(
latestUserMessage.agentName,
directory,
config.agentDirs?.length ? config.agentDirs : undefined
);
if (absPath) {
store.sessions.setAgentFile(sessionId, toRelativeAgentPath(absPath, directory));
}
}
}
} catch {
// Best-effort
}
}
// Resolve agent file if still missing (chat.message usually handles this,
// but session.error events bypass the hook)
if (sessionState.agentName && !sessionState.agentFile) {
const absPath = resolveAgentFile(
sessionState.agentName,
directory,
config.agentDirs?.length ? config.agentDirs : undefined
);
if (absPath) {
store.sessions.setAgentFile(sessionId, toRelativeAgentPath(absPath, directory));
}
}
logger.info("retry.detected", {
sessionId,
messageLength: message.length,
category,
agentName: sessionState.agentName,
agentFile: sessionState.agentFile,
});
const result = await attemptFallback(
sessionId,
category,
client,
store,
config,
logger,
directory
);
if (result.success && result.fallbackModel) {
await notifyFallback(client, result.fromModel ?? null, result.fallbackModel, category);
}
}
export async function handleIdle(
sessionId: string,
client: Parameters<Plugin>[0]["client"],
store: FallbackStore,
_config: ReturnType<typeof loadConfig>["config"],
logger: Logger
): Promise<void> {
const state = store.sessions.get(sessionId);
if (!state.originalModel) return;
if (state.currentModel === state.originalModel) {
state.recoveryNotifiedForModel = null;
state.fallbackActiveNotifiedKey = null;
return;
}
// Check if original model has recovered
const health = store.health.get(state.originalModel);
if (health.state !== "healthy") {
state.recoveryNotifiedForModel = null;
return;
}
if (state.recoveryNotifiedForModel === state.originalModel) return;
logger.info("recovery.available", {
sessionId,
originalModel: state.originalModel,
currentModel: state.currentModel,
});
await notifyRecovery(client, state.originalModel);
state.recoveryNotifiedForModel = state.originalModel;
}
function getLastUserModelAndAgent(data: unknown): {
modelKey: ModelKey;
agentName: string | null;
} | null {
if (!Array.isArray(data)) return null;
for (let i = data.length - 1; i >= 0; i--) {
const entry = data[i];
if (!entry || typeof entry !== "object") continue;
const info = (entry as { info?: unknown }).info;
if (!info || typeof info !== "object") continue;
const role = (info as { role?: unknown }).role;
if (role !== "user") continue;
const model = (info as { model?: unknown }).model;
if (!model || typeof model !== "object") continue;
const providerID = (model as { providerID?: unknown }).providerID;
const modelID = (model as { modelID?: unknown }).modelID;
if (typeof providerID !== "string" || typeof modelID !== "string") continue;
const agent = (info as { agent?: unknown }).agent;
return {
modelKey: `${providerID}/${modelID}`,
agentName: typeof agent === "string" ? agent : null,
};
}
return null;
}