@dsh-teamwork/dsh-teamwork 0.6.1 → 0.8.0

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.
Files changed (65) hide show
  1. package/README.md +109 -2
  2. package/icon.svg +4 -0
  3. package/lib/aes-gcm.js +22 -0
  4. package/lib/aes-gcm.js.map +1 -0
  5. package/lib/assistant-tools.js +421 -0
  6. package/lib/assistant-tools.js.map +1 -0
  7. package/lib/bridge.js +127 -8
  8. package/lib/bridge.js.map +1 -1
  9. package/lib/cli.js +1 -1
  10. package/lib/cli.js.map +1 -1
  11. package/lib/client.js +206 -18
  12. package/lib/client.js.map +1 -1
  13. package/lib/config-sync.js +2 -1
  14. package/lib/config-sync.js.map +1 -1
  15. package/lib/index.js +187 -73
  16. package/lib/index.js.map +1 -1
  17. package/lib/local-share.js +87 -0
  18. package/lib/local-share.js.map +1 -0
  19. package/lib/panel.js +9 -0
  20. package/lib/panel.js.map +1 -1
  21. package/lib/phone-security.js +283 -0
  22. package/lib/phone-security.js.map +1 -0
  23. package/lib/phone-session.js +20 -0
  24. package/lib/phone-session.js.map +1 -0
  25. package/lib/phone-uploads.js +136 -0
  26. package/lib/phone-uploads.js.map +1 -0
  27. package/lib/platform-models.js +2 -2
  28. package/lib/platform-models.js.map +1 -1
  29. package/lib/preset-context.js +1 -1
  30. package/lib/preset-context.js.map +1 -1
  31. package/lib/relay.js +9 -4
  32. package/lib/relay.js.map +1 -1
  33. package/lib/secure-channel.js +398 -0
  34. package/lib/secure-channel.js.map +1 -0
  35. package/lib/types/aes-gcm.d.ts +3 -0
  36. package/lib/types/aes-gcm.d.ts.map +1 -0
  37. package/lib/types/assistant-tools.d.ts +7 -0
  38. package/lib/types/assistant-tools.d.ts.map +1 -0
  39. package/lib/types/bridge.d.ts +5 -0
  40. package/lib/types/bridge.d.ts.map +1 -1
  41. package/lib/types/client.d.ts +432 -195
  42. package/lib/types/client.d.ts.map +1 -1
  43. package/lib/types/config-sync.d.ts +1 -1
  44. package/lib/types/config-sync.d.ts.map +1 -1
  45. package/lib/types/index.d.ts.map +1 -1
  46. package/lib/types/local-share.d.ts +11 -0
  47. package/lib/types/local-share.d.ts.map +1 -0
  48. package/lib/types/panel.d.ts +39 -5
  49. package/lib/types/panel.d.ts.map +1 -1
  50. package/lib/types/phone-security.d.ts +59 -0
  51. package/lib/types/phone-security.d.ts.map +1 -0
  52. package/lib/types/phone-session.d.ts +52 -0
  53. package/lib/types/phone-session.d.ts.map +1 -0
  54. package/lib/types/phone-uploads.d.ts +75 -0
  55. package/lib/types/phone-uploads.d.ts.map +1 -0
  56. package/lib/types/platform-models.d.ts.map +1 -1
  57. package/lib/types/preset-context.d.ts +2 -0
  58. package/lib/types/preset-context.d.ts.map +1 -1
  59. package/lib/types/preset-session.d.ts +1 -1
  60. package/lib/types/relay.d.ts +10 -2
  61. package/lib/types/relay.d.ts.map +1 -1
  62. package/lib/types/secure-channel.d.ts +79 -0
  63. package/lib/types/secure-channel.d.ts.map +1 -0
  64. package/lib/web/client.js +850 -269
  65. package/package.json +11 -2
package/lib/index.js CHANGED
@@ -1,13 +1,17 @@
1
+ import { PhoneKeys, PhoneSecurity } from './phone-security.js';
1
2
  import z from '@deepseek-ai/schemastery';
2
- import { ServerChoice, serverAddress, TeamOverlay, TeamworkClient } from './client.js';
3
+ import { allConfigs, findConfig, ServerChoice, serverAddress, teamOf, TeamOverlay, TeamworkClient } from './client.js';
3
4
  import { ConfigSync } from './config-sync.js';
4
5
  import { PresetStamps, presetStampPath, sameRevision, toolReport, assertBlank } from './preset-session.js';
5
- import { modelData } from './client.js';
6
+ import { modelData, inheritsModel, pinnedPlugin } from './client.js';
6
7
  import { taskProjection, TaskActions, recoveryHint, retryInstruction, outcomeText } from './task-session.js';
7
8
  import { pluginState, stateText } from './plugin-status.js';
8
9
  import { panelRoutes } from './panel.js';
10
+ import { registerAssistantTools } from './assistant-tools.js';
9
11
  import { platformAdapter, platformProvider } from './platform-models.js';
10
12
  import { Bridge } from './bridge.js';
13
+ import { PhoneSessionError, phonePresets } from './phone-session.js';
14
+ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
11
15
  import { listenForCode } from './login-callback.js';
12
16
  import { offerSchema, pairingSchema, RelayError, RelayLink, relayClientIdPath } from './relay.js';
13
17
  export const name = 'dsh-teamwork';
@@ -26,15 +30,15 @@ export async function apply(ctx, config) {
26
30
  ctx.effect(() => () => taskState.dispose());
27
31
  const stamps = new PresetStamps(presetStampPath(config.cachePath));
28
32
  await stamps.load();
29
- const overlay = new TeamOverlay(async (id, item) => ctx.agentPresets.register({
30
- id, name: `[团队] ${item.name}`,
33
+ const overlay = new TeamOverlay(async (id, item, team) => ctx.agentPresets.register({
34
+ id, name: `[${team.teamName}] ${item.name}`,
31
35
  ...(item.kind === 'preset' ? { description: item.data.description ?? '' } : {}),
32
36
  plugins: item.kind === 'preset' ? [{ name: 'cordis:group', group: true, isolate: { teamworkPreset: true }, config: [{ name: new URL('./preset-context.js', import.meta.url).href, config: {
33
- description: item.data.description ?? '', instructions: item.data.instructions ?? '', outputDescription: item.data.outputDescription ?? '',
37
+ inheritModel: item.data.inheritModel, builtin: item.builtin, description: item.data.description ?? '', instructions: item.data.instructions ?? '', outputDescription: item.data.outputDescription ?? '',
34
38
  pluginDependencies: item.data.pluginDependencies ?? [],
35
39
  requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [], systemPrompt: item.data.systemPrompt,
36
40
  ...(item.data.modelConfigId ? { modelConfigId: item.data.modelConfigId } : {}),
37
- teamId: client.current().teamId, id: item.id, name: item.name, version: item.version,
41
+ teamId: team.teamId, id: item.id, name: item.name, version: item.version,
38
42
  } }] }] : [],
39
43
  }));
40
44
  const restartRequired = new Set();
@@ -43,51 +47,61 @@ export async function apply(ctx, config) {
43
47
  const tools = ctx.get('tools');
44
48
  return toolReport(preset, name => !tools ? 'unknown' : !tools.get(name, agent) ? 'missing' : tools.executable(name, agent) ? 'available' : 'conditional');
45
49
  };
46
- const plugins = async (preset) => {
47
- const snapshot = client.current();
50
+ const readPluginInventory = async () => {
48
51
  const manager = ctx.get('pluginManager');
49
52
  const bundles = manager ? await manager.listBundles() : [];
50
53
  const entries = manager ? await manager.listPlugins() : [];
51
- const dependencies = preset ? preset.pluginDependencies ?? [] : (snapshot?.configs ?? []).filter(c => c.kind === 'plugin').map(c => ({ pluginConfigId: c.id, version: c.data.version }));
54
+ return { manager, bundles, entries };
55
+ };
56
+ const plugins = async (preset, readInventory = readPluginInventory) => {
57
+ const snapshot = client.current();
58
+ const dependencies = preset ? preset.pluginDependencies ?? [] : allConfigs(snapshot).filter(c => c.kind === 'plugin').map(c => ({ pluginConfigId: c.id, version: c.data.version }));
59
+ if (!dependencies.length)
60
+ return [];
61
+ const { manager, bundles, entries } = await readInventory();
52
62
  return dependencies.map(dependency => {
53
- const item = snapshot?.configs.find(c => c.id === dependency.pluginConfigId && c.kind === 'plugin');
54
- const valid = (!preset || preset.teamId === snapshot?.teamId) && item?.kind === 'plugin' && item.data.version === dependency.version;
63
+ const item = pinnedPlugin(snapshot, dependency.pluginConfigId, dependency.version);
64
+ // A preset's pin counts only in the preset's own team.
65
+ const valid = (!preset || teamOf(snapshot, dependency.pluginConfigId)?.teamId === preset.teamId) && item?.kind === 'plugin' && item.data.version === dependency.version;
55
66
  const bundle = item?.kind === 'plugin' ? bundles.find(b => b.name === item.data.package) : undefined;
56
67
  const state = !valid ? 'catalog-changed' : !manager ? 'unknown' : pluginState(dependency.version, bundle, entries, restartRequired.has(`${item.data.package}@${dependency.version}`));
57
68
  return { id: dependency.pluginConfigId, name: item?.name ?? dependency.pluginConfigId, package: item?.kind === 'plugin' ? item.data.package : undefined,
58
69
  version: dependency.version, description: item?.kind === 'plugin' ? item.data.description : '', localVersion: bundle?.version, state,
59
- text: `${item?.name ?? dependency.pluginConfigId} @${dependency.version}(本地 ${bundle?.version ?? '无'}):${stateText[state]}${state === 'missing' ? `;/teamwork install ${dependency.pluginConfigId}` : ''}` };
70
+ text: `${item?.name ?? dependency.pluginConfigId} @${dependency.version}(本地 ${bundle?.version ?? '无'}):${stateText[state]}${state === 'missing' ? `;/teamwork install ${dependency.pluginConfigId}@${dependency.version}` : ''}` };
60
71
  });
61
72
  };
62
73
  const checkPlugins = async (preset) => {
63
74
  const missing = (await plugins(preset)).filter(p => p.state !== 'ready');
64
75
  if (missing.length)
65
- throw new Error(missing.map(p => p.text).join('\n'));
76
+ throw new PhoneSessionError('missing_plugins', missing.map(p => p.text).join('\n'));
66
77
  };
67
78
  // A stamp that fails to save is retaken on the session's next request; the session itself is unaffected.
68
79
  const keep = (write) => { write.catch(error => ctx.logger.warn('团队预设版本记录保存失败:%s', error.message)); };
69
80
  const stamp = (agent, preset) => keep(stamps.set(String(agent.id), preset));
70
81
  const detail = (agent, preset, preview = false) => {
71
82
  const snapshot = client.current();
72
- const latest = snapshot?.teamId === preset.teamId ? snapshot.configs.find(c => c.id === preset.id) : undefined;
83
+ const team = teamOf(snapshot, preset.id);
84
+ const latest = team?.teamId === preset.teamId ? findConfig(snapshot, preset.id) : undefined;
73
85
  const tools = requirements(agent, preset);
74
86
  const labels = { available: '已注册(执行仍受宿主权限约束)', conditional: '条件可用,执行时检查', missing: '缺失', unknown: '无法检查' };
75
87
  const saved = preview ? null : stamps.get(String(agent.id));
76
88
  const revision = latest ? latest.version === preset.version ? '已是最新版本' : `可用版本 v${latest.version};开始对话后请新建会话使用更新` : '此预设已不在当前团队配置中';
77
- return [`${preset.name} · v${preset.version}`, `来源:团队 ${preset.teamId} / 预设 ${preset.id}`, revision,
78
- latest && snapshot && !modelData(snapshot, latest) ? '关联模型已不可用,请联系管理员重新关联团队模型。' : '',
89
+ return [`${preset.name} · v${preset.version}`, `来源:团队 ${team?.teamName ?? preset.teamId} / 预设 ${preset.id}`, revision,
90
+ latest && snapshot && !inheritsModel(latest) && !modelData(snapshot, latest) ? '关联模型已不可用,请联系管理员重新关联团队模型。' : '',
79
91
  saved && !sameRevision(saved, preset) ? `恢复前记录为 v${saved.version},与当前加载版本不同;已阻止继续推理,请新建会话。` : '',
80
92
  `当前会话模型:${agent.model.current()?.provider ?? "未选择"}/${agent.model.current()?.model ?? "未选择"}`,
81
- `预设关联模型:${preset.modelConfigId ?? '旧版独立模型'} · 经 platform;服务端模型策略始终采用当前值`,
93
+ `预设关联模型:${preset.inheritModel ? '沿用当前会话模型' : preset.modelConfigId ?? '旧版独立模型'} · 经 platform;服务端模型策略始终采用当前值`,
82
94
  `简介:${preset.description || '未填写'}`, `使用说明:${preset.instructions || '未填写'}`, `输出要求(说明):${preset.outputDescription || '未填写'}`,
83
95
  '提示词来源:本地原有提示词 + 以下团队字面文本', preset.systemPrompt || '(无团队追加提示词)',
84
- ...tools.map(t => { const declared = snapshot?.configs.filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(t.name)) ?? []; return `${t.required ? '必需' : '可选'}工具 ${t.name}:${labels[t.state]}${declared.length ? ';团队声明来源:' + declared.map(c => `${c.name}(/teamwork install ${c.id})`).join(', ') : ''}`; }),
96
+ ...tools.map(t => { const declared = (team?.configs ?? []).filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(t.name)); return `${t.required ? '必需' : '可选'}工具 ${t.name}:${labels[t.state]}${declared.length ? ';团队声明来源:' + declared.map(c => `${c.name}(/teamwork install ${c.id})`).join(', ') : ''}`; }),
85
97
  '缺失工具请通过本地插件管理器安装或启用;预设不会自动安装插件或授予权限。',
86
98
  ].filter(Boolean).join('\n');
87
99
  };
88
100
  ctx.on('agent/request', async ({ agent }, next) => {
89
101
  const preset = activePreset(agent);
90
102
  if (preset) {
103
+ if (preset.inheritModel && !agent.model.current())
104
+ throw new Error('请先选择可用的本地模型,或请管理员为团队助理关联团队模型。');
91
105
  if (preset.pluginDependencies?.length)
92
106
  await checkPlugins(preset);
93
107
  const saved = stamps.get(String(agent.id));
@@ -101,36 +115,38 @@ export async function apply(ctx, config) {
101
115
  }
102
116
  return next();
103
117
  });
118
+ ctx.inject(['tools'], child => registerAssistantTools(child, client, activePreset, () => configSync.sync(), async (id, version) => { const item = pinnedPlugin(client.current(), id, version); if (!item)
119
+ throw Error('Plugin version is unavailable'); return installPlugin(item); }));
104
120
  const configSync = new ConfigSync(client, overlay, config.autoSync ?? true, config.syncIntervalMs ?? 60000);
105
121
  const readiness = async (agent, fresh = false) => {
106
122
  const selection = agent.model.current();
107
123
  if (!selection)
108
- throw new Error('尚未选择模型,请先选择本地模型或 /teamwork use <id>。');
124
+ throw new PhoneSessionError('model_unavailable', '尚未选择模型,请先选择本地模型或 /teamwork use <id>。');
109
125
  if (selection.provider === platformProvider) {
110
126
  if (!client.authenticated())
111
- throw new Error('团队模型未登录或会话已失效,请 /teamwork login。');
127
+ throw new PhoneSessionError('not_authenticated', '团队模型未登录或会话已失效,请 /teamwork login。');
112
128
  if (fresh) {
113
129
  try {
114
130
  await configSync.sync();
115
131
  }
116
132
  catch {
117
- throw new Error('无法验证当前团队权限,请检查连接和 /teamwork status,必要时重新登录。');
133
+ throw new PhoneSessionError('unavailable', '无法验证当前团队权限,请检查连接和 /teamwork status,必要时重新登录。');
118
134
  }
119
135
  }
120
- const snapshot = client.current(), item = snapshot?.configs.find(c => c.id === selection.model);
136
+ const snapshot = client.current(), item = findConfig(snapshot, selection.model);
121
137
  if (!snapshot || !item || !modelData(snapshot, item))
122
- throw new Error('当前团队模型已删除或引用失效,请选择可用模型;预设变更请新建会话。');
138
+ throw new PhoneSessionError('model_unavailable', '当前团队模型已删除或引用失效,请选择可用模型;预设变更请新建会话。');
123
139
  }
124
140
  const preset = activePreset(agent);
125
141
  if (preset) {
126
142
  const saved = stamps.get(String(agent.id));
127
143
  if (saved && !sameRevision(saved, preset))
128
- throw new Error('恢复会话的预设版本不一致,请 /teamwork new <预设ID>。');
144
+ throw new PhoneSessionError('preset_changed', '恢复会话的预设版本不一致,请 /teamwork new <预设ID>。');
129
145
  if (preset.pluginDependencies?.length)
130
146
  await checkPlugins(preset);
131
147
  const missing = requirements(agent, preset).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
132
148
  if (missing.length)
133
- throw new Error(`缺少必需工具:${missing.map(t => t.name).join(', ')};运行 /teamwork info 查看安装指引。`);
149
+ throw new PhoneSessionError('missing_tools', `缺少必需工具:${missing.map(t => t.name).join(', ')};运行 /teamwork info 查看安装指引。`);
134
150
  }
135
151
  };
136
152
  const actions = new TaskActions(agent => readiness(agent, true), agent => {
@@ -146,8 +162,78 @@ export async function apply(ctx, config) {
146
162
  let launchUrl;
147
163
  const bridge = new Bridge({
148
164
  launchUrl: () => launchUrl?.(),
149
- send: (frame) => relay.send(frame),
165
+ send: (frame) => security.send(frame),
150
166
  log: (message, error) => ctx.logger.warn('%s:%s', message, error?.message ?? ''),
167
+ session: {
168
+ async configuration(sessionId) {
169
+ const agent = sessionAgent(sessionId);
170
+ if (sessionId && !agent)
171
+ throw new PhoneSessionError('busy');
172
+ const state = await panel.state(sessionId);
173
+ const roster = await ctx.agentPresets.remoteExportList();
174
+ return { presets: phonePresets(state, [...roster.presets]), current: agent ? {
175
+ sessionId: String(agent.id), cwd: agent.session.header.cwd,
176
+ agentPreset: ctx.agentPresets.presetForSession(agent.session), model: agent.model.current() ?? null,
177
+ started: state.session?.started ?? false, running: agent.status !== 'idle',
178
+ } : null };
179
+ },
180
+ async selectModel(request) {
181
+ const agent = sessionAgent(request.sessionId);
182
+ if (!agent)
183
+ throw new PhoneSessionError('not_found');
184
+ if (agent.status !== 'idle' || agent.inbox.nextTurn.length || agent.inbox.nextStep.length)
185
+ throw new PhoneSessionError('busy');
186
+ const selection = { provider: request.provider, model: request.model, ...(request.reasoningEffort ? { reasoningEffort: ReasoningEffortId(request.reasoningEffort) } : {}) };
187
+ try {
188
+ const model = (await ctx.llm.listModels(selection.provider)).find(model => model.id === selection.model);
189
+ if (!model)
190
+ throw new Error('Unavailable model');
191
+ await ctx.llm.resolveCallConfig(selection);
192
+ if (agent.status !== 'idle' || agent.inbox.nextTurn.length || agent.inbox.nextStep.length)
193
+ throw new PhoneSessionError('busy');
194
+ agent.model.select(selection);
195
+ return { selected: agent.model.current() };
196
+ }
197
+ catch (error) {
198
+ if (error instanceof PhoneSessionError)
199
+ throw error;
200
+ throw new PhoneSessionError('model_unavailable');
201
+ }
202
+ },
203
+ accepted(sessionId, requestId) {
204
+ const agent = sessionAgent(sessionId);
205
+ if (!agent)
206
+ return false;
207
+ const matches = (source) => typeof source === 'object' && source !== null && 'kind' in source && source.kind === 'user' && 'rpcId' in source && source.rpcId === requestId;
208
+ return [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(message => matches(message.source)) || agent.session.snapshotEvents().some(event => event.type === 'user/message' && matches(event.data.source));
209
+ },
210
+ async check(sessionId) {
211
+ const agent = sessionAgent(sessionId);
212
+ if (!agent)
213
+ throw new PhoneSessionError('not_found');
214
+ if (agent.status !== 'idle' || agent.inbox.nextTurn.length || agent.inbox.nextStep.length)
215
+ throw new PhoneSessionError('busy');
216
+ await readiness(agent, true);
217
+ },
218
+ },
219
+ });
220
+ let keyScope;
221
+ const security = new PhoneSecurity({
222
+ keys: new PhoneKeys(config.cachePath.replace(/\.json$/, '') + '.phone-keys.json'),
223
+ scope: () => {
224
+ const revision = client.sessionRevision();
225
+ if (!keyScope || keyScope.revision !== revision) {
226
+ const value = client.profile().then(profile => `${client.endpoint}|${profile.id}`);
227
+ keyScope = { revision, value };
228
+ void value.catch(() => { if (keyScope?.value === value)
229
+ keyScope = undefined; });
230
+ }
231
+ return keyScope.value;
232
+ },
233
+ send: frame => relay.send(frame), forward: frame => bridge.handle(frame),
234
+ confirm: async (id) => { await relay.request({ t: 'decide', pairingId: id, accept: true }); },
235
+ changed: () => { },
236
+ error: error => ctx.logger.warn('phone security: %s', error.message),
151
237
  });
152
238
  const relay = new RelayLink({
153
239
  endpoint: () => client.endpoint,
@@ -159,11 +245,12 @@ export async function apply(ctx, config) {
159
245
  void readPhones();
160
246
  else {
161
247
  phones = [];
248
+ security.reset();
162
249
  bridge.dropAll();
163
250
  }
164
251
  },
165
252
  onEvent: () => void readPhones(),
166
- onForward: (frame) => bridge.handle(frame),
253
+ onForward: (frame) => void security.handle(frame),
167
254
  });
168
255
  const readPhones = async () => {
169
256
  try {
@@ -184,7 +271,7 @@ export async function apply(ctx, config) {
184
271
  const reportWaiting = (kind) => function (request, next) {
185
272
  const agent = request?.agent ?? this;
186
273
  if (agent?.id !== undefined)
187
- relay.send({ t: 'waiting', sessionId: String(agent.id), kind });
274
+ relay.send({ t: 'waiting' });
188
275
  return next();
189
276
  };
190
277
  const listen = ctx.on.bind(ctx);
@@ -231,7 +318,8 @@ export async function apply(ctx, config) {
231
318
  return;
232
319
  const active = activePreset(agent);
233
320
  if (active) {
234
- agent.model.select({ provider: platformProvider, model: active.id });
321
+ if (!active.inheritModel)
322
+ agent.model.select({ provider: platformProvider, model: active.id });
235
323
  if (!sameRevision(stamps.get(String(agent.id)), active))
236
324
  stamp(agent, active);
237
325
  }
@@ -241,11 +329,11 @@ export async function apply(ctx, config) {
241
329
  ctx.on('agent/created', ({ agent, source }) => {
242
330
  const snapshot = client.current();
243
331
  const selected = ctx.agentPresets.presetForSession(agent.session);
244
- const item = snapshot?.configs.find(c => `team:${snapshot.teamId}:${c.id}` === selected);
332
+ const item = snapshot?.teams.flatMap(team => team.configs.filter(c => `team:${team.teamId}:${c.id}` === selected))[0];
245
333
  const preset = activePreset(agent);
246
334
  if (preset && !stamps.get(String(agent.id)))
247
335
  stamp(agent, preset);
248
- if (source !== 'resume' && item && item.kind !== 'plugin')
336
+ if (source !== 'resume' && item && item.kind !== 'plugin' && !inheritsModel(item))
249
337
  agent.model.select({ provider: platformProvider, model: item.id });
250
338
  return undefined;
251
339
  });
@@ -253,37 +341,43 @@ export async function apply(ctx, config) {
253
341
  /** `/teamwork use` and the panel's "use": a team model, or a preset before the session's first turn. */
254
342
  const useConfig = async (agent, id) => {
255
343
  const snapshot = client.current();
256
- const item = snapshot?.configs.find(c => c.id === id);
257
- if (!item || item.kind === 'plugin')
344
+ const item = findConfig(snapshot, id), team = teamOf(snapshot, id);
345
+ if (!item || !team || item.kind === 'plugin')
258
346
  throw new Error('请选择团队模型或预设 ID');
259
- if (!modelData(snapshot, item))
347
+ if (!inheritsModel(item) && !modelData(snapshot, item))
260
348
  throw new Error('预设引用的团队模型已不可用,请联系管理员。');
261
349
  if (item.kind === 'preset') {
262
350
  assertBlank(ctx.agents.turnBoundaryOf(agent.session));
263
351
  if (item.data.pluginDependencies?.length)
264
- await checkPlugins({ teamId: snapshot.teamId, pluginDependencies: item.data.pluginDependencies });
352
+ await checkPlugins({ teamId: team.teamId, pluginDependencies: item.data.pluginDependencies });
265
353
  const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
266
354
  const unavailable = requirements(agent, candidate).filter(t => t.required && ['missing', 'unknown'].includes(t.state));
267
355
  if (unavailable.length)
268
356
  throw new Error(`缺少必需工具:${unavailable.map(t => t.name).join(', ')}。请先通过本地插件管理器安装或启用。`);
269
- await ctx.agentPresets.select(agent, `team:${snapshot.teamId}:${item.id}`);
357
+ await ctx.agentPresets.select(agent, `team:${team.teamId}:${item.id}`);
270
358
  const active = activePreset(agent);
271
359
  if (active && !sameRevision(stamps.get(String(agent.id)), active))
272
360
  stamp(agent, active);
273
361
  }
274
- agent.model.select({ provider: platformProvider, model: item.id });
362
+ if (!inheritsModel(item))
363
+ agent.model.select({ provider: platformProvider, model: item.id });
275
364
  return { preset: item.kind === 'preset', text: `本会话已选择 ${item.name}。本地默认配置未改变。` };
276
365
  };
277
366
  /** Installs a pinned plugin disabled, enables it only when it adds configuration and overrides nothing. Callers confirm first. */
278
367
  const installPlugin = async (item, agent) => {
279
368
  const spec = `${item.data.package}@${item.data.version}`;
369
+ const epoch = client.sessionRevision(), signature = JSON.stringify(item);
280
370
  const manager = ctx.get('pluginManager');
281
371
  if (!manager)
282
372
  throw new Error('宿主没有插件管理服务');
283
373
  const existing = (await manager.listBundles()).find(bundle => bundle.name === item.data.package);
284
374
  if (existing && (existing.installed || existing.enabled || existing.availability === 'installation'))
285
375
  throw new Error('插件已存在,请通过本地插件管理器管理,团队同步不会覆盖它');
286
- const installed = await manager.installBundle(spec, { saveExact: true, enabled: false });
376
+ const teamId = teamOf(client.current(), item.id)?.teamId;
377
+ const target = item.data.artifactId ? await client.downloadArtifact(teamId, item.data.artifactId, item.data.sha256) : spec;
378
+ if (epoch !== client.sessionRevision() || JSON.stringify(pinnedPlugin(client.current(), item.id, item.data.version)) !== signature)
379
+ throw new Error('安装期间账号或插件配置已变化,请重新确认');
380
+ const installed = await manager.installBundle(target, { saveExact: true, enabled: false });
287
381
  if (installed.error || ['failed', 'cancelled', 'overridden'].includes(installed.application))
288
382
  throw new Error(`安装未完成(${installed.error?.code ?? installed.application}),请在本地插件管理器查看诊断后重新检查。`);
289
383
  const bundle = (await manager.listBundles()).find(bundle => bundle.name === item.data.package);
@@ -303,41 +397,52 @@ export async function apply(ctx, config) {
303
397
  };
304
398
  const sessionAgent = (sessionId) => sessionId ? ctx.agents.get(sessionId) : undefined;
305
399
  const panel = {
400
+ quota: teamId => client.quota(teamId),
401
+ profile: () => client.profile(),
402
+ updateProfile: (input) => client.updateProfile(input),
306
403
  async state(sessionId) {
307
404
  const status = configSync.status(), snapshot = client.current(), agent = sessionAgent(sessionId);
405
+ // Inventory scans read the whole host. Share one within this response, never across requests.
406
+ let inventory;
407
+ const readInventory = () => inventory ??= readPluginInventory();
308
408
  const presets = [];
309
- for (const item of snapshot?.configs ?? []) {
310
- if (item.kind !== 'preset')
311
- continue;
312
- const linked = item.data.modelConfigId ? snapshot.configs.find(c => c.id === item.data.modelConfigId) : undefined;
313
- const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
314
- presets.push({
315
- id: item.id, name: item.name, version: item.version, description: item.data.description ?? '',
316
- model: item.data.modelConfigId ? linked?.name ?? item.data.modelConfigId : `${item.data.provider}/${item.data.model}`,
317
- modelAvailable: !!modelData(snapshot, item),
318
- tools: agent ? requirements(agent, candidate) : toolReport(candidate, () => 'unknown'),
319
- plugins: item.data.pluginDependencies?.length ? await plugins({ teamId: snapshot.teamId, pluginDependencies: item.data.pluginDependencies }) : [],
320
- });
321
- }
409
+ for (const team of snapshot?.teams ?? [])
410
+ for (const item of team.configs) {
411
+ if (item.kind !== 'preset')
412
+ continue;
413
+ const linked = item.data.modelConfigId ? team.configs.find(c => c.id === item.data.modelConfigId) : undefined;
414
+ const candidate = { requiredTools: item.data.requiredTools ?? [], optionalTools: item.data.optionalTools ?? [] };
415
+ presets.push({
416
+ id: item.id, teamId: team.teamId, teamName: team.teamName, name: item.name, version: item.version, description: item.data.description ?? '',
417
+ model: item.data.inheritModel ? '本地/当前会话模型' : item.data.modelConfigId ? linked?.name ?? item.data.modelConfigId : `${item.data.provider}/${item.data.model}`,
418
+ modelAvailable: inheritsModel(item) || !!modelData(snapshot, item),
419
+ tools: agent ? requirements(agent, candidate) : toolReport(candidate, () => 'unknown'),
420
+ plugins: item.data.pluginDependencies?.length ? await plugins({ teamId: team.teamId, pluginDependencies: item.data.pluginDependencies }, readInventory) : [],
421
+ });
422
+ }
322
423
  const selection = agent?.model.current(), active = agent && activePreset(agent), boundary = agent && ctx.agents.turnBoundaryOf(agent.session);
323
424
  return {
425
+ authRevision: client.sessionRevision(),
324
426
  authenticated: status.authenticated,
325
- team: snapshot ? { id: snapshot.teamId, name: snapshot.teamName, role: snapshot.role } : null,
326
- consoleUrl: `${client.endpoint}/team`,
427
+ teams: (snapshot?.teams ?? []).map(team => ({ id: team.teamId, name: team.teamName, role: team.role, consoleUrl: `${client.endpoint}/teams/${team.teamId}` })),
327
428
  server: client.endpoint,
328
429
  defaultServer: serverAddress(config.apiEndpoint),
329
430
  sync: { auto: status.autoSync, running: status.syncing, lastSuccess: status.lastSuccess, lastError: status.lastError },
330
431
  relay: relay.status,
331
- phones,
432
+ phones: await Promise.all(phones.map(async (phone) => ({ ...phone, ...await security.details(phone.id) }))),
332
433
  session: agent ? {
333
434
  id: String(agent.id),
334
435
  model: selection ? { provider: selection.provider, model: selection.model, team: selection.provider === platformProvider } : null,
335
436
  preset: active ? { id: active.id, name: active.name, version: active.version } : null,
336
437
  started: boundary.openTurnStartSeq !== null || boundary.lastTurn > 0,
337
438
  } : null,
338
- presets,
339
- models: (snapshot?.configs ?? []).flatMap(c => c.kind === 'model' ? [{ id: c.id, name: c.name, version: c.version, upstream: `${c.data.provider}/${c.data.model}` }] : []),
340
- plugins: await plugins(),
439
+ presets: presets.sort((a, b) => Number(findConfig(snapshot, b.id)?.builtin === 'team-assistant') - Number(findConfig(snapshot, a.id)?.builtin === 'team-assistant')),
440
+ models: (snapshot?.teams ?? []).flatMap(team => team.configs.flatMap(c => c.kind === 'model'
441
+ ? [{ id: c.id, teamId: team.teamId, teamName: team.teamName, name: c.name, version: c.version, upstream: `${c.data.provider}/${c.data.model}` }] : [])),
442
+ plugins: (await plugins(undefined, readInventory)).map(plugin => {
443
+ const team = teamOf(snapshot, plugin.id);
444
+ return { ...plugin, teamId: team?.teamId, teamName: team?.teamName };
445
+ }),
341
446
  };
342
447
  },
343
448
  login: beginLogin,
@@ -358,14 +463,22 @@ export async function apply(ctx, config) {
358
463
  },
359
464
  async pairPhone() {
360
465
  const offer = offerSchema.parse(await relay.request({ t: 'offer' }).catch(phoneError));
361
- const link = `dshteamwork://pair?${new URLSearchParams({ server: client.endpoint, code: offer.code })}`;
466
+ security.offerCode(offer.expiresAt);
467
+ const key = await security.publicKey();
468
+ const link = `dshteamwork://pair?${new URLSearchParams({ server: client.endpoint, code: offer.code, key })}`;
362
469
  return { ...offer, link };
363
470
  },
364
471
  async decidePhone(id, accept) {
365
- await relay.request({ t: 'decide', pairingId: id, accept }).catch(phoneError);
472
+ if (accept)
473
+ await security.approve(id);
474
+ else {
475
+ await security.revoke(id);
476
+ await relay.request({ t: 'decide', pairingId: id, accept: false }).catch(phoneError);
477
+ }
366
478
  await readPhones();
367
479
  },
368
480
  async revokePhone(id) {
481
+ await security.revoke(id);
369
482
  await relay.request({ t: 'revoke', pairingId: id }).catch(phoneError);
370
483
  await readPhones();
371
484
  },
@@ -376,7 +489,7 @@ export async function apply(ctx, config) {
376
489
  return (await useConfig(agent, id)).text;
377
490
  },
378
491
  async install(id, version) {
379
- const item = client.current()?.configs.find(c => c.id === id);
492
+ const item = pinnedPlugin(client.current(), id, version);
380
493
  if (!item || item.kind !== 'plugin')
381
494
  throw new Error('请选择团队插件 ID');
382
495
  // The member confirmed this exact version; a sync since then may have changed the pin.
@@ -403,7 +516,8 @@ export async function apply(ctx, config) {
403
516
  name: 'teamwork', description: '团队登录、配置同步与模型选择',
404
517
  input: { hint: 'login | authorize <code> | sync | status | session [check] | continue <指令> | cancel | retry [confirm] | list | tools | plugins [presetId] | info [id] | new <id> | use <id> | install <id> confirm | logout' },
405
518
  handler: async ({ agent, rawInput }) => {
406
- const [action, id, confirmation] = rawInput.trim().split(/\s+/);
519
+ const [action, requestedId, confirmation] = rawInput.trim().split(/\s+/);
520
+ const [id, pinVersion] = requestedId?.split('@') ?? [];
407
521
  try {
408
522
  if (action === 'session') {
409
523
  let ready = '本地检查通过;继续前会重新验证团队权限。';
@@ -454,24 +568,24 @@ export async function apply(ctx, config) {
454
568
  }
455
569
  if (action === 'status') {
456
570
  const status = configSync.status();
457
- return { kind: 'success', text: [`登录:${status.authenticated ? '已登录' : '未登录(缓存不代表有效登录)'}`, `自动同步:${status.autoSync ? '开启' : '关闭'}`, `团队:${status.teamId ?? '无'} · 配置:${status.configCount}`, `最近成功同步:${status.lastSuccess ?? '本次启动尚未同步'}`, status.syncing ? '正在同步' : '', status.lastError ?? ''].filter(Boolean).join('\n') };
571
+ return { kind: 'success', text: [`登录:${status.authenticated ? '已登录' : '未登录(缓存不代表有效登录)'}`, `自动同步:${status.autoSync ? '开启' : '关闭'}`, `团队:${status.teams.length ? status.teams.join('、') : '无'} · 配置:${status.configCount}`, `最近成功同步:${status.lastSuccess ?? '本次启动尚未同步'}`, status.syncing ? '正在同步' : '', status.lastError ?? ''].filter(Boolean).join('\n') };
458
572
  }
459
573
  const snapshot = client.current();
460
- const item = snapshot?.configs.find(c => c.id === id);
574
+ const item = id ? action === 'install' && pinVersion ? pinnedPlugin(snapshot, id, pinVersion) : findConfig(snapshot, id) : undefined, team = id ? teamOf(snapshot, id) : undefined;
461
575
  if (action === 'tools') {
462
576
  const tools = child.get('tools');
463
577
  if (!tools)
464
578
  throw new Error('宿主未提供工具检查服务');
465
579
  const rows = tools.definitions(agent).map(tool => {
466
- const declared = snapshot?.configs.filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(tool.name)) ?? [];
467
- return `${tool.name} · ${tools.executable(tool.name, agent) ? '已注册,执行仍需权限检查' : '条件可用'} · ${declared.length ? '团队声明来源:' + declared.map(c => c.name).join(', ') : '来源:宿主未提供归属信息'}`;
580
+ const declared = (snapshot?.teams ?? []).flatMap(t => t.configs.filter(c => c.kind === 'plugin' && c.data.providesTools?.includes(tool.name)).map(c => `${c.name}(${t.teamName})`));
581
+ return `${tool.name} · ${tools.executable(tool.name, agent) ? '已注册,执行仍需权限检查' : '条件可用'} · ${declared.length ? '团队声明来源:' + declared.join(', ') : '来源:宿主未提供归属信息'}`;
468
582
  });
469
583
  return { kind: 'success', text: ['当前会话可见工具(声明来源不是已验证的运行时归属):', ...rows, rows.length ? '' : '无可见工具'].filter(Boolean).join('\n') };
470
584
  }
471
585
  if (action === 'plugins') {
472
586
  if (id && item?.kind !== 'preset')
473
587
  throw new Error('请选择团队预设 ID');
474
- const preset = item?.kind === 'preset' ? { teamId: snapshot.teamId, pluginDependencies: item.data.pluginDependencies } : undefined;
588
+ const preset = item?.kind === 'preset' ? { teamId: team.teamId, pluginDependencies: item.data.pluginDependencies } : undefined;
475
589
  return { kind: 'success', text: (await plugins(preset)).map(p => p.text).join('\n') || '暂无插件依赖。' };
476
590
  }
477
591
  if (action === 'info') {
@@ -481,17 +595,17 @@ export async function apply(ctx, config) {
481
595
  }
482
596
  if (!item || item.kind !== 'preset')
483
597
  throw new Error('请选择团队预设 ID');
484
- const info = { teamId: snapshot.teamId, id: item.id, name: item.name, version: item.version, description: '', instructions: '', outputDescription: '', requiredTools: [], optionalTools: [], ...item.data };
598
+ const info = { teamId: team.teamId, id: item.id, name: item.name, version: item.version, description: '', instructions: '', outputDescription: '', requiredTools: [], optionalTools: [], ...item.data };
485
599
  return { kind: 'success', text: detail(agent, info, true) + '\n' + (await plugins(info)).map(p => p.text).join('\n') + '\n工具检查基于当前会话;切换后及每次请求前重新检查。' };
486
600
  }
487
601
  if (action === 'new') {
488
602
  if (!item || item.kind !== 'preset')
489
603
  throw new Error('请选择团队预设 ID');
490
- if (!modelData(snapshot, item))
604
+ if (!inheritsModel(item) && !modelData(snapshot, item))
491
605
  throw new Error('预设引用的团队模型已不可用,请联系管理员。');
492
606
  const sessionId = `team-${crypto.randomUUID()}`;
493
- const agentPreset = `team:${snapshot.teamId}:${item.id}`;
494
- await child.agents.create({ sessionId, meta: { cwd: agent.session.header.cwd, agentPreset }, setup: async (agentCtx) => { await child.agentPresets.mount(agentCtx, agentPreset); } });
607
+ const agentPreset = `team:${team.teamId}:${item.id}`;
608
+ await child.agents.create({ sessionId, meta: { cwd: agent.session.header.cwd, agentPreset }, setup: async (agentCtx) => { await child.agentPresets.mount(agentCtx, agentPreset); }, ...(inheritsModel(item) && agent.model.current() ? { agentOptions: agent.model.current() } : {}) });
495
609
  return { kind: 'success', text: `已创建会话 ${sessionId},使用 ${item.name} v${item.version}。请在会话列表打开;原会话和历史保持不变。` };
496
610
  }
497
611
  if (action === 'use') {
@@ -503,15 +617,15 @@ export async function apply(ctx, config) {
503
617
  throw new Error('请选择团队插件 ID');
504
618
  const spec = `${item.data.package}@${item.data.version}`;
505
619
  if (confirmation !== 'confirm') {
506
- pendingInstalls.set(String(agent.id), spec);
620
+ pendingInstalls.set(String(agent.id), `${client.sessionRevision()}:${JSON.stringify(item)}`);
507
621
  return { kind: 'success', text: `安装并启用 ${spec} 将执行该插件代码。确认请运行 /teamwork install ${item.id} confirm` };
508
622
  }
509
- if (pendingInstalls.get(String(agent.id)) !== spec)
623
+ if (pendingInstalls.get(String(agent.id)) !== `${client.sessionRevision()}:${JSON.stringify(item)}`)
510
624
  throw new Error('请先查看当前插件版本的安装说明,再确认安装');
511
625
  pendingInstalls.delete(String(agent.id));
512
626
  return { kind: 'success', text: await installPlugin(item, agent) + '\n运行 /teamwork plugins 或 /teamwork info 重新检查依赖与工具。' };
513
627
  }
514
- return { kind: 'success', text: snapshot ? snapshot.configs.map(c => `${c.id} · ${c.kind} · ${c.name} · v${c.version}`).join('\n') || '暂无团队配置' : '尚未同步。运行 /teamwork login 开始。' };
628
+ return { kind: 'success', text: snapshot ? snapshot.teams.flatMap(t => t.configs.map(c => `${c.id} · ${c.kind} · ${c.name} · v${c.version} · ${t.teamName}`)).join('\n') || '暂无团队配置' : '尚未同步。运行 /teamwork login 开始。' };
515
629
  }
516
630
  catch (error) {
517
631
  return { kind: 'error', text: error.message };