@justsilver/opencode-team 0.2.0 → 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.
@@ -1,502 +1,502 @@
1
- import type { AgentInfo, ModelInfo, ProviderInfo } from "@opencode/client"
2
-
3
- import { formatModelRef, isChatModel, parseModelRef } from "../model-ref.ts"
4
- import { TEAM_SUBAGENT_IDS } from "../team-ids.ts"
5
-
6
- export { formatModelRef, parseModelRef } from "../model-ref.ts"
7
- export type { ModelRef as ParsedModelRef } from "../model-ref.ts"
8
-
9
- export type AgentMode = AgentInfo["mode"]
10
- export type ModelStatus = "native" | "inherit" | "custom"
11
- export type ModelSource = "team" | "agent" | "none"
12
- export type PermissionEffect = "allow" | "deny" | "ask"
13
-
14
- export interface DashboardAgentInput {
15
- readonly id: string
16
- readonly name?: string
17
- readonly mode?: AgentMode
18
- readonly hidden?: boolean
19
- readonly description?: string
20
- readonly system?: string
21
- readonly model?: AgentInfo["model"]
22
- readonly permissions?: AgentInfo["permissions"]
23
- readonly known: boolean
24
- }
25
-
26
- export interface PromptInfo {
27
- readonly available: boolean
28
- readonly text?: string
29
- readonly reason?: string
30
- }
31
-
32
- export interface PermissionHighlight {
33
- readonly effect: PermissionEffect
34
- readonly action: string
35
- readonly resource: string
36
- }
37
-
38
- export interface PermissionSummary {
39
- readonly total: number
40
- readonly allow: number
41
- readonly ask: number
42
- readonly deny: number
43
- readonly defaultEffect?: PermissionEffect
44
- readonly highlights: readonly PermissionHighlight[]
45
- }
46
-
47
- export interface DashboardAgent {
48
- readonly id: string
49
- readonly name: string
50
- readonly mode: AgentMode
51
- readonly known: boolean
52
- readonly description?: string
53
- readonly teamModel?: string
54
- readonly hostModel?: string
55
- readonly effectiveModel?: string
56
- readonly modelLabel: string
57
- readonly modelRefLabel?: string
58
- readonly variantLabel: string
59
- readonly status: ModelStatus
60
- readonly statusLabel: string
61
- readonly source: ModelSource
62
- readonly sourceLabel: string
63
- readonly canConfigure: boolean
64
- readonly canRestore: boolean
65
- readonly prompt: PromptInfo
66
- readonly permissions: PermissionSummary
67
- readonly searchText: string
68
- }
69
-
70
- export interface DashboardGroup {
71
- readonly key: "primary" | "subagents" | "unavailable"
72
- readonly title: string
73
- readonly agents: readonly DashboardAgent[]
74
- }
75
-
76
- export interface DashboardLayout {
77
- readonly split: boolean
78
- readonly compact: boolean
79
- readonly minimal: boolean
80
- readonly dialogHeight: number
81
- readonly listWidth: number
82
- }
83
-
84
- export const STATUS_LABELS: Readonly<Record<ModelStatus, string>> = {
85
- native: "原生",
86
- inherit: "继承",
87
- custom: "自定义",
88
- }
89
-
90
- export const SOURCE_LABELS: Readonly<Record<ModelSource, string>> = {
91
- team: "团队策略",
92
- agent: "Agent 配置",
93
- none: "无独立模型",
94
- }
95
-
96
- export type FeedbackTone = "info" | "success" | "warning" | "error"
97
-
98
- export interface Feedback {
99
- readonly tone: FeedbackTone
100
- readonly message: string
101
- }
102
-
103
- /** 错误保留到下一次操作或被关闭,其余状态自动收起,避免状态栏长期占用内容高度。 */
104
- export function feedbackDismissMs(tone: FeedbackTone): number {
105
- if (tone === "error") return 0
106
- if (tone === "warning") return 6000
107
- return 4000
108
- }
109
-
110
- export type Tone = "neutral" | "accent" | "success" | "warning" | "error" | "info"
111
-
112
- export function statusTone(status: ModelStatus): Tone {
113
- return status === "custom" ? "accent" : "neutral"
114
- }
115
-
116
- /** 允许规则数量多,保持中性;只有拒绝与询问用语义色,避免权限区抢走模型信息的注意力。 */
117
- export function effectTone(effect: PermissionEffect): Tone {
118
- if (effect === "deny") return "error"
119
- if (effect === "ask") return "warning"
120
- return "neutral"
121
- }
122
-
123
- export type ConfigRegion = "models" | "variants"
124
-
125
- /** 无 Variant 的模型没有可操作的第二栏,切换区域时始终留在模型列表。 */
126
- export function nextRegion(region: ConfigRegion, hasVariants: boolean): ConfigRegion {
127
- if (!hasVariants) return "models"
128
- return region === "models" ? "variants" : "models"
129
- }
130
-
131
- const PROMPT_UNAVAILABLE = "宿主未为该 Agent 提供独立 System Prompt。"
132
-
133
- function preferredRank(id: string): number {
134
- const index = TEAM_SUBAGENT_IDS.indexOf(id as (typeof TEAM_SUBAGENT_IDS)[number])
135
- return index === -1 ? TEAM_SUBAGENT_IDS.length : index
136
- }
137
-
138
- export function hostModelRef(model: AgentInfo["model"]): string | undefined {
139
- if (model === undefined) return undefined
140
- return formatModelRef({ providerID: model.providerID, id: model.id, variant: model.variant })
141
- }
142
-
143
- function providerName(providers: readonly ProviderInfo[], providerID: string): string {
144
- const provider = providers.find((candidate) => candidate.id === providerID)
145
- const name = provider?.name?.trim()
146
- return name === undefined || name === "" ? providerID : name
147
- }
148
-
149
- export function providerLabel(providers: readonly ProviderInfo[], providerID: string): string {
150
- return providerName(providers, providerID)
151
- }
152
-
153
- export interface ModelGroup {
154
- readonly providerID: string
155
- readonly providerName: string
156
- readonly models: readonly ModelInfo[]
157
- }
158
-
159
- export interface ModelConfigLayout extends DashboardLayout {
160
- readonly variantWidth: number
161
- }
162
-
163
- export function modelRefOf(model: ModelInfo): string {
164
- return `${model.providerID}/${model.id}`
165
- }
166
-
167
- export function roleLabel(mode: AgentMode): string {
168
- if (mode === "primary") return "PRIMARY"
169
- if (mode === "all") return "ALL"
170
- return "SUBAGENT"
171
- }
172
-
173
- export function resolveModel(
174
- models: readonly ModelInfo[],
175
- baseRef: string,
176
- ): ModelInfo | undefined {
177
- return models.find((candidate) => modelRefOf(candidate) === baseRef)
178
- }
179
-
180
- export function variantsFor(model: ModelInfo | undefined): readonly string[] {
181
- const seen = new Set<string>()
182
- const result: string[] = []
183
- for (const variant of model?.variants ?? []) {
184
- if (variant.id === "" || seen.has(variant.id)) continue
185
- seen.add(variant.id)
186
- result.push(variant.id)
187
- }
188
- return result
189
- }
190
-
191
- /** 搜索改变列表后,选中项必须落在可见模型上;没有可见模型时返回 undefined。 */
192
- export function firstVisibleRef(
193
- models: readonly ModelInfo[],
194
- current: string,
195
- ): string | undefined {
196
- if (models.some((model) => modelRefOf(model) === current)) return current
197
- const first = models[0]
198
- return first === undefined ? undefined : modelRefOf(first)
199
- }
200
-
201
- export function buildModelRef(baseRef: string, variant: string | undefined): string {
202
- return variant === undefined || variant === "" ? baseRef : `${baseRef}#${variant}`
203
- }
204
-
205
- export function modelGroups(
206
- models: readonly ModelInfo[],
207
- providers: readonly ProviderInfo[],
208
- query: string,
209
- ): ModelGroup[] {
210
- const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
211
- const byProvider = new Map<string, { name: string; models: ModelInfo[] }>()
212
- for (const model of models) {
213
- if (!isChatModel(model)) continue
214
- const provider = providerLabel(providers, model.providerID)
215
- const text = [model.name, model.id, model.providerID, provider, modelRefOf(model)]
216
- .join(" ")
217
- .toLowerCase()
218
- if (!tokens.every((token) => text.includes(token))) continue
219
- const group = byProvider.get(model.providerID) ?? { name: provider, models: [] }
220
- group.models.push(model)
221
- byProvider.set(model.providerID, group)
222
- }
223
- return [...byProvider.entries()]
224
- .map(([providerID, group]) => ({
225
- providerID,
226
- providerName: group.name,
227
- models: group.models.toSorted(
228
- (left, right) =>
229
- (left.name || left.id).localeCompare(right.name || right.id) || left.id.localeCompare(right.id),
230
- ),
231
- }))
232
- .toSorted(
233
- (left, right) =>
234
- left.providerName.localeCompare(right.providerName) ||
235
- left.providerID.localeCompare(right.providerID),
236
- )
237
- }
238
-
239
- export function modelConfigLayoutFor(width: number, height: number): ModelConfigLayout {
240
- return {
241
- ...layoutFor(width, height),
242
- variantWidth: width >= 112 ? 38 : 32,
243
- }
244
- }
245
-
246
- export function describeModel(
247
- ref: string | undefined,
248
- mode: AgentMode,
249
- models: readonly ModelInfo[],
250
- providers: readonly ProviderInfo[],
251
- ): { readonly label: string; readonly variantLabel: string; readonly refLabel?: string } {
252
- if (ref === undefined) {
253
- return {
254
- label: mode === "primary" ? "OpenCode 原生选择" : "继承调用方模型",
255
- variantLabel: "—",
256
- }
257
- }
258
- const parsed = parseModelRef(ref)
259
- if (parsed === undefined) {
260
- return { label: `${ref}(引用格式无效)`, variantLabel: "—", refLabel: ref }
261
- }
262
- const model = models.find(
263
- (candidate) => candidate.providerID === parsed.providerID && candidate.id === parsed.id,
264
- )
265
- const variantLabel = parsed.variant ?? "默认(不附加变体)"
266
- if (model === undefined) {
267
- return { label: `${ref}(当前目录不可用)`, variantLabel, refLabel: ref }
268
- }
269
- const base = `${providerName(providers, parsed.providerID)} / ${model.name}`
270
- return {
271
- label: parsed.variant === undefined ? base : `${base} · ${parsed.variant}`,
272
- variantLabel,
273
- refLabel: ref,
274
- }
275
- }
276
-
277
- function classifyModel(input: {
278
- readonly mode: AgentMode
279
- readonly teamModel?: string
280
- readonly hostModel?: string
281
- }): { readonly status: ModelStatus; readonly source: ModelSource } {
282
- if (input.teamModel !== undefined) return { status: "custom", source: "team" }
283
- if (input.hostModel !== undefined) return { status: "custom", source: "agent" }
284
- if (input.mode === "primary") return { status: "native", source: "none" }
285
- return { status: "inherit", source: "none" }
286
- }
287
-
288
- export function promptInfo(system: string | undefined): PromptInfo {
289
- if (system === undefined) return { available: false, reason: PROMPT_UNAVAILABLE }
290
- const text = system.replace(/\r\n?/g, "\n")
291
- if (text.trim() === "") return { available: false, reason: PROMPT_UNAVAILABLE }
292
- const lines = text.split("\n")
293
- if (lines.length > 0 && lines.at(-1) === "") lines.pop()
294
- return {
295
- available: true,
296
- text: lines.join("\n"),
297
- }
298
- }
299
-
300
- export function summarizePermissions(
301
- rules: readonly { readonly action: string; readonly resource: string; readonly effect: PermissionEffect }[] | undefined,
302
- ): PermissionSummary {
303
- if (rules === undefined || rules.length === 0) {
304
- return { total: 0, allow: 0, ask: 0, deny: 0, highlights: [] }
305
- }
306
- const seen = new Set<string>()
307
- const effective: { action: string; resource: string; effect: PermissionEffect }[] = []
308
- for (let index = rules.length - 1; index >= 0; index--) {
309
- const rule = rules[index]!
310
- const key = `${rule.action}\u0000${rule.resource}`
311
- if (seen.has(key)) continue
312
- seen.add(key)
313
- effective.push({ action: rule.action, resource: rule.resource, effect: rule.effect })
314
- }
315
- effective.reverse()
316
-
317
- let allow = 0
318
- let ask = 0
319
- let deny = 0
320
- for (const rule of effective) {
321
- if (rule.effect === "allow") allow++
322
- else if (rule.effect === "ask") ask++
323
- else deny++
324
- }
325
-
326
- const fallback = effective.find((rule) => rule.action === "*" && rule.resource === "*")
327
- const noteworthy = effective.filter(
328
- (rule) =>
329
- rule.resource !== "*" ||
330
- ["shell", "edit", "subagent", "question", "todowrite", "external_directory", "browser", "skill"].includes(
331
- rule.action,
332
- ),
333
- )
334
- const rank = (effect: PermissionEffect) => (effect === "deny" ? 0 : effect === "ask" ? 1 : 2)
335
- const highlights = noteworthy
336
- .toSorted((left, right) => rank(left.effect) - rank(right.effect))
337
- .slice(0, 4)
338
-
339
- return {
340
- total: effective.length,
341
- allow,
342
- ask,
343
- deny,
344
- ...(fallback === undefined ? {} : { defaultEffect: fallback.effect }),
345
- highlights,
346
- }
347
- }
348
-
349
- export function buildDashboardAgent(
350
- input: DashboardAgentInput,
351
- overrides: Readonly<Record<string, string>>,
352
- models: readonly ModelInfo[],
353
- providers: readonly ProviderInfo[],
354
- ): DashboardAgent {
355
- const mode = input.mode ?? "subagent"
356
- const teamModel = overrides[input.id]
357
- const hostModel = hostModelRef(input.model)
358
- const effectiveModel = teamModel ?? hostModel
359
- const { status, source } = classifyModel({
360
- mode,
361
- ...(teamModel === undefined ? {} : { teamModel }),
362
- ...(hostModel === undefined ? {} : { hostModel }),
363
- })
364
- const described = describeModel(effectiveModel, mode, models, providers)
365
- const prompt = input.known
366
- ? promptInfo(input.system)
367
- : {
368
- available: false,
369
- reason: "该 Agent 不在团队视图中,无法读取它的角色定义与 System Prompt。",
370
- }
371
- const description = input.known
372
- ? input.description?.trim() || undefined
373
- : "该 Agent 不在团队视图中;只能清除旧覆盖。"
374
- const name = input.name?.trim() || input.id
375
- const searchText = [
376
- input.id,
377
- name,
378
- mode,
379
- status,
380
- STATUS_LABELS[status],
381
- SOURCE_LABELS[source],
382
- described.label,
383
- teamModel ?? "",
384
- hostModel ?? "",
385
- ]
386
- .join(" ")
387
- .toLowerCase()
388
-
389
- return {
390
- id: input.id,
391
- name,
392
- mode,
393
- known: input.known,
394
- ...(description === undefined ? {} : { description }),
395
- ...(teamModel === undefined ? {} : { teamModel }),
396
- ...(hostModel === undefined ? {} : { hostModel }),
397
- ...(effectiveModel === undefined ? {} : { effectiveModel }),
398
- modelLabel: described.label,
399
- ...(described.refLabel === undefined ? {} : { modelRefLabel: described.refLabel }),
400
- variantLabel: described.variantLabel,
401
- status,
402
- statusLabel: STATUS_LABELS[status],
403
- source,
404
- sourceLabel: SOURCE_LABELS[source],
405
- canConfigure: input.known && mode !== "primary",
406
- canRestore: teamModel !== undefined,
407
- prompt,
408
- permissions: summarizePermissions(input.permissions),
409
- searchText,
410
- }
411
- }
412
-
413
- export function buildDashboardGroups(
414
- inputs: readonly DashboardAgentInput[],
415
- overrides: Readonly<Record<string, string>>,
416
- models: readonly ModelInfo[],
417
- providers: readonly ProviderInfo[],
418
- ): DashboardGroup[] {
419
- const known: DashboardAgentInput[] = []
420
- const knownIDs = new Set<string>()
421
- for (const agent of inputs) {
422
- if (agent.hidden) continue
423
- if (agent.mode === "primary" && agent.id !== "orchestrator") continue
424
- known.push(agent)
425
- knownIDs.add(agent.id)
426
- }
427
-
428
- const primary = known
429
- .filter((agent) => agent.mode === "primary")
430
- .map((agent) => buildDashboardAgent(agent, overrides, models, providers))
431
- .toSorted((left, right) => left.id.localeCompare(right.id))
432
- const subagents = known
433
- .filter((agent) => agent.mode !== "primary")
434
- .map((agent) => buildDashboardAgent(agent, overrides, models, providers))
435
- .toSorted(
436
- (left, right) =>
437
- preferredRank(left.id) - preferredRank(right.id) || left.id.localeCompare(right.id),
438
- )
439
- const unavailable = Object.keys(overrides)
440
- .filter((id) => !knownIDs.has(id))
441
- .toSorted()
442
- .map((id) =>
443
- buildDashboardAgent(
444
- { id, name: id, mode: "subagent", known: false },
445
- overrides,
446
- models,
447
- providers,
448
- ),
449
- )
450
-
451
- return [
452
- ...(primary.length === 0 ? [] : [{ key: "primary" as const, title: "PRIMARY", agents: primary }]),
453
- ...(subagents.length === 0
454
- ? []
455
- : [{ key: "subagents" as const, title: `SUBAGENTS · ${subagents.length}`, agents: subagents }]),
456
- ...(unavailable.length === 0
457
- ? []
458
- : [
459
- {
460
- key: "unavailable" as const,
461
- title: `已保存但不在团队视图 · ${unavailable.length}`,
462
- agents: unavailable,
463
- },
464
- ]),
465
- ]
466
- }
467
-
468
- export function filterDashboardGroups(
469
- groups: readonly DashboardGroup[],
470
- query: string,
471
- ): DashboardGroup[] {
472
- const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
473
- if (tokens.length === 0) return [...groups]
474
- return groups.flatMap((group) => {
475
- const agents = group.agents.filter((agent) =>
476
- tokens.every((token) => agent.searchText.includes(token)),
477
- )
478
- if (agents.length === 0) return []
479
- return [
480
- {
481
- ...group,
482
- title:
483
- group.key === "subagents"
484
- ? `SUBAGENTS · ${agents.length}`
485
- : group.key === "unavailable"
486
- ? `已保存但不在团队视图 · ${agents.length}`
487
- : group.title,
488
- agents,
489
- },
490
- ]
491
- })
492
- }
493
-
494
- export function layoutFor(width: number, height: number): DashboardLayout {
495
- return {
496
- split: width >= 90,
497
- compact: height < 20 || width < 100,
498
- minimal: width < 50,
499
- dialogHeight: Math.max(6, Math.min(30, height - 4)),
500
- listWidth: width >= 112 ? 32 : 28,
501
- }
1
+ import type { AgentInfo, ModelInfo, ProviderInfo } from "@opencode/client"
2
+
3
+ import { formatModelRef, isChatModel, parseModelRef } from "../model-ref.ts"
4
+ import { TEAM_SUBAGENT_IDS } from "../team-ids.ts"
5
+
6
+ export { formatModelRef, parseModelRef } from "../model-ref.ts"
7
+ export type { ModelRef as ParsedModelRef } from "../model-ref.ts"
8
+
9
+ export type AgentMode = AgentInfo["mode"]
10
+ export type ModelStatus = "native" | "inherit" | "custom"
11
+ export type ModelSource = "team" | "agent" | "none"
12
+ export type PermissionEffect = "allow" | "deny" | "ask"
13
+
14
+ export interface DashboardAgentInput {
15
+ readonly id: string
16
+ readonly name?: string
17
+ readonly mode?: AgentMode
18
+ readonly hidden?: boolean
19
+ readonly description?: string
20
+ readonly system?: string
21
+ readonly model?: AgentInfo["model"]
22
+ readonly permissions?: AgentInfo["permissions"]
23
+ readonly known: boolean
24
+ }
25
+
26
+ export interface PromptInfo {
27
+ readonly available: boolean
28
+ readonly text?: string
29
+ readonly reason?: string
30
+ }
31
+
32
+ export interface PermissionHighlight {
33
+ readonly effect: PermissionEffect
34
+ readonly action: string
35
+ readonly resource: string
36
+ }
37
+
38
+ export interface PermissionSummary {
39
+ readonly total: number
40
+ readonly allow: number
41
+ readonly ask: number
42
+ readonly deny: number
43
+ readonly defaultEffect?: PermissionEffect
44
+ readonly highlights: readonly PermissionHighlight[]
45
+ }
46
+
47
+ export interface DashboardAgent {
48
+ readonly id: string
49
+ readonly name: string
50
+ readonly mode: AgentMode
51
+ readonly known: boolean
52
+ readonly description?: string
53
+ readonly teamModel?: string
54
+ readonly hostModel?: string
55
+ readonly effectiveModel?: string
56
+ readonly modelLabel: string
57
+ readonly modelRefLabel?: string
58
+ readonly variantLabel: string
59
+ readonly status: ModelStatus
60
+ readonly statusLabel: string
61
+ readonly source: ModelSource
62
+ readonly sourceLabel: string
63
+ readonly canConfigure: boolean
64
+ readonly canRestore: boolean
65
+ readonly prompt: PromptInfo
66
+ readonly permissions: PermissionSummary
67
+ readonly searchText: string
68
+ }
69
+
70
+ export interface DashboardGroup {
71
+ readonly key: "primary" | "subagents" | "unavailable"
72
+ readonly title: string
73
+ readonly agents: readonly DashboardAgent[]
74
+ }
75
+
76
+ export interface DashboardLayout {
77
+ readonly split: boolean
78
+ readonly compact: boolean
79
+ readonly minimal: boolean
80
+ readonly dialogHeight: number
81
+ readonly listWidth: number
82
+ }
83
+
84
+ export const STATUS_LABELS: Readonly<Record<ModelStatus, string>> = {
85
+ native: "原生",
86
+ inherit: "继承",
87
+ custom: "自定义",
88
+ }
89
+
90
+ export const SOURCE_LABELS: Readonly<Record<ModelSource, string>> = {
91
+ team: "团队策略",
92
+ agent: "Agent 配置",
93
+ none: "无独立模型",
94
+ }
95
+
96
+ export type FeedbackTone = "info" | "success" | "warning" | "error"
97
+
98
+ export interface Feedback {
99
+ readonly tone: FeedbackTone
100
+ readonly message: string
101
+ }
102
+
103
+ /** 错误保留到下一次操作或被关闭,其余状态自动收起,避免状态栏长期占用内容高度。 */
104
+ export function feedbackDismissMs(tone: FeedbackTone): number {
105
+ if (tone === "error") return 0
106
+ if (tone === "warning") return 6000
107
+ return 4000
108
+ }
109
+
110
+ export type Tone = "neutral" | "accent" | "success" | "warning" | "error" | "info"
111
+
112
+ export function statusTone(status: ModelStatus): Tone {
113
+ return status === "custom" ? "accent" : "neutral"
114
+ }
115
+
116
+ /** 允许规则数量多,保持中性;只有拒绝与询问用语义色,避免权限区抢走模型信息的注意力。 */
117
+ export function effectTone(effect: PermissionEffect): Tone {
118
+ if (effect === "deny") return "error"
119
+ if (effect === "ask") return "warning"
120
+ return "neutral"
121
+ }
122
+
123
+ export type ConfigRegion = "models" | "variants"
124
+
125
+ /** 无 Variant 的模型没有可操作的第二栏,切换区域时始终留在模型列表。 */
126
+ export function nextRegion(region: ConfigRegion, hasVariants: boolean): ConfigRegion {
127
+ if (!hasVariants) return "models"
128
+ return region === "models" ? "variants" : "models"
129
+ }
130
+
131
+ const PROMPT_UNAVAILABLE = "宿主未为该 Agent 提供独立 System Prompt。"
132
+
133
+ function preferredRank(id: string): number {
134
+ const index = TEAM_SUBAGENT_IDS.indexOf(id as (typeof TEAM_SUBAGENT_IDS)[number])
135
+ return index === -1 ? TEAM_SUBAGENT_IDS.length : index
136
+ }
137
+
138
+ export function hostModelRef(model: AgentInfo["model"]): string | undefined {
139
+ if (model === undefined) return undefined
140
+ return formatModelRef({ providerID: model.providerID, id: model.id, variant: model.variant })
141
+ }
142
+
143
+ function providerName(providers: readonly ProviderInfo[], providerID: string): string {
144
+ const provider = providers.find((candidate) => candidate.id === providerID)
145
+ const name = provider?.name?.trim()
146
+ return name === undefined || name === "" ? providerID : name
147
+ }
148
+
149
+ export function providerLabel(providers: readonly ProviderInfo[], providerID: string): string {
150
+ return providerName(providers, providerID)
151
+ }
152
+
153
+ export interface ModelGroup {
154
+ readonly providerID: string
155
+ readonly providerName: string
156
+ readonly models: readonly ModelInfo[]
157
+ }
158
+
159
+ export interface ModelConfigLayout extends DashboardLayout {
160
+ readonly variantWidth: number
161
+ }
162
+
163
+ export function modelRefOf(model: ModelInfo): string {
164
+ return `${model.providerID}/${model.id}`
165
+ }
166
+
167
+ export function roleLabel(mode: AgentMode): string {
168
+ if (mode === "primary") return "PRIMARY"
169
+ if (mode === "all") return "ALL"
170
+ return "SUBAGENT"
171
+ }
172
+
173
+ export function resolveModel(
174
+ models: readonly ModelInfo[],
175
+ baseRef: string,
176
+ ): ModelInfo | undefined {
177
+ return models.find((candidate) => modelRefOf(candidate) === baseRef)
178
+ }
179
+
180
+ export function variantsFor(model: ModelInfo | undefined): readonly string[] {
181
+ const seen = new Set<string>()
182
+ const result: string[] = []
183
+ for (const variant of model?.variants ?? []) {
184
+ if (variant.id === "" || seen.has(variant.id)) continue
185
+ seen.add(variant.id)
186
+ result.push(variant.id)
187
+ }
188
+ return result
189
+ }
190
+
191
+ /** 搜索改变列表后,选中项必须落在可见模型上;没有可见模型时返回 undefined。 */
192
+ export function firstVisibleRef(
193
+ models: readonly ModelInfo[],
194
+ current: string,
195
+ ): string | undefined {
196
+ if (models.some((model) => modelRefOf(model) === current)) return current
197
+ const first = models[0]
198
+ return first === undefined ? undefined : modelRefOf(first)
199
+ }
200
+
201
+ export function buildModelRef(baseRef: string, variant: string | undefined): string {
202
+ return variant === undefined || variant === "" ? baseRef : `${baseRef}#${variant}`
203
+ }
204
+
205
+ export function modelGroups(
206
+ models: readonly ModelInfo[],
207
+ providers: readonly ProviderInfo[],
208
+ query: string,
209
+ ): ModelGroup[] {
210
+ const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
211
+ const byProvider = new Map<string, { name: string; models: ModelInfo[] }>()
212
+ for (const model of models) {
213
+ if (!isChatModel(model)) continue
214
+ const provider = providerLabel(providers, model.providerID)
215
+ const text = [model.name, model.id, model.providerID, provider, modelRefOf(model)]
216
+ .join(" ")
217
+ .toLowerCase()
218
+ if (!tokens.every((token) => text.includes(token))) continue
219
+ const group = byProvider.get(model.providerID) ?? { name: provider, models: [] }
220
+ group.models.push(model)
221
+ byProvider.set(model.providerID, group)
222
+ }
223
+ return [...byProvider.entries()]
224
+ .map(([providerID, group]) => ({
225
+ providerID,
226
+ providerName: group.name,
227
+ models: group.models.toSorted(
228
+ (left, right) =>
229
+ (left.name || left.id).localeCompare(right.name || right.id) || left.id.localeCompare(right.id),
230
+ ),
231
+ }))
232
+ .toSorted(
233
+ (left, right) =>
234
+ left.providerName.localeCompare(right.providerName) ||
235
+ left.providerID.localeCompare(right.providerID),
236
+ )
237
+ }
238
+
239
+ export function modelConfigLayoutFor(width: number, height: number): ModelConfigLayout {
240
+ return {
241
+ ...layoutFor(width, height),
242
+ variantWidth: width >= 112 ? 38 : 32,
243
+ }
244
+ }
245
+
246
+ export function describeModel(
247
+ ref: string | undefined,
248
+ mode: AgentMode,
249
+ models: readonly ModelInfo[],
250
+ providers: readonly ProviderInfo[],
251
+ ): { readonly label: string; readonly variantLabel: string; readonly refLabel?: string } {
252
+ if (ref === undefined) {
253
+ return {
254
+ label: mode === "primary" ? "OpenCode 原生选择" : "继承调用方模型",
255
+ variantLabel: "—",
256
+ }
257
+ }
258
+ const parsed = parseModelRef(ref)
259
+ if (parsed === undefined) {
260
+ return { label: `${ref}(引用格式无效)`, variantLabel: "—", refLabel: ref }
261
+ }
262
+ const model = models.find(
263
+ (candidate) => candidate.providerID === parsed.providerID && candidate.id === parsed.id,
264
+ )
265
+ const variantLabel = parsed.variant ?? "默认(不附加变体)"
266
+ if (model === undefined) {
267
+ return { label: `${ref}(当前目录不可用)`, variantLabel, refLabel: ref }
268
+ }
269
+ const base = `${providerName(providers, parsed.providerID)} / ${model.name}`
270
+ return {
271
+ label: parsed.variant === undefined ? base : `${base} · ${parsed.variant}`,
272
+ variantLabel,
273
+ refLabel: ref,
274
+ }
275
+ }
276
+
277
+ function classifyModel(input: {
278
+ readonly mode: AgentMode
279
+ readonly teamModel?: string
280
+ readonly hostModel?: string
281
+ }): { readonly status: ModelStatus; readonly source: ModelSource } {
282
+ if (input.teamModel !== undefined) return { status: "custom", source: "team" }
283
+ if (input.hostModel !== undefined) return { status: "custom", source: "agent" }
284
+ if (input.mode === "primary") return { status: "native", source: "none" }
285
+ return { status: "inherit", source: "none" }
286
+ }
287
+
288
+ export function promptInfo(system: string | undefined): PromptInfo {
289
+ if (system === undefined) return { available: false, reason: PROMPT_UNAVAILABLE }
290
+ const text = system.replace(/\r\n?/g, "\n")
291
+ if (text.trim() === "") return { available: false, reason: PROMPT_UNAVAILABLE }
292
+ const lines = text.split("\n")
293
+ if (lines.length > 0 && lines.at(-1) === "") lines.pop()
294
+ return {
295
+ available: true,
296
+ text: lines.join("\n"),
297
+ }
298
+ }
299
+
300
+ export function summarizePermissions(
301
+ rules: readonly { readonly action: string; readonly resource: string; readonly effect: PermissionEffect }[] | undefined,
302
+ ): PermissionSummary {
303
+ if (rules === undefined || rules.length === 0) {
304
+ return { total: 0, allow: 0, ask: 0, deny: 0, highlights: [] }
305
+ }
306
+ const seen = new Set<string>()
307
+ const effective: { action: string; resource: string; effect: PermissionEffect }[] = []
308
+ for (let index = rules.length - 1; index >= 0; index--) {
309
+ const rule = rules[index]!
310
+ const key = `${rule.action}\u0000${rule.resource}`
311
+ if (seen.has(key)) continue
312
+ seen.add(key)
313
+ effective.push({ action: rule.action, resource: rule.resource, effect: rule.effect })
314
+ }
315
+ effective.reverse()
316
+
317
+ let allow = 0
318
+ let ask = 0
319
+ let deny = 0
320
+ for (const rule of effective) {
321
+ if (rule.effect === "allow") allow++
322
+ else if (rule.effect === "ask") ask++
323
+ else deny++
324
+ }
325
+
326
+ const fallback = effective.find((rule) => rule.action === "*" && rule.resource === "*")
327
+ const noteworthy = effective.filter(
328
+ (rule) =>
329
+ rule.resource !== "*" ||
330
+ ["shell", "edit", "subagent", "question", "todowrite", "external_directory", "browser", "skill"].includes(
331
+ rule.action,
332
+ ),
333
+ )
334
+ const rank = (effect: PermissionEffect) => (effect === "deny" ? 0 : effect === "ask" ? 1 : 2)
335
+ const highlights = noteworthy
336
+ .toSorted((left, right) => rank(left.effect) - rank(right.effect))
337
+ .slice(0, 4)
338
+
339
+ return {
340
+ total: effective.length,
341
+ allow,
342
+ ask,
343
+ deny,
344
+ ...(fallback === undefined ? {} : { defaultEffect: fallback.effect }),
345
+ highlights,
346
+ }
347
+ }
348
+
349
+ export function buildDashboardAgent(
350
+ input: DashboardAgentInput,
351
+ overrides: Readonly<Record<string, string>>,
352
+ models: readonly ModelInfo[],
353
+ providers: readonly ProviderInfo[],
354
+ ): DashboardAgent {
355
+ const mode = input.mode ?? "subagent"
356
+ const teamModel = overrides[input.id]
357
+ const hostModel = hostModelRef(input.model)
358
+ const effectiveModel = teamModel ?? hostModel
359
+ const { status, source } = classifyModel({
360
+ mode,
361
+ ...(teamModel === undefined ? {} : { teamModel }),
362
+ ...(hostModel === undefined ? {} : { hostModel }),
363
+ })
364
+ const described = describeModel(effectiveModel, mode, models, providers)
365
+ const prompt = input.known
366
+ ? promptInfo(input.system)
367
+ : {
368
+ available: false,
369
+ reason: "该 Agent 不在团队视图中,无法读取它的角色定义与 System Prompt。",
370
+ }
371
+ const description = input.known
372
+ ? input.description?.trim() || undefined
373
+ : "该 Agent 不在团队视图中;只能清除旧覆盖。"
374
+ const name = input.name?.trim() || input.id
375
+ const searchText = [
376
+ input.id,
377
+ name,
378
+ mode,
379
+ status,
380
+ STATUS_LABELS[status],
381
+ SOURCE_LABELS[source],
382
+ described.label,
383
+ teamModel ?? "",
384
+ hostModel ?? "",
385
+ ]
386
+ .join(" ")
387
+ .toLowerCase()
388
+
389
+ return {
390
+ id: input.id,
391
+ name,
392
+ mode,
393
+ known: input.known,
394
+ ...(description === undefined ? {} : { description }),
395
+ ...(teamModel === undefined ? {} : { teamModel }),
396
+ ...(hostModel === undefined ? {} : { hostModel }),
397
+ ...(effectiveModel === undefined ? {} : { effectiveModel }),
398
+ modelLabel: described.label,
399
+ ...(described.refLabel === undefined ? {} : { modelRefLabel: described.refLabel }),
400
+ variantLabel: described.variantLabel,
401
+ status,
402
+ statusLabel: STATUS_LABELS[status],
403
+ source,
404
+ sourceLabel: SOURCE_LABELS[source],
405
+ canConfigure: input.known && mode !== "primary",
406
+ canRestore: teamModel !== undefined,
407
+ prompt,
408
+ permissions: summarizePermissions(input.permissions),
409
+ searchText,
410
+ }
411
+ }
412
+
413
+ export function buildDashboardGroups(
414
+ inputs: readonly DashboardAgentInput[],
415
+ overrides: Readonly<Record<string, string>>,
416
+ models: readonly ModelInfo[],
417
+ providers: readonly ProviderInfo[],
418
+ ): DashboardGroup[] {
419
+ const known: DashboardAgentInput[] = []
420
+ const knownIDs = new Set<string>()
421
+ for (const agent of inputs) {
422
+ if (agent.hidden) continue
423
+ if (agent.mode === "primary" && agent.id !== "orchestrator") continue
424
+ known.push(agent)
425
+ knownIDs.add(agent.id)
426
+ }
427
+
428
+ const primary = known
429
+ .filter((agent) => agent.mode === "primary")
430
+ .map((agent) => buildDashboardAgent(agent, overrides, models, providers))
431
+ .toSorted((left, right) => left.id.localeCompare(right.id))
432
+ const subagents = known
433
+ .filter((agent) => agent.mode !== "primary")
434
+ .map((agent) => buildDashboardAgent(agent, overrides, models, providers))
435
+ .toSorted(
436
+ (left, right) =>
437
+ preferredRank(left.id) - preferredRank(right.id) || left.id.localeCompare(right.id),
438
+ )
439
+ const unavailable = Object.keys(overrides)
440
+ .filter((id) => !knownIDs.has(id))
441
+ .toSorted()
442
+ .map((id) =>
443
+ buildDashboardAgent(
444
+ { id, name: id, mode: "subagent", known: false },
445
+ overrides,
446
+ models,
447
+ providers,
448
+ ),
449
+ )
450
+
451
+ return [
452
+ ...(primary.length === 0 ? [] : [{ key: "primary" as const, title: "PRIMARY", agents: primary }]),
453
+ ...(subagents.length === 0
454
+ ? []
455
+ : [{ key: "subagents" as const, title: `SUBAGENTS · ${subagents.length}`, agents: subagents }]),
456
+ ...(unavailable.length === 0
457
+ ? []
458
+ : [
459
+ {
460
+ key: "unavailable" as const,
461
+ title: `已保存但不在团队视图 · ${unavailable.length}`,
462
+ agents: unavailable,
463
+ },
464
+ ]),
465
+ ]
466
+ }
467
+
468
+ export function filterDashboardGroups(
469
+ groups: readonly DashboardGroup[],
470
+ query: string,
471
+ ): DashboardGroup[] {
472
+ const tokens = query.trim().toLowerCase().split(/\s+/).filter(Boolean)
473
+ if (tokens.length === 0) return [...groups]
474
+ return groups.flatMap((group) => {
475
+ const agents = group.agents.filter((agent) =>
476
+ tokens.every((token) => agent.searchText.includes(token)),
477
+ )
478
+ if (agents.length === 0) return []
479
+ return [
480
+ {
481
+ ...group,
482
+ title:
483
+ group.key === "subagents"
484
+ ? `SUBAGENTS · ${agents.length}`
485
+ : group.key === "unavailable"
486
+ ? `已保存但不在团队视图 · ${agents.length}`
487
+ : group.title,
488
+ agents,
489
+ },
490
+ ]
491
+ })
492
+ }
493
+
494
+ export function layoutFor(width: number, height: number): DashboardLayout {
495
+ return {
496
+ split: width >= 90,
497
+ compact: height < 20 || width < 100,
498
+ minimal: width < 50,
499
+ dialogHeight: Math.max(6, Math.min(30, height - 4)),
500
+ listWidth: width >= 112 ? 32 : 28,
501
+ }
502
502
  }