forked from code-yeongyu/oh-my-openagent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-plugin-module.ts
More file actions
353 lines (324 loc) · 13.9 KB
/
Copy pathcreate-plugin-module.ts
File metadata and controls
353 lines (324 loc) · 13.9 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
346
347
348
349
350
351
352
353
import type { Hooks, Plugin, PluginModule } from "@opencode-ai/plugin"
import type { HookName } from "../config"
import { validatePluginConfig } from "../config/validate"
import { initConfigContext } from "../cli/config-manager/config-context"
import { ensureTuiPluginEntry } from "../cli/config-manager/add-tui-plugin-to-tui-config"
import { createHooks } from "../create-hooks"
import { createManagers } from "../create-managers"
import { createRuntimeTmuxConfig, isTmuxIntegrationEnabled } from "../create-runtime-tmux-config"
import { createTools } from "../create-tools"
import { createRuntimeSkillSourceServer, selectRuntimeSecuritySkills } from "../features/opencode-runtime-skills"
import { initializeOpenClaw } from "../openclaw"
import { createPluginDispose } from "../plugin-dispose"
import { createPluginInterface } from "../plugin-interface"
import { loadPluginConfig } from "../plugin-config"
import { createModelCacheState } from "../plugin-state"
import {
createCompactionAutocontinueHandler,
createSessionCompactingHandler,
type CompactionAutocontinueHook,
} from "../plugin/session-compacting"
import { installAgentSortShim, setAgentSortOrder } from "../shared/agent-sort-shim"
import {
detectDuplicateOmoPlugin,
detectExternalSkillPlugin,
getDuplicateOmoPluginWarning,
getSkillPluginConflictWarning,
} from "../shared/external-plugin-detector"
import { createFirstMessageVariantGate } from "../shared/first-message-variant"
import { initI18n } from "../shared/i18n"
import { log } from "../shared/logger"
import { logLegacyPluginStartupWarning } from "../shared/log-legacy-plugin-startup-warning"
import { migrateLegacyWorkspaceDirectory } from "../shared/legacy-workspace-migration"
import { sweepOmoFamiliesBestEffort } from "../shared/omo-process-sweep"
import { injectServerAuthIntoClient } from "../shared/opencode-server-auth"
import { recordPluginTelemetry } from "../shared/posthog"
import {
initLiveServerRoute,
setLiveParentWakeRoutingDisabled,
warmLiveServerProbe,
} from "../shared/live-server-route"
import { startBackgroundCheck as startTmuxCheck } from "../tools/interactive-bash"
import { runOpenCodeStartupMigration } from "../startup-migration"
type StartupToastClient = {
readonly tui?: {
readonly showToast?: (input: { readonly body: Record<string, unknown> }) => Promise<unknown>
}
}
type HooksWithRuntimeLifecycle = Hooks & {
"experimental.compaction.autocontinue"?: CompactionAutocontinueHook
dispose?: () => Promise<void>
}
export type PluginModuleDeps = {
initConfigContext: typeof initConfigContext
installAgentSortShim: typeof installAgentSortShim
setAgentSortOrder: typeof setAgentSortOrder
log: typeof log
logLegacyPluginStartupWarning: typeof logLegacyPluginStartupWarning
migrateLegacyWorkspaceDirectory: typeof migrateLegacyWorkspaceDirectory
runOpenCodeStartupMigration: typeof runOpenCodeStartupMigration
startOmoProcessSweep: () => Promise<void>
detectDuplicateOmoPlugin: typeof detectDuplicateOmoPlugin
getDuplicateOmoPluginWarning: typeof getDuplicateOmoPluginWarning
detectExternalSkillPlugin: typeof detectExternalSkillPlugin
getSkillPluginConflictWarning: typeof getSkillPluginConflictWarning
injectServerAuthIntoClient: typeof injectServerAuthIntoClient
initLiveServerRoute: typeof initLiveServerRoute
setLiveParentWakeRoutingDisabled: typeof setLiveParentWakeRoutingDisabled
warmLiveServerProbe: typeof warmLiveServerProbe
loadConfigChain: typeof validatePluginConfig
loadPluginConfig: typeof loadPluginConfig
recordPluginTelemetry: typeof recordPluginTelemetry
initI18n: typeof initI18n
initializeOpenClaw: typeof initializeOpenClaw
isTmuxIntegrationEnabled: typeof isTmuxIntegrationEnabled
startTmuxCheck: typeof startTmuxCheck
createFirstMessageVariantGate: typeof createFirstMessageVariantGate
createRuntimeTmuxConfig: typeof createRuntimeTmuxConfig
createModelCacheState: typeof createModelCacheState
createManagers: typeof createManagers
createTools: typeof createTools
createRuntimeSkillSourceServer: typeof createRuntimeSkillSourceServer
createHooks: typeof createHooks
createPluginInterface: typeof createPluginInterface
}
const defaultPluginModuleDeps: PluginModuleDeps = {
initConfigContext,
installAgentSortShim,
setAgentSortOrder,
log,
logLegacyPluginStartupWarning,
migrateLegacyWorkspaceDirectory,
runOpenCodeStartupMigration,
startOmoProcessSweep: () => sweepOmoFamiliesBestEffort({ log }),
detectDuplicateOmoPlugin,
getDuplicateOmoPluginWarning,
detectExternalSkillPlugin,
getSkillPluginConflictWarning,
injectServerAuthIntoClient,
initLiveServerRoute,
setLiveParentWakeRoutingDisabled,
warmLiveServerProbe,
loadConfigChain: validatePluginConfig,
loadPluginConfig,
recordPluginTelemetry,
initI18n,
initializeOpenClaw,
isTmuxIntegrationEnabled,
startTmuxCheck,
createFirstMessageVariantGate,
createRuntimeTmuxConfig,
createModelCacheState,
createManagers,
createTools,
createRuntimeSkillSourceServer,
createHooks,
createPluginInterface,
}
function showStartupToast(
client: unknown,
body: Record<string, unknown>,
onFailure: (message: string, context: Record<string, unknown>) => void,
): void {
const tui = (client as StartupToastClient).tui
if (tui?.showToast === undefined) return
void tui.showToast({ body }).catch((error: unknown) => {
onFailure("[config-migration] startup toast failed", {
error: error instanceof Error ? error.message : String(error),
})
})
}
function startupToastBody(input: {
readonly diagnostics: readonly string[]
readonly error?: string
readonly migratedFrom: readonly string[]
readonly skippedConflictCount: number
}): Record<string, unknown> | undefined {
const summary = input.migratedFrom.length === 0
? ""
: `Migrated ${input.migratedFrom.length} legacy source${input.migratedFrom.length === 1 ? "" : "s"}.`
const conflicts = input.skippedConflictCount === 0
? ""
: ` Kept ${input.skippedConflictCount} existing value${input.skippedConflictCount === 1 ? "" : "s"}.`
const diagnostics = input.diagnostics.length === 0 ? "" : ` ${input.diagnostics.join(" ")}`
if (input.error !== undefined) {
return { title: "Configuration migration failed", message: `${input.error}${diagnostics}`, variant: "error" }
}
if (summary.length > 0) return { title: "Configuration migrated", message: `${summary}${conflicts}${diagnostics}`, variant: "success" }
if (diagnostics.length > 0) return { title: "Configuration diagnostics", message: input.diagnostics.join(" "), variant: "warning" }
return undefined
}
export function createPluginModule(overrides: Partial<PluginModuleDeps> = {}): PluginModule {
const deps = { ...defaultPluginModuleDeps, ...overrides }
let startupMigration: ReturnType<PluginModuleDeps["runOpenCodeStartupMigration"]> | undefined
const serverPlugin: Plugin = async (input, _options): Promise<Hooks> => {
deps.installAgentSortShim()
deps.initConfigContext("opencode", null)
deps.log("[oh-my-openagent] ENTRY - plugin loading", {
directory: input.directory,
})
deps.logLegacyPluginStartupWarning()
deps.migrateLegacyWorkspaceDirectory(input.directory)
startupMigration ??= deps.runOpenCodeStartupMigration({ cwd: input.directory })
const startupValidation = deps.loadConfigChain(input.directory)
const startupDiagnostics = startupValidation.valid ? [] : startupValidation.messages
deps.log("[config-migration] startup completed", {
error: startupMigration.error,
journalResumed: startupMigration.journalResumed,
migratedFrom: startupMigration.migratedFrom,
skippedConflictCount: startupMigration.skippedConflictCount,
})
if (startupMigration.error !== undefined) {
console.warn(`[config-migration] legacy configuration changes were not applied: ${startupMigration.error}`)
}
const toast = startupToastBody({
diagnostics: startupDiagnostics,
...(startupMigration.error === undefined ? {} : { error: startupMigration.error }),
migratedFrom: startupMigration.migratedFrom,
skippedConflictCount: startupMigration.skippedConflictCount,
})
if (toast !== undefined) showStartupToast(input.client, toast, deps.log)
// Unconditional omo process hygiene (T16): fire-and-forget family sweep,
// throttled per-family inside the sweep functions. Never awaited and
// never allowed to reject into startup.
try {
void deps
.startOmoProcessSweep()
.catch((error: unknown) => {
deps.log("[oh-my-openagent] omo process sweep failed", {
error: error instanceof Error ? error.message : String(error),
})
})
} catch (error) {
deps.log("[oh-my-openagent] omo process sweep failed to start", {
error: error instanceof Error ? error.message : String(error),
})
}
const duplicateOmoPluginCheck = deps.detectDuplicateOmoPlugin(input.directory)
if (duplicateOmoPluginCheck.detected) {
console.warn(deps.getDuplicateOmoPluginWarning(duplicateOmoPluginCheck.duplicatePlugins))
return {}
}
const skillPluginCheck = deps.detectExternalSkillPlugin(input.directory)
if (skillPluginCheck.detected && skillPluginCheck.pluginName) {
console.warn(deps.getSkillPluginConflictWarning(skillPluginCheck.pluginName))
}
deps.injectServerAuthIntoClient(input.client)
const pluginConfig = startupValidation.config
try {
deps.recordPluginTelemetry({ configEnabled: pluginConfig.telemetry })
} catch (error) {
deps.log("[posthog] plugin telemetry failed", {
error: error instanceof Error ? error.message : String(error),
})
}
try {
ensureTuiPluginEntry()
} catch (error) {
deps.log("[tui] tui.json self-heal failed", {
error: error instanceof Error ? error.message : String(error),
})
}
deps.initLiveServerRoute({ serverUrl: input.serverUrl, directory: input.directory, inProcessClient: input.client })
deps.setLiveParentWakeRoutingDisabled(pluginConfig.experimental?.disable_live_parent_wake_routing === true)
deps.warmLiveServerProbe()
const runtimeSecuritySkills = selectRuntimeSecuritySkills(pluginConfig)
let runtimeSkillSource: Awaited<ReturnType<PluginModuleDeps["createRuntimeSkillSourceServer"]>> | undefined
if (runtimeSecuritySkills.length > 0) {
try {
runtimeSkillSource = await deps.createRuntimeSkillSourceServer({ skills: runtimeSecuritySkills })
} catch (error) {
const detail = error instanceof Error ? error.message : String(error)
console.warn(`[runtime-skills] bundled security skill source unavailable; continuing without config.skills.urls: ${detail}`)
}
}
deps.initI18n(pluginConfig.i18n?.locale ? { locale: pluginConfig.i18n.locale } : undefined)
deps.setAgentSortOrder(pluginConfig.agent_order)
if (pluginConfig.openclaw) {
await deps.initializeOpenClaw(pluginConfig.openclaw)
}
if (pluginConfig.team_mode?.enabled) {
const teamModeConfig = pluginConfig.team_mode
try {
const { ensureBaseDirs, resolveBaseDir } = await import("../features/team-mode/team-registry/paths")
const { checkTeamModeDependencies } = await import("../features/team-mode/deps")
await checkTeamModeDependencies(teamModeConfig)
await ensureBaseDirs(resolveBaseDir(teamModeConfig))
if (pluginConfig.disabled_skills?.includes("team-mode")) {
console.warn(
"[team-mode] enabled=true but team-mode skill is disabled; skill docs hidden but tools still registered (D-29)",
)
}
} catch (error) {
if (error instanceof Error) {
console.warn("[team-mode] init failed:", error)
} else {
console.warn("[team-mode] init failed:", String(error))
}
}
}
const tmuxIntegrationEnabled = deps.isTmuxIntegrationEnabled(pluginConfig)
if (tmuxIntegrationEnabled) {
deps.startTmuxCheck()
}
const disabledHooks = new Set(pluginConfig.disabled_hooks ?? [])
const isHookEnabled = (hookName: HookName): boolean => !disabledHooks.has(hookName)
const safeHookEnabled = pluginConfig.experimental?.safe_hook_creation ?? true
const firstMessageVariantGate = deps.createFirstMessageVariantGate()
const tmuxConfig = deps.createRuntimeTmuxConfig(pluginConfig)
const modelCacheState = deps.createModelCacheState()
const managers = deps.createManagers({
ctx: input,
pluginConfig,
tmuxConfig,
modelCacheState,
backgroundNotificationHookEnabled: isHookEnabled("background-notification"),
runtimeSkillSourceUrl: runtimeSkillSource?.url,
})
const toolsResult = await deps.createTools({
ctx: input,
pluginConfig,
managers,
})
const hooks = deps.createHooks({
ctx: input,
pluginConfig,
modelCacheState,
backgroundManager: managers.backgroundManager,
modelFallbackControllerAccessor: managers.modelFallbackControllerAccessor,
monitorManager: managers.monitorManager,
isHookEnabled,
safeHookEnabled,
mergedSkills: toolsResult.mergedSkills,
availableSkills: toolsResult.availableSkills,
})
const pluginInterface = deps.createPluginInterface({
ctx: input,
pluginConfig,
firstMessageVariantGate,
managers,
hooks,
tools: toolsResult.filteredTools,
})
const dispose = createPluginDispose({
backgroundManager: managers.backgroundManager,
skillMcpManager: managers.skillMcpManager,
tuiStateMirror: managers.tuiStateMirror,
disposeHooks: hooks.disposeHooks,
})
const pluginHooks: HooksWithRuntimeLifecycle = {
...pluginInterface,
"experimental.session.compacting": createSessionCompactingHandler(hooks),
"experimental.compaction.autocontinue": createCompactionAutocontinueHandler(hooks),
dispose: async (): Promise<void> => {
runtimeSkillSource?.stop()
await dispose()
},
}
return pluginHooks
}
return {
id: "oh-my-openagent",
server: serverPlugin,
}
}