@justsilver/opencode-team 0.0.0-stage → 0.2.1
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/CHANGELOG.md +129 -0
- package/LICENSE +21 -0
- package/README.md +115 -2
- package/package.json +48 -4
- package/plugin/opencode-team/index.ts +41 -0
- package/plugin/opencode-team/legacy.ts +48 -0
- package/plugin/opencode-team/model-ref.ts +28 -0
- package/plugin/opencode-team/policy.ts +638 -0
- package/plugin/opencode-team/prompts.ts +138 -0
- package/plugin/opencode-team/rpc.ts +90 -0
- package/plugin/opencode-team/team-agents.ts +107 -0
- package/plugin/opencode-team/team-ids.ts +2 -0
- package/plugin/opencode-team/tui.ts +22 -0
- package/plugin/opencode-team/view/configure.tsx +71 -0
- package/plugin/opencode-team/view/dashboard.tsx +889 -0
- package/plugin/opencode-team/view/model-config.tsx +976 -0
- package/plugin/opencode-team/view/model.ts +502 -0
- package/plugin/opencode-team/view/team.ts +267 -0
- package/plugin/opencode-team/view/ui.tsx +165 -0
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
import { formatModelRef, isChatModel, parseModelRef, type ModelRef } from "./model-ref.ts"
|
|
2
|
+
import type { TeamConflict, TeamMigration, TeamPolicySummary } from "./rpc.ts"
|
|
3
|
+
|
|
4
|
+
const POLICY_KEY = "team-policy"
|
|
5
|
+
const MIGRATION_KEY = "team-legacy-migration"
|
|
6
|
+
const POLICY_VERSION = 1
|
|
7
|
+
const TOOL_NAME = "subagent"
|
|
8
|
+
|
|
9
|
+
export interface TeamToolEvent {
|
|
10
|
+
tool: string
|
|
11
|
+
input: unknown
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type ToolContent =
|
|
15
|
+
| { readonly type: "text"; readonly text: string }
|
|
16
|
+
| { readonly type: "file"; readonly uri: string; readonly mime: string; readonly name?: string }
|
|
17
|
+
|
|
18
|
+
interface ToolResult {
|
|
19
|
+
readonly content?: string | readonly ToolContent[]
|
|
20
|
+
readonly output?: unknown
|
|
21
|
+
readonly metadata?: Readonly<Record<string, unknown>>
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
type TeamToolAfterEvent = { readonly tool: string; readonly input: unknown } & (
|
|
25
|
+
| { readonly status: "completed"; result: ToolResult }
|
|
26
|
+
| { readonly status: "error"; readonly error: unknown }
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
interface HookRegistration {
|
|
30
|
+
dispose(): Promise<void>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface TeamModelInfo {
|
|
34
|
+
readonly id: string
|
|
35
|
+
readonly providerID: string
|
|
36
|
+
readonly type?: string
|
|
37
|
+
readonly variants?: readonly { readonly id: string }[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface TeamAgentInfo {
|
|
41
|
+
readonly id: string
|
|
42
|
+
readonly mode?: string
|
|
43
|
+
readonly hidden?: boolean
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface LegacySubagentModel {
|
|
47
|
+
readonly ok: boolean
|
|
48
|
+
readonly supported: boolean
|
|
49
|
+
readonly model?: string | null
|
|
50
|
+
readonly errors?: readonly string[]
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface LegacyPluginInfo {
|
|
54
|
+
readonly id?: string
|
|
55
|
+
readonly source: { readonly type: string; readonly target?: string; readonly path?: string }
|
|
56
|
+
readonly state: { readonly status: string }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The legacy plugin's RPC contract is reproduced locally so a loaded old package can hand its
|
|
61
|
+
* setting over before the user removes it. The host routes an RPC by its definition ID, not by
|
|
62
|
+
* which plugin registered it.
|
|
63
|
+
*/
|
|
64
|
+
export interface TeamPolicyContext {
|
|
65
|
+
readonly storage: {
|
|
66
|
+
get(key: string): Promise<unknown>
|
|
67
|
+
set(key: string, value: unknown): Promise<void>
|
|
68
|
+
}
|
|
69
|
+
/** Absent on hosts without tool hooks; the policy then reports unsupported. */
|
|
70
|
+
readonly tool?: {
|
|
71
|
+
hook(name: "execute.before", callback: (event: TeamToolEvent) => Promise<void>): Promise<HookRegistration>
|
|
72
|
+
hook(name: "execute.after", callback: (event: TeamToolAfterEvent) => void): Promise<HookRegistration>
|
|
73
|
+
}
|
|
74
|
+
/** Only needed to validate a save; reading, disabling and migration never call it. */
|
|
75
|
+
readonly model?: {
|
|
76
|
+
list(input?: { types?: readonly string[] }): Promise<{ data: readonly TeamModelInfo[] }>
|
|
77
|
+
}
|
|
78
|
+
/** Used to validate the agent and to enumerate subagents during legacy migration. */
|
|
79
|
+
readonly agent?: {
|
|
80
|
+
list(input?: unknown): Promise<{ data: readonly TeamAgentInfo[] }>
|
|
81
|
+
}
|
|
82
|
+
readonly plugin?: {
|
|
83
|
+
list(input?: unknown): Promise<{ data: readonly LegacyPluginInfo[] }>
|
|
84
|
+
}
|
|
85
|
+
readonly rpc?: <Definition>(definition: Definition) => {
|
|
86
|
+
getSubagentModel(input: Record<string, never>): Promise<LegacySubagentModel>
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface TeamPolicyOptions {
|
|
91
|
+
readonly conflict?: TeamConflict
|
|
92
|
+
readonly agentsSupported?: boolean
|
|
93
|
+
readonly agentsError?: string
|
|
94
|
+
/** Used when the host cannot list agents; the built-ins are enough for a faithful legacy import. */
|
|
95
|
+
readonly fallbackAgents?: readonly string[]
|
|
96
|
+
/**
|
|
97
|
+
* Re-checks whether the legacy plugin is active. Plugin setup order is not guaranteed, so a boot
|
|
98
|
+
* check alone can miss an old package that registers after this plugin.
|
|
99
|
+
*/
|
|
100
|
+
readonly resolveConflict?: () => Promise<TeamConflict | undefined>
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface TeamPolicyHandlers {
|
|
104
|
+
getTeamPolicy(input?: unknown): Promise<TeamPolicySummary>
|
|
105
|
+
setAgentModel(input?: unknown): Promise<TeamPolicySummary>
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface MigrationMarker {
|
|
109
|
+
readonly from: string
|
|
110
|
+
readonly status: "applied" | "empty"
|
|
111
|
+
readonly model: string | null
|
|
112
|
+
readonly agents: readonly string[]
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Reuses a conflict result the caller already probed instead of asking the plugin list again. */
|
|
116
|
+
interface MigrationProbe {
|
|
117
|
+
readonly conflict?: TeamConflict
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
121
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function message(error: unknown): string {
|
|
125
|
+
return error instanceof Error ? error.message : String(error)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function corruptPolicy(): Error {
|
|
129
|
+
return new Error(
|
|
130
|
+
`Agent model policy is corrupt: expected { version: ${POLICY_VERSION}, agents: Record<string, string> }.`,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function readPolicy(storage: TeamPolicyContext["storage"]): Promise<Record<string, string>> {
|
|
135
|
+
let raw: unknown
|
|
136
|
+
try {
|
|
137
|
+
raw = await storage.get(POLICY_KEY)
|
|
138
|
+
} catch (error) {
|
|
139
|
+
throw new Error(`Cannot read the agent model policy: ${message(error)}`)
|
|
140
|
+
}
|
|
141
|
+
if (raw === undefined) return {}
|
|
142
|
+
if (!isRecord(raw) || raw.version !== POLICY_VERSION || !isRecord(raw.agents)) throw corruptPolicy()
|
|
143
|
+
const agents: Record<string, string> = {}
|
|
144
|
+
for (const [agentID, model] of Object.entries(raw.agents)) {
|
|
145
|
+
if (agentID.trim() === "" || typeof model !== "string" || parseModelRef(model) === undefined) {
|
|
146
|
+
throw corruptPolicy()
|
|
147
|
+
}
|
|
148
|
+
agents[agentID] = model
|
|
149
|
+
}
|
|
150
|
+
return agents
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
async function writePolicy(storage: TeamPolicyContext["storage"], agents: Record<string, string>): Promise<void> {
|
|
154
|
+
try {
|
|
155
|
+
await storage.set(POLICY_KEY, { version: POLICY_VERSION, agents })
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw new Error(`Cannot save the agent model policy: ${message(error)}`)
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function readMarker(storage: TeamPolicyContext["storage"]): Promise<MigrationMarker | undefined> {
|
|
162
|
+
const raw = await storage.get(MIGRATION_KEY)
|
|
163
|
+
if (raw === undefined) return undefined
|
|
164
|
+
if (
|
|
165
|
+
!isRecord(raw) ||
|
|
166
|
+
typeof raw.from !== "string" ||
|
|
167
|
+
(raw.status !== "applied" && raw.status !== "empty") ||
|
|
168
|
+
(raw.model !== null && typeof raw.model !== "string") ||
|
|
169
|
+
!Array.isArray(raw.agents) ||
|
|
170
|
+
raw.agents.some((agent) => typeof agent !== "string")
|
|
171
|
+
) {
|
|
172
|
+
throw new Error("Agent model migration marker is corrupt.")
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
from: raw.from,
|
|
176
|
+
status: raw.status,
|
|
177
|
+
model: raw.model,
|
|
178
|
+
agents: raw.agents,
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function writeMarker(storage: TeamPolicyContext["storage"], marker: MigrationMarker): Promise<void> {
|
|
183
|
+
await storage.set(MIGRATION_KEY, marker)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function applyPolicy(
|
|
187
|
+
ctx: TeamPolicyContext,
|
|
188
|
+
event: TeamToolEvent,
|
|
189
|
+
forced: WeakMap<object, string>,
|
|
190
|
+
currentConflict: () => Promise<TeamConflict | undefined>,
|
|
191
|
+
ensureMigration: (probe?: MigrationProbe) => Promise<TeamMigration>,
|
|
192
|
+
): Promise<void> {
|
|
193
|
+
if (event.tool !== TOOL_NAME) return
|
|
194
|
+
if (!isRecord(event.input)) return
|
|
195
|
+
const agentID = event.input.agent
|
|
196
|
+
if (typeof agentID !== "string" || agentID.trim() === "") return
|
|
197
|
+
const agents = await readPolicy(ctx.storage)
|
|
198
|
+
const model = agents[agentID]
|
|
199
|
+
// Most calls target an agent without an override. Read the policy first so those calls never
|
|
200
|
+
// pay for the legacy-plugin probe.
|
|
201
|
+
if (model === undefined) return
|
|
202
|
+
const conflict = await currentConflict()
|
|
203
|
+
// While the legacy plugin is active its global hook owns this call. Importing its setting is
|
|
204
|
+
// safe, but writing a competing model would make the effective model depend on plugin order.
|
|
205
|
+
if (conflict !== undefined) {
|
|
206
|
+
try {
|
|
207
|
+
await ensureMigration({ conflict })
|
|
208
|
+
} catch {
|
|
209
|
+
// The old plugin still enforces this call; a migration failure is reported by the next read.
|
|
210
|
+
}
|
|
211
|
+
return
|
|
212
|
+
}
|
|
213
|
+
const input = { ...event.input, model }
|
|
214
|
+
event.input = input
|
|
215
|
+
forced.set(input, model)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function annotateResult(event: TeamToolAfterEvent, forced: WeakMap<object, string>): void {
|
|
219
|
+
if (event.tool !== TOOL_NAME || !isRecord(event.input)) return
|
|
220
|
+
const model = forced.get(event.input)
|
|
221
|
+
forced.delete(event.input)
|
|
222
|
+
if (model === undefined || event.status !== "completed" || event.input.model !== model) return
|
|
223
|
+
|
|
224
|
+
const marker = `[effective subagent model: ${model} (forced by policy)]`
|
|
225
|
+
const content = event.result.content
|
|
226
|
+
event.result = {
|
|
227
|
+
...event.result,
|
|
228
|
+
content: Array.isArray(content)
|
|
229
|
+
? [...content, { type: "text", text: `${content.length > 0 ? "\n\n" : ""}${marker}` }]
|
|
230
|
+
: `${content || ""}${content ? "\n\n" : ""}${marker}`,
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function validateModel(ctx: TeamPolicyContext, ref: ModelRef): Promise<string | undefined> {
|
|
235
|
+
const list = ctx.model?.list
|
|
236
|
+
if (typeof list !== "function") {
|
|
237
|
+
return "This host cannot list models, so the agent model cannot be validated."
|
|
238
|
+
}
|
|
239
|
+
let data: readonly TeamModelInfo[]
|
|
240
|
+
try {
|
|
241
|
+
data = (await list({ types: ["chat"] })).data
|
|
242
|
+
} catch (error) {
|
|
243
|
+
return `Cannot list models: ${message(error)}`
|
|
244
|
+
}
|
|
245
|
+
const reference = formatModelRef(ref)
|
|
246
|
+
const model = data.find((candidate) => candidate.providerID === ref.providerID && candidate.id === ref.id)
|
|
247
|
+
if (model === undefined) return `Model "${reference}" is not an available chat model.`
|
|
248
|
+
if (!isChatModel(model)) return `Model "${reference}" is not a chat model.`
|
|
249
|
+
if (ref.variant === undefined) return undefined
|
|
250
|
+
const variants = model.variants ?? []
|
|
251
|
+
if (variants.some((variant) => variant.id === ref.variant)) return undefined
|
|
252
|
+
return variants.length === 0
|
|
253
|
+
? `Model "${reference}" has no variants. Omit the variant.`
|
|
254
|
+
: `Variant "${ref.variant}" is not available for "${reference}". Available: ${variants
|
|
255
|
+
.map((variant) => variant.id)
|
|
256
|
+
.join(", ")}.`
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async function validateAgent(ctx: TeamPolicyContext, agentID: string): Promise<string | undefined> {
|
|
260
|
+
const list = ctx.agent?.list
|
|
261
|
+
if (typeof list !== "function") return undefined
|
|
262
|
+
let data: readonly TeamAgentInfo[]
|
|
263
|
+
try {
|
|
264
|
+
data = (await list()).data
|
|
265
|
+
} catch (error) {
|
|
266
|
+
return `Cannot list agents: ${message(error)}`
|
|
267
|
+
}
|
|
268
|
+
const agent = data.find((candidate) => candidate.id === agentID)
|
|
269
|
+
if (agent === undefined) return `Agent "${agentID}" is not available in this location.`
|
|
270
|
+
if (agent.mode === "primary") {
|
|
271
|
+
return `Agent "${agentID}" is a primary agent. Team policy only overrides subagent models; primary agents keep OpenCode's native selection.`
|
|
272
|
+
}
|
|
273
|
+
return undefined
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function supportsHook(ctx: TeamPolicyContext): boolean {
|
|
277
|
+
return typeof ctx.tool?.hook === "function"
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function unavailable(reason: string, agentsSupported: boolean, agentsError?: string): TeamPolicyHandlers {
|
|
281
|
+
const agentState = {
|
|
282
|
+
agentsSupported,
|
|
283
|
+
...(agentsError === undefined ? {} : { agentsError }),
|
|
284
|
+
}
|
|
285
|
+
return {
|
|
286
|
+
getTeamPolicy: async () => ({ ok: false, supported: false, ...agentState, errors: [reason] }),
|
|
287
|
+
setAgentModel: async () => ({ ok: false, supported: false, ...agentState, errors: [reason] }),
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function conflictSummary(conflict: TeamConflict): TeamPolicySummary {
|
|
292
|
+
return {
|
|
293
|
+
ok: false,
|
|
294
|
+
supported: true,
|
|
295
|
+
errors: [
|
|
296
|
+
`The legacy plugin "${conflict.pluginID}" is still loaded. Team policy mutates nothing until it is removed, because its global hook would override per-agent models.`,
|
|
297
|
+
],
|
|
298
|
+
conflict,
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function migrationSummary(marker: MigrationMarker): TeamMigration {
|
|
303
|
+
return {
|
|
304
|
+
from: marker.from,
|
|
305
|
+
status: marker.status,
|
|
306
|
+
agents: marker.agents,
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function listSubagentIDs(ctx: TeamPolicyContext, fallback: readonly string[]): Promise<string[]> {
|
|
311
|
+
const list = ctx.agent?.list
|
|
312
|
+
if (typeof list !== "function") return [...fallback]
|
|
313
|
+
try {
|
|
314
|
+
const data = (await list()).data
|
|
315
|
+
const ids = data
|
|
316
|
+
.filter((agent) => agent.mode !== "primary")
|
|
317
|
+
.map((agent) => agent.id)
|
|
318
|
+
.toSorted()
|
|
319
|
+
return ids.length > 0 ? ids : [...fallback]
|
|
320
|
+
} catch {
|
|
321
|
+
return [...fallback]
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function runMigration(
|
|
326
|
+
ctx: TeamPolicyContext,
|
|
327
|
+
fallbackAgents: readonly string[],
|
|
328
|
+
): Promise<MigrationMarker | { readonly status: "unavailable" | "failed"; readonly errors: readonly string[] }> {
|
|
329
|
+
try {
|
|
330
|
+
const existing = await readMarker(ctx.storage)
|
|
331
|
+
if (existing !== undefined) return existing
|
|
332
|
+
} catch (error) {
|
|
333
|
+
return { status: "failed", errors: [message(error)] }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const rpc = ctx.rpc
|
|
337
|
+
if (typeof rpc !== "function") {
|
|
338
|
+
return { status: "unavailable", errors: ["This host cannot call the legacy plugin's RPC."] }
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
let legacy: LegacySubagentModel
|
|
342
|
+
try {
|
|
343
|
+
legacy = await rpc(legacyRpcDefinition).getSubagentModel({})
|
|
344
|
+
} catch (error) {
|
|
345
|
+
return { status: "unavailable", errors: [`Cannot read the legacy subagent model: ${message(error)}`] }
|
|
346
|
+
}
|
|
347
|
+
if (!legacy.supported) {
|
|
348
|
+
return { status: "unavailable", errors: legacy.errors ?? ["The legacy plugin cannot report its model."] }
|
|
349
|
+
}
|
|
350
|
+
if (!legacy.ok) {
|
|
351
|
+
return { status: "failed", errors: legacy.errors ?? ["The legacy plugin failed to report its model."] }
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const legacyModel = legacy.model ?? null
|
|
355
|
+
if (legacyModel !== null && parseModelRef(legacyModel) === undefined) {
|
|
356
|
+
return { status: "failed", errors: [`The legacy model "${legacyModel}" is invalid.`] }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
let agents: Record<string, string>
|
|
360
|
+
try {
|
|
361
|
+
agents = await readPolicy(ctx.storage)
|
|
362
|
+
} catch (error) {
|
|
363
|
+
return { status: "failed", errors: [message(error)] }
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const imported =
|
|
367
|
+
legacyModel === null ? [] : (await listSubagentIDs(ctx, fallbackAgents)).filter((agent) => agents[agent] === undefined)
|
|
368
|
+
if (legacyModel !== null) {
|
|
369
|
+
for (const agentID of imported) agents[agentID] = legacyModel
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
const marker: MigrationMarker = {
|
|
373
|
+
from: "opencode-subagent-model",
|
|
374
|
+
status: legacyModel === null ? "empty" : "applied",
|
|
375
|
+
model: legacyModel,
|
|
376
|
+
agents: imported,
|
|
377
|
+
}
|
|
378
|
+
try {
|
|
379
|
+
if (imported.length > 0) await writePolicy(ctx.storage, agents)
|
|
380
|
+
await writeMarker(ctx.storage, marker)
|
|
381
|
+
} catch (error) {
|
|
382
|
+
return { status: "failed", errors: [message(error)] }
|
|
383
|
+
}
|
|
384
|
+
return marker
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* The legacy package keeps its own storage namespace, so its value is readable only while its
|
|
389
|
+
* server plugin is loaded. Every attempt is memoized after success; a transient miss is retried
|
|
390
|
+
* the next time the TUI or an intercepted call asks.
|
|
391
|
+
*/
|
|
392
|
+
function migration(
|
|
393
|
+
ctx: TeamPolicyContext,
|
|
394
|
+
currentConflict: () => Promise<TeamConflict | undefined>,
|
|
395
|
+
fallbackAgents: readonly string[],
|
|
396
|
+
) {
|
|
397
|
+
let settled: TeamMigration | undefined
|
|
398
|
+
let pending: Promise<TeamMigration> | undefined
|
|
399
|
+
const attempt = async (probe?: MigrationProbe): Promise<TeamMigration> => {
|
|
400
|
+
const conflict = probe === undefined ? await currentConflict() : probe.conflict
|
|
401
|
+
if (conflict === undefined) {
|
|
402
|
+
try {
|
|
403
|
+
const marker = await readMarker(ctx.storage)
|
|
404
|
+
if (marker !== undefined) return migrationSummary(marker)
|
|
405
|
+
} catch (error) {
|
|
406
|
+
return { from: "opencode-subagent-model", status: "failed", errors: [message(error)] }
|
|
407
|
+
}
|
|
408
|
+
return { from: "opencode-subagent-model", status: "unavailable" }
|
|
409
|
+
}
|
|
410
|
+
if (settled !== undefined) return settled
|
|
411
|
+
if (pending !== undefined) return pending
|
|
412
|
+
pending = (async () => {
|
|
413
|
+
const result = await runMigration(ctx, fallbackAgents)
|
|
414
|
+
if ("from" in result) {
|
|
415
|
+
settled = migrationSummary(result)
|
|
416
|
+
return settled
|
|
417
|
+
}
|
|
418
|
+
return {
|
|
419
|
+
from: "opencode-subagent-model",
|
|
420
|
+
status: result.status,
|
|
421
|
+
errors: result.errors,
|
|
422
|
+
} satisfies TeamMigration
|
|
423
|
+
})()
|
|
424
|
+
try {
|
|
425
|
+
return await pending
|
|
426
|
+
} finally {
|
|
427
|
+
pending = undefined
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
return attempt
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
async function getState(
|
|
434
|
+
ctx: TeamPolicyContext,
|
|
435
|
+
options: TeamPolicyOptions,
|
|
436
|
+
currentConflict: () => Promise<TeamConflict | undefined>,
|
|
437
|
+
ensureMigration: (probe?: MigrationProbe) => Promise<TeamMigration>,
|
|
438
|
+
): Promise<TeamPolicySummary> {
|
|
439
|
+
const agentState = {
|
|
440
|
+
agentsSupported: options.agentsSupported ?? false,
|
|
441
|
+
...(options.agentsError === undefined ? {} : { agentsError: options.agentsError }),
|
|
442
|
+
}
|
|
443
|
+
const conflict = await currentConflict()
|
|
444
|
+
if (!supportsHook(ctx)) {
|
|
445
|
+
return {
|
|
446
|
+
ok: false,
|
|
447
|
+
supported: false,
|
|
448
|
+
...agentState,
|
|
449
|
+
errors: ["This host cannot enforce a subagent model."],
|
|
450
|
+
...(conflict === undefined ? {} : { conflict }),
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
try {
|
|
454
|
+
const migrated = await ensureMigration({ conflict })
|
|
455
|
+
const models = await readPolicy(ctx.storage)
|
|
456
|
+
return {
|
|
457
|
+
ok: true,
|
|
458
|
+
supported: true,
|
|
459
|
+
...agentState,
|
|
460
|
+
models,
|
|
461
|
+
...(migrated.status === "unavailable" && conflict === undefined ? {} : { migration: migrated }),
|
|
462
|
+
...(conflict === undefined ? {} : { conflict }),
|
|
463
|
+
}
|
|
464
|
+
} catch (error) {
|
|
465
|
+
return {
|
|
466
|
+
ok: false,
|
|
467
|
+
supported: true,
|
|
468
|
+
...agentState,
|
|
469
|
+
errors: [message(error)],
|
|
470
|
+
...(conflict === undefined ? {} : { conflict }),
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
async function setAgentModel(
|
|
476
|
+
ctx: TeamPolicyContext,
|
|
477
|
+
input: unknown,
|
|
478
|
+
options: TeamPolicyOptions,
|
|
479
|
+
currentConflict: () => Promise<TeamConflict | undefined>,
|
|
480
|
+
ensureMigration: (probe?: MigrationProbe) => Promise<TeamMigration>,
|
|
481
|
+
): Promise<TeamPolicySummary> {
|
|
482
|
+
const agentsSupported = options.agentsSupported ?? false
|
|
483
|
+
if (!supportsHook(ctx)) {
|
|
484
|
+
return {
|
|
485
|
+
ok: false,
|
|
486
|
+
supported: false,
|
|
487
|
+
agentsSupported,
|
|
488
|
+
errors: ["This host cannot enforce a subagent model."],
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const conflict = await currentConflict()
|
|
492
|
+
if (conflict !== undefined) {
|
|
493
|
+
return { ...conflictSummary(conflict), agentsSupported }
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
const agentID = isRecord(input) ? input.agentID : undefined
|
|
497
|
+
const model = isRecord(input) ? input.model : undefined
|
|
498
|
+
if (typeof agentID !== "string" || agentID.trim() === "") {
|
|
499
|
+
return { ok: false, supported: true, agentsSupported, errors: ["The agent ID must be a non-empty string."] }
|
|
500
|
+
}
|
|
501
|
+
if (model !== null && typeof model !== "string") {
|
|
502
|
+
return { ok: false, supported: true, agentsSupported, errors: ["The agent model must be a string or null."] }
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
let ref: ModelRef | undefined
|
|
506
|
+
if (model !== null) {
|
|
507
|
+
ref = parseModelRef(model)
|
|
508
|
+
if (ref === undefined) {
|
|
509
|
+
return {
|
|
510
|
+
ok: false,
|
|
511
|
+
supported: true,
|
|
512
|
+
agentsSupported,
|
|
513
|
+
errors: [`Invalid model "${model}". Use "providerID/modelID" or "providerID/modelID#variant".`],
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
const invalidModel = await validateModel(ctx, ref)
|
|
517
|
+
if (invalidModel !== undefined) return { ok: false, supported: true, agentsSupported, errors: [invalidModel] }
|
|
518
|
+
const invalidAgent = await validateAgent(ctx, agentID)
|
|
519
|
+
if (invalidAgent !== undefined) return { ok: false, supported: true, agentsSupported, errors: [invalidAgent] }
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
let agents: Record<string, string>
|
|
523
|
+
try {
|
|
524
|
+
agents = await readPolicy(ctx.storage)
|
|
525
|
+
} catch (error) {
|
|
526
|
+
return { ok: false, supported: true, agentsSupported, errors: [message(error)] }
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (model === null) {
|
|
530
|
+
delete agents[agentID]
|
|
531
|
+
} else {
|
|
532
|
+
agents[agentID] = formatModelRef(ref!)
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
try {
|
|
536
|
+
await writePolicy(ctx.storage, agents)
|
|
537
|
+
} catch (error) {
|
|
538
|
+
return { ok: false, supported: true, agentsSupported, errors: [message(error)] }
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
let migrated: TeamMigration | undefined
|
|
542
|
+
try {
|
|
543
|
+
migrated = await ensureMigration({ conflict })
|
|
544
|
+
} catch {
|
|
545
|
+
// The save already succeeded; migration remains visible on the next read.
|
|
546
|
+
}
|
|
547
|
+
return {
|
|
548
|
+
ok: true,
|
|
549
|
+
supported: true,
|
|
550
|
+
agentsSupported,
|
|
551
|
+
models: agents,
|
|
552
|
+
...(migrated === undefined || migrated.status === "unavailable" ? {} : { migration: migrated }),
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
export async function registerTeamPolicy(
|
|
557
|
+
ctx: TeamPolicyContext,
|
|
558
|
+
options: TeamPolicyOptions = {},
|
|
559
|
+
): Promise<TeamPolicyHandlers> {
|
|
560
|
+
const hook = ctx.tool?.hook
|
|
561
|
+
if (typeof hook !== "function") {
|
|
562
|
+
return unavailable(
|
|
563
|
+
"This host does not expose the tool execute.before hook.",
|
|
564
|
+
options.agentsSupported ?? false,
|
|
565
|
+
options.agentsError,
|
|
566
|
+
)
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
let cachedConflict = options.conflict
|
|
570
|
+
const resolveConflict = options.resolveConflict
|
|
571
|
+
const currentConflict = async (): Promise<TeamConflict | undefined> => {
|
|
572
|
+
if (typeof resolveConflict !== "function") return cachedConflict
|
|
573
|
+
try {
|
|
574
|
+
cachedConflict = await resolveConflict()
|
|
575
|
+
} catch {
|
|
576
|
+
// A failed probe must not enable a second policy; keep the last known answer.
|
|
577
|
+
}
|
|
578
|
+
return cachedConflict
|
|
579
|
+
}
|
|
580
|
+
const ensureMigration = migration(ctx, currentConflict, options.fallbackAgents ?? [])
|
|
581
|
+
const initialConflict = await currentConflict()
|
|
582
|
+
if (initialConflict !== undefined) await ensureMigration({ conflict: initialConflict })
|
|
583
|
+
|
|
584
|
+
const forced = new WeakMap<object, string>()
|
|
585
|
+
let ready = false
|
|
586
|
+
let before: HookRegistration | undefined
|
|
587
|
+
try {
|
|
588
|
+
before = await hook("execute.before", async (event) => {
|
|
589
|
+
if (ready) await applyPolicy(ctx, event, forced, currentConflict, ensureMigration)
|
|
590
|
+
})
|
|
591
|
+
await hook("execute.after", (event) => annotateResult(event, forced))
|
|
592
|
+
ready = true
|
|
593
|
+
} catch (error) {
|
|
594
|
+
try {
|
|
595
|
+
await before?.dispose()
|
|
596
|
+
} catch (cleanupError) {
|
|
597
|
+
return unavailable(
|
|
598
|
+
`Agent model policy hook registration failed: ${message(error)}; cleanup failed: ${message(cleanupError)}`,
|
|
599
|
+
options.agentsSupported ?? false,
|
|
600
|
+
options.agentsError,
|
|
601
|
+
)
|
|
602
|
+
}
|
|
603
|
+
return unavailable(
|
|
604
|
+
`Agent model policy hook registration failed: ${message(error)}`,
|
|
605
|
+
options.agentsSupported ?? false,
|
|
606
|
+
options.agentsError,
|
|
607
|
+
)
|
|
608
|
+
}
|
|
609
|
+
return {
|
|
610
|
+
getTeamPolicy: () => getState(ctx, options, currentConflict, ensureMigration),
|
|
611
|
+
setAgentModel: (input) => setAgentModel(ctx, input, options, currentConflict, ensureMigration),
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* Only the method and input shape matter for routing; the output is checked as plain JSON.
|
|
617
|
+
* The old package's RPC ID is part of its storage-era contract and must stay exact.
|
|
618
|
+
*/
|
|
619
|
+
const legacyRpcDefinition = {
|
|
620
|
+
id: "opencode-subagent-model",
|
|
621
|
+
methods: {
|
|
622
|
+
getSubagentModel: {
|
|
623
|
+
input: { type: "object", properties: {}, additionalProperties: false },
|
|
624
|
+
output: {
|
|
625
|
+
type: "object",
|
|
626
|
+
properties: {
|
|
627
|
+
ok: { type: "boolean" },
|
|
628
|
+
supported: { type: "boolean" },
|
|
629
|
+
model: { type: ["string", "null"] },
|
|
630
|
+
errors: { type: "array", items: { type: "string" } },
|
|
631
|
+
},
|
|
632
|
+
required: ["ok", "supported"],
|
|
633
|
+
additionalProperties: false,
|
|
634
|
+
},
|
|
635
|
+
},
|
|
636
|
+
},
|
|
637
|
+
events: {},
|
|
638
|
+
} as const
|