-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
249 lines (224 loc) · 7.84 KB
/
index.ts
File metadata and controls
249 lines (224 loc) · 7.84 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
import type {
PluginContext,
FallbackPluginConfig,
HookDeps,
ChatMessageInput,
ChatMessageOutput,
} from "./types"
import { DEFAULT_CONFIG, PLUGIN_NAME } from "./constants"
import { createAutoRetryHelpers } from "./auto-retry"
import { createEventHandler } from "./event-handler"
import { createMessageUpdateHandler } from "./message-update-handler"
import { createChatMessageHandler } from "./chat-message-handler"
import { normalizeFallbackModelsField } from "./config-reader"
import { isEmptyTaskResult, extractChildSessionID, waitForChildFallbackResult } from "./subagent-result-sync"
import { readFileSync, existsSync } from "fs"
import { join } from "path"
import { parse as parseJsonc } from "jsonc-parser"
import { logInfo } from "./logger"
declare function setInterval(
callback: () => void,
delay: number
): { unref: () => void } & ReturnType<typeof globalThis.setInterval>
function loadPluginConfig(directory: string): Partial<FallbackPluginConfig> {
const configPaths = [
join(directory, ".opencode", "opencode-fallback.json"),
join(directory, ".opencode", "opencode-fallback.jsonc"),
join(process.env.HOME || "", ".config", "opencode", "opencode-fallback.json"),
join(process.env.HOME || "", ".config", "opencode", "opencode-fallback.jsonc"),
]
for (const configPath of configPaths) {
if (existsSync(configPath)) {
try {
const content = readFileSync(configPath, "utf-8")
// parseJsonc handles // comments, /* */ blocks, and trailing commas seamlessly
return parseJsonc(content) as Partial<FallbackPluginConfig>
} catch (err) {
logInfo(`[${PLUGIN_NAME}] Failed to parse config: ${configPath}`, err as Record<string, unknown>)
}
}
}
return {}
}
export default async function OpenCodeFallbackPlugin(
ctx: PluginContext,
configOverrides?: Partial<FallbackPluginConfig>
) {
let agentConfigs: Record<string, unknown> | undefined
let fileConfig: Partial<FallbackPluginConfig> = loadPluginConfig(ctx.directory)
let mergedConfig: Required<FallbackPluginConfig> | undefined
const globalFallbackModels = normalizeFallbackModelsField(fileConfig.fallback_models)
// Config getter that builds config on first access
const getConfig = (): Required<FallbackPluginConfig> => {
mergedConfig ??= {
enabled:
configOverrides?.enabled ??
fileConfig?.enabled ??
DEFAULT_CONFIG.enabled,
retry_on_errors:
configOverrides?.retry_on_errors ??
fileConfig?.retry_on_errors ??
DEFAULT_CONFIG.retry_on_errors,
retryable_error_patterns:
configOverrides?.retryable_error_patterns ??
fileConfig?.retryable_error_patterns ??
DEFAULT_CONFIG.retryable_error_patterns,
max_fallback_attempts:
configOverrides?.max_fallback_attempts ??
fileConfig?.max_fallback_attempts ??
DEFAULT_CONFIG.max_fallback_attempts,
cooldown_seconds:
configOverrides?.cooldown_seconds ??
fileConfig?.cooldown_seconds ??
DEFAULT_CONFIG.cooldown_seconds,
timeout_seconds:
configOverrides?.timeout_seconds ??
fileConfig?.timeout_seconds ??
DEFAULT_CONFIG.timeout_seconds,
notify_on_fallback:
configOverrides?.notify_on_fallback ??
fileConfig?.notify_on_fallback ??
DEFAULT_CONFIG.notify_on_fallback,
fallback_models:
configOverrides?.fallback_models ??
fileConfig?.fallback_models ??
DEFAULT_CONFIG.fallback_models,
}
return mergedConfig
}
const deps: HookDeps = {
ctx,
get config() {
return getConfig()
},
get agentConfigs() {
return agentConfigs
},
globalFallbackModels,
sessionStates: new Map(),
sessionLastAccess: new Map(),
sessionRetryInFlight: new Set(),
sessionAwaitingFallbackResult: new Set(),
sessionFallbackTimeouts: new Map(),
sessionFirstTokenReceived: new Map(),
sessionSelfAbortTimestamp: new Map(),
sessionParentID: new Map(),
sessionIdleResolvers: new Map(),
sessionLastMessageTime: new Map(),
sessionCompactionInFlight: new Set(),
}
const helpers = createAutoRetryHelpers(deps)
const { handleEvent: baseEventHandler, handleActivity } = createEventHandler(deps, helpers)
const messageUpdateHandler = createMessageUpdateHandler(deps, helpers)
const chatMessageHandler = createChatMessageHandler(deps, helpers)
const cleanupInterval = setInterval(
helpers.cleanupStaleSessions,
5 * 60 * 1000
)
cleanupInterval.unref()
logInfo(`Plugin initialized (${globalFallbackModels.length} global fallback model(s) configured)`)
return {
name: PLUGIN_NAME,
config: (opencodeConfig: Record<string, unknown>) => {
// Try 'agents' (plural) first, then 'agent' (singular)
const agentsValue = opencodeConfig.agents
const agentValue = opencodeConfig.agent
if (agentsValue && typeof agentsValue === "object" && !Array.isArray(agentsValue)) {
agentConfigs = agentsValue as Record<string, unknown>
} else if (agentValue && typeof agentValue === "object" && !Array.isArray(agentValue)) {
agentConfigs = agentValue as Record<string, unknown>
} else {
agentConfigs = undefined
}
logInfo(`Plugin initialized with ${agentConfigs ? Object.keys(agentConfigs).length : 0} agents`)
},
event: async ({
event,
}: {
event: { type: string; properties?: unknown }
}) => {
if (event.type === "message.updated") {
if (!deps.config.enabled) return
const props = event.properties as
| Record<string, unknown>
| undefined
await messageUpdateHandler(props)
return
}
if (
event.type === "message.part.delta" ||
event.type === "session.diff" ||
event.type === "message.part.updated"
) {
const props = event.properties as Record<string, unknown> | undefined
const info = props?.info as Record<string, unknown> | undefined
const sessionID =
(props?.sessionID as string | undefined) ??
(info?.sessionID as string | undefined) ??
(info?.id as string | undefined)
// Extract model from activity event so handleActivity can
// distinguish stale activity from the failed model vs real
// activity from the fallback model.
const activityModel =
(info?.model as string | undefined) ??
(typeof info?.providerID === "string" && typeof info?.modelID === "string"
? `${info.providerID}/${info.modelID}`
: undefined) ??
(props?.model as string | undefined)
if (sessionID) {
await handleActivity(sessionID, activityModel)
}
}
await baseEventHandler({ event })
},
"tool.execute.after": async (
input: { tool: string; sessionID: string; callID: string; args: any },
output: { title: string; output: string; metadata: any }
) => {
// Only intercept task tool calls with empty results
if (input.tool !== "task" || !isEmptyTaskResult(output.output)) {
return
}
const childSessionID = extractChildSessionID(output.output)
if (!childSessionID) {
logInfo("Empty task result but no child session ID found", {
sessionID: input.sessionID,
outputPreview: output.output?.substring(0, 200),
})
return
}
logInfo("Detected empty task result, waiting for child fallback", {
parentSession: input.sessionID,
childSession: childSessionID,
})
// Wait for child session fallback to complete (bounded)
const maxWaitMs = Math.min(
(deps.config.timeout_seconds || 120) * 1000,
120_000,
)
const replacementText = await waitForChildFallbackResult(deps, childSessionID, {
maxWaitMs,
pollIntervalMs: 500,
})
if (replacementText) {
output.output = replacementText
logInfo("Replaced empty task result with fallback response", {
parentSession: input.sessionID,
childSession: childSessionID,
responseLength: replacementText.length,
})
} else {
logInfo("No fallback response available, preserving original output", {
parentSession: input.sessionID,
childSession: childSessionID,
})
}
},
"chat.message": async (
input: ChatMessageInput,
output: ChatMessageOutput
) => {
await chatMessageHandler(input, output)
},
}
}