@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.
@@ -0,0 +1,267 @@
1
+ import type { AgentInfo, ModelInfo, ProviderInfo } from "@opencode/client"
2
+ import type { Plugin } from "@opencode/plugin/tui"
3
+
4
+ import { isChatModel } from "../model-ref.ts"
5
+ import { teamRpc, type TeamPolicySummary } from "../rpc.ts"
6
+ import type {
7
+ DashboardAgent,
8
+ DashboardAgentInput,
9
+ FeedbackTone,
10
+ } from "./model.ts"
11
+
12
+ type Context = Plugin.Context
13
+ type Location = ReturnType<typeof currentLocation>
14
+
15
+ export interface TeamDashboardData {
16
+ readonly agents: readonly DashboardAgentInput[]
17
+ readonly overrides: Readonly<Record<string, string>>
18
+ readonly models: readonly ModelInfo[]
19
+ readonly providers: readonly ProviderInfo[]
20
+ readonly modelError?: string
21
+ readonly warning?: string
22
+ readonly agentsSupported: boolean
23
+ readonly agentsError?: string
24
+ }
25
+
26
+ export type LoadTeamDashboardResult =
27
+ | { readonly kind: "ready"; readonly data: TeamDashboardData }
28
+ | { readonly kind: "blocked"; readonly message: string }
29
+
30
+ type StateRead =
31
+ | { readonly summary: TeamPolicySummary }
32
+ | { readonly problem: string }
33
+
34
+ export interface ModelSelectionResult {
35
+ readonly saved: boolean
36
+ readonly tone: FeedbackTone
37
+ readonly message: string
38
+ readonly models?: Readonly<Record<string, string>>
39
+ }
40
+
41
+ export function currentLocation(ctx: Context): NonNullable<Context["location"]> {
42
+ return ctx.location ?? ctx.data.location.default()
43
+ }
44
+
45
+ /**
46
+ * 面板打开时重新同步 Agent 定义,System Prompt 与权限必须来自宿主当前生效值;
47
+ * 同步失败但有缓存时继续展示,并明确标注可能不是最新。
48
+ */
49
+ export async function loadTeamDashboard(
50
+ ctx: Context,
51
+ location: Location,
52
+ ): Promise<LoadTeamDashboardResult> {
53
+ const state = await readState(ctx, location)
54
+ if ("problem" in state) return { kind: "blocked", message: state.problem }
55
+ const summary = state.summary
56
+ if (summary.conflict !== undefined) {
57
+ return { kind: "blocked", message: conflictMessage(summary) }
58
+ }
59
+
60
+ const agents = await readAgents(ctx, location)
61
+ if (agents.message !== undefined) return { kind: "blocked", message: agents.message }
62
+
63
+ const models = await readModels(ctx, location)
64
+ const providers = await readProviders(ctx, location)
65
+ const inputs: DashboardAgentInput[] = agents.agents.map((agent) => ({
66
+ id: agent.id,
67
+ name: agent.name,
68
+ mode: agent.mode,
69
+ hidden: agent.hidden,
70
+ description: agent.description,
71
+ system: agent.system,
72
+ model: agent.model,
73
+ permissions: agent.permissions,
74
+ known: true,
75
+ }))
76
+
77
+ return {
78
+ kind: "ready",
79
+ data: {
80
+ agents: inputs,
81
+ overrides: summary.models ?? {},
82
+ models: models.models,
83
+ providers,
84
+ ...(models.error === undefined ? {} : { modelError: models.error }),
85
+ ...(agents.warning === undefined ? {} : { warning: agents.warning }),
86
+ agentsSupported: summary.agentsSupported ?? false,
87
+ ...(summary.agentsError === undefined ? {} : { agentsError: summary.agentsError }),
88
+ },
89
+ }
90
+ }
91
+
92
+ export async function saveAgentModel(
93
+ ctx: Context,
94
+ location: Location,
95
+ agent: DashboardAgent,
96
+ model: string | null,
97
+ ): Promise<ModelSelectionResult> {
98
+ if (model !== null) {
99
+ if (!agent.known) {
100
+ return {
101
+ saved: false,
102
+ tone: "warning",
103
+ message: "该 Agent 当前目录不可用,只能清除旧覆盖。",
104
+ }
105
+ }
106
+ if (agent.mode === "primary") {
107
+ return {
108
+ saved: false,
109
+ tone: "info",
110
+ message: "主代理模型由 OpenCode 会话选择,团队策略只覆盖子代理。",
111
+ }
112
+ }
113
+ }
114
+ return saveModel(ctx, location, agent.id, agent.name, model, agent.hostModel)
115
+ }
116
+
117
+ export async function restoreAgentModel(
118
+ ctx: Context,
119
+ location: Location,
120
+ agent: DashboardAgent,
121
+ ): Promise<ModelSelectionResult> {
122
+ if (!agent.canRestore) {
123
+ return {
124
+ saved: false,
125
+ tone: "info",
126
+ message: `${agent.name} 没有团队模型覆盖,无需恢复。`,
127
+ }
128
+ }
129
+ return saveAgentModel(ctx, location, agent, null)
130
+ }
131
+
132
+ async function readState(ctx: Context, location: Location): Promise<StateRead> {
133
+ let result: TeamPolicySummary
134
+ try {
135
+ result = (await ctx.client.rpc(teamRpc).getTeamPolicy({}, { location })) as TeamPolicySummary
136
+ } catch (error) {
137
+ return { problem: `无法读取团队模型设置:${message(error)}` }
138
+ }
139
+ if (!result.supported) {
140
+ return {
141
+ problem: "当前宿主不支持子代理模型覆盖(所需工具钩子不可用),团队模型功能不可用。",
142
+ }
143
+ }
144
+ if (!result.ok) return { problem: `无法读取团队模型设置:${summarize(result)}` }
145
+ return { summary: result }
146
+ }
147
+
148
+ async function readAgents(
149
+ ctx: Context,
150
+ location: Location,
151
+ ): Promise<{ readonly agents: AgentInfo[]; readonly warning?: string; readonly message?: string }> {
152
+ const collection = ctx.data.location.agent
153
+ let warning: string | undefined
154
+ try {
155
+ await collection.sync(location)
156
+ } catch (error) {
157
+ const cached = collection.list(location)
158
+ if (cached === undefined) return { agents: [], message: `无法读取 Agent 列表:${message(error)}` }
159
+ warning = `Agent 定义同步失败,正在使用缓存,内容可能不是最新:${message(error)}`
160
+ }
161
+ try {
162
+ const agents = collection.list(location)
163
+ if (agents === undefined) throw new Error("Agent 目录未返回数据")
164
+ return { agents, ...(warning === undefined ? {} : { warning }) }
165
+ } catch (error) {
166
+ return { agents: [], message: `无法读取 Agent 列表:${message(error)}` }
167
+ }
168
+ }
169
+
170
+ async function readModels(
171
+ ctx: Context,
172
+ location: Location,
173
+ force = false,
174
+ ): Promise<{ readonly models: ModelInfo[]; readonly error?: string }> {
175
+ const collection = ctx.data.location.model
176
+ try {
177
+ // `list` reads the per-location cache the host fills at boot; syncing only when it is
178
+ // absent avoids a network hop on every open while still distinguishing "not loaded"
179
+ // from a genuinely empty catalog.
180
+ if (force || collection.list(location) === undefined) await collection.sync(location)
181
+ const models = collection.list(location)
182
+ if (models === undefined) throw new Error("模型目录未返回数据")
183
+ return { models: models.filter(isChatModel) }
184
+ } catch (error) {
185
+ return { models: [], error: `无法读取模型列表:${message(error)}` }
186
+ }
187
+ }
188
+
189
+ /** 打开模型配置前重新同步一次目录,覆盖首次加载失败或目录为空的情况。 */
190
+ export async function refreshModels(
191
+ ctx: Context,
192
+ location: Location,
193
+ ): Promise<{ readonly models: ModelInfo[]; readonly error?: string }> {
194
+ return readModels(ctx, location, true)
195
+ }
196
+
197
+ async function readProviders(ctx: Context, location: Location): Promise<ProviderInfo[]> {
198
+ const collection = ctx.data.location.provider
199
+ try {
200
+ if (collection.list(location) === undefined) await collection.sync(location)
201
+ return collection.list(location) ?? []
202
+ } catch {
203
+ return collection.list(location) ?? []
204
+ }
205
+ }
206
+
207
+ function conflictMessage(state: TeamPolicySummary): string {
208
+ const migration = state.migration
209
+ if (migration?.status === "applied") {
210
+ const count = migration.agents?.length ?? 0
211
+ const imported =
212
+ count === 0 ? "当前没有可迁移的子代理" : `已迁移旧全局模型到 ${count} 个子代理`
213
+ return `检测到旧版插件 ${state.conflict?.pluginID ?? ""} 仍在加载。${imported};请移除旧插件并完全重启 OpenCode,之后才能调整团队模型。`
214
+ }
215
+ if (migration?.status === "empty") {
216
+ return `检测到旧版插件 ${state.conflict?.pluginID ?? ""} 仍在加载。旧插件没有启用模型覆盖;请移除旧插件并完全重启 OpenCode。`
217
+ }
218
+ const reason = migration?.errors?.join("; ")
219
+ const label = migration?.status === "unavailable" ? "旧设置迁移不可用" : "旧设置迁移失败"
220
+ return `检测到旧版插件 ${state.conflict?.pluginID ?? ""} 仍在加载,它会覆盖按 Agent 的模型设置。请移除旧插件并完全重启 OpenCode。${reason === undefined ? "" : `(${label}:${reason})`}`
221
+ }
222
+
223
+ async function saveModel(
224
+ ctx: Context,
225
+ location: Location,
226
+ agentID: string,
227
+ agentName: string,
228
+ model: string | null,
229
+ hostModel: string | undefined,
230
+ ): Promise<ModelSelectionResult> {
231
+ let result: TeamPolicySummary
232
+ try {
233
+ result = (await ctx.client.rpc(teamRpc).setAgentModel({ agentID, model }, { location })) as TeamPolicySummary
234
+ } catch (error) {
235
+ return {
236
+ saved: false,
237
+ tone: "error",
238
+ message: `保存 Agent 模型失败:${message(error)}`,
239
+ }
240
+ }
241
+ if (!result.ok) {
242
+ return {
243
+ saved: false,
244
+ tone: "error",
245
+ message: `保存 Agent 模型失败:${summarize(result)}`,
246
+ }
247
+ }
248
+ return {
249
+ saved: true,
250
+ tone: "success",
251
+ message:
252
+ model === null
253
+ ? hostModel === undefined
254
+ ? `已恢复 ${agentName} 的 OpenCode 原生模型选择`
255
+ : `已清除 ${agentName} 的团队覆盖,回到 Agent 配置的 ${hostModel}`
256
+ : `${agentName} 的子代理模型已设为 ${result.models?.[agentID] ?? model}`,
257
+ ...(result.models === undefined ? {} : { models: result.models }),
258
+ }
259
+ }
260
+
261
+ function summarize(result: TeamPolicySummary): string {
262
+ return (result.errors ?? []).join("; ") || "未知错误"
263
+ }
264
+
265
+ function message(error: unknown): string {
266
+ return error instanceof Error ? error.message : String(error)
267
+ }
@@ -0,0 +1,165 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { TextAttributes } from "@opentui/core"
3
+ import type { Plugin } from "@opencode/plugin/tui"
4
+ import { For, type JSX } from "solid-js"
5
+
6
+ import type { Feedback, Tone } from "./model.ts"
7
+
8
+ export type { Tone } from "./model.ts"
9
+ export { effectTone, statusTone } from "./model.ts"
10
+
11
+ export type Theme = Plugin.Context["theme"]
12
+ export type KeymapLayer = ReturnType<Parameters<Plugin.Context["keymap"]["layer"]>[0]>
13
+ export type Hint = { readonly key: string; readonly label: string }
14
+
15
+ export function toneColor(theme: Theme, tone: Tone) {
16
+ if (tone === "neutral") return theme.text.muted
17
+ if (tone === "accent") return theme.text.action.primary.selected
18
+ return theme.text.feedback[tone].base
19
+ }
20
+
21
+ /**
22
+ * 原生选择器用 accent 色阶做分组标题(默认主题是紫色),这里沿用同一来源,
23
+ * 不另造强调色,浅色/深色都由主题解析。
24
+ */
25
+ export function providerTitleColor(theme: Theme) {
26
+ return theme.hue.accent[200]
27
+ }
28
+
29
+ /**
30
+ * 选中行统一使用抬升表面和强调色指示条,不再用整行主操作色填充;
31
+ * 当前操作区域由面板边框或标题表示,避免多个区域同时高饱和。
32
+ */
33
+ export function rowBackground(theme: Theme, selected: boolean) {
34
+ return selected ? theme.background.raised.high : undefined
35
+ }
36
+
37
+ export function rowForeground(theme: Theme) {
38
+ return theme.text.base
39
+ }
40
+
41
+ export function rowSecondary(theme: Theme, selected: boolean) {
42
+ return selected ? theme.text.base : theme.text.muted
43
+ }
44
+
45
+ export function rowMarker(theme: Theme, selected: boolean) {
46
+ // 指示条统一使用宿主选中强调色;强选中背景本身就是该强调色时自然融入原生选中态。
47
+ return selected ? theme.text.action.primary.selected : theme.text.faint
48
+ }
49
+
50
+ export function selectedRowAccent(theme: Theme) {
51
+ return theme.text.action.primary.selected
52
+ }
53
+
54
+ export function Divider(props: { readonly theme: Theme }) {
55
+ return <box height={1} flexShrink={0} border={["bottom"]} borderColor={props.theme.border.base} />
56
+ }
57
+
58
+ /**
59
+ * 面板内滚动条放在右侧预留列,使用主题 scrollbar 色,常驻显示以提示内容可滚动。
60
+ * 绝对定位避免出现/消失时改变内容宽度。
61
+ */
62
+ export function scrollbarOptions(theme: Theme) {
63
+ return {
64
+ position: "absolute" as const,
65
+ right: 0,
66
+ top: 0,
67
+ width: 1,
68
+ height: "100%" as const,
69
+ trackOptions: {
70
+ backgroundColor: theme.background.raised.base,
71
+ foregroundColor: theme.scrollbar.base,
72
+ },
73
+ }
74
+ }
75
+
76
+ export function Section(props: {
77
+ readonly theme: Theme
78
+ readonly title: string
79
+ readonly children: JSX.Element
80
+ }) {
81
+ return (
82
+ <box flexDirection="column">
83
+ <text fg={props.theme.text.muted} attributes={TextAttributes.BOLD}>
84
+ {props.title}
85
+ </text>
86
+ {props.children}
87
+ </box>
88
+ )
89
+ }
90
+
91
+ export function Badge(props: {
92
+ readonly theme: Theme
93
+ readonly text: string
94
+ readonly tone: Tone
95
+ }) {
96
+ return (
97
+ <box
98
+ // 用主题自身的高低阶推导 chip 背景,深色/浅色都不需要硬编码。
99
+ backgroundColor={props.theme.decrease(props.theme.background.base)}
100
+ paddingLeft={1}
101
+ paddingRight={1}
102
+ flexShrink={0}
103
+ >
104
+ <text fg={toneColor(props.theme, props.tone)}>{props.text}</text>
105
+ </box>
106
+ )
107
+ }
108
+
109
+ export function Hints(props: { readonly theme: Theme; readonly hints: readonly Hint[] }) {
110
+ return (
111
+ <box flexDirection="row" gap={2} flexWrap="wrap">
112
+ <For each={props.hints}>
113
+ {(hint) => (
114
+ <text fg={props.theme.text.muted}>
115
+ <span style={{ fg: props.theme.text.base }}>{hint.key}</span> {hint.label}
116
+ </text>
117
+ )}
118
+ </For>
119
+ </box>
120
+ )
121
+ }
122
+
123
+ /**
124
+ * Modal 内状态栏:普通状态紧凑一行,错误可换行展示完整内容。
125
+ * 作为独立布局行放在快捷键栏上方,不覆盖模型列表、搜索或 Variant。
126
+ */
127
+ export function FeedbackBar(props: { readonly theme: Theme; readonly feedback: Feedback }) {
128
+ const color = () => toneColor(props.theme, props.feedback.tone)
129
+ const marker = () => {
130
+ if (props.feedback.tone === "success") return "✓"
131
+ if (props.feedback.tone === "info") return "·"
132
+ return "!"
133
+ }
134
+ return (
135
+ <box
136
+ flexShrink={0}
137
+ flexDirection="row"
138
+ gap={1}
139
+ border={["top"]}
140
+ borderColor={color()}
141
+ >
142
+ <text flexShrink={0} fg={color()} attributes={TextAttributes.BOLD}>
143
+ {marker()}
144
+ </text>
145
+ <text flexGrow={1} fg={color()} wrapMode="word">
146
+ {props.feedback.message}
147
+ </text>
148
+ </box>
149
+ )
150
+ }
151
+
152
+ /** 需要确认的破坏性操作留在当前 Modal,不打开第二个宿主弹窗。 */
153
+ export function ConfirmBar(props: { readonly theme: Theme; readonly message: string }) {
154
+ return (
155
+ <box
156
+ flexShrink={0}
157
+ border={["top"]}
158
+ borderColor={props.theme.text.feedback.warning.base}
159
+ >
160
+ <text fg={props.theme.text.feedback.warning.base} wrapMode="word">
161
+ {props.message}
162
+ </text>
163
+ </box>
164
+ )
165
+ }